repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
pypyr/pypyr-cli
pypyr/parser/keyvaluepairs.py
get_parsed_context
def get_parsed_context(context_arg): """Parse input context string and returns context as dictionary.""" if not context_arg: logger.debug("pipeline invoked without context arg set. For " "this keyvaluepairs parser you're looking for " "something like: " ...
python
def get_parsed_context(context_arg): """Parse input context string and returns context as dictionary.""" if not context_arg: logger.debug("pipeline invoked without context arg set. For " "this keyvaluepairs parser you're looking for " "something like: " ...
[ "def", "get_parsed_context", "(", "context_arg", ")", ":", "if", "not", "context_arg", ":", "logger", ".", "debug", "(", "\"pipeline invoked without context arg set. For \"", "\"this keyvaluepairs parser you're looking for \"", "\"something like: \"", "\"pypyr pipelinename 'key1=va...
Parse input context string and returns context as dictionary.
[ "Parse", "input", "context", "string", "and", "returns", "context", "as", "dictionary", "." ]
train
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/parser/keyvaluepairs.py#L18-L29
pypyr/pypyr-cli
pypyr/steps/fetchjson.py
run_step
def run_step(context): """Load a json file into the pypyr context. json parsed from the file will be merged into the pypyr context. This will overwrite existing values if the same keys are already in there. I.e if file json has {'eggs' : 'boiled'} and context {'eggs': 'fried'} already exists, retur...
python
def run_step(context): """Load a json file into the pypyr context. json parsed from the file will be merged into the pypyr context. This will overwrite existing values if the same keys are already in there. I.e if file json has {'eggs' : 'boiled'} and context {'eggs': 'fried'} already exists, retur...
[ "def", "run_step", "(", "context", ")", ":", "logger", ".", "debug", "(", "\"started\"", ")", "deprecated", "(", "context", ")", "context", ".", "assert_key_has_value", "(", "key", "=", "'fetchJson'", ",", "caller", "=", "__name__", ")", "fetch_json_input", ...
Load a json file into the pypyr context. json parsed from the file will be merged into the pypyr context. This will overwrite existing values if the same keys are already in there. I.e if file json has {'eggs' : 'boiled'} and context {'eggs': 'fried'} already exists, returned context['eggs'] will be 'b...
[ "Load", "a", "json", "file", "into", "the", "pypyr", "context", "." ]
train
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/fetchjson.py#L10-L82
pypyr/pypyr-cli
pypyr/steps/fetchjson.py
deprecated
def deprecated(context): """Create new style in params from deprecated.""" if 'fetchJsonPath' in context: context.assert_key_has_value(key='fetchJsonPath', caller=__name__) context['fetchJson'] = {'path': context['fetchJsonPath']} if 'fetchJsonKey' in context: context['fetc...
python
def deprecated(context): """Create new style in params from deprecated.""" if 'fetchJsonPath' in context: context.assert_key_has_value(key='fetchJsonPath', caller=__name__) context['fetchJson'] = {'path': context['fetchJsonPath']} if 'fetchJsonKey' in context: context['fetc...
[ "def", "deprecated", "(", "context", ")", ":", "if", "'fetchJsonPath'", "in", "context", ":", "context", ".", "assert_key_has_value", "(", "key", "=", "'fetchJsonPath'", ",", "caller", "=", "__name__", ")", "context", "[", "'fetchJson'", "]", "=", "{", "'pat...
Create new style in params from deprecated.
[ "Create", "new", "style", "in", "params", "from", "deprecated", "." ]
train
https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/fetchjson.py#L85-L100
bradmontgomery/django-querycount
querycount/middleware.py
QueryCountMiddleware._ignore_request
def _ignore_request(self, path): """Check to see if we should ignore the request.""" return any([ re.match(pattern, path) for pattern in QC_SETTINGS['IGNORE_REQUEST_PATTERNS'] ])
python
def _ignore_request(self, path): """Check to see if we should ignore the request.""" return any([ re.match(pattern, path) for pattern in QC_SETTINGS['IGNORE_REQUEST_PATTERNS'] ])
[ "def", "_ignore_request", "(", "self", ",", "path", ")", ":", "return", "any", "(", "[", "re", ".", "match", "(", "pattern", ",", "path", ")", "for", "pattern", "in", "QC_SETTINGS", "[", "'IGNORE_REQUEST_PATTERNS'", "]", "]", ")" ]
Check to see if we should ignore the request.
[ "Check", "to", "see", "if", "we", "should", "ignore", "the", "request", "." ]
train
https://github.com/bradmontgomery/django-querycount/blob/61a380d98bc55e926c011367ecc2031102c3484c/querycount/middleware.py#L83-L87
bradmontgomery/django-querycount
querycount/middleware.py
QueryCountMiddleware._ignore_sql
def _ignore_sql(self, query): """Check to see if we should ignore the sql query.""" return any([ re.search(pattern, query.get('sql')) for pattern in QC_SETTINGS['IGNORE_SQL_PATTERNS'] ])
python
def _ignore_sql(self, query): """Check to see if we should ignore the sql query.""" return any([ re.search(pattern, query.get('sql')) for pattern in QC_SETTINGS['IGNORE_SQL_PATTERNS'] ])
[ "def", "_ignore_sql", "(", "self", ",", "query", ")", ":", "return", "any", "(", "[", "re", ".", "search", "(", "pattern", ",", "query", ".", "get", "(", "'sql'", ")", ")", "for", "pattern", "in", "QC_SETTINGS", "[", "'IGNORE_SQL_PATTERNS'", "]", "]", ...
Check to see if we should ignore the sql query.
[ "Check", "to", "see", "if", "we", "should", "ignore", "the", "sql", "query", "." ]
train
https://github.com/bradmontgomery/django-querycount/blob/61a380d98bc55e926c011367ecc2031102c3484c/querycount/middleware.py#L89-L93
bradmontgomery/django-querycount
querycount/middleware.py
QueryCountMiddleware._duplicate_queries
def _duplicate_queries(self, output): """Appends the most common duplicate queries to the given output.""" if QC_SETTINGS['DISPLAY_DUPLICATES']: for query, count in self.queries.most_common(QC_SETTINGS['DISPLAY_DUPLICATES']): lines = ['\nRepeated {0} times.'.format(count)] ...
python
def _duplicate_queries(self, output): """Appends the most common duplicate queries to the given output.""" if QC_SETTINGS['DISPLAY_DUPLICATES']: for query, count in self.queries.most_common(QC_SETTINGS['DISPLAY_DUPLICATES']): lines = ['\nRepeated {0} times.'.format(count)] ...
[ "def", "_duplicate_queries", "(", "self", ",", "output", ")", ":", "if", "QC_SETTINGS", "[", "'DISPLAY_DUPLICATES'", "]", ":", "for", "query", ",", "count", "in", "self", ".", "queries", ".", "most_common", "(", "QC_SETTINGS", "[", "'DISPLAY_DUPLICATES'", "]",...
Appends the most common duplicate queries to the given output.
[ "Appends", "the", "most", "common", "duplicate", "queries", "to", "the", "given", "output", "." ]
train
https://github.com/bradmontgomery/django-querycount/blob/61a380d98bc55e926c011367ecc2031102c3484c/querycount/middleware.py#L142-L150
bradmontgomery/django-querycount
querycount/middleware.py
QueryCountMiddleware._calculate_num_queries
def _calculate_num_queries(self): """ Calculate the total number of request and response queries. Used for count header and count table. """ request_totals = self._totals("request") response_totals = self._totals("response") return request_totals[2] + response_to...
python
def _calculate_num_queries(self): """ Calculate the total number of request and response queries. Used for count header and count table. """ request_totals = self._totals("request") response_totals = self._totals("response") return request_totals[2] + response_to...
[ "def", "_calculate_num_queries", "(", "self", ")", ":", "request_totals", "=", "self", ".", "_totals", "(", "\"request\"", ")", "response_totals", "=", "self", ".", "_totals", "(", "\"response\"", ")", "return", "request_totals", "[", "2", "]", "+", "response_...
Calculate the total number of request and response queries. Used for count header and count table.
[ "Calculate", "the", "total", "number", "of", "request", "and", "response", "queries", ".", "Used", "for", "count", "header", "and", "count", "table", "." ]
train
https://github.com/bradmontgomery/django-querycount/blob/61a380d98bc55e926c011367ecc2031102c3484c/querycount/middleware.py#L193-L201
bradmontgomery/django-querycount
querycount/qc_settings.py
_process_settings
def _process_settings(**kwargs): """ Apply user supplied settings. """ # If we are in this method due to a signal, only reload for our settings setting_name = kwargs.get('setting', None) if setting_name is not None and setting_name != 'QUERYCOUNT': return # Support the old-style s...
python
def _process_settings(**kwargs): """ Apply user supplied settings. """ # If we are in this method due to a signal, only reload for our settings setting_name = kwargs.get('setting', None) if setting_name is not None and setting_name != 'QUERYCOUNT': return # Support the old-style s...
[ "def", "_process_settings", "(", "*", "*", "kwargs", ")", ":", "# If we are in this method due to a signal, only reload for our settings", "setting_name", "=", "kwargs", ".", "get", "(", "'setting'", ",", "None", ")", "if", "setting_name", "is", "not", "None", "and", ...
Apply user supplied settings.
[ "Apply", "user", "supplied", "settings", "." ]
train
https://github.com/bradmontgomery/django-querycount/blob/61a380d98bc55e926c011367ecc2031102c3484c/querycount/qc_settings.py#L23-L55
xiyouMc/ncmbot
ncmbot/core.py
login
def login(password, phone=None, email=None, rememberLogin=True): """ 登录接口,返回 :class:'Response' 对象 :param password: 网易云音乐的密码 :param phone: (optional) 手机登录 :param email: (optional) 邮箱登录 :param rememberLogin: (optional) 是否记住密码,默认 True """ if (phone is None) and (email is None): raise Pa...
python
def login(password, phone=None, email=None, rememberLogin=True): """ 登录接口,返回 :class:'Response' 对象 :param password: 网易云音乐的密码 :param phone: (optional) 手机登录 :param email: (optional) 邮箱登录 :param rememberLogin: (optional) 是否记住密码,默认 True """ if (phone is None) and (email is None): raise Pa...
[ "def", "login", "(", "password", ",", "phone", "=", "None", ",", "email", "=", "None", ",", "rememberLogin", "=", "True", ")", ":", "if", "(", "phone", "is", "None", ")", "and", "(", "email", "is", "None", ")", ":", "raise", "ParamsError", "(", ")"...
登录接口,返回 :class:'Response' 对象 :param password: 网易云音乐的密码 :param phone: (optional) 手机登录 :param email: (optional) 邮箱登录 :param rememberLogin: (optional) 是否记住密码,默认 True
[ "登录接口,返回", ":", "class", ":", "Response", "对象", ":", "param", "password", ":", "网易云音乐的密码", ":", "param", "phone", ":", "(", "optional", ")", "手机登录", ":", "param", "email", ":", "(", "optional", ")", "邮箱登录", ":", "param", "rememberLogin", ":", "(", "opt...
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L218-L245
xiyouMc/ncmbot
ncmbot/core.py
user_play_list
def user_play_list(uid, offset=0, limit=1000): """获取用户歌单,包含收藏的歌单 :param uid: 用户的ID,可通过登录或者其他接口获取 :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 1000 """ if uid is None: raise ParamsError() r = NCloudBot() r.method = 'USER_PLAY_LIST' r.data = {'...
python
def user_play_list(uid, offset=0, limit=1000): """获取用户歌单,包含收藏的歌单 :param uid: 用户的ID,可通过登录或者其他接口获取 :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 1000 """ if uid is None: raise ParamsError() r = NCloudBot() r.method = 'USER_PLAY_LIST' r.data = {'...
[ "def", "user_play_list", "(", "uid", ",", "offset", "=", "0", ",", "limit", "=", "1000", ")", ":", "if", "uid", "is", "None", ":", "raise", "ParamsError", "(", ")", "r", "=", "NCloudBot", "(", ")", "r", ".", "method", "=", "'USER_PLAY_LIST'", "r", ...
获取用户歌单,包含收藏的歌单 :param uid: 用户的ID,可通过登录或者其他接口获取 :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 1000
[ "获取用户歌单,包含收藏的歌单", ":", "param", "uid", ":", "用户的ID,可通过登录或者其他接口获取", ":", "param", "offset", ":", "(", "optional", ")", "分段起始位置,默认", "0", ":", "param", "limit", ":", "(", "optional", ")", "数据上限多少行,默认", "1000" ]
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L248-L261
xiyouMc/ncmbot
ncmbot/core.py
user_dj
def user_dj(uid, offset=0, limit=30): """获取用户电台数据 :param uid: 用户的ID,可通过登录或者其他接口获取 :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 30 """ if uid is None: raise ParamsError() r = NCloudBot() r.method = 'USER_DJ' r.data = {'offset': offset, 'limit': li...
python
def user_dj(uid, offset=0, limit=30): """获取用户电台数据 :param uid: 用户的ID,可通过登录或者其他接口获取 :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 30 """ if uid is None: raise ParamsError() r = NCloudBot() r.method = 'USER_DJ' r.data = {'offset': offset, 'limit': li...
[ "def", "user_dj", "(", "uid", ",", "offset", "=", "0", ",", "limit", "=", "30", ")", ":", "if", "uid", "is", "None", ":", "raise", "ParamsError", "(", ")", "r", "=", "NCloudBot", "(", ")", "r", ".", "method", "=", "'USER_DJ'", "r", ".", "data", ...
获取用户电台数据 :param uid: 用户的ID,可通过登录或者其他接口获取 :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 30
[ "获取用户电台数据" ]
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L264-L279
xiyouMc/ncmbot
ncmbot/core.py
search
def search(keyword, type=1, offset=0, limit=30): """搜索歌曲,支持搜索歌曲、歌手、专辑等 :param keyword: 关键词 :param type: (optional) 搜索类型,1: 单曲, 100: 歌手, 1000: 歌单, 1002: 用户 :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 30 """ if keyword is None: raise ParamsError() r =...
python
def search(keyword, type=1, offset=0, limit=30): """搜索歌曲,支持搜索歌曲、歌手、专辑等 :param keyword: 关键词 :param type: (optional) 搜索类型,1: 单曲, 100: 歌手, 1000: 歌单, 1002: 用户 :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 30 """ if keyword is None: raise ParamsError() r =...
[ "def", "search", "(", "keyword", ",", "type", "=", "1", ",", "offset", "=", "0", ",", "limit", "=", "30", ")", ":", "if", "keyword", "is", "None", ":", "raise", "ParamsError", "(", ")", "r", "=", "NCloudBot", "(", ")", "r", ".", "method", "=", ...
搜索歌曲,支持搜索歌曲、歌手、专辑等 :param keyword: 关键词 :param type: (optional) 搜索类型,1: 单曲, 100: 歌手, 1000: 歌单, 1002: 用户 :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 30
[ "搜索歌曲,支持搜索歌曲、歌手、专辑等" ]
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L282-L302
xiyouMc/ncmbot
ncmbot/core.py
user_follows
def user_follows(uid, offset='0', limit=30): """获取用户关注列表 :param uid: 用户的ID,可通过登录或者其他接口获取 :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 30 """ if uid is None: raise ParamsError() r = NCloudBot() r.method = 'USER_FOLLOWS' r.params = {'uid': uid} ...
python
def user_follows(uid, offset='0', limit=30): """获取用户关注列表 :param uid: 用户的ID,可通过登录或者其他接口获取 :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 30 """ if uid is None: raise ParamsError() r = NCloudBot() r.method = 'USER_FOLLOWS' r.params = {'uid': uid} ...
[ "def", "user_follows", "(", "uid", ",", "offset", "=", "'0'", ",", "limit", "=", "30", ")", ":", "if", "uid", "is", "None", ":", "raise", "ParamsError", "(", ")", "r", "=", "NCloudBot", "(", ")", "r", ".", "method", "=", "'USER_FOLLOWS'", "r", ".",...
获取用户关注列表 :param uid: 用户的ID,可通过登录或者其他接口获取 :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 30
[ "获取用户关注列表" ]
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L305-L320
xiyouMc/ncmbot
ncmbot/core.py
user_event
def user_event(uid): """获取用户动态 :param uid: 用户的ID,可通过登录或者其他接口获取 """ if uid is None: raise ParamsError() r = NCloudBot() r.method = 'USER_EVENT' r.params = {'uid': uid} r.data = {'time': -1, 'getcounts': True, "csrf_token": ""} r.send() return r.response
python
def user_event(uid): """获取用户动态 :param uid: 用户的ID,可通过登录或者其他接口获取 """ if uid is None: raise ParamsError() r = NCloudBot() r.method = 'USER_EVENT' r.params = {'uid': uid} r.data = {'time': -1, 'getcounts': True, "csrf_token": ""} r.send() return r.response
[ "def", "user_event", "(", "uid", ")", ":", "if", "uid", "is", "None", ":", "raise", "ParamsError", "(", ")", "r", "=", "NCloudBot", "(", ")", "r", ".", "method", "=", "'USER_EVENT'", "r", ".", "params", "=", "{", "'uid'", ":", "uid", "}", "r", "....
获取用户动态 :param uid: 用户的ID,可通过登录或者其他接口获取
[ "获取用户动态" ]
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L345-L358
xiyouMc/ncmbot
ncmbot/core.py
user_record
def user_record(uid, type=0): """获取用户的播放列表,必须登录 :param uid: 用户的ID,可通过登录或者其他接口获取 :param type: (optional) 数据类型,0:获取所有记录,1:获取 weekData """ if uid is None: raise ParamsError() r = NCloudBot() r.method = 'USER_RECORD' r.data = {'type': type, 'uid': uid, "csrf_token": ""} r.send()...
python
def user_record(uid, type=0): """获取用户的播放列表,必须登录 :param uid: 用户的ID,可通过登录或者其他接口获取 :param type: (optional) 数据类型,0:获取所有记录,1:获取 weekData """ if uid is None: raise ParamsError() r = NCloudBot() r.method = 'USER_RECORD' r.data = {'type': type, 'uid': uid, "csrf_token": ""} r.send()...
[ "def", "user_record", "(", "uid", ",", "type", "=", "0", ")", ":", "if", "uid", "is", "None", ":", "raise", "ParamsError", "(", ")", "r", "=", "NCloudBot", "(", ")", "r", ".", "method", "=", "'USER_RECORD'", "r", ".", "data", "=", "{", "'type'", ...
获取用户的播放列表,必须登录 :param uid: 用户的ID,可通过登录或者其他接口获取 :param type: (optional) 数据类型,0:获取所有记录,1:获取 weekData
[ "获取用户的播放列表", "必须登录" ]
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L361-L374
xiyouMc/ncmbot
ncmbot/core.py
event
def event(): """获取好友的动态,包括分享视频、音乐、动态等 """ r = NCloudBot() r.method = 'EVENT' r.data = {"csrf_token": ""} r.send() return r.response
python
def event(): """获取好友的动态,包括分享视频、音乐、动态等 """ r = NCloudBot() r.method = 'EVENT' r.data = {"csrf_token": ""} r.send() return r.response
[ "def", "event", "(", ")", ":", "r", "=", "NCloudBot", "(", ")", "r", ".", "method", "=", "'EVENT'", "r", ".", "data", "=", "{", "\"csrf_token\"", ":", "\"\"", "}", "r", ".", "send", "(", ")", "return", "r", ".", "response" ]
获取好友的动态,包括分享视频、音乐、动态等
[ "获取好友的动态,包括分享视频、音乐、动态等" ]
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L377-L386
xiyouMc/ncmbot
ncmbot/core.py
top_playlist_highquality
def top_playlist_highquality(cat='全部', offset=0, limit=20): """获取网易云音乐的精品歌单 :param cat: (optional) 歌单类型,默认 ‘全部’,比如 华语、欧美等 :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 20 """ r = NCloudBot() r.method = 'TOP_PLAYLIST_HIGHQUALITY' r.data = {'cat': cat, 'offset'...
python
def top_playlist_highquality(cat='全部', offset=0, limit=20): """获取网易云音乐的精品歌单 :param cat: (optional) 歌单类型,默认 ‘全部’,比如 华语、欧美等 :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 20 """ r = NCloudBot() r.method = 'TOP_PLAYLIST_HIGHQUALITY' r.data = {'cat': cat, 'offset'...
[ "def", "top_playlist_highquality", "(", "cat", "=", "'全部', of", "f", "et=0, ", "l", "i", "m", "t=20)", ":", "", "", "", "r", "=", "NCloudBot", "(", ")", "r", ".", "method", "=", "'TOP_PLAYLIST_HIGHQUALITY'", "r", ".", "data", "=", "{", "'cat'", ":", ...
获取网易云音乐的精品歌单 :param cat: (optional) 歌单类型,默认 ‘全部’,比如 华语、欧美等 :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 20
[ "获取网易云音乐的精品歌单" ]
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L390-L402
xiyouMc/ncmbot
ncmbot/core.py
play_list_detail
def play_list_detail(id, limit=20): """获取歌单中的所有音乐。由于获取精品中,只能看到歌单名字和 ID 并没有歌单的音乐,因此增加该接口传入歌单 ID 获取歌单中的所有音乐. :param id: 歌单的ID :param limit: (optional) 数据上限多少行,默认 20 """ if id is None: raise ParamsError() r = NCloudBot() r.method = 'PLAY_LIST_DETAIL' r.data = {'id': id, 'limit'...
python
def play_list_detail(id, limit=20): """获取歌单中的所有音乐。由于获取精品中,只能看到歌单名字和 ID 并没有歌单的音乐,因此增加该接口传入歌单 ID 获取歌单中的所有音乐. :param id: 歌单的ID :param limit: (optional) 数据上限多少行,默认 20 """ if id is None: raise ParamsError() r = NCloudBot() r.method = 'PLAY_LIST_DETAIL' r.data = {'id': id, 'limit'...
[ "def", "play_list_detail", "(", "id", ",", "limit", "=", "20", ")", ":", "if", "id", "is", "None", ":", "raise", "ParamsError", "(", ")", "r", "=", "NCloudBot", "(", ")", "r", ".", "method", "=", "'PLAY_LIST_DETAIL'", "r", ".", "data", "=", "{", "'...
获取歌单中的所有音乐。由于获取精品中,只能看到歌单名字和 ID 并没有歌单的音乐,因此增加该接口传入歌单 ID 获取歌单中的所有音乐. :param id: 歌单的ID :param limit: (optional) 数据上限多少行,默认 20
[ "获取歌单中的所有音乐。由于获取精品中,只能看到歌单名字和", "ID", "并没有歌单的音乐,因此增加该接口传入歌单", "ID", "获取歌单中的所有音乐", "." ]
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L406-L420
xiyouMc/ncmbot
ncmbot/core.py
music_url
def music_url(ids=[]): """通过歌曲 ID 获取歌曲下载地址 :param ids: 歌曲 ID 的 list """ if not isinstance(ids, list): raise ParamsError() r = NCloudBot() r.method = 'MUSIC_URL' r.data = {'ids': ids, 'br': 999000, "csrf_token": ""} r.send() return r.response
python
def music_url(ids=[]): """通过歌曲 ID 获取歌曲下载地址 :param ids: 歌曲 ID 的 list """ if not isinstance(ids, list): raise ParamsError() r = NCloudBot() r.method = 'MUSIC_URL' r.data = {'ids': ids, 'br': 999000, "csrf_token": ""} r.send() return r.response
[ "def", "music_url", "(", "ids", "=", "[", "]", ")", ":", "if", "not", "isinstance", "(", "ids", ",", "list", ")", ":", "raise", "ParamsError", "(", ")", "r", "=", "NCloudBot", "(", ")", "r", ".", "method", "=", "'MUSIC_URL'", "r", ".", "data", "=...
通过歌曲 ID 获取歌曲下载地址 :param ids: 歌曲 ID 的 list
[ "通过歌曲", "ID", "获取歌曲下载地址" ]
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L424-L436
xiyouMc/ncmbot
ncmbot/core.py
lyric
def lyric(id): """通过歌曲 ID 获取歌曲歌词地址 :param id: 歌曲ID """ if id is None: raise ParamsError() r = NCloudBot() r.method = 'LYRIC' r.params = {'id': id} r.send() return r.response
python
def lyric(id): """通过歌曲 ID 获取歌曲歌词地址 :param id: 歌曲ID """ if id is None: raise ParamsError() r = NCloudBot() r.method = 'LYRIC' r.params = {'id': id} r.send() return r.response
[ "def", "lyric", "(", "id", ")", ":", "if", "id", "is", "None", ":", "raise", "ParamsError", "(", ")", "r", "=", "NCloudBot", "(", ")", "r", ".", "method", "=", "'LYRIC'", "r", ".", "params", "=", "{", "'id'", ":", "id", "}", "r", ".", "send", ...
通过歌曲 ID 获取歌曲歌词地址 :param id: 歌曲ID
[ "通过歌曲", "ID", "获取歌曲歌词地址" ]
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L440-L452
xiyouMc/ncmbot
ncmbot/core.py
music_comment
def music_comment(id, offset=0, limit=20): """获取歌曲的评论列表 :param id: 歌曲 ID :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 20 """ if id is None: raise ParamsError() r = NCloudBot() r.method = 'MUSIC_COMMENT' r.params = {'id': id} r.data = {'offset...
python
def music_comment(id, offset=0, limit=20): """获取歌曲的评论列表 :param id: 歌曲 ID :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 20 """ if id is None: raise ParamsError() r = NCloudBot() r.method = 'MUSIC_COMMENT' r.params = {'id': id} r.data = {'offset...
[ "def", "music_comment", "(", "id", ",", "offset", "=", "0", ",", "limit", "=", "20", ")", ":", "if", "id", "is", "None", ":", "raise", "ParamsError", "(", ")", "r", "=", "NCloudBot", "(", ")", "r", ".", "method", "=", "'MUSIC_COMMENT'", "r", ".", ...
获取歌曲的评论列表 :param id: 歌曲 ID :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 20
[ "获取歌曲的评论列表" ]
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L456-L471
xiyouMc/ncmbot
ncmbot/core.py
song_detail
def song_detail(ids): """通过歌曲 ID 获取歌曲的详细信息 :param ids: 歌曲 ID 的 list """ if not isinstance(ids, list): raise ParamsError() c = [] for id in ids: c.append({'id': id}) r = NCloudBot() r.method = 'SONG_DETAIL' r.data = {'c': json.dumps(c), 'ids': c, "csrf_token": ""} ...
python
def song_detail(ids): """通过歌曲 ID 获取歌曲的详细信息 :param ids: 歌曲 ID 的 list """ if not isinstance(ids, list): raise ParamsError() c = [] for id in ids: c.append({'id': id}) r = NCloudBot() r.method = 'SONG_DETAIL' r.data = {'c': json.dumps(c), 'ids': c, "csrf_token": ""} ...
[ "def", "song_detail", "(", "ids", ")", ":", "if", "not", "isinstance", "(", "ids", ",", "list", ")", ":", "raise", "ParamsError", "(", ")", "c", "=", "[", "]", "for", "id", "in", "ids", ":", "c", ".", "append", "(", "{", "'id'", ":", "id", "}",...
通过歌曲 ID 获取歌曲的详细信息 :param ids: 歌曲 ID 的 list
[ "通过歌曲", "ID", "获取歌曲的详细信息" ]
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L488-L503
xiyouMc/ncmbot
ncmbot/core.py
personal_fm
def personal_fm(): """ 个人的 FM ,必须在登录之后调用,即 login 之后调用 """ r = NCloudBot() r.method = 'PERSONAL_FM' r.data = {"csrf_token": ""} r.send() return r.response
python
def personal_fm(): """ 个人的 FM ,必须在登录之后调用,即 login 之后调用 """ r = NCloudBot() r.method = 'PERSONAL_FM' r.data = {"csrf_token": ""} r.send() return r.response
[ "def", "personal_fm", "(", ")", ":", "r", "=", "NCloudBot", "(", ")", "r", ".", "method", "=", "'PERSONAL_FM'", "r", ".", "data", "=", "{", "\"csrf_token\"", ":", "\"\"", "}", "r", ".", "send", "(", ")", "return", "r", ".", "response" ]
个人的 FM ,必须在登录之后调用,即 login 之后调用
[ "个人的", "FM", "必须在登录之后调用,即", "login", "之后调用" ]
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L507-L514
xiyouMc/ncmbot
ncmbot/core.py
NCloudBot._get_webapi_requests
def _get_webapi_requests(self): """Update headers of webapi for Requests.""" headers = { 'Accept': '*/*', 'Accept-Language': 'zh-CN,zh;q=0.8,gl;q=0.6,zh-TW;q=0.4', 'Connection': 'keep-alive', 'Content-Type': ...
python
def _get_webapi_requests(self): """Update headers of webapi for Requests.""" headers = { 'Accept': '*/*', 'Accept-Language': 'zh-CN,zh;q=0.8,gl;q=0.6,zh-TW;q=0.4', 'Connection': 'keep-alive', 'Content-Type': ...
[ "def", "_get_webapi_requests", "(", "self", ")", ":", "headers", "=", "{", "'Accept'", ":", "'*/*'", ",", "'Accept-Language'", ":", "'zh-CN,zh;q=0.8,gl;q=0.6,zh-TW;q=0.4'", ",", "'Connection'", ":", "'keep-alive'", ",", "'Content-Type'", ":", "'application/x-www-form-ur...
Update headers of webapi for Requests.
[ "Update", "headers", "of", "webapi", "for", "Requests", "." ]
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L104-L124
xiyouMc/ncmbot
ncmbot/core.py
NCloudBot._build_response
def _build_response(self, resp): """Build internal Response object from given response.""" # rememberLogin # if self.method is 'LOGIN' and resp.json().get('code') == 200: # cookiesJar.save_cookies(resp, NCloudBot.username) self.response.content = resp.content self.res...
python
def _build_response(self, resp): """Build internal Response object from given response.""" # rememberLogin # if self.method is 'LOGIN' and resp.json().get('code') == 200: # cookiesJar.save_cookies(resp, NCloudBot.username) self.response.content = resp.content self.res...
[ "def", "_build_response", "(", "self", ",", "resp", ")", ":", "# rememberLogin", "# if self.method is 'LOGIN' and resp.json().get('code') == 200:", "# cookiesJar.save_cookies(resp, NCloudBot.username)", "self", ".", "response", ".", "content", "=", "resp", ".", "content", ...
Build internal Response object from given response.
[ "Build", "internal", "Response", "object", "from", "given", "response", "." ]
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L141-L148
xiyouMc/ncmbot
ncmbot/core.py
NCloudBot.send
def send(self): """Sens the request.""" success = False if self.method is None: raise ParamsError() try: if self.method == 'SEARCH': req = self._get_requests() _url = self.__NETEAST_HOST + self._METHODS[self.method] ...
python
def send(self): """Sens the request.""" success = False if self.method is None: raise ParamsError() try: if self.method == 'SEARCH': req = self._get_requests() _url = self.__NETEAST_HOST + self._METHODS[self.method] ...
[ "def", "send", "(", "self", ")", ":", "success", "=", "False", "if", "self", ".", "method", "is", "None", ":", "raise", "ParamsError", "(", ")", "try", ":", "if", "self", ".", "method", "==", "'SEARCH'", ":", "req", "=", "self", ".", "_get_requests",...
Sens the request.
[ "Sens", "the", "request", "." ]
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L150-L185
xiyouMc/ncmbot
ncmbot/core.py
Response.json
def json(self): """Returns the json-encoded content of a response, if any.""" if not self.headers and len(self.content) > 3: encoding = get_encoding_from_headers(self.headers) if encoding is not None: return json.loads(self.content.decode(encoding)) retur...
python
def json(self): """Returns the json-encoded content of a response, if any.""" if not self.headers and len(self.content) > 3: encoding = get_encoding_from_headers(self.headers) if encoding is not None: return json.loads(self.content.decode(encoding)) retur...
[ "def", "json", "(", "self", ")", ":", "if", "not", "self", ".", "headers", "and", "len", "(", "self", ".", "content", ")", ">", "3", ":", "encoding", "=", "get_encoding_from_headers", "(", "self", ".", "headers", ")", "if", "encoding", "is", "not", "...
Returns the json-encoded content of a response, if any.
[ "Returns", "the", "json", "-", "encoded", "content", "of", "a", "response", "if", "any", "." ]
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L208-L215
has2k1/plydata
plydata/options.py
set_option
def set_option(name, value): """ Set plydata option Parameters ---------- name : str Name of the option value : object New value of the option Returns ------- old : object Old value of the option See also -------- :class:`options` """ ol...
python
def set_option(name, value): """ Set plydata option Parameters ---------- name : str Name of the option value : object New value of the option Returns ------- old : object Old value of the option See also -------- :class:`options` """ ol...
[ "def", "set_option", "(", "name", ",", "value", ")", ":", "old", "=", "get_option", "(", "name", ")", "globals", "(", ")", "[", "name", "]", "=", "value", "return", "old" ]
Set plydata option Parameters ---------- name : str Name of the option value : object New value of the option Returns ------- old : object Old value of the option See also -------- :class:`options`
[ "Set", "plydata", "option" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/options.py#L45-L67
has2k1/plydata
plydata/dataframe/two_table.py
_join
def _join(verb): """ Join helper """ data = pd.merge(verb.x, verb.y, **verb.kwargs) # Preserve x groups if isinstance(verb.x, GroupedDataFrame): data.plydata_groups = list(verb.x.plydata_groups) return data
python
def _join(verb): """ Join helper """ data = pd.merge(verb.x, verb.y, **verb.kwargs) # Preserve x groups if isinstance(verb.x, GroupedDataFrame): data.plydata_groups = list(verb.x.plydata_groups) return data
[ "def", "_join", "(", "verb", ")", ":", "data", "=", "pd", ".", "merge", "(", "verb", ".", "x", ",", "verb", ".", "y", ",", "*", "*", "verb", ".", "kwargs", ")", "# Preserve x groups", "if", "isinstance", "(", "verb", ".", "x", ",", "GroupedDataFram...
Join helper
[ "Join", "helper" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/two_table.py#L50-L59
has2k1/plydata
plydata/types.py
GroupedDataFrame.groupby
def groupby(self, by=None, **kwargs): """ Group by and do not sort (unless specified) For plydata use cases, there is no need to specify group columns. """ if by is None: by = self.plydata_groups # Turn off sorting by groups messes with some verbs ...
python
def groupby(self, by=None, **kwargs): """ Group by and do not sort (unless specified) For plydata use cases, there is no need to specify group columns. """ if by is None: by = self.plydata_groups # Turn off sorting by groups messes with some verbs ...
[ "def", "groupby", "(", "self", ",", "by", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "by", "is", "None", ":", "by", "=", "self", ".", "plydata_groups", "# Turn off sorting by groups messes with some verbs", "if", "'sort'", "not", "in", "kwargs", ...
Group by and do not sort (unless specified) For plydata use cases, there is no need to specify group columns.
[ "Group", "by", "and", "do", "not", "sort", "(", "unless", "specified", ")" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/types.py#L33-L47
has2k1/plydata
plydata/types.py
GroupedDataFrame.group_indices
def group_indices(self): """ Return group indices """ # No groups if not self.plydata_groups: return np.ones(len(self), dtype=int) grouper = self.groupby() indices = np.empty(len(self), dtype=int) for i, (_, idx) in enumerate(sorted(grouper.in...
python
def group_indices(self): """ Return group indices """ # No groups if not self.plydata_groups: return np.ones(len(self), dtype=int) grouper = self.groupby() indices = np.empty(len(self), dtype=int) for i, (_, idx) in enumerate(sorted(grouper.in...
[ "def", "group_indices", "(", "self", ")", ":", "# No groups", "if", "not", "self", ".", "plydata_groups", ":", "return", "np", ".", "ones", "(", "len", "(", "self", ")", ",", "dtype", "=", "int", ")", "grouper", "=", "self", ".", "groupby", "(", ")",...
Return group indices
[ "Return", "group", "indices" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/types.py#L49-L61
has2k1/plydata
plydata/dataframe/helpers.py
_make_verb_helper
def _make_verb_helper(verb_func, add_groups=False): """ Create function that prepares verb for the verb function The functions created add expressions to be evaluated to the verb, then call the core verb function Parameters ---------- verb_func : function Core verb function. This i...
python
def _make_verb_helper(verb_func, add_groups=False): """ Create function that prepares verb for the verb function The functions created add expressions to be evaluated to the verb, then call the core verb function Parameters ---------- verb_func : function Core verb function. This i...
[ "def", "_make_verb_helper", "(", "verb_func", ",", "add_groups", "=", "False", ")", ":", "@", "wraps", "(", "verb_func", ")", "def", "_verb_func", "(", "verb", ")", ":", "verb", ".", "expressions", ",", "new_columns", "=", "build_expressions", "(", "verb", ...
Create function that prepares verb for the verb function The functions created add expressions to be evaluated to the verb, then call the core verb function Parameters ---------- verb_func : function Core verb function. This is the function called after expressions created and adde...
[ "Create", "function", "that", "prepares", "verb", "for", "the", "verb", "function" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/helpers.py#L156-L188
has2k1/plydata
plydata/dataframe/common.py
_get_base_dataframe
def _get_base_dataframe(df): """ Remove all columns other than those grouped on """ if isinstance(df, GroupedDataFrame): base_df = GroupedDataFrame( df.loc[:, df.plydata_groups], df.plydata_groups, copy=True) else: base_df = pd.DataFrame(index=df.index) re...
python
def _get_base_dataframe(df): """ Remove all columns other than those grouped on """ if isinstance(df, GroupedDataFrame): base_df = GroupedDataFrame( df.loc[:, df.plydata_groups], df.plydata_groups, copy=True) else: base_df = pd.DataFrame(index=df.index) re...
[ "def", "_get_base_dataframe", "(", "df", ")", ":", "if", "isinstance", "(", "df", ",", "GroupedDataFrame", ")", ":", "base_df", "=", "GroupedDataFrame", "(", "df", ".", "loc", "[", ":", ",", "df", ".", "plydata_groups", "]", ",", "df", ".", "plydata_grou...
Remove all columns other than those grouped on
[ "Remove", "all", "columns", "other", "than", "those", "grouped", "on" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/common.py#L27-L37
has2k1/plydata
plydata/dataframe/common.py
_add_group_columns
def _add_group_columns(data, gdf): """ Add group columns to data with a value from the grouped dataframe It is assumed that the grouped dataframe contains a single group >>> data = pd.DataFrame({ ... 'x': [5, 6, 7]}) >>> gdf = GroupedDataFrame({ ... 'g': list('aaa'), ... 'x...
python
def _add_group_columns(data, gdf): """ Add group columns to data with a value from the grouped dataframe It is assumed that the grouped dataframe contains a single group >>> data = pd.DataFrame({ ... 'x': [5, 6, 7]}) >>> gdf = GroupedDataFrame({ ... 'g': list('aaa'), ... 'x...
[ "def", "_add_group_columns", "(", "data", ",", "gdf", ")", ":", "n", "=", "len", "(", "data", ")", "if", "isinstance", "(", "gdf", ",", "GroupedDataFrame", ")", ":", "for", "i", ",", "col", "in", "enumerate", "(", "gdf", ".", "plydata_groups", ")", "...
Add group columns to data with a value from the grouped dataframe It is assumed that the grouped dataframe contains a single group >>> data = pd.DataFrame({ ... 'x': [5, 6, 7]}) >>> gdf = GroupedDataFrame({ ... 'g': list('aaa'), ... 'x': range(3)}, groups=['g']) >>> _add_group_...
[ "Add", "group", "columns", "to", "data", "with", "a", "value", "from", "the", "grouped", "dataframe" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/common.py#L40-L78
has2k1/plydata
plydata/dataframe/common.py
_create_column
def _create_column(data, col, value): """ Create column in dataframe Helper method meant to deal with problematic column values. e.g When the series index does not match that of the data. Parameters ---------- data : pandas.DataFrame dataframe in which to insert value col :...
python
def _create_column(data, col, value): """ Create column in dataframe Helper method meant to deal with problematic column values. e.g When the series index does not match that of the data. Parameters ---------- data : pandas.DataFrame dataframe in which to insert value col :...
[ "def", "_create_column", "(", "data", ",", "col", ",", "value", ")", ":", "with", "suppress", "(", "AttributeError", ")", ":", "# If the index of a series and the dataframe", "# in which the series will be assigned to a", "# column do not match, missing values/NaNs", "# are cre...
Create column in dataframe Helper method meant to deal with problematic column values. e.g When the series index does not match that of the data. Parameters ---------- data : pandas.DataFrame dataframe in which to insert value col : column label Column name value : obje...
[ "Create", "column", "in", "dataframe" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/common.py#L81-L157
has2k1/plydata
plydata/dataframe/common.py
build_expressions
def build_expressions(verb): """ Build expressions for helper verbs Parameters ---------- verb : verb A verb with a *functions* attribute. Returns ------- out : tuple (List of Expressions, New columns). The expressions and the new columns in which the results of...
python
def build_expressions(verb): """ Build expressions for helper verbs Parameters ---------- verb : verb A verb with a *functions* attribute. Returns ------- out : tuple (List of Expressions, New columns). The expressions and the new columns in which the results of...
[ "def", "build_expressions", "(", "verb", ")", ":", "def", "partial", "(", "func", ",", "col", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"\n Make a function that acts on a column in a dataframe\n\n Parameters\n ----------\n func :...
Build expressions for helper verbs Parameters ---------- verb : verb A verb with a *functions* attribute. Returns ------- out : tuple (List of Expressions, New columns). The expressions and the new columns in which the results of those expressions will be stored...
[ "Build", "expressions", "for", "helper", "verbs" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/common.py#L502-L613
has2k1/plydata
plydata/dataframe/common.py
Evaluator.process
def process(self): """ Run the expressions Returns ------- out : pandas.DataFrame Resulting data """ # Short cut if self._all_expressions_evaluated(): if self.drop: # Drop extra columns. They do not correspond to ...
python
def process(self): """ Run the expressions Returns ------- out : pandas.DataFrame Resulting data """ # Short cut if self._all_expressions_evaluated(): if self.drop: # Drop extra columns. They do not correspond to ...
[ "def", "process", "(", "self", ")", ":", "# Short cut", "if", "self", ".", "_all_expressions_evaluated", "(", ")", ":", "if", "self", ".", "drop", ":", "# Drop extra columns. They do not correspond to", "# any expressions.", "columns", "=", "[", "expr", ".", "colu...
Run the expressions Returns ------- out : pandas.DataFrame Resulting data
[ "Run", "the", "expressions" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/common.py#L195-L220
has2k1/plydata
plydata/dataframe/common.py
Evaluator._all_expressions_evaluated
def _all_expressions_evaluated(self): """ Return True all expressions match with the columns Saves some processor cycles """ def present(expr): return expr.stmt == expr.column and expr.column in self.data return all(present(expr) for expr in self.expressions)
python
def _all_expressions_evaluated(self): """ Return True all expressions match with the columns Saves some processor cycles """ def present(expr): return expr.stmt == expr.column and expr.column in self.data return all(present(expr) for expr in self.expressions)
[ "def", "_all_expressions_evaluated", "(", "self", ")", ":", "def", "present", "(", "expr", ")", ":", "return", "expr", ".", "stmt", "==", "expr", ".", "column", "and", "expr", ".", "column", "in", "self", ".", "data", "return", "all", "(", "present", "...
Return True all expressions match with the columns Saves some processor cycles
[ "Return", "True", "all", "expressions", "match", "with", "the", "columns" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/common.py#L222-L230
has2k1/plydata
plydata/dataframe/common.py
Evaluator._get_group_dataframes
def _get_group_dataframes(self): """ Get group dataframes Returns ------- out : tuple or generator Group dataframes """ if isinstance(self.data, GroupedDataFrame): grouper = self.data.groupby() # groupby on categorical columns ...
python
def _get_group_dataframes(self): """ Get group dataframes Returns ------- out : tuple or generator Group dataframes """ if isinstance(self.data, GroupedDataFrame): grouper = self.data.groupby() # groupby on categorical columns ...
[ "def", "_get_group_dataframes", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "data", ",", "GroupedDataFrame", ")", ":", "grouper", "=", "self", ".", "data", ".", "groupby", "(", ")", "# groupby on categorical columns uses the categories", "# even i...
Get group dataframes Returns ------- out : tuple or generator Group dataframes
[ "Get", "group", "dataframes" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/common.py#L232-L248
has2k1/plydata
plydata/dataframe/common.py
Evaluator._evaluate_group_dataframe
def _evaluate_group_dataframe(self, gdf): """ Evaluate a single group dataframe Parameters ---------- gdf : pandas.DataFrame Input group dataframe Returns ------- out : pandas.DataFrame Result data """ gdf._is_copy...
python
def _evaluate_group_dataframe(self, gdf): """ Evaluate a single group dataframe Parameters ---------- gdf : pandas.DataFrame Input group dataframe Returns ------- out : pandas.DataFrame Result data """ gdf._is_copy...
[ "def", "_evaluate_group_dataframe", "(", "self", ",", "gdf", ")", ":", "gdf", ".", "_is_copy", "=", "None", "result_index", "=", "gdf", ".", "index", "if", "self", ".", "keep_index", "else", "[", "]", "data", "=", "pd", ".", "DataFrame", "(", "index", ...
Evaluate a single group dataframe Parameters ---------- gdf : pandas.DataFrame Input group dataframe Returns ------- out : pandas.DataFrame Result data
[ "Evaluate", "a", "single", "group", "dataframe" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/common.py#L266-L291
has2k1/plydata
plydata/dataframe/common.py
Evaluator._concat
def _concat(self, egdfs): """ Concatenate evaluated group dataframes Parameters ---------- egdfs : iterable Evaluated dataframes Returns ------- edata : pandas.DataFrame Evaluated data """ egdfs = list(egdfs) ...
python
def _concat(self, egdfs): """ Concatenate evaluated group dataframes Parameters ---------- egdfs : iterable Evaluated dataframes Returns ------- edata : pandas.DataFrame Evaluated data """ egdfs = list(egdfs) ...
[ "def", "_concat", "(", "self", ",", "egdfs", ")", ":", "egdfs", "=", "list", "(", "egdfs", ")", "edata", "=", "pd", ".", "concat", "(", "egdfs", ",", "axis", "=", "0", ",", "ignore_index", "=", "False", ",", "copy", "=", "False", ")", "# groupby ca...
Concatenate evaluated group dataframes Parameters ---------- egdfs : iterable Evaluated dataframes Returns ------- edata : pandas.DataFrame Evaluated data
[ "Concatenate", "evaluated", "group", "dataframes" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/common.py#L293-L325
has2k1/plydata
plydata/dataframe/common.py
Selector._resolve_slices
def _resolve_slices(data_columns, names): """ Convert any slices into column names Parameters ---------- data_columns : pandas.Index Dataframe columns names : tuple Names (including slices) of columns in the dataframe. Returns...
python
def _resolve_slices(data_columns, names): """ Convert any slices into column names Parameters ---------- data_columns : pandas.Index Dataframe columns names : tuple Names (including slices) of columns in the dataframe. Returns...
[ "def", "_resolve_slices", "(", "data_columns", ",", "names", ")", ":", "def", "_get_slice_cols", "(", "sc", ")", ":", "\"\"\"\n Convert slice to list of names\n \"\"\"", "# Just like pandas.DataFrame.loc the stop", "# column is included", "idx_start", "=", ...
Convert any slices into column names Parameters ---------- data_columns : pandas.Index Dataframe columns names : tuple Names (including slices) of columns in the dataframe. Returns ------- out : tuple Names of colu...
[ "Convert", "any", "slices", "into", "column", "names" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/common.py#L333-L367
has2k1/plydata
plydata/dataframe/common.py
Selector.select
def select(cls, verb): """ Return selected columns for the select verb Parameters ---------- verb : object verb with the column selection attributes: - names - startswith - endswith - contains ...
python
def select(cls, verb): """ Return selected columns for the select verb Parameters ---------- verb : object verb with the column selection attributes: - names - startswith - endswith - contains ...
[ "def", "select", "(", "cls", ",", "verb", ")", ":", "columns", "=", "verb", ".", "data", ".", "columns", "contains", "=", "verb", ".", "contains", "matches", "=", "verb", ".", "matches", "groups", "=", "_get_groups", "(", "verb", ")", "names", "=", "...
Return selected columns for the select verb Parameters ---------- verb : object verb with the column selection attributes: - names - startswith - endswith - contains - matches
[ "Return", "selected", "columns", "for", "the", "select", "verb" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/common.py#L370-L437
has2k1/plydata
plydata/dataframe/common.py
Selector._all
def _all(cls, verb): """ A verb """ groups = set(_get_groups(verb)) return [col for col in verb.data if col not in groups]
python
def _all(cls, verb): """ A verb """ groups = set(_get_groups(verb)) return [col for col in verb.data if col not in groups]
[ "def", "_all", "(", "cls", ",", "verb", ")", ":", "groups", "=", "set", "(", "_get_groups", "(", "verb", ")", ")", "return", "[", "col", "for", "col", "in", "verb", ".", "data", "if", "col", "not", "in", "groups", "]" ]
A verb
[ "A", "verb" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/common.py#L440-L445
has2k1/plydata
plydata/dataframe/common.py
Selector._at
def _at(cls, verb): """ A verb with a select text match """ # Named (listed) columns are always included columns = cls.select(verb) final_columns_set = set(cls.select(verb)) groups_set = set(_get_groups(verb)) final_columns_set -= groups_set - set(verb.nam...
python
def _at(cls, verb): """ A verb with a select text match """ # Named (listed) columns are always included columns = cls.select(verb) final_columns_set = set(cls.select(verb)) groups_set = set(_get_groups(verb)) final_columns_set -= groups_set - set(verb.nam...
[ "def", "_at", "(", "cls", ",", "verb", ")", ":", "# Named (listed) columns are always included", "columns", "=", "cls", ".", "select", "(", "verb", ")", "final_columns_set", "=", "set", "(", "cls", ".", "select", "(", "verb", ")", ")", "groups_set", "=", "...
A verb with a select text match
[ "A", "verb", "with", "a", "select", "text", "match" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/common.py#L448-L464
has2k1/plydata
plydata/dataframe/common.py
Selector._if
def _if(cls, verb): """ A verb with a predicate function """ pred = verb.predicate data = verb.data groups = set(_get_groups(verb)) # force predicate if isinstance(pred, str): if not pred.endswith('_dtype'): pred = '{}_dtype'.f...
python
def _if(cls, verb): """ A verb with a predicate function """ pred = verb.predicate data = verb.data groups = set(_get_groups(verb)) # force predicate if isinstance(pred, str): if not pred.endswith('_dtype'): pred = '{}_dtype'.f...
[ "def", "_if", "(", "cls", ",", "verb", ")", ":", "pred", "=", "verb", ".", "predicate", "data", "=", "verb", ".", "data", "groups", "=", "set", "(", "_get_groups", "(", "verb", ")", ")", "# force predicate", "if", "isinstance", "(", "pred", ",", "str...
A verb with a predicate function
[ "A", "verb", "with", "a", "predicate", "function" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/common.py#L467-L488
has2k1/plydata
plydata/operators.py
get_verb_function
def get_verb_function(data, verb): """ Return function that implements the verb for given data type """ try: module = type_lookup[type(data)] except KeyError: # Some guess work for subclasses for type_, mod in type_lookup.items(): if isinstance(data, type_): ...
python
def get_verb_function(data, verb): """ Return function that implements the verb for given data type """ try: module = type_lookup[type(data)] except KeyError: # Some guess work for subclasses for type_, mod in type_lookup.items(): if isinstance(data, type_): ...
[ "def", "get_verb_function", "(", "data", ",", "verb", ")", ":", "try", ":", "module", "=", "type_lookup", "[", "type", "(", "data", ")", "]", "except", "KeyError", ":", "# Some guess work for subclasses", "for", "type_", ",", "mod", "in", "type_lookup", ".",...
Return function that implements the verb for given data type
[ "Return", "function", "that", "implements", "the", "verb", "for", "given", "data", "type" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/operators.py#L23-L39
has2k1/plydata
plydata/expressions.py
Expression
def Expression(*args, **kwargs): """ Return an appropriate Expression given the arguments Parameters ---------- args : tuple Positional arguments passed to the Expression class kwargs : dict Keyword arguments passed to the Expression class """ # dispatch if not hasat...
python
def Expression(*args, **kwargs): """ Return an appropriate Expression given the arguments Parameters ---------- args : tuple Positional arguments passed to the Expression class kwargs : dict Keyword arguments passed to the Expression class """ # dispatch if not hasat...
[ "def", "Expression", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# dispatch", "if", "not", "hasattr", "(", "args", "[", "0", "]", ",", "'_Expression'", ")", ":", "return", "BaseExpression", "(", "*", "args", ",", "*", "kwargs", ")", "else",...
Return an appropriate Expression given the arguments Parameters ---------- args : tuple Positional arguments passed to the Expression class kwargs : dict Keyword arguments passed to the Expression class
[ "Return", "an", "appropriate", "Expression", "given", "the", "arguments" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/expressions.py#L176-L191
has2k1/plydata
plydata/expressions.py
BaseExpression.evaluate
def evaluate(self, data, env): """ Evaluate statement Parameters ---------- data : pandas.DataFrame Data in whose namespace the statement will be evaluated. Typically, this is a group dataframe. Returns ------- out : object ...
python
def evaluate(self, data, env): """ Evaluate statement Parameters ---------- data : pandas.DataFrame Data in whose namespace the statement will be evaluated. Typically, this is a group dataframe. Returns ------- out : object ...
[ "def", "evaluate", "(", "self", ",", "data", ",", "env", ")", ":", "def", "n", "(", ")", ":", "\"\"\"\n Return number of rows in groups\n\n This function is part of the public API\n \"\"\"", "return", "len", "(", "data", ")", "if", "isinst...
Evaluate statement Parameters ---------- data : pandas.DataFrame Data in whose namespace the statement will be evaluated. Typically, this is a group dataframe. Returns ------- out : object Result of the evaluation.pandas.DataFrame
[ "Evaluate", "statement" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/expressions.py#L58-L101
has2k1/plydata
plydata/expressions.py
CaseWhenExpression.evaluate
def evaluate(self, data, env): """ Evaluate the predicates and values """ # For each predicate-value, we keep track of the positions # that have been copied to the result, so that the later # more general values do not overwrite the previous ones. result = np.repe...
python
def evaluate(self, data, env): """ Evaluate the predicates and values """ # For each predicate-value, we keep track of the positions # that have been copied to the result, so that the later # more general values do not overwrite the previous ones. result = np.repe...
[ "def", "evaluate", "(", "self", ",", "data", ",", "env", ")", ":", "# For each predicate-value, we keep track of the positions", "# that have been copied to the result, so that the later", "# more general values do not overwrite the previous ones.", "result", "=", "np", ".", "repea...
Evaluate the predicates and values
[ "Evaluate", "the", "predicates", "and", "values" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/expressions.py#L130-L150
has2k1/plydata
plydata/expressions.py
IfElseExpression.evaluate
def evaluate(self, data, env): """ Evaluate the predicates and values """ bool_idx = self.predicate_expr.evaluate(data, env) true_value = self.true_value_expr.evaluate(data, env) false_value = self.false_value_expr.evaluate(data, env) true_idx = np.where(bool_idx)...
python
def evaluate(self, data, env): """ Evaluate the predicates and values """ bool_idx = self.predicate_expr.evaluate(data, env) true_value = self.true_value_expr.evaluate(data, env) false_value = self.false_value_expr.evaluate(data, env) true_idx = np.where(bool_idx)...
[ "def", "evaluate", "(", "self", ",", "data", ",", "env", ")", ":", "bool_idx", "=", "self", ".", "predicate_expr", ".", "evaluate", "(", "data", ",", "env", ")", "true_value", "=", "self", ".", "true_value_expr", ".", "evaluate", "(", "data", ",", "env...
Evaluate the predicates and values
[ "Evaluate", "the", "predicates", "and", "values" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/expressions.py#L161-L173
has2k1/plydata
plydata/eval.py
EvalEnvironment.with_outer_namespace
def with_outer_namespace(self, outer_namespace): """Return a new EvalEnvironment with an extra namespace added. This namespace will be used only for variables that are not found in any existing namespace, i.e., it is "outside" them all.""" return self.__class__(self._namespaces + [outer_...
python
def with_outer_namespace(self, outer_namespace): """Return a new EvalEnvironment with an extra namespace added. This namespace will be used only for variables that are not found in any existing namespace, i.e., it is "outside" them all.""" return self.__class__(self._namespaces + [outer_...
[ "def", "with_outer_namespace", "(", "self", ",", "outer_namespace", ")", ":", "return", "self", ".", "__class__", "(", "self", ".", "_namespaces", "+", "[", "outer_namespace", "]", ",", "self", ".", "flags", ")" ]
Return a new EvalEnvironment with an extra namespace added. This namespace will be used only for variables that are not found in any existing namespace, i.e., it is "outside" them all.
[ "Return", "a", "new", "EvalEnvironment", "with", "an", "extra", "namespace", "added", ".", "This", "namespace", "will", "be", "used", "only", "for", "variables", "that", "are", "not", "found", "in", "any", "existing", "namespace", "i", ".", "e", ".", "it",...
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/eval.py#L81-L86
has2k1/plydata
plydata/eval.py
EvalEnvironment.eval
def eval(self, expr, source_name="<string>", inner_namespace={}): """Evaluate some Python code in the encapsulated environment. :arg expr: A string containing a Python expression. :arg source_name: A name for this string, for use in tracebacks. :arg inner_namespace: A dict-like object th...
python
def eval(self, expr, source_name="<string>", inner_namespace={}): """Evaluate some Python code in the encapsulated environment. :arg expr: A string containing a Python expression. :arg source_name: A name for this string, for use in tracebacks. :arg inner_namespace: A dict-like object th...
[ "def", "eval", "(", "self", ",", "expr", ",", "source_name", "=", "\"<string>\"", ",", "inner_namespace", "=", "{", "}", ")", ":", "code", "=", "compile", "(", "expr", ",", "source_name", ",", "\"eval\"", ",", "self", ".", "flags", ",", "False", ")", ...
Evaluate some Python code in the encapsulated environment. :arg expr: A string containing a Python expression. :arg source_name: A name for this string, for use in tracebacks. :arg inner_namespace: A dict-like object that will be checked first when `expr` attempts to access any variabl...
[ "Evaluate", "some", "Python", "code", "in", "the", "encapsulated", "environment", ".", ":", "arg", "expr", ":", "A", "string", "containing", "a", "Python", "expression", ".", ":", "arg", "source_name", ":", "A", "name", "for", "this", "string", "for", "use...
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/eval.py#L88-L98
has2k1/plydata
plydata/eval.py
EvalEnvironment.capture
def capture(cls, eval_env=0, reference=0): """Capture an execution environment from the stack. If `eval_env` is already an :class:`EvalEnvironment`, it is returned unchanged. Otherwise, we walk up the stack by ``eval_env + reference`` steps and capture that function's evaluation environm...
python
def capture(cls, eval_env=0, reference=0): """Capture an execution environment from the stack. If `eval_env` is already an :class:`EvalEnvironment`, it is returned unchanged. Otherwise, we walk up the stack by ``eval_env + reference`` steps and capture that function's evaluation environm...
[ "def", "capture", "(", "cls", ",", "eval_env", "=", "0", ",", "reference", "=", "0", ")", ":", "if", "isinstance", "(", "eval_env", ",", "cls", ")", ":", "return", "eval_env", "elif", "isinstance", "(", "eval_env", ",", "numbers", ".", "Integral", ")",...
Capture an execution environment from the stack. If `eval_env` is already an :class:`EvalEnvironment`, it is returned unchanged. Otherwise, we walk up the stack by ``eval_env + reference`` steps and capture that function's evaluation environment. For ``eval_env=0`` and ``reference=0``, t...
[ "Capture", "an", "execution", "environment", "from", "the", "stack", ".", "If", "eval_env", "is", "already", "an", ":", "class", ":", "EvalEnvironment", "it", "is", "returned", "unchanged", ".", "Otherwise", "we", "walk", "up", "the", "stack", "by", "eval_en...
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/eval.py#L101-L157
has2k1/plydata
plydata/eval.py
EvalEnvironment.subset
def subset(self, names): """Creates a new, flat EvalEnvironment that contains only the variables specified.""" vld = VarLookupDict(self._namespaces) new_ns = dict((name, vld[name]) for name in names) return EvalEnvironment([new_ns], self.flags)
python
def subset(self, names): """Creates a new, flat EvalEnvironment that contains only the variables specified.""" vld = VarLookupDict(self._namespaces) new_ns = dict((name, vld[name]) for name in names) return EvalEnvironment([new_ns], self.flags)
[ "def", "subset", "(", "self", ",", "names", ")", ":", "vld", "=", "VarLookupDict", "(", "self", ".", "_namespaces", ")", "new_ns", "=", "dict", "(", "(", "name", ",", "vld", "[", "name", "]", ")", "for", "name", "in", "names", ")", "return", "EvalE...
Creates a new, flat EvalEnvironment that contains only the variables specified.
[ "Creates", "a", "new", "flat", "EvalEnvironment", "that", "contains", "only", "the", "variables", "specified", "." ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/eval.py#L159-L164
has2k1/plydata
plydata/utils.py
temporary_key
def temporary_key(d, key, value): """ Context manager that removes key from dictionary on closing The dictionary will hold the key for the duration of the context. Parameters ---------- d : dict-like Dictionary in which to insert a temporary key. key : hashable Location...
python
def temporary_key(d, key, value): """ Context manager that removes key from dictionary on closing The dictionary will hold the key for the duration of the context. Parameters ---------- d : dict-like Dictionary in which to insert a temporary key. key : hashable Location...
[ "def", "temporary_key", "(", "d", ",", "key", ",", "value", ")", ":", "d", "[", "key", "]", "=", "value", "try", ":", "yield", "d", "finally", ":", "del", "d", "[", "key", "]" ]
Context manager that removes key from dictionary on closing The dictionary will hold the key for the duration of the context. Parameters ---------- d : dict-like Dictionary in which to insert a temporary key. key : hashable Location at which to insert ``value``. value : obj...
[ "Context", "manager", "that", "removes", "key", "from", "dictionary", "on", "closing" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/utils.py#L16-L36
has2k1/plydata
plydata/utils.py
temporary_attr
def temporary_attr(obj, name, value): """ Context manager that removes key from dictionary on closing The dictionary will hold the key for the duration of the context. Parameters ---------- obj : object Object onto which to add a temporary attribute. name : str Name of ...
python
def temporary_attr(obj, name, value): """ Context manager that removes key from dictionary on closing The dictionary will hold the key for the duration of the context. Parameters ---------- obj : object Object onto which to add a temporary attribute. name : str Name of ...
[ "def", "temporary_attr", "(", "obj", ",", "name", ",", "value", ")", ":", "setattr", "(", "obj", ",", "name", ",", "value", ")", "try", ":", "yield", "obj", "finally", ":", "delattr", "(", "obj", ",", "name", ")" ]
Context manager that removes key from dictionary on closing The dictionary will hold the key for the duration of the context. Parameters ---------- obj : object Object onto which to add a temporary attribute. name : str Name of attribute to add to ``obj``. value : object ...
[ "Context", "manager", "that", "removes", "key", "from", "dictionary", "on", "closing" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/utils.py#L40-L60
has2k1/plydata
plydata/utils.py
Q
def Q(name): """ Quote a variable name A way to 'quote' variable names, especially ones that do not otherwise meet Python's variable name rules. Parameters ---------- name : str Name of variable Returns ------- value : object Value of variable Examples ...
python
def Q(name): """ Quote a variable name A way to 'quote' variable names, especially ones that do not otherwise meet Python's variable name rules. Parameters ---------- name : str Name of variable Returns ------- value : object Value of variable Examples ...
[ "def", "Q", "(", "name", ")", ":", "env", "=", "EvalEnvironment", ".", "capture", "(", "1", ")", "try", ":", "return", "env", ".", "namespace", "[", "name", "]", "except", "KeyError", ":", "raise", "NameError", "(", "\"No data named {!r} found\"", ".", "...
Quote a variable name A way to 'quote' variable names, especially ones that do not otherwise meet Python's variable name rules. Parameters ---------- name : str Name of variable Returns ------- value : object Value of variable Examples -------- >>> import ...
[ "Quote", "a", "variable", "name" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/utils.py#L72-L119
has2k1/plydata
plydata/utils.py
regular_index
def regular_index(*dfs): """ Change & restore the indices of dataframes Dataframe with duplicate values can be hard to work with. When split and recombined, you cannot restore the row order. This can be the case even if the index has unique but irregular/unordered. This contextmanager resets th...
python
def regular_index(*dfs): """ Change & restore the indices of dataframes Dataframe with duplicate values can be hard to work with. When split and recombined, you cannot restore the row order. This can be the case even if the index has unique but irregular/unordered. This contextmanager resets th...
[ "def", "regular_index", "(", "*", "dfs", ")", ":", "original_index", "=", "[", "df", ".", "index", "for", "df", "in", "dfs", "]", "have_bad_index", "=", "[", "not", "isinstance", "(", "df", ".", "index", ",", "pd", ".", "RangeIndex", ")", "for", "df"...
Change & restore the indices of dataframes Dataframe with duplicate values can be hard to work with. When split and recombined, you cannot restore the row order. This can be the case even if the index has unique but irregular/unordered. This contextmanager resets the unordered indices of any datafr...
[ "Change", "&", "restore", "the", "indices", "of", "dataframes" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/utils.py#L147-L212
has2k1/plydata
plydata/utils.py
unique
def unique(lst): """ Return unique elements :class:`pandas.unique` and :class:`numpy.unique` cast mixed type lists to the same type. They are faster, but some times we want to maintain the type. Parameters ---------- lst : list-like List of items Returns ------- ou...
python
def unique(lst): """ Return unique elements :class:`pandas.unique` and :class:`numpy.unique` cast mixed type lists to the same type. They are faster, but some times we want to maintain the type. Parameters ---------- lst : list-like List of items Returns ------- ou...
[ "def", "unique", "(", "lst", ")", ":", "seen", "=", "set", "(", ")", "def", "make_seen", "(", "x", ")", ":", "seen", ".", "add", "(", "x", ")", "return", "x", "return", "[", "make_seen", "(", "x", ")", "for", "x", "in", "lst", "if", "x", "not...
Return unique elements :class:`pandas.unique` and :class:`numpy.unique` cast mixed type lists to the same type. They are faster, but some times we want to maintain the type. Parameters ---------- lst : list-like List of items Returns ------- out : list Unique items...
[ "Return", "unique", "elements" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/utils.py#L215-L256
has2k1/plydata
plydata/dataframe/one_table.py
_nth
def _nth(arr, n): """ Return the nth value of array If it is missing return NaN """ try: return arr.iloc[n] except (KeyError, IndexError): return np.nan
python
def _nth(arr, n): """ Return the nth value of array If it is missing return NaN """ try: return arr.iloc[n] except (KeyError, IndexError): return np.nan
[ "def", "_nth", "(", "arr", ",", "n", ")", ":", "try", ":", "return", "arr", ".", "iloc", "[", "n", "]", "except", "(", "KeyError", ",", "IndexError", ")", ":", "return", "np", ".", "nan" ]
Return the nth value of array If it is missing return NaN
[ "Return", "the", "nth", "value", "of", "array" ]
train
https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/dataframe/one_table.py#L217-L226
tkarabela/pysubs2
pysubs2/time.py
make_time
def make_time(h=0, m=0, s=0, ms=0, frames=None, fps=None): """ Convert time to milliseconds. See :func:`pysubs2.time.times_to_ms()`. When both frames and fps are specified, :func:`pysubs2.time.frames_to_ms()` is called instead. Raises: ValueError: Invalid fps, or one of frames/fps is missi...
python
def make_time(h=0, m=0, s=0, ms=0, frames=None, fps=None): """ Convert time to milliseconds. See :func:`pysubs2.time.times_to_ms()`. When both frames and fps are specified, :func:`pysubs2.time.frames_to_ms()` is called instead. Raises: ValueError: Invalid fps, or one of frames/fps is missi...
[ "def", "make_time", "(", "h", "=", "0", ",", "m", "=", "0", ",", "s", "=", "0", ",", "ms", "=", "0", ",", "frames", "=", "None", ",", "fps", "=", "None", ")", ":", "if", "frames", "is", "None", "and", "fps", "is", "None", ":", "return", "ti...
Convert time to milliseconds. See :func:`pysubs2.time.times_to_ms()`. When both frames and fps are specified, :func:`pysubs2.time.frames_to_ms()` is called instead. Raises: ValueError: Invalid fps, or one of frames/fps is missing. Example: >>> make_time(s=1.5) 1500 >>>...
[ "Convert", "time", "to", "milliseconds", "." ]
train
https://github.com/tkarabela/pysubs2/blob/6439eb5159e6aa6b47e0f8e1d950e8bdd7c5341f/pysubs2/time.py#L12-L34
tkarabela/pysubs2
pysubs2/time.py
timestamp_to_ms
def timestamp_to_ms(groups): """ Convert groups from :data:`pysubs2.time.TIMESTAMP` match to milliseconds. Example: >>> timestamp_to_ms(TIMESTAMP.match("0:00:00.42").groups()) 420 """ h, m, s, frac = map(int, groups) ms = frac * 10**(3 - len(groups[-1])) ms += s * 1...
python
def timestamp_to_ms(groups): """ Convert groups from :data:`pysubs2.time.TIMESTAMP` match to milliseconds. Example: >>> timestamp_to_ms(TIMESTAMP.match("0:00:00.42").groups()) 420 """ h, m, s, frac = map(int, groups) ms = frac * 10**(3 - len(groups[-1])) ms += s * 1...
[ "def", "timestamp_to_ms", "(", "groups", ")", ":", "h", ",", "m", ",", "s", ",", "frac", "=", "map", "(", "int", ",", "groups", ")", "ms", "=", "frac", "*", "10", "**", "(", "3", "-", "len", "(", "groups", "[", "-", "1", "]", ")", ")", "ms"...
Convert groups from :data:`pysubs2.time.TIMESTAMP` match to milliseconds. Example: >>> timestamp_to_ms(TIMESTAMP.match("0:00:00.42").groups()) 420
[ "Convert", "groups", "from", ":", "data", ":", "pysubs2", ".", "time", ".", "TIMESTAMP", "match", "to", "milliseconds", ".", "Example", ":", ">>>", "timestamp_to_ms", "(", "TIMESTAMP", ".", "match", "(", "0", ":", "00", ":", "00", ".", "42", ")", ".", ...
train
https://github.com/tkarabela/pysubs2/blob/6439eb5159e6aa6b47e0f8e1d950e8bdd7c5341f/pysubs2/time.py#L36-L50
tkarabela/pysubs2
pysubs2/time.py
times_to_ms
def times_to_ms(h=0, m=0, s=0, ms=0): """ Convert hours, minutes, seconds to milliseconds. Arguments may be positive or negative, int or float, need not be normalized (``s=120`` is okay). Returns: Number of milliseconds (rounded to int). """ ms += s * 1000 ms += m ...
python
def times_to_ms(h=0, m=0, s=0, ms=0): """ Convert hours, minutes, seconds to milliseconds. Arguments may be positive or negative, int or float, need not be normalized (``s=120`` is okay). Returns: Number of milliseconds (rounded to int). """ ms += s * 1000 ms += m ...
[ "def", "times_to_ms", "(", "h", "=", "0", ",", "m", "=", "0", ",", "s", "=", "0", ",", "ms", "=", "0", ")", ":", "ms", "+=", "s", "*", "1000", "ms", "+=", "m", "*", "60000", "ms", "+=", "h", "*", "3600000", "return", "int", "(", "round", ...
Convert hours, minutes, seconds to milliseconds. Arguments may be positive or negative, int or float, need not be normalized (``s=120`` is okay). Returns: Number of milliseconds (rounded to int).
[ "Convert", "hours", "minutes", "seconds", "to", "milliseconds", ".", "Arguments", "may", "be", "positive", "or", "negative", "int", "or", "float", "need", "not", "be", "normalized", "(", "s", "=", "120", "is", "okay", ")", ".", "Returns", ":", "Number", ...
train
https://github.com/tkarabela/pysubs2/blob/6439eb5159e6aa6b47e0f8e1d950e8bdd7c5341f/pysubs2/time.py#L52-L66
tkarabela/pysubs2
pysubs2/time.py
frames_to_ms
def frames_to_ms(frames, fps): """ Convert frame-based duration to milliseconds. Arguments: frames: Number of frames (should be int). fps: Framerate (must be a positive number, eg. 23.976). Returns: Number of milliseconds (rounded to int). Raises: V...
python
def frames_to_ms(frames, fps): """ Convert frame-based duration to milliseconds. Arguments: frames: Number of frames (should be int). fps: Framerate (must be a positive number, eg. 23.976). Returns: Number of milliseconds (rounded to int). Raises: V...
[ "def", "frames_to_ms", "(", "frames", ",", "fps", ")", ":", "if", "fps", "<=", "0", ":", "raise", "ValueError", "(", "\"Framerate must be positive number (%f).\"", "%", "fps", ")", "return", "int", "(", "round", "(", "frames", "*", "(", "1000", "/", "fps",...
Convert frame-based duration to milliseconds. Arguments: frames: Number of frames (should be int). fps: Framerate (must be a positive number, eg. 23.976). Returns: Number of milliseconds (rounded to int). Raises: ValueError: fps was negative or zero.
[ "Convert", "frame", "-", "based", "duration", "to", "milliseconds", ".", "Arguments", ":", "frames", ":", "Number", "of", "frames", "(", "should", "be", "int", ")", ".", "fps", ":", "Framerate", "(", "must", "be", "a", "positive", "number", "eg", ".", ...
train
https://github.com/tkarabela/pysubs2/blob/6439eb5159e6aa6b47e0f8e1d950e8bdd7c5341f/pysubs2/time.py#L68-L86
tkarabela/pysubs2
pysubs2/time.py
ms_to_frames
def ms_to_frames(ms, fps): """ Convert milliseconds to number of frames. Arguments: ms: Number of milliseconds (may be int, float or other numeric class). fps: Framerate (must be a positive number, eg. 23.976). Returns: Number of frames (int). Raises: ...
python
def ms_to_frames(ms, fps): """ Convert milliseconds to number of frames. Arguments: ms: Number of milliseconds (may be int, float or other numeric class). fps: Framerate (must be a positive number, eg. 23.976). Returns: Number of frames (int). Raises: ...
[ "def", "ms_to_frames", "(", "ms", ",", "fps", ")", ":", "if", "fps", "<=", "0", ":", "raise", "ValueError", "(", "\"Framerate must be positive number (%f).\"", "%", "fps", ")", "return", "int", "(", "round", "(", "(", "ms", "/", "1000", ")", "*", "fps", ...
Convert milliseconds to number of frames. Arguments: ms: Number of milliseconds (may be int, float or other numeric class). fps: Framerate (must be a positive number, eg. 23.976). Returns: Number of frames (int). Raises: ValueError: fps was negative or zero...
[ "Convert", "milliseconds", "to", "number", "of", "frames", ".", "Arguments", ":", "ms", ":", "Number", "of", "milliseconds", "(", "may", "be", "int", "float", "or", "other", "numeric", "class", ")", ".", "fps", ":", "Framerate", "(", "must", "be", "a", ...
train
https://github.com/tkarabela/pysubs2/blob/6439eb5159e6aa6b47e0f8e1d950e8bdd7c5341f/pysubs2/time.py#L88-L106
tkarabela/pysubs2
pysubs2/time.py
ms_to_times
def ms_to_times(ms): """ Convert milliseconds to normalized tuple (h, m, s, ms). Arguments: ms: Number of milliseconds (may be int, float or other numeric class). Should be non-negative. Returns: Named tuple (h, m, s, ms) of ints. Invariants: ``ms in range(1...
python
def ms_to_times(ms): """ Convert milliseconds to normalized tuple (h, m, s, ms). Arguments: ms: Number of milliseconds (may be int, float or other numeric class). Should be non-negative. Returns: Named tuple (h, m, s, ms) of ints. Invariants: ``ms in range(1...
[ "def", "ms_to_times", "(", "ms", ")", ":", "ms", "=", "int", "(", "round", "(", "ms", ")", ")", "h", ",", "ms", "=", "divmod", "(", "ms", ",", "3600000", ")", "m", ",", "ms", "=", "divmod", "(", "ms", ",", "60000", ")", "s", ",", "ms", "=",...
Convert milliseconds to normalized tuple (h, m, s, ms). Arguments: ms: Number of milliseconds (may be int, float or other numeric class). Should be non-negative. Returns: Named tuple (h, m, s, ms) of ints. Invariants: ``ms in range(1000) and s in range(60) and m in ...
[ "Convert", "milliseconds", "to", "normalized", "tuple", "(", "h", "m", "s", "ms", ")", ".", "Arguments", ":", "ms", ":", "Number", "of", "milliseconds", "(", "may", "be", "int", "float", "or", "other", "numeric", "class", ")", ".", "Should", "be", "non...
train
https://github.com/tkarabela/pysubs2/blob/6439eb5159e6aa6b47e0f8e1d950e8bdd7c5341f/pysubs2/time.py#L108-L125
tkarabela/pysubs2
pysubs2/time.py
ms_to_str
def ms_to_str(ms, fractions=False): """ Prettyprint milliseconds to [-]H:MM:SS[.mmm] Handles huge and/or negative times. Non-negative times with ``fractions=True`` are matched by :data:`pysubs2.time.TIMESTAMP`. Arguments: ms: Number of milliseconds (int, float or other numeric clas...
python
def ms_to_str(ms, fractions=False): """ Prettyprint milliseconds to [-]H:MM:SS[.mmm] Handles huge and/or negative times. Non-negative times with ``fractions=True`` are matched by :data:`pysubs2.time.TIMESTAMP`. Arguments: ms: Number of milliseconds (int, float or other numeric clas...
[ "def", "ms_to_str", "(", "ms", ",", "fractions", "=", "False", ")", ":", "sgn", "=", "\"-\"", "if", "ms", "<", "0", "else", "\"\"", "h", ",", "m", ",", "s", ",", "ms", "=", "ms_to_times", "(", "abs", "(", "ms", ")", ")", "if", "fractions", ":",...
Prettyprint milliseconds to [-]H:MM:SS[.mmm] Handles huge and/or negative times. Non-negative times with ``fractions=True`` are matched by :data:`pysubs2.time.TIMESTAMP`. Arguments: ms: Number of milliseconds (int, float or other numeric class). fractions: Whether to print up to mi...
[ "Prettyprint", "milliseconds", "to", "[", "-", "]", "H", ":", "MM", ":", "SS", "[", ".", "mmm", "]", "Handles", "huge", "and", "/", "or", "negative", "times", ".", "Non", "-", "negative", "times", "with", "fractions", "=", "True", "are", "matched", "...
train
https://github.com/tkarabela/pysubs2/blob/6439eb5159e6aa6b47e0f8e1d950e8bdd7c5341f/pysubs2/time.py#L127-L147
tkarabela/pysubs2
pysubs2/substation.py
ms_to_timestamp
def ms_to_timestamp(ms): """Convert ms to 'H:MM:SS.cc'""" # XXX throw on overflow/underflow? if ms < 0: ms = 0 if ms > MAX_REPRESENTABLE_TIME: ms = MAX_REPRESENTABLE_TIME h, m, s, ms = ms_to_times(ms) return "%01d:%02d:%02d.%02d" % (h, m, s, ms//10)
python
def ms_to_timestamp(ms): """Convert ms to 'H:MM:SS.cc'""" # XXX throw on overflow/underflow? if ms < 0: ms = 0 if ms > MAX_REPRESENTABLE_TIME: ms = MAX_REPRESENTABLE_TIME h, m, s, ms = ms_to_times(ms) return "%01d:%02d:%02d.%02d" % (h, m, s, ms//10)
[ "def", "ms_to_timestamp", "(", "ms", ")", ":", "# XXX throw on overflow/underflow?", "if", "ms", "<", "0", ":", "ms", "=", "0", "if", "ms", ">", "MAX_REPRESENTABLE_TIME", ":", "ms", "=", "MAX_REPRESENTABLE_TIME", "h", ",", "m", ",", "s", ",", "ms", "=", ...
Convert ms to 'H:MM:SS.cc
[ "Convert", "ms", "to", "H", ":", "MM", ":", "SS", ".", "cc" ]
train
https://github.com/tkarabela/pysubs2/blob/6439eb5159e6aa6b47e0f8e1d950e8bdd7c5341f/pysubs2/substation.py#L49-L55
tkarabela/pysubs2
pysubs2/substation.py
parse_tags
def parse_tags(text, style=SSAStyle.DEFAULT_STYLE, styles={}): """ Split text into fragments with computed SSAStyles. Returns list of tuples (fragment, style), where fragment is a part of text between two brace-delimited override sequences, and style is the computed styling of the fragment, ie....
python
def parse_tags(text, style=SSAStyle.DEFAULT_STYLE, styles={}): """ Split text into fragments with computed SSAStyles. Returns list of tuples (fragment, style), where fragment is a part of text between two brace-delimited override sequences, and style is the computed styling of the fragment, ie....
[ "def", "parse_tags", "(", "text", ",", "style", "=", "SSAStyle", ".", "DEFAULT_STYLE", ",", "styles", "=", "{", "}", ")", ":", "fragments", "=", "SSAEvent", ".", "OVERRIDE_SEQUENCE", ".", "split", "(", "text", ")", "if", "len", "(", "fragments", ")", "...
Split text into fragments with computed SSAStyles. Returns list of tuples (fragment, style), where fragment is a part of text between two brace-delimited override sequences, and style is the computed styling of the fragment, ie. the original style modified by all override sequences before the fragm...
[ "Split", "text", "into", "fragments", "with", "computed", "SSAStyles", ".", "Returns", "list", "of", "tuples", "(", "fragment", "style", ")", "where", "fragment", "is", "a", "part", "of", "text", "between", "two", "brace", "-", "delimited", "override", "sequ...
train
https://github.com/tkarabela/pysubs2/blob/6439eb5159e6aa6b47e0f8e1d950e8bdd7c5341f/pysubs2/substation.py#L89-L130
tkarabela/pysubs2
pysubs2/ssaevent.py
SSAEvent.plaintext
def plaintext(self): """ Subtitle text as multi-line string with no tags (read/write property). Writing to this property replaces :attr:`SSAEvent.text` with given plain text. Newlines are converted to ``\\N`` tags. """ text = self.text text = self.OVERRIDE_SEQUEN...
python
def plaintext(self): """ Subtitle text as multi-line string with no tags (read/write property). Writing to this property replaces :attr:`SSAEvent.text` with given plain text. Newlines are converted to ``\\N`` tags. """ text = self.text text = self.OVERRIDE_SEQUEN...
[ "def", "plaintext", "(", "self", ")", ":", "text", "=", "self", ".", "text", "text", "=", "self", ".", "OVERRIDE_SEQUENCE", ".", "sub", "(", "\"\"", ",", "text", ")", "text", "=", "text", ".", "replace", "(", "r\"\\h\"", ",", "\" \"", ")", "text", ...
Subtitle text as multi-line string with no tags (read/write property). Writing to this property replaces :attr:`SSAEvent.text` with given plain text. Newlines are converted to ``\\N`` tags.
[ "Subtitle", "text", "as", "multi", "-", "line", "string", "with", "no", "tags", "(", "read", "/", "write", "property", ")", "." ]
train
https://github.com/tkarabela/pysubs2/blob/6439eb5159e6aa6b47e0f8e1d950e8bdd7c5341f/pysubs2/ssaevent.py#L87-L99
tkarabela/pysubs2
pysubs2/ssaevent.py
SSAEvent.shift
def shift(self, h=0, m=0, s=0, ms=0, frames=None, fps=None): """ Shift start and end times. See :meth:`SSAFile.shift()` for full description. """ delta = make_time(h=h, m=m, s=s, ms=ms, frames=frames, fps=fps) self.start += delta self.end += delta
python
def shift(self, h=0, m=0, s=0, ms=0, frames=None, fps=None): """ Shift start and end times. See :meth:`SSAFile.shift()` for full description. """ delta = make_time(h=h, m=m, s=s, ms=ms, frames=frames, fps=fps) self.start += delta self.end += delta
[ "def", "shift", "(", "self", ",", "h", "=", "0", ",", "m", "=", "0", ",", "s", "=", "0", ",", "ms", "=", "0", ",", "frames", "=", "None", ",", "fps", "=", "None", ")", ":", "delta", "=", "make_time", "(", "h", "=", "h", ",", "m", "=", "...
Shift start and end times. See :meth:`SSAFile.shift()` for full description.
[ "Shift", "start", "and", "end", "times", "." ]
train
https://github.com/tkarabela/pysubs2/blob/6439eb5159e6aa6b47e0f8e1d950e8bdd7c5341f/pysubs2/ssaevent.py#L105-L114
tkarabela/pysubs2
pysubs2/ssaevent.py
SSAEvent.equals
def equals(self, other): """Field-based equality for SSAEvents.""" if isinstance(other, SSAEvent): return self.as_dict() == other.as_dict() else: raise TypeError("Cannot compare to non-SSAEvent object")
python
def equals(self, other): """Field-based equality for SSAEvents.""" if isinstance(other, SSAEvent): return self.as_dict() == other.as_dict() else: raise TypeError("Cannot compare to non-SSAEvent object")
[ "def", "equals", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "SSAEvent", ")", ":", "return", "self", ".", "as_dict", "(", ")", "==", "other", ".", "as_dict", "(", ")", "else", ":", "raise", "TypeError", "(", "\"Cannot ...
Field-based equality for SSAEvents.
[ "Field", "-", "based", "equality", "for", "SSAEvents", "." ]
train
https://github.com/tkarabela/pysubs2/blob/6439eb5159e6aa6b47e0f8e1d950e8bdd7c5341f/pysubs2/ssaevent.py#L123-L128
tkarabela/pysubs2
pysubs2/ssafile.py
SSAFile.load
def load(cls, path, encoding="utf-8", format_=None, fps=None, **kwargs): """ Load subtitle file from given path. Arguments: path (str): Path to subtitle file. encoding (str): Character encoding of input file. Defaults to UTF-8, you may need to change this...
python
def load(cls, path, encoding="utf-8", format_=None, fps=None, **kwargs): """ Load subtitle file from given path. Arguments: path (str): Path to subtitle file. encoding (str): Character encoding of input file. Defaults to UTF-8, you may need to change this...
[ "def", "load", "(", "cls", ",", "path", ",", "encoding", "=", "\"utf-8\"", ",", "format_", "=", "None", ",", "fps", "=", "None", ",", "*", "*", "kwargs", ")", ":", "with", "open", "(", "path", ",", "encoding", "=", "encoding", ")", "as", "fp", ":...
Load subtitle file from given path. Arguments: path (str): Path to subtitle file. encoding (str): Character encoding of input file. Defaults to UTF-8, you may need to change this. format_ (str): Optional, forces use of specific parser (eg. `"s...
[ "Load", "subtitle", "file", "from", "given", "path", "." ]
train
https://github.com/tkarabela/pysubs2/blob/6439eb5159e6aa6b47e0f8e1d950e8bdd7c5341f/pysubs2/ssafile.py#L52-L92
tkarabela/pysubs2
pysubs2/ssafile.py
SSAFile.from_string
def from_string(cls, string, format_=None, fps=None, **kwargs): """ Load subtitle file from string. See :meth:`SSAFile.load()` for full description. Arguments: string (str): Subtitle file in a string. Note that the string must be Unicode (in Python 2). ...
python
def from_string(cls, string, format_=None, fps=None, **kwargs): """ Load subtitle file from string. See :meth:`SSAFile.load()` for full description. Arguments: string (str): Subtitle file in a string. Note that the string must be Unicode (in Python 2). ...
[ "def", "from_string", "(", "cls", ",", "string", ",", "format_", "=", "None", ",", "fps", "=", "None", ",", "*", "*", "kwargs", ")", ":", "fp", "=", "io", ".", "StringIO", "(", "string", ")", "return", "cls", ".", "from_file", "(", "fp", ",", "fo...
Load subtitle file from string. See :meth:`SSAFile.load()` for full description. Arguments: string (str): Subtitle file in a string. Note that the string must be Unicode (in Python 2). Returns: SSAFile Example: >>> text = ''' ...
[ "Load", "subtitle", "file", "from", "string", "." ]
train
https://github.com/tkarabela/pysubs2/blob/6439eb5159e6aa6b47e0f8e1d950e8bdd7c5341f/pysubs2/ssafile.py#L95-L118
tkarabela/pysubs2
pysubs2/ssafile.py
SSAFile.from_file
def from_file(cls, fp, format_=None, fps=None, **kwargs): """ Read subtitle file from file object. See :meth:`SSAFile.load()` for full description. Note: This is a low-level method. Usually, one of :meth:`SSAFile.load()` or :meth:`SSAFile.from_string()` is prefe...
python
def from_file(cls, fp, format_=None, fps=None, **kwargs): """ Read subtitle file from file object. See :meth:`SSAFile.load()` for full description. Note: This is a low-level method. Usually, one of :meth:`SSAFile.load()` or :meth:`SSAFile.from_string()` is prefe...
[ "def", "from_file", "(", "cls", ",", "fp", ",", "format_", "=", "None", ",", "fps", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "format_", "is", "None", ":", "# Autodetect subtitle format, then read again using correct parser.", "# The file might be a pi...
Read subtitle file from file object. See :meth:`SSAFile.load()` for full description. Note: This is a low-level method. Usually, one of :meth:`SSAFile.load()` or :meth:`SSAFile.from_string()` is preferable. Arguments: fp (file object): A file object, ie. :c...
[ "Read", "subtitle", "file", "from", "file", "object", "." ]
train
https://github.com/tkarabela/pysubs2/blob/6439eb5159e6aa6b47e0f8e1d950e8bdd7c5341f/pysubs2/ssafile.py#L121-L153
tkarabela/pysubs2
pysubs2/ssafile.py
SSAFile.save
def save(self, path, encoding="utf-8", format_=None, fps=None, **kwargs): """ Save subtitle file to given path. Arguments: path (str): Path to subtitle file. encoding (str): Character encoding of output file. Defaults to UTF-8, which should be fine for mo...
python
def save(self, path, encoding="utf-8", format_=None, fps=None, **kwargs): """ Save subtitle file to given path. Arguments: path (str): Path to subtitle file. encoding (str): Character encoding of output file. Defaults to UTF-8, which should be fine for mo...
[ "def", "save", "(", "self", ",", "path", ",", "encoding", "=", "\"utf-8\"", ",", "format_", "=", "None", ",", "fps", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "format_", "is", "None", ":", "ext", "=", "os", ".", "path", ".", "splitext...
Save subtitle file to given path. Arguments: path (str): Path to subtitle file. encoding (str): Character encoding of output file. Defaults to UTF-8, which should be fine for most purposes. format_ (str): Optional, specifies desired subtitle format ...
[ "Save", "subtitle", "file", "to", "given", "path", "." ]
train
https://github.com/tkarabela/pysubs2/blob/6439eb5159e6aa6b47e0f8e1d950e8bdd7c5341f/pysubs2/ssafile.py#L155-L190
tkarabela/pysubs2
pysubs2/ssafile.py
SSAFile.to_string
def to_string(self, format_, fps=None, **kwargs): """ Get subtitle file as a string. See :meth:`SSAFile.save()` for full description. Returns: str """ fp = io.StringIO() self.to_file(fp, format_, fps=fps, **kwargs) return fp.getvalue()
python
def to_string(self, format_, fps=None, **kwargs): """ Get subtitle file as a string. See :meth:`SSAFile.save()` for full description. Returns: str """ fp = io.StringIO() self.to_file(fp, format_, fps=fps, **kwargs) return fp.getvalue()
[ "def", "to_string", "(", "self", ",", "format_", ",", "fps", "=", "None", ",", "*", "*", "kwargs", ")", ":", "fp", "=", "io", ".", "StringIO", "(", ")", "self", ".", "to_file", "(", "fp", ",", "format_", ",", "fps", "=", "fps", ",", "*", "*", ...
Get subtitle file as a string. See :meth:`SSAFile.save()` for full description. Returns: str
[ "Get", "subtitle", "file", "as", "a", "string", "." ]
train
https://github.com/tkarabela/pysubs2/blob/6439eb5159e6aa6b47e0f8e1d950e8bdd7c5341f/pysubs2/ssafile.py#L192-L204
tkarabela/pysubs2
pysubs2/ssafile.py
SSAFile.to_file
def to_file(self, fp, format_, fps=None, **kwargs): """ Write subtitle file to file object. See :meth:`SSAFile.save()` for full description. Note: This is a low-level method. Usually, one of :meth:`SSAFile.save()` or :meth:`SSAFile.to_string()` is preferable. ...
python
def to_file(self, fp, format_, fps=None, **kwargs): """ Write subtitle file to file object. See :meth:`SSAFile.save()` for full description. Note: This is a low-level method. Usually, one of :meth:`SSAFile.save()` or :meth:`SSAFile.to_string()` is preferable. ...
[ "def", "to_file", "(", "self", ",", "fp", ",", "format_", ",", "fps", "=", "None", ",", "*", "*", "kwargs", ")", ":", "impl", "=", "get_format_class", "(", "format_", ")", "impl", ".", "to_file", "(", "self", ",", "fp", ",", "format_", ",", "fps", ...
Write subtitle file to file object. See :meth:`SSAFile.save()` for full description. Note: This is a low-level method. Usually, one of :meth:`SSAFile.save()` or :meth:`SSAFile.to_string()` is preferable. Arguments: fp (file object): A file object, ie. :clas...
[ "Write", "subtitle", "file", "to", "file", "object", "." ]
train
https://github.com/tkarabela/pysubs2/blob/6439eb5159e6aa6b47e0f8e1d950e8bdd7c5341f/pysubs2/ssafile.py#L206-L222
tkarabela/pysubs2
pysubs2/ssafile.py
SSAFile.transform_framerate
def transform_framerate(self, in_fps, out_fps): """ Rescale all timestamps by ratio of in_fps/out_fps. Can be used to fix files converted from frame-based to time-based with wrongly assumed framerate. Arguments: in_fps (float) out_fps (float) Ra...
python
def transform_framerate(self, in_fps, out_fps): """ Rescale all timestamps by ratio of in_fps/out_fps. Can be used to fix files converted from frame-based to time-based with wrongly assumed framerate. Arguments: in_fps (float) out_fps (float) Ra...
[ "def", "transform_framerate", "(", "self", ",", "in_fps", ",", "out_fps", ")", ":", "if", "in_fps", "<=", "0", "or", "out_fps", "<=", "0", ":", "raise", "ValueError", "(", "\"Framerates must be positive, cannot transform %f -> %f\"", "%", "(", "in_fps", ",", "ou...
Rescale all timestamps by ratio of in_fps/out_fps. Can be used to fix files converted from frame-based to time-based with wrongly assumed framerate. Arguments: in_fps (float) out_fps (float) Raises: ValueError: Non-positive framerate given.
[ "Rescale", "all", "timestamps", "by", "ratio", "of", "in_fps", "/", "out_fps", "." ]
train
https://github.com/tkarabela/pysubs2/blob/6439eb5159e6aa6b47e0f8e1d950e8bdd7c5341f/pysubs2/ssafile.py#L250-L271
tkarabela/pysubs2
pysubs2/ssafile.py
SSAFile.rename_style
def rename_style(self, old_name, new_name): """ Rename a style, including references to it. Arguments: old_name (str): Style to be renamed. new_name (str): New name for the style (must be unused). Raises: KeyError: No style named old_name. ...
python
def rename_style(self, old_name, new_name): """ Rename a style, including references to it. Arguments: old_name (str): Style to be renamed. new_name (str): New name for the style (must be unused). Raises: KeyError: No style named old_name. ...
[ "def", "rename_style", "(", "self", ",", "old_name", ",", "new_name", ")", ":", "if", "old_name", "not", "in", "self", ".", "styles", ":", "raise", "KeyError", "(", "\"Style %r not found\"", "%", "old_name", ")", "if", "new_name", "in", "self", ".", "style...
Rename a style, including references to it. Arguments: old_name (str): Style to be renamed. new_name (str): New name for the style (must be unused). Raises: KeyError: No style named old_name. ValueError: new_name is not a legal name (cannot use commas) ...
[ "Rename", "a", "style", "including", "references", "to", "it", "." ]
train
https://github.com/tkarabela/pysubs2/blob/6439eb5159e6aa6b47e0f8e1d950e8bdd7c5341f/pysubs2/ssafile.py#L277-L304
tkarabela/pysubs2
pysubs2/ssafile.py
SSAFile.import_styles
def import_styles(self, subs, overwrite=True): """ Merge in styles from other SSAFile. Arguments: subs (SSAFile): Subtitle file imported from. overwrite (bool): On name conflict, use style from the other file (default: True). """ if not i...
python
def import_styles(self, subs, overwrite=True): """ Merge in styles from other SSAFile. Arguments: subs (SSAFile): Subtitle file imported from. overwrite (bool): On name conflict, use style from the other file (default: True). """ if not i...
[ "def", "import_styles", "(", "self", ",", "subs", ",", "overwrite", "=", "True", ")", ":", "if", "not", "isinstance", "(", "subs", ",", "SSAFile", ")", ":", "raise", "TypeError", "(", "\"Must supply an SSAFile.\"", ")", "for", "name", ",", "style", "in", ...
Merge in styles from other SSAFile. Arguments: subs (SSAFile): Subtitle file imported from. overwrite (bool): On name conflict, use style from the other file (default: True).
[ "Merge", "in", "styles", "from", "other", "SSAFile", "." ]
train
https://github.com/tkarabela/pysubs2/blob/6439eb5159e6aa6b47e0f8e1d950e8bdd7c5341f/pysubs2/ssafile.py#L306-L321
tkarabela/pysubs2
pysubs2/ssafile.py
SSAFile.equals
def equals(self, other): """ Equality of two SSAFiles. Compares :attr:`SSAFile.info`, :attr:`SSAFile.styles` and :attr:`SSAFile.events`. Order of entries in OrderedDicts does not matter. "ScriptType" key in info is considered an implementation detail and thus ignored. U...
python
def equals(self, other): """ Equality of two SSAFiles. Compares :attr:`SSAFile.info`, :attr:`SSAFile.styles` and :attr:`SSAFile.events`. Order of entries in OrderedDicts does not matter. "ScriptType" key in info is considered an implementation detail and thus ignored. U...
[ "def", "equals", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "SSAFile", ")", ":", "for", "key", "in", "set", "(", "chain", "(", "self", ".", "info", ".", "keys", "(", ")", ",", "other", ".", "info", ".", "keys", ...
Equality of two SSAFiles. Compares :attr:`SSAFile.info`, :attr:`SSAFile.styles` and :attr:`SSAFile.events`. Order of entries in OrderedDicts does not matter. "ScriptType" key in info is considered an implementation detail and thus ignored. Useful mostly in unit tests. Differences are l...
[ "Equality", "of", "two", "SSAFiles", "." ]
train
https://github.com/tkarabela/pysubs2/blob/6439eb5159e6aa6b47e0f8e1d950e8bdd7c5341f/pysubs2/ssafile.py#L327-L379
tkarabela/pysubs2
pysubs2/formats.py
get_file_extension
def get_file_extension(format_): """Format identifier -> file extension""" if format_ not in FORMAT_IDENTIFIER_TO_FORMAT_CLASS: raise UnknownFormatIdentifierError(format_) for ext, f in FILE_EXTENSION_TO_FORMAT_IDENTIFIER.items(): if f == format_: return ext raise RuntimeEr...
python
def get_file_extension(format_): """Format identifier -> file extension""" if format_ not in FORMAT_IDENTIFIER_TO_FORMAT_CLASS: raise UnknownFormatIdentifierError(format_) for ext, f in FILE_EXTENSION_TO_FORMAT_IDENTIFIER.items(): if f == format_: return ext raise RuntimeEr...
[ "def", "get_file_extension", "(", "format_", ")", ":", "if", "format_", "not", "in", "FORMAT_IDENTIFIER_TO_FORMAT_CLASS", ":", "raise", "UnknownFormatIdentifierError", "(", "format_", ")", "for", "ext", ",", "f", "in", "FILE_EXTENSION_TO_FORMAT_IDENTIFIER", ".", "item...
Format identifier -> file extension
[ "Format", "identifier", "-", ">", "file", "extension" ]
train
https://github.com/tkarabela/pysubs2/blob/6439eb5159e6aa6b47e0f8e1d950e8bdd7c5341f/pysubs2/formats.py#L42-L51
tkarabela/pysubs2
pysubs2/formats.py
autodetect_format
def autodetect_format(content): """Return format identifier for given fragment or raise FormatAutodetectionError.""" formats = set() for impl in FORMAT_IDENTIFIER_TO_FORMAT_CLASS.values(): guess = impl.guess_format(content) if guess is not None: formats.add(guess) if len(for...
python
def autodetect_format(content): """Return format identifier for given fragment or raise FormatAutodetectionError.""" formats = set() for impl in FORMAT_IDENTIFIER_TO_FORMAT_CLASS.values(): guess = impl.guess_format(content) if guess is not None: formats.add(guess) if len(for...
[ "def", "autodetect_format", "(", "content", ")", ":", "formats", "=", "set", "(", ")", "for", "impl", "in", "FORMAT_IDENTIFIER_TO_FORMAT_CLASS", ".", "values", "(", ")", ":", "guess", "=", "impl", ".", "guess_format", "(", "content", ")", "if", "guess", "i...
Return format identifier for given fragment or raise FormatAutodetectionError.
[ "Return", "format", "identifier", "for", "given", "fragment", "or", "raise", "FormatAutodetectionError", "." ]
train
https://github.com/tkarabela/pysubs2/blob/6439eb5159e6aa6b47e0f8e1d950e8bdd7c5341f/pysubs2/formats.py#L53-L66
aio-libs/aiohttp-devtools
aiohttp_devtools/runserver/serve.py
modify_main_app
def modify_main_app(app, config: Config): """ Modify the app we're serving to make development easier, eg. * modify responses to add the livereload snippet * set ``static_root_url`` on the app * setup the debug toolbar """ app._debug = True dft_logger.debug('livereload enabled: %s', '✓' ...
python
def modify_main_app(app, config: Config): """ Modify the app we're serving to make development easier, eg. * modify responses to add the livereload snippet * set ``static_root_url`` on the app * setup the debug toolbar """ app._debug = True dft_logger.debug('livereload enabled: %s', '✓' ...
[ "def", "modify_main_app", "(", "app", ",", "config", ":", "Config", ")", ":", "app", ".", "_debug", "=", "True", "dft_logger", ".", "debug", "(", "'livereload enabled: %s'", ",", "'✓' i", " c", "nfig.l", "i", "vereload e", "se '", "')", "", "def", "get_hos...
Modify the app we're serving to make development easier, eg. * modify responses to add the livereload snippet * set ``static_root_url`` on the app * setup the debug toolbar
[ "Modify", "the", "app", "we", "re", "serving", "to", "make", "development", "easier", "eg", ".", "*", "modify", "responses", "to", "add", "the", "livereload", "snippet", "*", "set", "static_root_url", "on", "the", "app", "*", "setup", "the", "debug", "tool...
train
https://github.com/aio-libs/aiohttp-devtools/blob/e9ea6feb43558e6e64595ea0ea5613f226cba81f/aiohttp_devtools/runserver/serve.py#L36-L80
aio-libs/aiohttp-devtools
aiohttp_devtools/runserver/serve.py
src_reload
async def src_reload(app, path: str = None): """ prompt each connected browser to reload by sending websocket message. :param path: if supplied this must be a path relative to app['static_path'], eg. reload of a single file is only supported for static resources. :return: number of sources relo...
python
async def src_reload(app, path: str = None): """ prompt each connected browser to reload by sending websocket message. :param path: if supplied this must be a path relative to app['static_path'], eg. reload of a single file is only supported for static resources. :return: number of sources relo...
[ "async", "def", "src_reload", "(", "app", ",", "path", ":", "str", "=", "None", ")", ":", "cli_count", "=", "len", "(", "app", "[", "WS", "]", ")", "if", "cli_count", "==", "0", ":", "return", "0", "is_html", "=", "None", "if", "path", ":", "path...
prompt each connected browser to reload by sending websocket message. :param path: if supplied this must be a path relative to app['static_path'], eg. reload of a single file is only supported for static resources. :return: number of sources reloaded
[ "prompt", "each", "connected", "browser", "to", "reload", "by", "sending", "websocket", "message", "." ]
train
https://github.com/aio-libs/aiohttp-devtools/blob/e9ea6feb43558e6e64595ea0ea5613f226cba81f/aiohttp_devtools/runserver/serve.py#L145-L186
aio-libs/aiohttp-devtools
aiohttp_devtools/runserver/serve.py
CustomStaticResource.modify_request
def modify_request(self, request): """ Apply common path conventions eg. / > /index.html, /foobar > /foobar.html """ filename = URL.build(path=request.match_info['filename'], encoded=True).path raw_path = self._directory.joinpath(filename) try: filepath = raw_...
python
def modify_request(self, request): """ Apply common path conventions eg. / > /index.html, /foobar > /foobar.html """ filename = URL.build(path=request.match_info['filename'], encoded=True).path raw_path = self._directory.joinpath(filename) try: filepath = raw_...
[ "def", "modify_request", "(", "self", ",", "request", ")", ":", "filename", "=", "URL", ".", "build", "(", "path", "=", "request", ".", "match_info", "[", "'filename'", "]", ",", "encoded", "=", "True", ")", ".", "path", "raw_path", "=", "self", ".", ...
Apply common path conventions eg. / > /index.html, /foobar > /foobar.html
[ "Apply", "common", "path", "conventions", "eg", ".", "/", ">", "/", "index", ".", "html", "/", "foobar", ">", "/", "foobar", ".", "html" ]
train
https://github.com/aio-libs/aiohttp-devtools/blob/e9ea6feb43558e6e64595ea0ea5613f226cba81f/aiohttp_devtools/runserver/serve.py#L288-L314
aio-libs/aiohttp-devtools
aiohttp_devtools/start/template/app/settings.py
Settings.substitute_environ
def substitute_environ(self): """ Substitute environment variables into settings. """ for attr_name in dir(self): if attr_name.startswith('_') or attr_name.upper() != attr_name: continue orig_value = getattr(self, attr_name) is_require...
python
def substitute_environ(self): """ Substitute environment variables into settings. """ for attr_name in dir(self): if attr_name.startswith('_') or attr_name.upper() != attr_name: continue orig_value = getattr(self, attr_name) is_require...
[ "def", "substitute_environ", "(", "self", ")", ":", "for", "attr_name", "in", "dir", "(", "self", ")", ":", "if", "attr_name", ".", "startswith", "(", "'_'", ")", "or", "attr_name", ".", "upper", "(", ")", "!=", "attr_name", ":", "continue", "orig_value"...
Substitute environment variables into settings.
[ "Substitute", "environment", "variables", "into", "settings", "." ]
train
https://github.com/aio-libs/aiohttp-devtools/blob/e9ea6feb43558e6e64595ea0ea5613f226cba81f/aiohttp_devtools/start/template/app/settings.py#L48-L76
aio-libs/aiohttp-devtools
aiohttp_devtools/start/template/app/management.py
prepare_database
def prepare_database(delete_existing: bool) -> bool: """ (Re)create a fresh database and run migrations. :param delete_existing: whether or not to drop an existing database if it exists :return: whether or not a database has been (re)created """ settings = Settings() conn = psycopg2.connec...
python
def prepare_database(delete_existing: bool) -> bool: """ (Re)create a fresh database and run migrations. :param delete_existing: whether or not to drop an existing database if it exists :return: whether or not a database has been (re)created """ settings = Settings() conn = psycopg2.connec...
[ "def", "prepare_database", "(", "delete_existing", ":", "bool", ")", "->", "bool", ":", "settings", "=", "Settings", "(", ")", "conn", "=", "psycopg2", ".", "connect", "(", "password", "=", "settings", ".", "DB_PASSWORD", ",", "host", "=", "settings", ".",...
(Re)create a fresh database and run migrations. :param delete_existing: whether or not to drop an existing database if it exists :return: whether or not a database has been (re)created
[ "(", "Re", ")", "create", "a", "fresh", "database", "and", "run", "migrations", "." ]
train
https://github.com/aio-libs/aiohttp-devtools/blob/e9ea6feb43558e6e64595ea0ea5613f226cba81f/aiohttp_devtools/start/template/app/management.py#L11-L54
aio-libs/aiohttp-devtools
aiohttp_devtools/start/template/app/views.py
index
async def index(request): """ This is the view handler for the "/" url. **Note: returning html without a template engine like jinja2 is ugly, no way around that.** :param request: the request object see http://aiohttp.readthedocs.io/en/stable/web_reference.html#request :return: aiohttp.web.Respons...
python
async def index(request): """ This is the view handler for the "/" url. **Note: returning html without a template engine like jinja2 is ugly, no way around that.** :param request: the request object see http://aiohttp.readthedocs.io/en/stable/web_reference.html#request :return: aiohttp.web.Respons...
[ "async", "def", "index", "(", "request", ")", ":", "# {% if database.is_none and example.is_message_board %}", "# app.router allows us to generate urls based on their names,", "# see http://aiohttp.readthedocs.io/en/stable/web.html#reverse-url-constructing-using-named-resources", "message_url", ...
This is the view handler for the "/" url. **Note: returning html without a template engine like jinja2 is ugly, no way around that.** :param request: the request object see http://aiohttp.readthedocs.io/en/stable/web_reference.html#request :return: aiohttp.web.Response object
[ "This", "is", "the", "view", "handler", "for", "the", "/", "url", "." ]
train
https://github.com/aio-libs/aiohttp-devtools/blob/e9ea6feb43558e6e64595ea0ea5613f226cba81f/aiohttp_devtools/start/template/app/views.py#L60-L91
aio-libs/aiohttp-devtools
aiohttp_devtools/start/template/app/views.py
message_data
async def message_data(request): """ As an example of aiohttp providing a non-html response, we load the actual messages for the "messages" view above via ajax using this endpoint to get data. see static/message_display.js for details of rendering. """ messages = [] # {% if database.is_none %} ...
python
async def message_data(request): """ As an example of aiohttp providing a non-html response, we load the actual messages for the "messages" view above via ajax using this endpoint to get data. see static/message_display.js for details of rendering. """ messages = [] # {% if database.is_none %} ...
[ "async", "def", "message_data", "(", "request", ")", ":", "messages", "=", "[", "]", "# {% if database.is_none %}", "if", "request", ".", "app", "[", "'settings'", "]", ".", "MESSAGE_FILE", ".", "exists", "(", ")", ":", "# read the message file, process it and pop...
As an example of aiohttp providing a non-html response, we load the actual messages for the "messages" view above via ajax using this endpoint to get data. see static/message_display.js for details of rendering.
[ "As", "an", "example", "of", "aiohttp", "providing", "a", "non", "-", "html", "response", "we", "load", "the", "actual", "messages", "for", "the", "messages", "view", "above", "via", "ajax", "using", "this", "endpoint", "to", "get", "data", ".", "see", "...
train
https://github.com/aio-libs/aiohttp-devtools/blob/e9ea6feb43558e6e64595ea0ea5613f226cba81f/aiohttp_devtools/start/template/app/views.py#L193-L220
aio-libs/aiohttp-devtools
aiohttp_devtools/start/template/app/main.py
pg_dsn
def pg_dsn(settings: Settings) -> str: """ :param settings: settings including connection settings :return: DSN url suitable for sqlalchemy and aiopg. """ return str(URL( database=settings.DB_NAME, password=settings.DB_PASSWORD, host=settings.DB_HOST, port=settings.DB...
python
def pg_dsn(settings: Settings) -> str: """ :param settings: settings including connection settings :return: DSN url suitable for sqlalchemy and aiopg. """ return str(URL( database=settings.DB_NAME, password=settings.DB_PASSWORD, host=settings.DB_HOST, port=settings.DB...
[ "def", "pg_dsn", "(", "settings", ":", "Settings", ")", "->", "str", ":", "return", "str", "(", "URL", "(", "database", "=", "settings", ".", "DB_NAME", ",", "password", "=", "settings", ".", "DB_PASSWORD", ",", "host", "=", "settings", ".", "DB_HOST", ...
:param settings: settings including connection settings :return: DSN url suitable for sqlalchemy and aiopg.
[ ":", "param", "settings", ":", "settings", "including", "connection", "settings", ":", "return", ":", "DSN", "url", "suitable", "for", "sqlalchemy", "and", "aiopg", "." ]
train
https://github.com/aio-libs/aiohttp-devtools/blob/e9ea6feb43558e6e64595ea0ea5613f226cba81f/aiohttp_devtools/start/template/app/main.py#L32-L44
aio-libs/aiohttp-devtools
aiohttp_devtools/cli.py
serve
def serve(path, livereload, port, verbose): """ Serve static files from a directory. """ setup_logging(verbose) run_app(*serve_static(static_path=path, livereload=livereload, port=port))
python
def serve(path, livereload, port, verbose): """ Serve static files from a directory. """ setup_logging(verbose) run_app(*serve_static(static_path=path, livereload=livereload, port=port))
[ "def", "serve", "(", "path", ",", "livereload", ",", "port", ",", "verbose", ")", ":", "setup_logging", "(", "verbose", ")", "run_app", "(", "*", "serve_static", "(", "static_path", "=", "path", ",", "livereload", "=", "livereload", ",", "port", "=", "po...
Serve static files from a directory.
[ "Serve", "static", "files", "from", "a", "directory", "." ]
train
https://github.com/aio-libs/aiohttp-devtools/blob/e9ea6feb43558e6e64595ea0ea5613f226cba81f/aiohttp_devtools/cli.py#L38-L43
aio-libs/aiohttp-devtools
aiohttp_devtools/cli.py
runserver
def runserver(**config): """ Run a development server for an aiohttp apps. Takes one argument "app-path" which should be a path to either a directory containing a recognized default file ("app.py" or "main.py") or to a specific file. Defaults to the environment variable "AIO_APP_PATH" or ".". The ...
python
def runserver(**config): """ Run a development server for an aiohttp apps. Takes one argument "app-path" which should be a path to either a directory containing a recognized default file ("app.py" or "main.py") or to a specific file. Defaults to the environment variable "AIO_APP_PATH" or ".". The ...
[ "def", "runserver", "(", "*", "*", "config", ")", ":", "active_config", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "config", ".", "items", "(", ")", "if", "v", "is", "not", "None", "}", "setup_logging", "(", "config", "[", "'verbose'", ...
Run a development server for an aiohttp apps. Takes one argument "app-path" which should be a path to either a directory containing a recognized default file ("app.py" or "main.py") or to a specific file. Defaults to the environment variable "AIO_APP_PATH" or ".". The app path is run directly, see the "--...
[ "Run", "a", "development", "server", "for", "an", "aiohttp", "apps", "." ]
train
https://github.com/aio-libs/aiohttp-devtools/blob/e9ea6feb43558e6e64595ea0ea5613f226cba81f/aiohttp_devtools/cli.py#L73-L92
aio-libs/aiohttp-devtools
aiohttp_devtools/cli.py
start
def start(*, path, name, verbose, **kwargs): """ Create a new aiohttp app. """ setup_logging(verbose) try: check_dir_clean(Path(path)) if name is None: name = Path(path).name for kwarg_name, choice_enum in DECISIONS: docs = dedent(choice_enum.__doc__)...
python
def start(*, path, name, verbose, **kwargs): """ Create a new aiohttp app. """ setup_logging(verbose) try: check_dir_clean(Path(path)) if name is None: name = Path(path).name for kwarg_name, choice_enum in DECISIONS: docs = dedent(choice_enum.__doc__)...
[ "def", "start", "(", "*", ",", "path", ",", "name", ",", "verbose", ",", "*", "*", "kwargs", ")", ":", "setup_logging", "(", "verbose", ")", "try", ":", "check_dir_clean", "(", "Path", "(", "path", ")", ")", "if", "name", "is", "None", ":", "name",...
Create a new aiohttp app.
[ "Create", "a", "new", "aiohttp", "app", "." ]
train
https://github.com/aio-libs/aiohttp-devtools/blob/e9ea6feb43558e6e64595ea0ea5613f226cba81f/aiohttp_devtools/cli.py#L125-L154
aio-libs/aiohttp-devtools
aiohttp_devtools/runserver/config.py
Config.import_app_factory
def import_app_factory(self): """ Import attribute/class from from a python module. Raise AdevConfigError if the import failed. :return: (attribute, Path object for directory of file) """ rel_py_file = self.py_file.relative_to(self.python_path) module_path = '.'.join(rel...
python
def import_app_factory(self): """ Import attribute/class from from a python module. Raise AdevConfigError if the import failed. :return: (attribute, Path object for directory of file) """ rel_py_file = self.py_file.relative_to(self.python_path) module_path = '.'.join(rel...
[ "def", "import_app_factory", "(", "self", ")", ":", "rel_py_file", "=", "self", ".", "py_file", ".", "relative_to", "(", "self", ".", "python_path", ")", "module_path", "=", "'.'", ".", "join", "(", "rel_py_file", ".", "with_suffix", "(", "''", ")", ".", ...
Import attribute/class from from a python module. Raise AdevConfigError if the import failed. :return: (attribute, Path object for directory of file)
[ "Import", "attribute", "/", "class", "from", "from", "a", "python", "module", ".", "Raise", "AdevConfigError", "if", "the", "import", "failed", "." ]
train
https://github.com/aio-libs/aiohttp-devtools/blob/e9ea6feb43558e6e64595ea0ea5613f226cba81f/aiohttp_devtools/runserver/config.py#L123-L158
aio-libs/aiohttp-devtools
aiohttp_devtools/runserver/main.py
runserver
def runserver(**config_kwargs): """ Prepare app ready to run development server. :param config_kwargs: see config.Config for more details :return: tuple (auxiliary app, auxiliary app port, event loop) """ # force a full reload in sub processes so they load an updated version of code, this must ...
python
def runserver(**config_kwargs): """ Prepare app ready to run development server. :param config_kwargs: see config.Config for more details :return: tuple (auxiliary app, auxiliary app port, event loop) """ # force a full reload in sub processes so they load an updated version of code, this must ...
[ "def", "runserver", "(", "*", "*", "config_kwargs", ")", ":", "# force a full reload in sub processes so they load an updated version of code, this must be called only once", "set_start_method", "(", "'spawn'", ")", "config", "=", "Config", "(", "*", "*", "config_kwargs", ")"...
Prepare app ready to run development server. :param config_kwargs: see config.Config for more details :return: tuple (auxiliary app, auxiliary app port, event loop)
[ "Prepare", "app", "ready", "to", "run", "development", "server", "." ]
train
https://github.com/aio-libs/aiohttp-devtools/blob/e9ea6feb43558e6e64595ea0ea5613f226cba81f/aiohttp_devtools/runserver/main.py#L34-L73
aio-libs/aiohttp-devtools
aiohttp_devtools/logs.py
log_config
def log_config(verbose: bool) -> dict: """ Setup default config. for dictConfig. :param verbose: level: DEBUG if True, INFO if False :return: dict suitable for ``logging.config.dictConfig`` """ log_level = 'DEBUG' if verbose else 'INFO' return { 'version': 1, 'disable_existin...
python
def log_config(verbose: bool) -> dict: """ Setup default config. for dictConfig. :param verbose: level: DEBUG if True, INFO if False :return: dict suitable for ``logging.config.dictConfig`` """ log_level = 'DEBUG' if verbose else 'INFO' return { 'version': 1, 'disable_existin...
[ "def", "log_config", "(", "verbose", ":", "bool", ")", "->", "dict", ":", "log_level", "=", "'DEBUG'", "if", "verbose", "else", "'INFO'", "return", "{", "'version'", ":", "1", ",", "'disable_existing_loggers'", ":", "False", ",", "'formatters'", ":", "{", ...
Setup default config. for dictConfig. :param verbose: level: DEBUG if True, INFO if False :return: dict suitable for ``logging.config.dictConfig``
[ "Setup", "default", "config", ".", "for", "dictConfig", ".", ":", "param", "verbose", ":", "level", ":", "DEBUG", "if", "True", "INFO", "if", "False", ":", "return", ":", "dict", "suitable", "for", "logging", ".", "config", ".", "dictConfig" ]
train
https://github.com/aio-libs/aiohttp-devtools/blob/e9ea6feb43558e6e64595ea0ea5613f226cba81f/aiohttp_devtools/logs.py#L93-L166
loads/molotov
molotov/api.py
scenario
def scenario(weight=1, delay=0.0, name=None): """Decorator to register a function as a Molotov test. Options: - **weight** used by Molotov when the scenarii are randomly picked. The functions with the highest values are more likely to be picked. Integer, defaults to 1. This value is ignored wh...
python
def scenario(weight=1, delay=0.0, name=None): """Decorator to register a function as a Molotov test. Options: - **weight** used by Molotov when the scenarii are randomly picked. The functions with the highest values are more likely to be picked. Integer, defaults to 1. This value is ignored wh...
[ "def", "scenario", "(", "weight", "=", "1", ",", "delay", "=", "0.0", ",", "name", "=", "None", ")", ":", "def", "_scenario", "(", "func", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "_check_coroutine", "(", "func", ")", "if", "weight", ">",...
Decorator to register a function as a Molotov test. Options: - **weight** used by Molotov when the scenarii are randomly picked. The functions with the highest values are more likely to be picked. Integer, defaults to 1. This value is ignored when the *scenario_picker* decorator is used. ...
[ "Decorator", "to", "register", "a", "function", "as", "a", "Molotov", "test", "." ]
train
https://github.com/loads/molotov/blob/bd2c94e7f250e1fbb21940f02c68b4437655bc11/molotov/api.py#L24-L56