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 |
|---|---|---|---|---|---|---|---|---|---|---|
BlendedSiteGenerator/Blended | blended/functions.py | getunzipped | def getunzipped(username, repo, thedir):
"""Downloads and unzips a zip file"""
theurl = "https://github.com/" + username + "/" + repo + "/archive/master.zip"
name = os.path.join(thedir, 'temp.zip')
try:
name = urllib.urlretrieve(theurl, name)
name = os.path.join(thedir, 'temp.zip')
except IOError as e:
print("Can't retrieve %r to %r: %s" % (theurl, thedir, e))
return
try:
z = zipfile.ZipFile(name)
except zipfile.error as e:
print("Bad zipfile (from %r): %s" % (theurl, e))
return
z.extractall(thedir)
z.close()
os.remove(name)
copy_tree(os.path.join(thedir, repo + "-master"), thedir)
shutil.rmtree(os.path.join(thedir, repo + "-master")) | python | def getunzipped(username, repo, thedir):
"""Downloads and unzips a zip file"""
theurl = "https://github.com/" + username + "/" + repo + "/archive/master.zip"
name = os.path.join(thedir, 'temp.zip')
try:
name = urllib.urlretrieve(theurl, name)
name = os.path.join(thedir, 'temp.zip')
except IOError as e:
print("Can't retrieve %r to %r: %s" % (theurl, thedir, e))
return
try:
z = zipfile.ZipFile(name)
except zipfile.error as e:
print("Bad zipfile (from %r): %s" % (theurl, e))
return
z.extractall(thedir)
z.close()
os.remove(name)
copy_tree(os.path.join(thedir, repo + "-master"), thedir)
shutil.rmtree(os.path.join(thedir, repo + "-master")) | [
"def",
"getunzipped",
"(",
"username",
",",
"repo",
",",
"thedir",
")",
":",
"theurl",
"=",
"\"https://github.com/\"",
"+",
"username",
"+",
"\"/\"",
"+",
"repo",
"+",
"\"/archive/master.zip\"",
"name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"thedir",
"... | Downloads and unzips a zip file | [
"Downloads",
"and",
"unzips",
"a",
"zip",
"file"
] | train | https://github.com/BlendedSiteGenerator/Blended/blob/e5865a8633e461a22c86ef6ee98cdd7051c412ac/blended/functions.py#L72-L92 |
BlendedSiteGenerator/Blended | blended/functions.py | checkConfig | def checkConfig():
"""If the config.py file exists, back it up"""
config_file_dir = os.path.join(cwd, "config.py")
if os.path.exists(config_file_dir):
print("Making a backup of your config file!")
config_file_dir2 = os.path.join(cwd, "config.py.oldbak")
copyfile(config_file_dir, config_file_dir2) | python | def checkConfig():
"""If the config.py file exists, back it up"""
config_file_dir = os.path.join(cwd, "config.py")
if os.path.exists(config_file_dir):
print("Making a backup of your config file!")
config_file_dir2 = os.path.join(cwd, "config.py.oldbak")
copyfile(config_file_dir, config_file_dir2) | [
"def",
"checkConfig",
"(",
")",
":",
"config_file_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cwd",
",",
"\"config.py\"",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"config_file_dir",
")",
":",
"print",
"(",
"\"Making a backup of your config file... | If the config.py file exists, back it up | [
"If",
"the",
"config",
".",
"py",
"file",
"exists",
"back",
"it",
"up"
] | train | https://github.com/BlendedSiteGenerator/Blended/blob/e5865a8633e461a22c86ef6ee98cdd7051c412ac/blended/functions.py#L95-L101 |
BlendedSiteGenerator/Blended | blended/functions.py | createConfig | def createConfig(app_version=5.0, wname="", wdesc="", wdescl="", wlic="", wlan="", wurl="", aname="", abio=""):
"""Generates a config file from the information"""
config_file_dir = os.path.join(cwd, "config.py")
config_file = open(config_file_dir, "w")
config_file.write('blended_version = ' + app_version + '\n')
config_file.write('\n')
config_file.write(
'# Configuration is automatically generated by Blended (http://jmroper.com/blended), feel free to edit any values below')
config_file.write('\n')
config_file.write('website_name = "' + wname + '"\n')
config_file.write('website_description = "' + wdesc + '"\n')
config_file.write(
'website_description_long = "' + wdescl + '"\n')
config_file.write('website_license = "' + wlic + '"\n')
config_file.write('website_language = "' + wlan + '"\n')
config_file.write('website_url = "' + wurl + '"\n')
config_file.write('\n')
config_file.write('author_name = "' + aname + '"\n')
config_file.write('author_bio = "' + abio + '"\n')
config_file.write('\n')
config_file.write('home_page_list = True\n')
config_file.write('\n')
config_file.write('plugins = [] # Place all needed plugins in here\n')
config_file.write(
'custom_variables = {} # Place all custom variables in here\n')
config_file.write('\n')
config_file.write('minify_css = False\n')
config_file.write('minify_js = False\n')
config_file.write('\n')
config_file.write('# The following values are used for FTP uploads')
config_file.write('\n')
config_file.write('ftp_server = "localhost"\n')
config_file.write('ftp_username = "user"\n')
config_file.write('ftp_password = "pass"\n')
config_file.write('ftp_port = 21\n')
config_file.write('ftp_upload_path = "public_html/myWebsite"\n')
config_file.close() | python | def createConfig(app_version=5.0, wname="", wdesc="", wdescl="", wlic="", wlan="", wurl="", aname="", abio=""):
"""Generates a config file from the information"""
config_file_dir = os.path.join(cwd, "config.py")
config_file = open(config_file_dir, "w")
config_file.write('blended_version = ' + app_version + '\n')
config_file.write('\n')
config_file.write(
'# Configuration is automatically generated by Blended (http://jmroper.com/blended), feel free to edit any values below')
config_file.write('\n')
config_file.write('website_name = "' + wname + '"\n')
config_file.write('website_description = "' + wdesc + '"\n')
config_file.write(
'website_description_long = "' + wdescl + '"\n')
config_file.write('website_license = "' + wlic + '"\n')
config_file.write('website_language = "' + wlan + '"\n')
config_file.write('website_url = "' + wurl + '"\n')
config_file.write('\n')
config_file.write('author_name = "' + aname + '"\n')
config_file.write('author_bio = "' + abio + '"\n')
config_file.write('\n')
config_file.write('home_page_list = True\n')
config_file.write('\n')
config_file.write('plugins = [] # Place all needed plugins in here\n')
config_file.write(
'custom_variables = {} # Place all custom variables in here\n')
config_file.write('\n')
config_file.write('minify_css = False\n')
config_file.write('minify_js = False\n')
config_file.write('\n')
config_file.write('# The following values are used for FTP uploads')
config_file.write('\n')
config_file.write('ftp_server = "localhost"\n')
config_file.write('ftp_username = "user"\n')
config_file.write('ftp_password = "pass"\n')
config_file.write('ftp_port = 21\n')
config_file.write('ftp_upload_path = "public_html/myWebsite"\n')
config_file.close() | [
"def",
"createConfig",
"(",
"app_version",
"=",
"5.0",
",",
"wname",
"=",
"\"\"",
",",
"wdesc",
"=",
"\"\"",
",",
"wdescl",
"=",
"\"\"",
",",
"wlic",
"=",
"\"\"",
",",
"wlan",
"=",
"\"\"",
",",
"wurl",
"=",
"\"\"",
",",
"aname",
"=",
"\"\"",
",",
... | Generates a config file from the information | [
"Generates",
"a",
"config",
"file",
"from",
"the",
"information"
] | train | https://github.com/BlendedSiteGenerator/Blended/blob/e5865a8633e461a22c86ef6ee98cdd7051c412ac/blended/functions.py#L104-L141 |
BlendedSiteGenerator/Blended | blended/functions.py | createBlendedFolders | def createBlendedFolders():
"""Creates the standard folders for a Blended website"""
# Create the templates folder
create_folder(os.path.join(cwd, "templates"))
# Create the templates/assets folder
create_folder(os.path.join(cwd, "templates", "assets"))
# Create the templates/assets/css folder
create_folder(os.path.join(cwd, "templates", "assets", "css"))
# Create the templates/assets/js folder
create_folder(os.path.join(cwd, "templates", "assets", "js"))
# Create the templates/assets/img folder
create_folder(os.path.join(cwd, "templates", "assets", "img"))
# Create the content folder
create_folder(os.path.join(cwd, "content")) | python | def createBlendedFolders():
"""Creates the standard folders for a Blended website"""
# Create the templates folder
create_folder(os.path.join(cwd, "templates"))
# Create the templates/assets folder
create_folder(os.path.join(cwd, "templates", "assets"))
# Create the templates/assets/css folder
create_folder(os.path.join(cwd, "templates", "assets", "css"))
# Create the templates/assets/js folder
create_folder(os.path.join(cwd, "templates", "assets", "js"))
# Create the templates/assets/img folder
create_folder(os.path.join(cwd, "templates", "assets", "img"))
# Create the content folder
create_folder(os.path.join(cwd, "content")) | [
"def",
"createBlendedFolders",
"(",
")",
":",
"# Create the templates folder",
"create_folder",
"(",
"os",
".",
"path",
".",
"join",
"(",
"cwd",
",",
"\"templates\"",
")",
")",
"# Create the templates/assets folder",
"create_folder",
"(",
"os",
".",
"path",
".",
"... | Creates the standard folders for a Blended website | [
"Creates",
"the",
"standard",
"folders",
"for",
"a",
"Blended",
"website"
] | train | https://github.com/BlendedSiteGenerator/Blended/blob/e5865a8633e461a22c86ef6ee98cdd7051c412ac/blended/functions.py#L144-L162 |
tkf/rash | rash/record.py | get_environ | def get_environ(keys):
"""
Get environment variables from :data:`os.environ`.
:type keys: [str]
:rtype: dict
Some additional features.
* If 'HOST' is not in :data:`os.environ`, this function
automatically fetch it using :meth:`platform.node`.
* If 'TTY' is not in :data:`os.environ`, this function
automatically fetch it using :meth:`os.ttyname`.
* Set 'RASH_SPENV_TERMINAL' if needed.
"""
items = ((k, os.environ.get(k)) for k in keys)
subenv = dict((k, v) for (k, v) in items if v is not None)
needset = lambda k: k in keys and not subenv.get(k)
def setifnonempty(key, value):
if value:
subenv[key] = value
if needset('HOST'):
import platform
subenv['HOST'] = platform.node()
if needset('TTY'):
setifnonempty('TTY', get_tty())
if needset('RASH_SPENV_TERMINAL'):
from .utils.termdetection import detect_terminal
setifnonempty('RASH_SPENV_TERMINAL', detect_terminal())
return subenv | python | def get_environ(keys):
"""
Get environment variables from :data:`os.environ`.
:type keys: [str]
:rtype: dict
Some additional features.
* If 'HOST' is not in :data:`os.environ`, this function
automatically fetch it using :meth:`platform.node`.
* If 'TTY' is not in :data:`os.environ`, this function
automatically fetch it using :meth:`os.ttyname`.
* Set 'RASH_SPENV_TERMINAL' if needed.
"""
items = ((k, os.environ.get(k)) for k in keys)
subenv = dict((k, v) for (k, v) in items if v is not None)
needset = lambda k: k in keys and not subenv.get(k)
def setifnonempty(key, value):
if value:
subenv[key] = value
if needset('HOST'):
import platform
subenv['HOST'] = platform.node()
if needset('TTY'):
setifnonempty('TTY', get_tty())
if needset('RASH_SPENV_TERMINAL'):
from .utils.termdetection import detect_terminal
setifnonempty('RASH_SPENV_TERMINAL', detect_terminal())
return subenv | [
"def",
"get_environ",
"(",
"keys",
")",
":",
"items",
"=",
"(",
"(",
"k",
",",
"os",
".",
"environ",
".",
"get",
"(",
"k",
")",
")",
"for",
"k",
"in",
"keys",
")",
"subenv",
"=",
"dict",
"(",
"(",
"k",
",",
"v",
")",
"for",
"(",
"k",
",",
... | Get environment variables from :data:`os.environ`.
:type keys: [str]
:rtype: dict
Some additional features.
* If 'HOST' is not in :data:`os.environ`, this function
automatically fetch it using :meth:`platform.node`.
* If 'TTY' is not in :data:`os.environ`, this function
automatically fetch it using :meth:`os.ttyname`.
* Set 'RASH_SPENV_TERMINAL' if needed. | [
"Get",
"environment",
"variables",
"from",
":",
"data",
":",
"os",
".",
"environ",
"."
] | train | https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/record.py#L51-L83 |
tkf/rash | rash/record.py | generate_session_id | def generate_session_id(data):
"""
Generate session ID based on HOST, TTY, PID [#]_ and start time.
:type data: dict
:rtype: str
.. [#] PID of the shell, i.e., PPID of this Python process.
"""
host = data['environ']['HOST']
tty = data['environ'].get('TTY') or 'NO_TTY'
return ':'.join(map(str, [
host, tty, os.getppid(), data['start']])) | python | def generate_session_id(data):
"""
Generate session ID based on HOST, TTY, PID [#]_ and start time.
:type data: dict
:rtype: str
.. [#] PID of the shell, i.e., PPID of this Python process.
"""
host = data['environ']['HOST']
tty = data['environ'].get('TTY') or 'NO_TTY'
return ':'.join(map(str, [
host, tty, os.getppid(), data['start']])) | [
"def",
"generate_session_id",
"(",
"data",
")",
":",
"host",
"=",
"data",
"[",
"'environ'",
"]",
"[",
"'HOST'",
"]",
"tty",
"=",
"data",
"[",
"'environ'",
"]",
".",
"get",
"(",
"'TTY'",
")",
"or",
"'NO_TTY'",
"return",
"':'",
".",
"join",
"(",
"map",... | Generate session ID based on HOST, TTY, PID [#]_ and start time.
:type data: dict
:rtype: str
.. [#] PID of the shell, i.e., PPID of this Python process. | [
"Generate",
"session",
"ID",
"based",
"on",
"HOST",
"TTY",
"PID",
"[",
"#",
"]",
"_",
"and",
"start",
"time",
"."
] | train | https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/record.py#L86-L99 |
tkf/rash | rash/record.py | record_run | def record_run(record_type, print_session_id, **kwds):
"""
Record shell history.
"""
if print_session_id and record_type != 'init':
raise RuntimeError(
'--print-session-id should be used with --record-type=init')
cfstore = ConfigStore()
# SOMEDAY: Pass a list of environment variables to shell by "rash
# init" and don't read configuration in "rash record" command. It
# is faster.
config = cfstore.get_config()
envkeys = config.record.environ[record_type]
json_path = os.path.join(cfstore.record_path,
record_type,
time.strftime('%Y-%m-%d-%H%M%S.json'))
mkdirp(os.path.dirname(json_path))
# Command line options directly map to record keys
data = dict((k, v) for (k, v) in kwds.items() if v is not None)
data.update(
environ=get_environ(envkeys),
)
# Automatically set some missing variables:
data.setdefault('cwd', getcwd())
if record_type in ['command', 'exit']:
data.setdefault('stop', int(time.time()))
elif record_type in ['init']:
data.setdefault('start', int(time.time()))
if print_session_id:
data['session_id'] = generate_session_id(data)
print(data['session_id'])
with open(json_path, 'w') as fp:
json.dump(data, fp) | python | def record_run(record_type, print_session_id, **kwds):
"""
Record shell history.
"""
if print_session_id and record_type != 'init':
raise RuntimeError(
'--print-session-id should be used with --record-type=init')
cfstore = ConfigStore()
# SOMEDAY: Pass a list of environment variables to shell by "rash
# init" and don't read configuration in "rash record" command. It
# is faster.
config = cfstore.get_config()
envkeys = config.record.environ[record_type]
json_path = os.path.join(cfstore.record_path,
record_type,
time.strftime('%Y-%m-%d-%H%M%S.json'))
mkdirp(os.path.dirname(json_path))
# Command line options directly map to record keys
data = dict((k, v) for (k, v) in kwds.items() if v is not None)
data.update(
environ=get_environ(envkeys),
)
# Automatically set some missing variables:
data.setdefault('cwd', getcwd())
if record_type in ['command', 'exit']:
data.setdefault('stop', int(time.time()))
elif record_type in ['init']:
data.setdefault('start', int(time.time()))
if print_session_id:
data['session_id'] = generate_session_id(data)
print(data['session_id'])
with open(json_path, 'w') as fp:
json.dump(data, fp) | [
"def",
"record_run",
"(",
"record_type",
",",
"print_session_id",
",",
"*",
"*",
"kwds",
")",
":",
"if",
"print_session_id",
"and",
"record_type",
"!=",
"'init'",
":",
"raise",
"RuntimeError",
"(",
"'--print-session-id should be used with --record-type=init'",
")",
"c... | Record shell history. | [
"Record",
"shell",
"history",
"."
] | train | https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/record.py#L102-L139 |
staticdev/django-sorting-bootstrap | sorting_bootstrap/compat.py | format_html | def format_html(format_string, *args, **kwargs):
"""
Similar to str.format, but passes all arguments through conditional_escape,
and calls 'mark_safe' on the result. This function should be used instead
of str.format or % interpolation to build up small HTML fragments.
"""
args_safe = map(conditional_escape, args)
kwargs_safe = dict([(k, conditional_escape(v)) for (k, v) in
six.iteritems(kwargs)])
return mark_safe(format_string.format(*args_safe, **kwargs_safe)) | python | def format_html(format_string, *args, **kwargs):
"""
Similar to str.format, but passes all arguments through conditional_escape,
and calls 'mark_safe' on the result. This function should be used instead
of str.format or % interpolation to build up small HTML fragments.
"""
args_safe = map(conditional_escape, args)
kwargs_safe = dict([(k, conditional_escape(v)) for (k, v) in
six.iteritems(kwargs)])
return mark_safe(format_string.format(*args_safe, **kwargs_safe)) | [
"def",
"format_html",
"(",
"format_string",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args_safe",
"=",
"map",
"(",
"conditional_escape",
",",
"args",
")",
"kwargs_safe",
"=",
"dict",
"(",
"[",
"(",
"k",
",",
"conditional_escape",
"(",
"v",
... | Similar to str.format, but passes all arguments through conditional_escape,
and calls 'mark_safe' on the result. This function should be used instead
of str.format or % interpolation to build up small HTML fragments. | [
"Similar",
"to",
"str",
".",
"format",
"but",
"passes",
"all",
"arguments",
"through",
"conditional_escape",
"and",
"calls",
"mark_safe",
"on",
"the",
"result",
".",
"This",
"function",
"should",
"be",
"used",
"instead",
"of",
"str",
".",
"format",
"or",
"%"... | train | https://github.com/staticdev/django-sorting-bootstrap/blob/cfdc6e671b1b57aad04e44b041b9df10ee8288d3/sorting_bootstrap/compat.py#L15-L24 |
tkf/rash | rash/database.py | normalize_directory | def normalize_directory(path):
"""
Append "/" to `path` if needed.
"""
if path is None:
return None
if path.endswith(os.path.sep):
return path
else:
return path + os.path.sep | python | def normalize_directory(path):
"""
Append "/" to `path` if needed.
"""
if path is None:
return None
if path.endswith(os.path.sep):
return path
else:
return path + os.path.sep | [
"def",
"normalize_directory",
"(",
"path",
")",
":",
"if",
"path",
"is",
"None",
":",
"return",
"None",
"if",
"path",
".",
"endswith",
"(",
"os",
".",
"path",
".",
"sep",
")",
":",
"return",
"path",
"else",
":",
"return",
"path",
"+",
"os",
".",
"p... | Append "/" to `path` if needed. | [
"Append",
"/",
"to",
"path",
"if",
"needed",
"."
] | train | https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/database.py#L52-L61 |
tkf/rash | rash/database.py | sql_program_name_func | def sql_program_name_func(command):
"""
Extract program name from `command`.
>>> sql_program_name_func('ls')
'ls'
>>> sql_program_name_func('git status')
'git'
>>> sql_program_name_func('EMACS=emacs make')
'make'
:type command: str
"""
args = command.split(' ')
for prog in args:
if '=' not in prog:
return prog
return args[0] | python | def sql_program_name_func(command):
"""
Extract program name from `command`.
>>> sql_program_name_func('ls')
'ls'
>>> sql_program_name_func('git status')
'git'
>>> sql_program_name_func('EMACS=emacs make')
'make'
:type command: str
"""
args = command.split(' ')
for prog in args:
if '=' not in prog:
return prog
return args[0] | [
"def",
"sql_program_name_func",
"(",
"command",
")",
":",
"args",
"=",
"command",
".",
"split",
"(",
"' '",
")",
"for",
"prog",
"in",
"args",
":",
"if",
"'='",
"not",
"in",
"prog",
":",
"return",
"prog",
"return",
"args",
"[",
"0",
"]"
] | Extract program name from `command`.
>>> sql_program_name_func('ls')
'ls'
>>> sql_program_name_func('git status')
'git'
>>> sql_program_name_func('EMACS=emacs make')
'make'
:type command: str | [
"Extract",
"program",
"name",
"from",
"command",
"."
] | train | https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/database.py#L68-L86 |
tkf/rash | rash/database.py | sql_pathdist_func | def sql_pathdist_func(path1, path2, sep=os.path.sep):
"""
Return a distance between `path1` and `path2`.
>>> sql_pathdist_func('a/b/', 'a/b/', sep='/')
0
>>> sql_pathdist_func('a/', 'a/b/', sep='/')
1
>>> sql_pathdist_func('a', 'a/', sep='/')
0
"""
seq1 = path1.rstrip(sep).split(sep)
seq2 = path2.rstrip(sep).split(sep)
return sum(1 for (p1, p2) in zip_longest(seq1, seq2) if p1 != p2) | python | def sql_pathdist_func(path1, path2, sep=os.path.sep):
"""
Return a distance between `path1` and `path2`.
>>> sql_pathdist_func('a/b/', 'a/b/', sep='/')
0
>>> sql_pathdist_func('a/', 'a/b/', sep='/')
1
>>> sql_pathdist_func('a', 'a/', sep='/')
0
"""
seq1 = path1.rstrip(sep).split(sep)
seq2 = path2.rstrip(sep).split(sep)
return sum(1 for (p1, p2) in zip_longest(seq1, seq2) if p1 != p2) | [
"def",
"sql_pathdist_func",
"(",
"path1",
",",
"path2",
",",
"sep",
"=",
"os",
".",
"path",
".",
"sep",
")",
":",
"seq1",
"=",
"path1",
".",
"rstrip",
"(",
"sep",
")",
".",
"split",
"(",
"sep",
")",
"seq2",
"=",
"path2",
".",
"rstrip",
"(",
"sep"... | Return a distance between `path1` and `path2`.
>>> sql_pathdist_func('a/b/', 'a/b/', sep='/')
0
>>> sql_pathdist_func('a/', 'a/b/', sep='/')
1
>>> sql_pathdist_func('a', 'a/', sep='/')
0 | [
"Return",
"a",
"distance",
"between",
"path1",
"and",
"path2",
"."
] | train | https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/database.py#L89-L103 |
tkf/rash | rash/database.py | DataBase._init_db | def _init_db(self):
"""Creates the database tables."""
with self._get_db() as db:
with open(self.schemapath) as f:
db.cursor().executescript(f.read())
db.commit() | python | def _init_db(self):
"""Creates the database tables."""
with self._get_db() as db:
with open(self.schemapath) as f:
db.cursor().executescript(f.read())
db.commit() | [
"def",
"_init_db",
"(",
"self",
")",
":",
"with",
"self",
".",
"_get_db",
"(",
")",
"as",
"db",
":",
"with",
"open",
"(",
"self",
".",
"schemapath",
")",
"as",
"f",
":",
"db",
".",
"cursor",
"(",
")",
".",
"executescript",
"(",
"f",
".",
"read",
... | Creates the database tables. | [
"Creates",
"the",
"database",
"tables",
"."
] | train | https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/database.py#L121-L126 |
tkf/rash | rash/database.py | DataBase.connection | def connection(self, commit=False):
"""
Context manager to keep around DB connection.
:rtype: sqlite3.Connection
SOMEDAY: Get rid of this function. Keeping connection around as
an argument to the method using this context manager is
probably better as it is more explicit.
Also, holding "global state" as instance attribute is bad for
supporting threaded search, which is required for more fluent
percol integration.
"""
if commit:
self._need_commit = True
if self._db:
yield self._db
else:
try:
with self._get_db() as db:
self._db = db
db.create_function("REGEXP", 2, sql_regexp_func)
db.create_function("PROGRAM_NAME", 1,
sql_program_name_func)
db.create_function("PATHDIST", 2, sql_pathdist_func)
yield self._db
if self._need_commit:
db.commit()
finally:
self._db = None
self._need_commit = False | python | def connection(self, commit=False):
"""
Context manager to keep around DB connection.
:rtype: sqlite3.Connection
SOMEDAY: Get rid of this function. Keeping connection around as
an argument to the method using this context manager is
probably better as it is more explicit.
Also, holding "global state" as instance attribute is bad for
supporting threaded search, which is required for more fluent
percol integration.
"""
if commit:
self._need_commit = True
if self._db:
yield self._db
else:
try:
with self._get_db() as db:
self._db = db
db.create_function("REGEXP", 2, sql_regexp_func)
db.create_function("PROGRAM_NAME", 1,
sql_program_name_func)
db.create_function("PATHDIST", 2, sql_pathdist_func)
yield self._db
if self._need_commit:
db.commit()
finally:
self._db = None
self._need_commit = False | [
"def",
"connection",
"(",
"self",
",",
"commit",
"=",
"False",
")",
":",
"if",
"commit",
":",
"self",
".",
"_need_commit",
"=",
"True",
"if",
"self",
".",
"_db",
":",
"yield",
"self",
".",
"_db",
"else",
":",
"try",
":",
"with",
"self",
".",
"_get_... | Context manager to keep around DB connection.
:rtype: sqlite3.Connection
SOMEDAY: Get rid of this function. Keeping connection around as
an argument to the method using this context manager is
probably better as it is more explicit.
Also, holding "global state" as instance attribute is bad for
supporting threaded search, which is required for more fluent
percol integration. | [
"Context",
"manager",
"to",
"keep",
"around",
"DB",
"connection",
"."
] | train | https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/database.py#L129-L160 |
tkf/rash | rash/database.py | DataBase.close_connection | def close_connection(self):
"""
Close connection kept by :meth:`connection`.
If commit is needed, :meth:`sqlite3.Connection.commit`
is called first and then :meth:`sqlite3.Connection.interrupt`
is called.
A few methods/generators support :meth:`close_connection`:
- :meth:`search_command_record`
- :meth:`select_by_command_record`
"""
if self._db:
db = self._db
try:
if self._need_commit:
db.commit()
finally:
db.interrupt()
self._db = None
self._need_commit = False | python | def close_connection(self):
"""
Close connection kept by :meth:`connection`.
If commit is needed, :meth:`sqlite3.Connection.commit`
is called first and then :meth:`sqlite3.Connection.interrupt`
is called.
A few methods/generators support :meth:`close_connection`:
- :meth:`search_command_record`
- :meth:`select_by_command_record`
"""
if self._db:
db = self._db
try:
if self._need_commit:
db.commit()
finally:
db.interrupt()
self._db = None
self._need_commit = False | [
"def",
"close_connection",
"(",
"self",
")",
":",
"if",
"self",
".",
"_db",
":",
"db",
"=",
"self",
".",
"_db",
"try",
":",
"if",
"self",
".",
"_need_commit",
":",
"db",
".",
"commit",
"(",
")",
"finally",
":",
"db",
".",
"interrupt",
"(",
")",
"... | Close connection kept by :meth:`connection`.
If commit is needed, :meth:`sqlite3.Connection.commit`
is called first and then :meth:`sqlite3.Connection.interrupt`
is called.
A few methods/generators support :meth:`close_connection`:
- :meth:`search_command_record`
- :meth:`select_by_command_record` | [
"Close",
"connection",
"kept",
"by",
":",
"meth",
":",
"connection",
"."
] | train | https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/database.py#L164-L186 |
tkf/rash | rash/database.py | DataBase._executing | def _executing(self, sql, params=[]):
"""
Execute and yield rows in a way to support :meth:`close_connection`.
"""
with self.connection() as connection:
for row in connection.execute(sql, params):
yield row
if not self._db:
return | python | def _executing(self, sql, params=[]):
"""
Execute and yield rows in a way to support :meth:`close_connection`.
"""
with self.connection() as connection:
for row in connection.execute(sql, params):
yield row
if not self._db:
return | [
"def",
"_executing",
"(",
"self",
",",
"sql",
",",
"params",
"=",
"[",
"]",
")",
":",
"with",
"self",
".",
"connection",
"(",
")",
"as",
"connection",
":",
"for",
"row",
"in",
"connection",
".",
"execute",
"(",
"sql",
",",
"params",
")",
":",
"yiel... | Execute and yield rows in a way to support :meth:`close_connection`. | [
"Execute",
"and",
"yield",
"rows",
"in",
"a",
"way",
"to",
"support",
":",
"meth",
":",
"close_connection",
"."
] | train | https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/database.py#L188-L196 |
tkf/rash | rash/database.py | DataBase.get_version_records | def get_version_records(self):
"""
Yield RASH version information stored in DB. Latest first.
:rtype: [VersionRecord]
"""
keys = ['id', 'rash_version', 'schema_version', 'updated']
sql = """
SELECT id, rash_version, schema_version, updated
FROM rash_info
ORDER BY id DESC
"""
with self.connection() as connection:
for row in connection.execute(sql):
yield VersionRecord(**dict(zip(keys, row))) | python | def get_version_records(self):
"""
Yield RASH version information stored in DB. Latest first.
:rtype: [VersionRecord]
"""
keys = ['id', 'rash_version', 'schema_version', 'updated']
sql = """
SELECT id, rash_version, schema_version, updated
FROM rash_info
ORDER BY id DESC
"""
with self.connection() as connection:
for row in connection.execute(sql):
yield VersionRecord(**dict(zip(keys, row))) | [
"def",
"get_version_records",
"(",
"self",
")",
":",
"keys",
"=",
"[",
"'id'",
",",
"'rash_version'",
",",
"'schema_version'",
",",
"'updated'",
"]",
"sql",
"=",
"\"\"\"\n SELECT id, rash_version, schema_version, updated\n FROM rash_info\n ORDER BY id DESC\... | Yield RASH version information stored in DB. Latest first.
:rtype: [VersionRecord] | [
"Yield",
"RASH",
"version",
"information",
"stored",
"in",
"DB",
".",
"Latest",
"first",
"."
] | train | https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/database.py#L202-L217 |
tkf/rash | rash/database.py | DataBase.update_version_records | def update_version_records(self):
"""
Update rash_info table if necessary.
"""
from .__init__ import __version__ as version
with self.connection(commit=True) as connection:
for vrec in self.get_version_records():
if (vrec.rash_version == version and
vrec.schema_version == schema_version):
return # no need to insert the new one!
connection.execute(
'INSERT INTO rash_info (rash_version, schema_version) '
'VALUES (?, ?)',
[version, schema_version]) | python | def update_version_records(self):
"""
Update rash_info table if necessary.
"""
from .__init__ import __version__ as version
with self.connection(commit=True) as connection:
for vrec in self.get_version_records():
if (vrec.rash_version == version and
vrec.schema_version == schema_version):
return # no need to insert the new one!
connection.execute(
'INSERT INTO rash_info (rash_version, schema_version) '
'VALUES (?, ?)',
[version, schema_version]) | [
"def",
"update_version_records",
"(",
"self",
")",
":",
"from",
".",
"__init__",
"import",
"__version__",
"as",
"version",
"with",
"self",
".",
"connection",
"(",
"commit",
"=",
"True",
")",
"as",
"connection",
":",
"for",
"vrec",
"in",
"self",
".",
"get_v... | Update rash_info table if necessary. | [
"Update",
"rash_info",
"table",
"if",
"necessary",
"."
] | train | https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/database.py#L219-L232 |
tkf/rash | rash/database.py | DataBase.select_by_command_record | def select_by_command_record(self, crec):
"""
Yield records that matches to `crec`.
All attributes of `crec` except for `environ` are concerned.
"""
keys = ['command_history_id', 'command', 'session_history_id',
'cwd', 'terminal',
'start', 'stop', 'exit_code']
sql = """
SELECT
command_history.id, CL.command, session_id,
DL.directory, TL.terminal,
start_time, stop_time, exit_code
FROM command_history
LEFT JOIN command_list AS CL ON command_id = CL.id
LEFT JOIN directory_list AS DL ON directory_id = DL.id
LEFT JOIN terminal_list AS TL ON terminal_id = TL.id
WHERE
(CL.command = ? OR (CL.command IS NULL AND ? IS NULL)) AND
(DL.directory = ? OR (DL.directory IS NULL AND ? IS NULL)) AND
(TL.terminal = ? OR (TL.terminal IS NULL AND ? IS NULL)) AND
(start_time = ? OR (start_time IS NULL AND ? IS NULL)) AND
(stop_time = ? OR (stop_time IS NULL AND ? IS NULL)) AND
(exit_code = ? OR (exit_code IS NULL AND ? IS NULL))
"""
desired_row = [
crec.command, normalize_directory(crec.cwd), crec.terminal,
convert_ts(crec.start), convert_ts(crec.stop), crec.exit_code]
params = list(itertools.chain(*zip(desired_row, desired_row)))
return self._select_rows(CommandRecord, keys, sql, params) | python | def select_by_command_record(self, crec):
"""
Yield records that matches to `crec`.
All attributes of `crec` except for `environ` are concerned.
"""
keys = ['command_history_id', 'command', 'session_history_id',
'cwd', 'terminal',
'start', 'stop', 'exit_code']
sql = """
SELECT
command_history.id, CL.command, session_id,
DL.directory, TL.terminal,
start_time, stop_time, exit_code
FROM command_history
LEFT JOIN command_list AS CL ON command_id = CL.id
LEFT JOIN directory_list AS DL ON directory_id = DL.id
LEFT JOIN terminal_list AS TL ON terminal_id = TL.id
WHERE
(CL.command = ? OR (CL.command IS NULL AND ? IS NULL)) AND
(DL.directory = ? OR (DL.directory IS NULL AND ? IS NULL)) AND
(TL.terminal = ? OR (TL.terminal IS NULL AND ? IS NULL)) AND
(start_time = ? OR (start_time IS NULL AND ? IS NULL)) AND
(stop_time = ? OR (stop_time IS NULL AND ? IS NULL)) AND
(exit_code = ? OR (exit_code IS NULL AND ? IS NULL))
"""
desired_row = [
crec.command, normalize_directory(crec.cwd), crec.terminal,
convert_ts(crec.start), convert_ts(crec.stop), crec.exit_code]
params = list(itertools.chain(*zip(desired_row, desired_row)))
return self._select_rows(CommandRecord, keys, sql, params) | [
"def",
"select_by_command_record",
"(",
"self",
",",
"crec",
")",
":",
"keys",
"=",
"[",
"'command_history_id'",
",",
"'command'",
",",
"'session_history_id'",
",",
"'cwd'",
",",
"'terminal'",
",",
"'start'",
",",
"'stop'",
",",
"'exit_code'",
"]",
"sql",
"=",... | Yield records that matches to `crec`.
All attributes of `crec` except for `environ` are concerned. | [
"Yield",
"records",
"that",
"matches",
"to",
"crec",
"."
] | train | https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/database.py#L346-L377 |
tkf/rash | rash/database.py | DataBase.search_command_record | def search_command_record(
self,
after_context, before_context, context, context_type,
**kwds):
"""
Search command history.
:rtype: [CommandRecord]
"""
if after_context or before_context or context:
kwds['condition_as_column'] = True
limit = kwds['limit']
kwds['limit'] = -1
kwds['unique'] = False
kwds['sort_by'] = {
'session': ['session_start_time', 'start_time'],
'time': ['start_time'],
}[context_type]
if not kwds['reverse']:
# Default (reverse=False) means latest history comes first.
after_context, before_context = before_context, after_context
(sql, params, keys) = self._compile_sql_search_command_record(**kwds)
records = self._select_rows(CommandRecord, keys, sql, params)
# SOMEDAY: optimize context search; do not create CommandRecord
# object for all (including non-matching) records.
predicate = lambda r: r.condition
if context:
records = include_context(predicate, context, records)
elif before_context:
records = include_before(predicate, before_context, records)
elif after_context:
records = include_after(predicate, after_context, records)
if after_context or before_context or context and limit >= 0:
records = itertools.islice(records, limit)
# NOTE: as SQLite does not support row_number function, let's
# do the filtering at Python side when context modifier
# is given. This is *very* inefficient but at least it
# works..
return records | python | def search_command_record(
self,
after_context, before_context, context, context_type,
**kwds):
"""
Search command history.
:rtype: [CommandRecord]
"""
if after_context or before_context or context:
kwds['condition_as_column'] = True
limit = kwds['limit']
kwds['limit'] = -1
kwds['unique'] = False
kwds['sort_by'] = {
'session': ['session_start_time', 'start_time'],
'time': ['start_time'],
}[context_type]
if not kwds['reverse']:
# Default (reverse=False) means latest history comes first.
after_context, before_context = before_context, after_context
(sql, params, keys) = self._compile_sql_search_command_record(**kwds)
records = self._select_rows(CommandRecord, keys, sql, params)
# SOMEDAY: optimize context search; do not create CommandRecord
# object for all (including non-matching) records.
predicate = lambda r: r.condition
if context:
records = include_context(predicate, context, records)
elif before_context:
records = include_before(predicate, before_context, records)
elif after_context:
records = include_after(predicate, after_context, records)
if after_context or before_context or context and limit >= 0:
records = itertools.islice(records, limit)
# NOTE: as SQLite does not support row_number function, let's
# do the filtering at Python side when context modifier
# is given. This is *very* inefficient but at least it
# works..
return records | [
"def",
"search_command_record",
"(",
"self",
",",
"after_context",
",",
"before_context",
",",
"context",
",",
"context_type",
",",
"*",
"*",
"kwds",
")",
":",
"if",
"after_context",
"or",
"before_context",
"or",
"context",
":",
"kwds",
"[",
"'condition_as_colum... | Search command history.
:rtype: [CommandRecord] | [
"Search",
"command",
"history",
"."
] | train | https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/database.py#L379-L421 |
tkf/rash | rash/database.py | DataBase.get_full_command_record | def get_full_command_record(self, command_history_id,
merge_session_environ=True):
"""
Get fully retrieved :class:`CommandRecord` instance by ID.
By "fully", it means that complex slots such as `environ` and
`pipestatus` are available.
:type command_history_id: int
:type merge_session_environ: bool
"""
with self.connection() as db:
crec = self._select_command_record(db, command_history_id)
crec.pipestatus = self._get_pipestatus(db, command_history_id)
# Set environment variables
cenv = self._select_environ(db, 'command', command_history_id)
crec.environ.update(cenv)
if merge_session_environ:
senv = self._select_environ(
db, 'session', crec.session_history_id)
crec.environ.update(senv)
return crec | python | def get_full_command_record(self, command_history_id,
merge_session_environ=True):
"""
Get fully retrieved :class:`CommandRecord` instance by ID.
By "fully", it means that complex slots such as `environ` and
`pipestatus` are available.
:type command_history_id: int
:type merge_session_environ: bool
"""
with self.connection() as db:
crec = self._select_command_record(db, command_history_id)
crec.pipestatus = self._get_pipestatus(db, command_history_id)
# Set environment variables
cenv = self._select_environ(db, 'command', command_history_id)
crec.environ.update(cenv)
if merge_session_environ:
senv = self._select_environ(
db, 'session', crec.session_history_id)
crec.environ.update(senv)
return crec | [
"def",
"get_full_command_record",
"(",
"self",
",",
"command_history_id",
",",
"merge_session_environ",
"=",
"True",
")",
":",
"with",
"self",
".",
"connection",
"(",
")",
"as",
"db",
":",
"crec",
"=",
"self",
".",
"_select_command_record",
"(",
"db",
",",
"... | Get fully retrieved :class:`CommandRecord` instance by ID.
By "fully", it means that complex slots such as `environ` and
`pipestatus` are available.
:type command_history_id: int
:type merge_session_environ: bool | [
"Get",
"fully",
"retrieved",
":",
"class",
":",
"CommandRecord",
"instance",
"by",
"ID",
"."
] | train | https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/database.py#L742-L764 |
mathiasertl/xmpp-backends | xmpp_backends/dummy.py | DummyBackend.start_user_session | def start_user_session(self, username, domain, resource, **kwargs):
"""Method to add a user session for debugging.
Accepted parameters are the same as to the constructor of :py:class:`~xmpp_backends.base.UserSession`.
"""
kwargs.setdefault('uptime', pytz.utc.localize(datetime.utcnow()))
kwargs.setdefault('priority', 0)
kwargs.setdefault('status', 'online')
kwargs.setdefault('status_text', '')
kwargs.setdefault('connection_type', CONNECTION_XMPP)
kwargs.setdefault('encrypted', True)
kwargs.setdefault('compressed', False)
kwargs.setdefault('ip_address', '127.0.0.1')
if six.PY2 and isinstance(kwargs['ip_address'], str):
# ipaddress constructor does not eat str in py2 :-/
kwargs['ip_address'] = kwargs['ip_address'].decode('utf-8')
if isinstance(kwargs['ip_address'], six.string_types):
kwargs['ip_address'] = ipaddress.ip_address(kwargs['ip_address'])
user = '%s@%s' % (username, domain)
session = UserSession(self, username, domain, resource, **kwargs)
data = self.module.get(user)
if data is None:
raise UserNotFound(username, domain, resource)
data.setdefault('sessions', set())
if isinstance(data['sessions'], list):
# Cast old data to set
data['sessions'] = set(data['sessions'])
data['sessions'].add(session)
self.module.set(user, data)
all_sessions = self.module.get('all_sessions', set())
all_sessions.add(session)
self.module.set('all_sessions', all_sessions) | python | def start_user_session(self, username, domain, resource, **kwargs):
"""Method to add a user session for debugging.
Accepted parameters are the same as to the constructor of :py:class:`~xmpp_backends.base.UserSession`.
"""
kwargs.setdefault('uptime', pytz.utc.localize(datetime.utcnow()))
kwargs.setdefault('priority', 0)
kwargs.setdefault('status', 'online')
kwargs.setdefault('status_text', '')
kwargs.setdefault('connection_type', CONNECTION_XMPP)
kwargs.setdefault('encrypted', True)
kwargs.setdefault('compressed', False)
kwargs.setdefault('ip_address', '127.0.0.1')
if six.PY2 and isinstance(kwargs['ip_address'], str):
# ipaddress constructor does not eat str in py2 :-/
kwargs['ip_address'] = kwargs['ip_address'].decode('utf-8')
if isinstance(kwargs['ip_address'], six.string_types):
kwargs['ip_address'] = ipaddress.ip_address(kwargs['ip_address'])
user = '%s@%s' % (username, domain)
session = UserSession(self, username, domain, resource, **kwargs)
data = self.module.get(user)
if data is None:
raise UserNotFound(username, domain, resource)
data.setdefault('sessions', set())
if isinstance(data['sessions'], list):
# Cast old data to set
data['sessions'] = set(data['sessions'])
data['sessions'].add(session)
self.module.set(user, data)
all_sessions = self.module.get('all_sessions', set())
all_sessions.add(session)
self.module.set('all_sessions', all_sessions) | [
"def",
"start_user_session",
"(",
"self",
",",
"username",
",",
"domain",
",",
"resource",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'uptime'",
",",
"pytz",
".",
"utc",
".",
"localize",
"(",
"datetime",
".",
"utcnow",
"(",
"... | Method to add a user session for debugging.
Accepted parameters are the same as to the constructor of :py:class:`~xmpp_backends.base.UserSession`. | [
"Method",
"to",
"add",
"a",
"user",
"session",
"for",
"debugging",
"."
] | train | https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/dummy.py#L66-L103 |
INM-6/hybridLFPy | examples/example_microcircuit.py | merge_gdf | def merge_gdf(model_params, raw_label='spikes_', file_type='gdf',
fileprefix='spikes'):
'''
NEST produces one file per virtual process containing recorder output.
This function gathers and combines them into one single file per
network population.
Parameters
----------
model_params : object
network parameters object
Returns
-------
None
'''
def get_raw_gids(model_params):
'''
Reads text file containing gids of neuron populations as created within
the NEST simulation. These gids are not continuous as in the simulation
devices get created in between.
Parameters
----------
model_params : object
network parameters object
Returns
-------
gids : list
list of neuron ids and value (spike time, voltage etc.)
'''
gidfile = open(os.path.join(model_params.raw_nest_output_path,
model_params.GID_filename),'r')
gids = []
for l in gidfile :
a = l.split()
gids.append([int(a[0]),int(a[1])])
return gids
#some preprocessing
raw_gids = get_raw_gids(model_params)
pop_sizes = [raw_gids[i][1]-raw_gids[i][0]+1
for i in np.arange(model_params.Npops)]
raw_first_gids = [raw_gids[i][0] for i in np.arange(model_params.Npops)]
converted_first_gids = [int(1 + np.sum(pop_sizes[:i]))
for i in np.arange(model_params.Npops)]
for pop_idx in np.arange(model_params.Npops):
if pop_idx % SIZE == RANK:
files = glob(os.path.join(model_params.raw_nest_output_path,
raw_label + str(pop_idx) +
'*.' + file_type))
gdf = [] # init
for f in files:
new_gdf = helpers.read_gdf(f)
for line in new_gdf:
line[0] = line[0] - raw_first_gids[pop_idx] + \
converted_first_gids[pop_idx]
gdf.append(line)
print 'writing: %s' % os.path.join(model_params.spike_output_path,
fileprefix +
'_%s.gdf' % model_params.X[pop_idx])
helpers.write_gdf(gdf, os.path.join(model_params.spike_output_path,
fileprefix +
'_%s.gdf' % model_params.X[pop_idx]))
COMM.Barrier()
return | python | def merge_gdf(model_params, raw_label='spikes_', file_type='gdf',
fileprefix='spikes'):
'''
NEST produces one file per virtual process containing recorder output.
This function gathers and combines them into one single file per
network population.
Parameters
----------
model_params : object
network parameters object
Returns
-------
None
'''
def get_raw_gids(model_params):
'''
Reads text file containing gids of neuron populations as created within
the NEST simulation. These gids are not continuous as in the simulation
devices get created in between.
Parameters
----------
model_params : object
network parameters object
Returns
-------
gids : list
list of neuron ids and value (spike time, voltage etc.)
'''
gidfile = open(os.path.join(model_params.raw_nest_output_path,
model_params.GID_filename),'r')
gids = []
for l in gidfile :
a = l.split()
gids.append([int(a[0]),int(a[1])])
return gids
#some preprocessing
raw_gids = get_raw_gids(model_params)
pop_sizes = [raw_gids[i][1]-raw_gids[i][0]+1
for i in np.arange(model_params.Npops)]
raw_first_gids = [raw_gids[i][0] for i in np.arange(model_params.Npops)]
converted_first_gids = [int(1 + np.sum(pop_sizes[:i]))
for i in np.arange(model_params.Npops)]
for pop_idx in np.arange(model_params.Npops):
if pop_idx % SIZE == RANK:
files = glob(os.path.join(model_params.raw_nest_output_path,
raw_label + str(pop_idx) +
'*.' + file_type))
gdf = [] # init
for f in files:
new_gdf = helpers.read_gdf(f)
for line in new_gdf:
line[0] = line[0] - raw_first_gids[pop_idx] + \
converted_first_gids[pop_idx]
gdf.append(line)
print 'writing: %s' % os.path.join(model_params.spike_output_path,
fileprefix +
'_%s.gdf' % model_params.X[pop_idx])
helpers.write_gdf(gdf, os.path.join(model_params.spike_output_path,
fileprefix +
'_%s.gdf' % model_params.X[pop_idx]))
COMM.Barrier()
return | [
"def",
"merge_gdf",
"(",
"model_params",
",",
"raw_label",
"=",
"'spikes_'",
",",
"file_type",
"=",
"'gdf'",
",",
"fileprefix",
"=",
"'spikes'",
")",
":",
"def",
"get_raw_gids",
"(",
"model_params",
")",
":",
"'''\n Reads text file containing gids of neuron pop... | NEST produces one file per virtual process containing recorder output.
This function gathers and combines them into one single file per
network population.
Parameters
----------
model_params : object
network parameters object
Returns
-------
None | [
"NEST",
"produces",
"one",
"file",
"per",
"virtual",
"process",
"containing",
"recorder",
"output",
".",
"This",
"function",
"gathers",
"and",
"combines",
"them",
"into",
"one",
"single",
"file",
"per",
"network",
"population",
".",
"Parameters",
"----------",
"... | train | https://github.com/INM-6/hybridLFPy/blob/c38bdf38982c4624c2f70caeb50c40f1d5980abd/examples/example_microcircuit.py#L86-L159 |
INM-6/hybridLFPy | examples/example_microcircuit.py | dict_of_numpyarray_to_dict_of_list | def dict_of_numpyarray_to_dict_of_list(d):
'''
Convert dictionary containing numpy arrays to dictionary containing lists
Parameters
----------
d : dict
sli parameter name and value as dictionary key and value pairs
Returns
-------
d : dict
modified dictionary
'''
for key,value in d.iteritems():
if isinstance(value,dict): # if value == dict
# recurse
d[key] = dict_of_numpyarray_to_dict_of_list(value)
elif isinstance(value,np.ndarray): # or isinstance(value,list) :
d[key] = value.tolist()
return d | python | def dict_of_numpyarray_to_dict_of_list(d):
'''
Convert dictionary containing numpy arrays to dictionary containing lists
Parameters
----------
d : dict
sli parameter name and value as dictionary key and value pairs
Returns
-------
d : dict
modified dictionary
'''
for key,value in d.iteritems():
if isinstance(value,dict): # if value == dict
# recurse
d[key] = dict_of_numpyarray_to_dict_of_list(value)
elif isinstance(value,np.ndarray): # or isinstance(value,list) :
d[key] = value.tolist()
return d | [
"def",
"dict_of_numpyarray_to_dict_of_list",
"(",
"d",
")",
":",
"for",
"key",
",",
"value",
"in",
"d",
".",
"iteritems",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"# if value == dict ",
"# recurse",
"d",
"[",
"key",
"]",
"=... | Convert dictionary containing numpy arrays to dictionary containing lists
Parameters
----------
d : dict
sli parameter name and value as dictionary key and value pairs
Returns
-------
d : dict
modified dictionary | [
"Convert",
"dictionary",
"containing",
"numpy",
"arrays",
"to",
"dictionary",
"containing",
"lists",
"Parameters",
"----------",
"d",
":",
"dict",
"sli",
"parameter",
"name",
"and",
"value",
"as",
"dictionary",
"key",
"and",
"value",
"pairs",
"Returns",
"-------",... | train | https://github.com/INM-6/hybridLFPy/blob/c38bdf38982c4624c2f70caeb50c40f1d5980abd/examples/example_microcircuit.py#L162-L183 |
INM-6/hybridLFPy | examples/example_microcircuit.py | send_nest_params_to_sli | def send_nest_params_to_sli(p):
'''
Read parameters and send them to SLI
Parameters
----------
p : dict
sli parameter name and value as dictionary key and value pairs
Returns
-------
None
'''
for name in p.keys():
value = p[name]
if type(value) == np.ndarray:
value = value.tolist()
if type(value) == dict:
value = dict_of_numpyarray_to_dict_of_list(value)
if name == 'neuron_model': # special case as neuron_model is a
# NEST model and not a string
try:
nest.sli_run('/'+name)
nest.sli_push(value)
nest.sli_run('eval')
nest.sli_run('def')
except:
print 'Could not put variable %s on SLI stack' % (name)
print type(value)
else:
try:
nest.sli_run('/'+name)
nest.sli_push(value)
nest.sli_run('def')
except:
print 'Could not put variable %s on SLI stack' % (name)
print type(value)
return | python | def send_nest_params_to_sli(p):
'''
Read parameters and send them to SLI
Parameters
----------
p : dict
sli parameter name and value as dictionary key and value pairs
Returns
-------
None
'''
for name in p.keys():
value = p[name]
if type(value) == np.ndarray:
value = value.tolist()
if type(value) == dict:
value = dict_of_numpyarray_to_dict_of_list(value)
if name == 'neuron_model': # special case as neuron_model is a
# NEST model and not a string
try:
nest.sli_run('/'+name)
nest.sli_push(value)
nest.sli_run('eval')
nest.sli_run('def')
except:
print 'Could not put variable %s on SLI stack' % (name)
print type(value)
else:
try:
nest.sli_run('/'+name)
nest.sli_push(value)
nest.sli_run('def')
except:
print 'Could not put variable %s on SLI stack' % (name)
print type(value)
return | [
"def",
"send_nest_params_to_sli",
"(",
"p",
")",
":",
"for",
"name",
"in",
"p",
".",
"keys",
"(",
")",
":",
"value",
"=",
"p",
"[",
"name",
"]",
"if",
"type",
"(",
"value",
")",
"==",
"np",
".",
"ndarray",
":",
"value",
"=",
"value",
".",
"tolist... | Read parameters and send them to SLI
Parameters
----------
p : dict
sli parameter name and value as dictionary key and value pairs
Returns
-------
None | [
"Read",
"parameters",
"and",
"send",
"them",
"to",
"SLI",
"Parameters",
"----------",
"p",
":",
"dict",
"sli",
"parameter",
"name",
"and",
"value",
"as",
"dictionary",
"key",
"and",
"value",
"pairs",
"Returns",
"-------",
"None"
] | train | https://github.com/INM-6/hybridLFPy/blob/c38bdf38982c4624c2f70caeb50c40f1d5980abd/examples/example_microcircuit.py#L186-L223 |
staticdev/django-sorting-bootstrap | sorting_bootstrap/util.py | label_for_field | def label_for_field(name, model, return_attr=False):
"""
Returns a sensible label for a field name. The name can be a callable,
property (but not created with @property decorator) or the name of an
object's attribute, as well as a genuine fields. If return_attr is
True, the resolved attribute (which could be a callable) is also returned.
This will be None if (and only if) the name refers to a field.
"""
attr = None
try:
field = model._meta.get_field_by_name(name)[0]
if isinstance(field, RelatedObject):
label = field.opts.verbose_name
else:
label = field.verbose_name
except models.FieldDoesNotExist:
if name == "__unicode__":
label = force_text(model._meta.verbose_name)
attr = six.text_type
elif name == "__str__":
label = force_str(model._meta.verbose_name)
attr = bytes
else:
if callable(name):
attr = name
elif hasattr(model, name):
attr = getattr(model, name)
else:
message = "Unable to lookup '%s' on %s" % (name, model._meta.object_name)
raise AttributeError(message)
if hasattr(attr, "short_description"):
label = attr.short_description
elif (isinstance(attr, property) and
hasattr(attr, "fget") and
hasattr(attr.fget, "short_description")):
label = attr.fget.short_description
elif callable(attr):
if attr.__name__ == "<lambda>":
label = "--"
else:
label = pretty_name(attr.__name__)
else:
label = pretty_name(name)
if return_attr:
return (label, attr)
else:
return label | python | def label_for_field(name, model, return_attr=False):
"""
Returns a sensible label for a field name. The name can be a callable,
property (but not created with @property decorator) or the name of an
object's attribute, as well as a genuine fields. If return_attr is
True, the resolved attribute (which could be a callable) is also returned.
This will be None if (and only if) the name refers to a field.
"""
attr = None
try:
field = model._meta.get_field_by_name(name)[0]
if isinstance(field, RelatedObject):
label = field.opts.verbose_name
else:
label = field.verbose_name
except models.FieldDoesNotExist:
if name == "__unicode__":
label = force_text(model._meta.verbose_name)
attr = six.text_type
elif name == "__str__":
label = force_str(model._meta.verbose_name)
attr = bytes
else:
if callable(name):
attr = name
elif hasattr(model, name):
attr = getattr(model, name)
else:
message = "Unable to lookup '%s' on %s" % (name, model._meta.object_name)
raise AttributeError(message)
if hasattr(attr, "short_description"):
label = attr.short_description
elif (isinstance(attr, property) and
hasattr(attr, "fget") and
hasattr(attr.fget, "short_description")):
label = attr.fget.short_description
elif callable(attr):
if attr.__name__ == "<lambda>":
label = "--"
else:
label = pretty_name(attr.__name__)
else:
label = pretty_name(name)
if return_attr:
return (label, attr)
else:
return label | [
"def",
"label_for_field",
"(",
"name",
",",
"model",
",",
"return_attr",
"=",
"False",
")",
":",
"attr",
"=",
"None",
"try",
":",
"field",
"=",
"model",
".",
"_meta",
".",
"get_field_by_name",
"(",
"name",
")",
"[",
"0",
"]",
"if",
"isinstance",
"(",
... | Returns a sensible label for a field name. The name can be a callable,
property (but not created with @property decorator) or the name of an
object's attribute, as well as a genuine fields. If return_attr is
True, the resolved attribute (which could be a callable) is also returned.
This will be None if (and only if) the name refers to a field. | [
"Returns",
"a",
"sensible",
"label",
"for",
"a",
"field",
"name",
".",
"The",
"name",
"can",
"be",
"a",
"callable",
"property",
"(",
"but",
"not",
"created",
"with"
] | train | https://github.com/staticdev/django-sorting-bootstrap/blob/cfdc6e671b1b57aad04e44b041b9df10ee8288d3/sorting_bootstrap/util.py#L17-L64 |
avalente/appmetrics | appmetrics/meter.py | EWMA.update | def update(self, value):
"""
Update the current rate with the given value.
The value must be an integer.
"""
value = int(value)
with self.lock:
self.value += value | python | def update(self, value):
"""
Update the current rate with the given value.
The value must be an integer.
"""
value = int(value)
with self.lock:
self.value += value | [
"def",
"update",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"int",
"(",
"value",
")",
"with",
"self",
".",
"lock",
":",
"self",
".",
"value",
"+=",
"value"
] | Update the current rate with the given value.
The value must be an integer. | [
"Update",
"the",
"current",
"rate",
"with",
"the",
"given",
"value",
".",
"The",
"value",
"must",
"be",
"an",
"integer",
"."
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/meter.py#L60-L69 |
avalente/appmetrics | appmetrics/meter.py | EWMA.tick | def tick(self):
"""Decay the current rate according to the elapsed time"""
instant_rate = float(self.value) / float(self.tick_interval)
with self.lock:
if self.initialized:
self.rate += (self.alpha * (instant_rate - self.rate))
else:
self.initialized = True
self.rate = instant_rate
self.value = 0 | python | def tick(self):
"""Decay the current rate according to the elapsed time"""
instant_rate = float(self.value) / float(self.tick_interval)
with self.lock:
if self.initialized:
self.rate += (self.alpha * (instant_rate - self.rate))
else:
self.initialized = True
self.rate = instant_rate
self.value = 0 | [
"def",
"tick",
"(",
"self",
")",
":",
"instant_rate",
"=",
"float",
"(",
"self",
".",
"value",
")",
"/",
"float",
"(",
"self",
".",
"tick_interval",
")",
"with",
"self",
".",
"lock",
":",
"if",
"self",
".",
"initialized",
":",
"self",
".",
"rate",
... | Decay the current rate according to the elapsed time | [
"Decay",
"the",
"current",
"rate",
"according",
"to",
"the",
"elapsed",
"time"
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/meter.py#L71-L83 |
avalente/appmetrics | appmetrics/meter.py | Meter.notify | def notify(self, value):
"""Add a new observation to the metric"""
with self.lock:
#TODO: this could slow down slow-rate incoming updates
# since the number of ticks depends on the actual time
# passed since the latest notification. Consider using
# a real timer to tick the EWMA.
self.tick()
for avg in (self.m1, self.m5, self.m15, self.day):
avg.update(value)
self.count += value | python | def notify(self, value):
"""Add a new observation to the metric"""
with self.lock:
#TODO: this could slow down slow-rate incoming updates
# since the number of ticks depends on the actual time
# passed since the latest notification. Consider using
# a real timer to tick the EWMA.
self.tick()
for avg in (self.m1, self.m5, self.m15, self.day):
avg.update(value)
self.count += value | [
"def",
"notify",
"(",
"self",
",",
"value",
")",
":",
"with",
"self",
".",
"lock",
":",
"#TODO: this could slow down slow-rate incoming updates",
"# since the number of ticks depends on the actual time",
"# passed since the latest notification. Consider using",
"# a real timer to tic... | Add a new observation to the metric | [
"Add",
"a",
"new",
"observation",
"to",
"the",
"metric"
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/meter.py#L112-L125 |
avalente/appmetrics | appmetrics/meter.py | Meter.tick_all | def tick_all(self, times):
"""
Tick all the EWMAs for the given number of times
"""
for i in range(times):
for avg in (self.m1, self.m5, self.m15, self.day):
avg.tick() | python | def tick_all(self, times):
"""
Tick all the EWMAs for the given number of times
"""
for i in range(times):
for avg in (self.m1, self.m5, self.m15, self.day):
avg.tick() | [
"def",
"tick_all",
"(",
"self",
",",
"times",
")",
":",
"for",
"i",
"in",
"range",
"(",
"times",
")",
":",
"for",
"avg",
"in",
"(",
"self",
".",
"m1",
",",
"self",
".",
"m5",
",",
"self",
".",
"m15",
",",
"self",
".",
"day",
")",
":",
"avg",
... | Tick all the EWMAs for the given number of times | [
"Tick",
"all",
"the",
"EWMAs",
"for",
"the",
"given",
"number",
"of",
"times"
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/meter.py#L127-L134 |
avalente/appmetrics | appmetrics/meter.py | Meter.tick | def tick(self):
"""
Emulate a timer: in order to avoid a real timer we "tick" a number
of times depending on the actual time passed since the last tick
"""
now = time.time()
elapsed = now - self.latest_tick
if elapsed > self.tick_interval:
ticks = int(elapsed / self.tick_interval)
self.tick_all(ticks)
self.latest_tick = now | python | def tick(self):
"""
Emulate a timer: in order to avoid a real timer we "tick" a number
of times depending on the actual time passed since the last tick
"""
now = time.time()
elapsed = now - self.latest_tick
if elapsed > self.tick_interval:
ticks = int(elapsed / self.tick_interval)
self.tick_all(ticks)
self.latest_tick = now | [
"def",
"tick",
"(",
"self",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"elapsed",
"=",
"now",
"-",
"self",
".",
"latest_tick",
"if",
"elapsed",
">",
"self",
".",
"tick_interval",
":",
"ticks",
"=",
"int",
"(",
"elapsed",
"/",
"self",
".",... | Emulate a timer: in order to avoid a real timer we "tick" a number
of times depending on the actual time passed since the last tick | [
"Emulate",
"a",
"timer",
":",
"in",
"order",
"to",
"avoid",
"a",
"real",
"timer",
"we",
"tick",
"a",
"number",
"of",
"times",
"depending",
"on",
"the",
"actual",
"time",
"passed",
"since",
"the",
"last",
"tick"
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/meter.py#L136-L151 |
avalente/appmetrics | appmetrics/meter.py | Meter.get | def get(self):
"""
Return the computed statistics over the gathered data
"""
with self.lock:
self.tick()
data = dict(
kind="meter",
count=self.count,
mean=self.count / (time.time() - self.started_on),
one=self.m1.rate,
five=self.m5.rate,
fifteen=self.m15.rate,
day=self.day.rate)
return data | python | def get(self):
"""
Return the computed statistics over the gathered data
"""
with self.lock:
self.tick()
data = dict(
kind="meter",
count=self.count,
mean=self.count / (time.time() - self.started_on),
one=self.m1.rate,
five=self.m5.rate,
fifteen=self.m15.rate,
day=self.day.rate)
return data | [
"def",
"get",
"(",
"self",
")",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"tick",
"(",
")",
"data",
"=",
"dict",
"(",
"kind",
"=",
"\"meter\"",
",",
"count",
"=",
"self",
".",
"count",
",",
"mean",
"=",
"self",
".",
"count",
"/",
"(",... | Return the computed statistics over the gathered data | [
"Return",
"the",
"computed",
"statistics",
"over",
"the",
"gathered",
"data"
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/meter.py#L158-L175 |
intiocean/pyinter | pyinter/interval.py | open | def open(lower_value, upper_value):
"""Helper function to construct an interval object with open lower and upper.
For example:
>>> open(100.2, 800.9)
(100.2, 800.9)
"""
return Interval(Interval.OPEN, lower_value, upper_value, Interval.OPEN) | python | def open(lower_value, upper_value):
"""Helper function to construct an interval object with open lower and upper.
For example:
>>> open(100.2, 800.9)
(100.2, 800.9)
"""
return Interval(Interval.OPEN, lower_value, upper_value, Interval.OPEN) | [
"def",
"open",
"(",
"lower_value",
",",
"upper_value",
")",
":",
"return",
"Interval",
"(",
"Interval",
".",
"OPEN",
",",
"lower_value",
",",
"upper_value",
",",
"Interval",
".",
"OPEN",
")"
] | Helper function to construct an interval object with open lower and upper.
For example:
>>> open(100.2, 800.9)
(100.2, 800.9) | [
"Helper",
"function",
"to",
"construct",
"an",
"interval",
"object",
"with",
"open",
"lower",
"and",
"upper",
"."
] | train | https://github.com/intiocean/pyinter/blob/fb6e904307477fa43123cc9ab326680aa1a8cd62/pyinter/interval.py#L6-L14 |
intiocean/pyinter | pyinter/interval.py | closed | def closed(lower_value, upper_value):
"""Helper function to construct an interval object with closed lower and upper.
For example:
>>> closed(100.2, 800.9)
[100.2, 800.9]
"""
return Interval(Interval.CLOSED, lower_value, upper_value, Interval.CLOSED) | python | def closed(lower_value, upper_value):
"""Helper function to construct an interval object with closed lower and upper.
For example:
>>> closed(100.2, 800.9)
[100.2, 800.9]
"""
return Interval(Interval.CLOSED, lower_value, upper_value, Interval.CLOSED) | [
"def",
"closed",
"(",
"lower_value",
",",
"upper_value",
")",
":",
"return",
"Interval",
"(",
"Interval",
".",
"CLOSED",
",",
"lower_value",
",",
"upper_value",
",",
"Interval",
".",
"CLOSED",
")"
] | Helper function to construct an interval object with closed lower and upper.
For example:
>>> closed(100.2, 800.9)
[100.2, 800.9] | [
"Helper",
"function",
"to",
"construct",
"an",
"interval",
"object",
"with",
"closed",
"lower",
"and",
"upper",
"."
] | train | https://github.com/intiocean/pyinter/blob/fb6e904307477fa43123cc9ab326680aa1a8cd62/pyinter/interval.py#L17-L25 |
intiocean/pyinter | pyinter/interval.py | openclosed | def openclosed(lower_value, upper_value):
"""Helper function to construct an interval object with a open lower and closed upper.
For example:
>>> openclosed(100.2, 800.9)
(100.2, 800.9]
"""
return Interval(Interval.OPEN, lower_value, upper_value, Interval.CLOSED) | python | def openclosed(lower_value, upper_value):
"""Helper function to construct an interval object with a open lower and closed upper.
For example:
>>> openclosed(100.2, 800.9)
(100.2, 800.9]
"""
return Interval(Interval.OPEN, lower_value, upper_value, Interval.CLOSED) | [
"def",
"openclosed",
"(",
"lower_value",
",",
"upper_value",
")",
":",
"return",
"Interval",
"(",
"Interval",
".",
"OPEN",
",",
"lower_value",
",",
"upper_value",
",",
"Interval",
".",
"CLOSED",
")"
] | Helper function to construct an interval object with a open lower and closed upper.
For example:
>>> openclosed(100.2, 800.9)
(100.2, 800.9] | [
"Helper",
"function",
"to",
"construct",
"an",
"interval",
"object",
"with",
"a",
"open",
"lower",
"and",
"closed",
"upper",
"."
] | train | https://github.com/intiocean/pyinter/blob/fb6e904307477fa43123cc9ab326680aa1a8cd62/pyinter/interval.py#L28-L36 |
intiocean/pyinter | pyinter/interval.py | closedopen | def closedopen(lower_value, upper_value):
"""Helper function to construct an interval object with a closed lower and open upper.
For example:
>>> closedopen(100.2, 800.9)
[100.2, 800.9)
"""
return Interval(Interval.CLOSED, lower_value, upper_value, Interval.OPEN) | python | def closedopen(lower_value, upper_value):
"""Helper function to construct an interval object with a closed lower and open upper.
For example:
>>> closedopen(100.2, 800.9)
[100.2, 800.9)
"""
return Interval(Interval.CLOSED, lower_value, upper_value, Interval.OPEN) | [
"def",
"closedopen",
"(",
"lower_value",
",",
"upper_value",
")",
":",
"return",
"Interval",
"(",
"Interval",
".",
"CLOSED",
",",
"lower_value",
",",
"upper_value",
",",
"Interval",
".",
"OPEN",
")"
] | Helper function to construct an interval object with a closed lower and open upper.
For example:
>>> closedopen(100.2, 800.9)
[100.2, 800.9) | [
"Helper",
"function",
"to",
"construct",
"an",
"interval",
"object",
"with",
"a",
"closed",
"lower",
"and",
"open",
"upper",
"."
] | train | https://github.com/intiocean/pyinter/blob/fb6e904307477fa43123cc9ab326680aa1a8cd62/pyinter/interval.py#L39-L47 |
intiocean/pyinter | pyinter/interval.py | Interval.copy | def copy(self):
"""Returns a new :class:`~pyinter.Interval` object with the same bounds and values."""
return Interval(self._lower, self._lower_value, self._upper_value, self._upper) | python | def copy(self):
"""Returns a new :class:`~pyinter.Interval` object with the same bounds and values."""
return Interval(self._lower, self._lower_value, self._upper_value, self._upper) | [
"def",
"copy",
"(",
"self",
")",
":",
"return",
"Interval",
"(",
"self",
".",
"_lower",
",",
"self",
".",
"_lower_value",
",",
"self",
".",
"_upper_value",
",",
"self",
".",
"_upper",
")"
] | Returns a new :class:`~pyinter.Interval` object with the same bounds and values. | [
"Returns",
"a",
"new",
":",
"class",
":",
"~pyinter",
".",
"Interval",
"object",
"with",
"the",
"same",
"bounds",
"and",
"values",
"."
] | train | https://github.com/intiocean/pyinter/blob/fb6e904307477fa43123cc9ab326680aa1a8cd62/pyinter/interval.py#L101-L103 |
intiocean/pyinter | pyinter/interval.py | Interval._contains_value | def _contains_value(self, value):
"""Helper function for __contains__ to check a single value is contained within the interval"""
g = operator.gt if self._lower is self.OPEN else operator.ge
l = operator.lt if self._upper is self.OPEN else operator.le
return g(value, self.lower_value) and l(value, self._upper_value) | python | def _contains_value(self, value):
"""Helper function for __contains__ to check a single value is contained within the interval"""
g = operator.gt if self._lower is self.OPEN else operator.ge
l = operator.lt if self._upper is self.OPEN else operator.le
return g(value, self.lower_value) and l(value, self._upper_value) | [
"def",
"_contains_value",
"(",
"self",
",",
"value",
")",
":",
"g",
"=",
"operator",
".",
"gt",
"if",
"self",
".",
"_lower",
"is",
"self",
".",
"OPEN",
"else",
"operator",
".",
"ge",
"l",
"=",
"operator",
".",
"lt",
"if",
"self",
".",
"_upper",
"is... | Helper function for __contains__ to check a single value is contained within the interval | [
"Helper",
"function",
"for",
"__contains__",
"to",
"check",
"a",
"single",
"value",
"is",
"contained",
"within",
"the",
"interval"
] | train | https://github.com/intiocean/pyinter/blob/fb6e904307477fa43123cc9ab326680aa1a8cd62/pyinter/interval.py#L162-L166 |
intiocean/pyinter | pyinter/interval.py | Interval.overlaps | def overlaps(self, other):
"""If self and other have any overlapping values returns True, otherwise returns False"""
if self > other:
smaller, larger = other, self
else:
smaller, larger = self, other
if larger.empty():
return False
if smaller._upper_value == larger._lower_value:
return smaller._upper == smaller.CLOSED and larger._lower == smaller.CLOSED
return larger._lower_value < smaller._upper_value | python | def overlaps(self, other):
"""If self and other have any overlapping values returns True, otherwise returns False"""
if self > other:
smaller, larger = other, self
else:
smaller, larger = self, other
if larger.empty():
return False
if smaller._upper_value == larger._lower_value:
return smaller._upper == smaller.CLOSED and larger._lower == smaller.CLOSED
return larger._lower_value < smaller._upper_value | [
"def",
"overlaps",
"(",
"self",
",",
"other",
")",
":",
"if",
"self",
">",
"other",
":",
"smaller",
",",
"larger",
"=",
"other",
",",
"self",
"else",
":",
"smaller",
",",
"larger",
"=",
"self",
",",
"other",
"if",
"larger",
".",
"empty",
"(",
")",
... | If self and other have any overlapping values returns True, otherwise returns False | [
"If",
"self",
"and",
"other",
"have",
"any",
"overlapping",
"values",
"returns",
"True",
"otherwise",
"returns",
"False"
] | train | https://github.com/intiocean/pyinter/blob/fb6e904307477fa43123cc9ab326680aa1a8cd62/pyinter/interval.py#L223-L233 |
intiocean/pyinter | pyinter/interval.py | Interval.intersect | def intersect(self, other):
"""Returns a new :class:`~pyinter.Interval` representing the intersection of this :class:`~pyinter.Interval`
with the other :class:`~pyinter.Interval`"""
if self.overlaps(other):
newlower_value = max(self.lower_value, other.lower_value)
new_upper_value = min(self._upper_value, other._upper_value)
new_lower, new_upper = self._get_new_lower_upper(other, self.intersect)
return Interval(new_lower, newlower_value, new_upper_value, new_upper)
else:
return None | python | def intersect(self, other):
"""Returns a new :class:`~pyinter.Interval` representing the intersection of this :class:`~pyinter.Interval`
with the other :class:`~pyinter.Interval`"""
if self.overlaps(other):
newlower_value = max(self.lower_value, other.lower_value)
new_upper_value = min(self._upper_value, other._upper_value)
new_lower, new_upper = self._get_new_lower_upper(other, self.intersect)
return Interval(new_lower, newlower_value, new_upper_value, new_upper)
else:
return None | [
"def",
"intersect",
"(",
"self",
",",
"other",
")",
":",
"if",
"self",
".",
"overlaps",
"(",
"other",
")",
":",
"newlower_value",
"=",
"max",
"(",
"self",
".",
"lower_value",
",",
"other",
".",
"lower_value",
")",
"new_upper_value",
"=",
"min",
"(",
"s... | Returns a new :class:`~pyinter.Interval` representing the intersection of this :class:`~pyinter.Interval`
with the other :class:`~pyinter.Interval` | [
"Returns",
"a",
"new",
":",
"class",
":",
"~pyinter",
".",
"Interval",
"representing",
"the",
"intersection",
"of",
"this",
":",
"class",
":",
"~pyinter",
".",
"Interval",
"with",
"the",
"other",
":",
"class",
":",
"~pyinter",
".",
"Interval"
] | train | https://github.com/intiocean/pyinter/blob/fb6e904307477fa43123cc9ab326680aa1a8cd62/pyinter/interval.py#L235-L244 |
intiocean/pyinter | pyinter/interval.py | Interval.difference | def difference(self, other):
"""Returns a new Interval or an :class:`~pyinter.IntervalSet` representing the subtraction of this
:class:`~pyinter.Interval` with the other :class:`~pyinter.Interval`.
The result will contain everything that is contained by the left interval but not contained
by the second interval.
If the `other` interval is enclosed in this one then this will return a
:class:`~pyinter.IntervalSet`, otherwise this returns a :class:`~pyinter.Interval`.
"""
if other.empty():
return self
if self in other:
return open(self._lower_value, self._lower_value)
if self._lower == other._lower and self._lower_value == other._lower_value:
return Interval(self._opposite_boundary_type(other._upper), other._upper_value, self._upper_value, self._upper)
if self._upper == other._upper and self._upper_value == other._upper_value:
return Interval(self._lower, self._lower_value, other._lower_value, self._opposite_boundary_type(other._lower))
if other in self:
return IntervalSet([
Interval(self._lower, self._lower_value, other.lower_value, self._opposite_boundary_type(other._lower)),
Interval(self._opposite_boundary_type(other._upper), other._upper_value, self.upper_value, self._upper),
])
if other.lower_value in self:
return Interval(self._lower, self._lower_value, other._lower_value, self._opposite_boundary_type(other._lower))
if other.upper_value in self:
return Interval(self._opposite_boundary_type(other._upper), other._upper_value, self._upper_value, self._upper)
return Interval(self._lower, self._lower_value, self._upper_value, self._upper) | python | def difference(self, other):
"""Returns a new Interval or an :class:`~pyinter.IntervalSet` representing the subtraction of this
:class:`~pyinter.Interval` with the other :class:`~pyinter.Interval`.
The result will contain everything that is contained by the left interval but not contained
by the second interval.
If the `other` interval is enclosed in this one then this will return a
:class:`~pyinter.IntervalSet`, otherwise this returns a :class:`~pyinter.Interval`.
"""
if other.empty():
return self
if self in other:
return open(self._lower_value, self._lower_value)
if self._lower == other._lower and self._lower_value == other._lower_value:
return Interval(self._opposite_boundary_type(other._upper), other._upper_value, self._upper_value, self._upper)
if self._upper == other._upper and self._upper_value == other._upper_value:
return Interval(self._lower, self._lower_value, other._lower_value, self._opposite_boundary_type(other._lower))
if other in self:
return IntervalSet([
Interval(self._lower, self._lower_value, other.lower_value, self._opposite_boundary_type(other._lower)),
Interval(self._opposite_boundary_type(other._upper), other._upper_value, self.upper_value, self._upper),
])
if other.lower_value in self:
return Interval(self._lower, self._lower_value, other._lower_value, self._opposite_boundary_type(other._lower))
if other.upper_value in self:
return Interval(self._opposite_boundary_type(other._upper), other._upper_value, self._upper_value, self._upper)
return Interval(self._lower, self._lower_value, self._upper_value, self._upper) | [
"def",
"difference",
"(",
"self",
",",
"other",
")",
":",
"if",
"other",
".",
"empty",
"(",
")",
":",
"return",
"self",
"if",
"self",
"in",
"other",
":",
"return",
"open",
"(",
"self",
".",
"_lower_value",
",",
"self",
".",
"_lower_value",
")",
"if",... | Returns a new Interval or an :class:`~pyinter.IntervalSet` representing the subtraction of this
:class:`~pyinter.Interval` with the other :class:`~pyinter.Interval`.
The result will contain everything that is contained by the left interval but not contained
by the second interval.
If the `other` interval is enclosed in this one then this will return a
:class:`~pyinter.IntervalSet`, otherwise this returns a :class:`~pyinter.Interval`. | [
"Returns",
"a",
"new",
"Interval",
"or",
"an",
":",
"class",
":",
"~pyinter",
".",
"IntervalSet",
"representing",
"the",
"subtraction",
"of",
"this",
":",
"class",
":",
"~pyinter",
".",
"Interval",
"with",
"the",
"other",
":",
"class",
":",
"~pyinter",
"."... | train | https://github.com/intiocean/pyinter/blob/fb6e904307477fa43123cc9ab326680aa1a8cd62/pyinter/interval.py#L264-L291 |
avalente/appmetrics | appmetrics/reporter.py | register | def register(callback, schedule, tag=None):
"""
Register a callback which will be called at scheduled intervals with
the metrics that have the given tag (or all the metrics if None).
Return an identifier which can be used to access the registered callback later.
"""
try:
iter(schedule)
except TypeError:
raise TypeError("{} is not iterable".format(schedule))
if not callable(callback):
raise TypeError("{} is not callable".format(callback))
thread = Timer(schedule, callback, tag)
id_ = str(uuid.uuid4())
with LOCK:
REGISTRY[id_] = thread
thread.start()
return id_ | python | def register(callback, schedule, tag=None):
"""
Register a callback which will be called at scheduled intervals with
the metrics that have the given tag (or all the metrics if None).
Return an identifier which can be used to access the registered callback later.
"""
try:
iter(schedule)
except TypeError:
raise TypeError("{} is not iterable".format(schedule))
if not callable(callback):
raise TypeError("{} is not callable".format(callback))
thread = Timer(schedule, callback, tag)
id_ = str(uuid.uuid4())
with LOCK:
REGISTRY[id_] = thread
thread.start()
return id_ | [
"def",
"register",
"(",
"callback",
",",
"schedule",
",",
"tag",
"=",
"None",
")",
":",
"try",
":",
"iter",
"(",
"schedule",
")",
"except",
"TypeError",
":",
"raise",
"TypeError",
"(",
"\"{} is not iterable\"",
".",
"format",
"(",
"schedule",
")",
")",
"... | Register a callback which will be called at scheduled intervals with
the metrics that have the given tag (or all the metrics if None).
Return an identifier which can be used to access the registered callback later. | [
"Register",
"a",
"callback",
"which",
"will",
"be",
"called",
"at",
"scheduled",
"intervals",
"with",
"the",
"metrics",
"that",
"have",
"the",
"given",
"tag",
"(",
"or",
"all",
"the",
"metrics",
"if",
"None",
")",
".",
"Return",
"an",
"identifier",
"which"... | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/reporter.py#L40-L63 |
avalente/appmetrics | appmetrics/reporter.py | remove | def remove(id_):
"""
Remove the callback and its schedule
"""
with LOCK:
thread = REGISTRY.pop(id_, None)
if thread is not None:
thread.cancel()
return thread | python | def remove(id_):
"""
Remove the callback and its schedule
"""
with LOCK:
thread = REGISTRY.pop(id_, None)
if thread is not None:
thread.cancel()
return thread | [
"def",
"remove",
"(",
"id_",
")",
":",
"with",
"LOCK",
":",
"thread",
"=",
"REGISTRY",
".",
"pop",
"(",
"id_",
",",
"None",
")",
"if",
"thread",
"is",
"not",
"None",
":",
"thread",
".",
"cancel",
"(",
")",
"return",
"thread"
] | Remove the callback and its schedule | [
"Remove",
"the",
"callback",
"and",
"its",
"schedule"
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/reporter.py#L73-L82 |
avalente/appmetrics | appmetrics/reporter.py | get_metrics | def get_metrics(tag):
"""
Return the values for the metrics with the given tag or all the available metrics if None
"""
if tag is None:
return metrics.metrics_by_name_list(metrics.metrics())
else:
return metrics.metrics_by_tag(tag) | python | def get_metrics(tag):
"""
Return the values for the metrics with the given tag or all the available metrics if None
"""
if tag is None:
return metrics.metrics_by_name_list(metrics.metrics())
else:
return metrics.metrics_by_tag(tag) | [
"def",
"get_metrics",
"(",
"tag",
")",
":",
"if",
"tag",
"is",
"None",
":",
"return",
"metrics",
".",
"metrics_by_name_list",
"(",
"metrics",
".",
"metrics",
"(",
")",
")",
"else",
":",
"return",
"metrics",
".",
"metrics_by_tag",
"(",
"tag",
")"
] | Return the values for the metrics with the given tag or all the available metrics if None | [
"Return",
"the",
"values",
"for",
"the",
"metrics",
"with",
"the",
"given",
"tag",
"or",
"all",
"the",
"available",
"metrics",
"if",
"None"
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/reporter.py#L140-L147 |
avalente/appmetrics | appmetrics/reporter.py | fixed_interval_scheduler | def fixed_interval_scheduler(interval):
"""
A scheduler that ticks at fixed intervals of "interval" seconds
"""
start = time.time()
next_tick = start
while True:
next_tick += interval
yield next_tick | python | def fixed_interval_scheduler(interval):
"""
A scheduler that ticks at fixed intervals of "interval" seconds
"""
start = time.time()
next_tick = start
while True:
next_tick += interval
yield next_tick | [
"def",
"fixed_interval_scheduler",
"(",
"interval",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"next_tick",
"=",
"start",
"while",
"True",
":",
"next_tick",
"+=",
"interval",
"yield",
"next_tick"
] | A scheduler that ticks at fixed intervals of "interval" seconds | [
"A",
"scheduler",
"that",
"ticks",
"at",
"fixed",
"intervals",
"of",
"interval",
"seconds"
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/reporter.py#L150-L159 |
Pytwitcher/pytwitcherapi | src/pytwitcherapi/models.py | Game.wrap_search | def wrap_search(cls, response):
"""Wrap the response from a game search into instances
and return them
:param response: The response from searching a game
:type response: :class:`requests.Response`
:returns: the new game instances
:rtype: :class:`list` of :class:`Game`
:raises: None
"""
games = []
json = response.json()
gamejsons = json['games']
for j in gamejsons:
g = cls.wrap_json(j)
games.append(g)
return games | python | def wrap_search(cls, response):
"""Wrap the response from a game search into instances
and return them
:param response: The response from searching a game
:type response: :class:`requests.Response`
:returns: the new game instances
:rtype: :class:`list` of :class:`Game`
:raises: None
"""
games = []
json = response.json()
gamejsons = json['games']
for j in gamejsons:
g = cls.wrap_json(j)
games.append(g)
return games | [
"def",
"wrap_search",
"(",
"cls",
",",
"response",
")",
":",
"games",
"=",
"[",
"]",
"json",
"=",
"response",
".",
"json",
"(",
")",
"gamejsons",
"=",
"json",
"[",
"'games'",
"]",
"for",
"j",
"in",
"gamejsons",
":",
"g",
"=",
"cls",
".",
"wrap_json... | Wrap the response from a game search into instances
and return them
:param response: The response from searching a game
:type response: :class:`requests.Response`
:returns: the new game instances
:rtype: :class:`list` of :class:`Game`
:raises: None | [
"Wrap",
"the",
"response",
"from",
"a",
"game",
"search",
"into",
"instances",
"and",
"return",
"them"
] | train | https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/models.py#L11-L27 |
Pytwitcher/pytwitcherapi | src/pytwitcherapi/models.py | Game.wrap_topgames | def wrap_topgames(cls, response):
"""Wrap the response from quering the top games into instances
and return them
:param response: The response for quering the top games
:type response: :class:`requests.Response`
:returns: the new game instances
:rtype: :class:`list` of :class:`Game`
:raises: None
"""
games = []
json = response.json()
topjsons = json['top']
for t in topjsons:
g = cls.wrap_json(json=t['game'],
viewers=t['viewers'],
channels=t['channels'])
games.append(g)
return games | python | def wrap_topgames(cls, response):
"""Wrap the response from quering the top games into instances
and return them
:param response: The response for quering the top games
:type response: :class:`requests.Response`
:returns: the new game instances
:rtype: :class:`list` of :class:`Game`
:raises: None
"""
games = []
json = response.json()
topjsons = json['top']
for t in topjsons:
g = cls.wrap_json(json=t['game'],
viewers=t['viewers'],
channels=t['channels'])
games.append(g)
return games | [
"def",
"wrap_topgames",
"(",
"cls",
",",
"response",
")",
":",
"games",
"=",
"[",
"]",
"json",
"=",
"response",
".",
"json",
"(",
")",
"topjsons",
"=",
"json",
"[",
"'top'",
"]",
"for",
"t",
"in",
"topjsons",
":",
"g",
"=",
"cls",
".",
"wrap_json",... | Wrap the response from quering the top games into instances
and return them
:param response: The response for quering the top games
:type response: :class:`requests.Response`
:returns: the new game instances
:rtype: :class:`list` of :class:`Game`
:raises: None | [
"Wrap",
"the",
"response",
"from",
"quering",
"the",
"top",
"games",
"into",
"instances",
"and",
"return",
"them"
] | train | https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/models.py#L30-L48 |
Pytwitcher/pytwitcherapi | src/pytwitcherapi/models.py | Game.wrap_json | def wrap_json(cls, json, viewers=None, channels=None):
"""Create a Game instance for the given json
:param json: the dict with the information of the game
:type json: :class:`dict`
:param viewers: The viewer count
:type viewers: :class:`int`
:param channels: The viewer count
:type channels: :class:`int`
:returns: the new game instance
:rtype: :class:`Game`
:raises: None
"""
g = Game(name=json.get('name'),
box=json.get('box'),
logo=json.get('logo'),
twitchid=json.get('_id'),
viewers=viewers,
channels=channels)
return g | python | def wrap_json(cls, json, viewers=None, channels=None):
"""Create a Game instance for the given json
:param json: the dict with the information of the game
:type json: :class:`dict`
:param viewers: The viewer count
:type viewers: :class:`int`
:param channels: The viewer count
:type channels: :class:`int`
:returns: the new game instance
:rtype: :class:`Game`
:raises: None
"""
g = Game(name=json.get('name'),
box=json.get('box'),
logo=json.get('logo'),
twitchid=json.get('_id'),
viewers=viewers,
channels=channels)
return g | [
"def",
"wrap_json",
"(",
"cls",
",",
"json",
",",
"viewers",
"=",
"None",
",",
"channels",
"=",
"None",
")",
":",
"g",
"=",
"Game",
"(",
"name",
"=",
"json",
".",
"get",
"(",
"'name'",
")",
",",
"box",
"=",
"json",
".",
"get",
"(",
"'box'",
")"... | Create a Game instance for the given json
:param json: the dict with the information of the game
:type json: :class:`dict`
:param viewers: The viewer count
:type viewers: :class:`int`
:param channels: The viewer count
:type channels: :class:`int`
:returns: the new game instance
:rtype: :class:`Game`
:raises: None | [
"Create",
"a",
"Game",
"instance",
"for",
"the",
"given",
"json"
] | train | https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/models.py#L51-L70 |
Pytwitcher/pytwitcherapi | src/pytwitcherapi/models.py | Channel.wrap_search | def wrap_search(cls, response):
"""Wrap the response from a channel search into instances
and return them
:param response: The response from searching a channel
:type response: :class:`requests.Response`
:returns: the new channel instances
:rtype: :class:`list` of :class:`channel`
:raises: None
"""
channels = []
json = response.json()
channeljsons = json['channels']
for j in channeljsons:
c = cls.wrap_json(j)
channels.append(c)
return channels | python | def wrap_search(cls, response):
"""Wrap the response from a channel search into instances
and return them
:param response: The response from searching a channel
:type response: :class:`requests.Response`
:returns: the new channel instances
:rtype: :class:`list` of :class:`channel`
:raises: None
"""
channels = []
json = response.json()
channeljsons = json['channels']
for j in channeljsons:
c = cls.wrap_json(j)
channels.append(c)
return channels | [
"def",
"wrap_search",
"(",
"cls",
",",
"response",
")",
":",
"channels",
"=",
"[",
"]",
"json",
"=",
"response",
".",
"json",
"(",
")",
"channeljsons",
"=",
"json",
"[",
"'channels'",
"]",
"for",
"j",
"in",
"channeljsons",
":",
"c",
"=",
"cls",
".",
... | Wrap the response from a channel search into instances
and return them
:param response: The response from searching a channel
:type response: :class:`requests.Response`
:returns: the new channel instances
:rtype: :class:`list` of :class:`channel`
:raises: None | [
"Wrap",
"the",
"response",
"from",
"a",
"channel",
"search",
"into",
"instances",
"and",
"return",
"them"
] | train | https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/models.py#L119-L135 |
Pytwitcher/pytwitcherapi | src/pytwitcherapi/models.py | Channel.wrap_get_channel | def wrap_get_channel(cls, response):
"""Wrap the response from getting a channel into an instance
and return it
:param response: The response from getting a channel
:type response: :class:`requests.Response`
:returns: the new channel instance
:rtype: :class:`list` of :class:`channel`
:raises: None
"""
json = response.json()
c = cls.wrap_json(json)
return c | python | def wrap_get_channel(cls, response):
"""Wrap the response from getting a channel into an instance
and return it
:param response: The response from getting a channel
:type response: :class:`requests.Response`
:returns: the new channel instance
:rtype: :class:`list` of :class:`channel`
:raises: None
"""
json = response.json()
c = cls.wrap_json(json)
return c | [
"def",
"wrap_get_channel",
"(",
"cls",
",",
"response",
")",
":",
"json",
"=",
"response",
".",
"json",
"(",
")",
"c",
"=",
"cls",
".",
"wrap_json",
"(",
"json",
")",
"return",
"c"
] | Wrap the response from getting a channel into an instance
and return it
:param response: The response from getting a channel
:type response: :class:`requests.Response`
:returns: the new channel instance
:rtype: :class:`list` of :class:`channel`
:raises: None | [
"Wrap",
"the",
"response",
"from",
"getting",
"a",
"channel",
"into",
"an",
"instance",
"and",
"return",
"it"
] | train | https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/models.py#L138-L150 |
Pytwitcher/pytwitcherapi | src/pytwitcherapi/models.py | Channel.wrap_json | def wrap_json(cls, json):
"""Create a Channel instance for the given json
:param json: the dict with the information of the channel
:type json: :class:`dict`
:returns: the new channel instance
:rtype: :class:`Channel`
:raises: None
"""
c = Channel(name=json.get('name'),
status=json.get('status'),
displayname=json.get('display_name'),
game=json.get('game'),
twitchid=json.get('_id'),
views=json.get('views'),
followers=json.get('followers'),
url=json.get('url'),
language=json.get('language'),
broadcaster_language=json.get('broadcaster_language'),
mature=json.get('mature'),
logo=json.get('logo'),
banner=json.get('banner'),
video_banner=json.get('video_banner'),
delay=json.get('delay'))
return c | python | def wrap_json(cls, json):
"""Create a Channel instance for the given json
:param json: the dict with the information of the channel
:type json: :class:`dict`
:returns: the new channel instance
:rtype: :class:`Channel`
:raises: None
"""
c = Channel(name=json.get('name'),
status=json.get('status'),
displayname=json.get('display_name'),
game=json.get('game'),
twitchid=json.get('_id'),
views=json.get('views'),
followers=json.get('followers'),
url=json.get('url'),
language=json.get('language'),
broadcaster_language=json.get('broadcaster_language'),
mature=json.get('mature'),
logo=json.get('logo'),
banner=json.get('banner'),
video_banner=json.get('video_banner'),
delay=json.get('delay'))
return c | [
"def",
"wrap_json",
"(",
"cls",
",",
"json",
")",
":",
"c",
"=",
"Channel",
"(",
"name",
"=",
"json",
".",
"get",
"(",
"'name'",
")",
",",
"status",
"=",
"json",
".",
"get",
"(",
"'status'",
")",
",",
"displayname",
"=",
"json",
".",
"get",
"(",
... | Create a Channel instance for the given json
:param json: the dict with the information of the channel
:type json: :class:`dict`
:returns: the new channel instance
:rtype: :class:`Channel`
:raises: None | [
"Create",
"a",
"Channel",
"instance",
"for",
"the",
"given",
"json"
] | train | https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/models.py#L153-L177 |
Pytwitcher/pytwitcherapi | src/pytwitcherapi/models.py | Stream.wrap_search | def wrap_search(cls, response):
"""Wrap the response from a stream search into instances
and return them
:param response: The response from searching a stream
:type response: :class:`requests.Response`
:returns: the new stream instances
:rtype: :class:`list` of :class:`stream`
:raises: None
"""
streams = []
json = response.json()
streamjsons = json['streams']
for j in streamjsons:
s = cls.wrap_json(j)
streams.append(s)
return streams | python | def wrap_search(cls, response):
"""Wrap the response from a stream search into instances
and return them
:param response: The response from searching a stream
:type response: :class:`requests.Response`
:returns: the new stream instances
:rtype: :class:`list` of :class:`stream`
:raises: None
"""
streams = []
json = response.json()
streamjsons = json['streams']
for j in streamjsons:
s = cls.wrap_json(j)
streams.append(s)
return streams | [
"def",
"wrap_search",
"(",
"cls",
",",
"response",
")",
":",
"streams",
"=",
"[",
"]",
"json",
"=",
"response",
".",
"json",
"(",
")",
"streamjsons",
"=",
"json",
"[",
"'streams'",
"]",
"for",
"j",
"in",
"streamjsons",
":",
"s",
"=",
"cls",
".",
"w... | Wrap the response from a stream search into instances
and return them
:param response: The response from searching a stream
:type response: :class:`requests.Response`
:returns: the new stream instances
:rtype: :class:`list` of :class:`stream`
:raises: None | [
"Wrap",
"the",
"response",
"from",
"a",
"stream",
"search",
"into",
"instances",
"and",
"return",
"them"
] | train | https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/models.py#L264-L280 |
Pytwitcher/pytwitcherapi | src/pytwitcherapi/models.py | Stream.wrap_get_stream | def wrap_get_stream(cls, response):
"""Wrap the response from getting a stream into an instance
and return it
:param response: The response from getting a stream
:type response: :class:`requests.Response`
:returns: the new stream instance
:rtype: :class:`list` of :class:`stream`
:raises: None
"""
json = response.json()
s = cls.wrap_json(json['stream'])
return s | python | def wrap_get_stream(cls, response):
"""Wrap the response from getting a stream into an instance
and return it
:param response: The response from getting a stream
:type response: :class:`requests.Response`
:returns: the new stream instance
:rtype: :class:`list` of :class:`stream`
:raises: None
"""
json = response.json()
s = cls.wrap_json(json['stream'])
return s | [
"def",
"wrap_get_stream",
"(",
"cls",
",",
"response",
")",
":",
"json",
"=",
"response",
".",
"json",
"(",
")",
"s",
"=",
"cls",
".",
"wrap_json",
"(",
"json",
"[",
"'stream'",
"]",
")",
"return",
"s"
] | Wrap the response from getting a stream into an instance
and return it
:param response: The response from getting a stream
:type response: :class:`requests.Response`
:returns: the new stream instance
:rtype: :class:`list` of :class:`stream`
:raises: None | [
"Wrap",
"the",
"response",
"from",
"getting",
"a",
"stream",
"into",
"an",
"instance",
"and",
"return",
"it"
] | train | https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/models.py#L283-L295 |
Pytwitcher/pytwitcherapi | src/pytwitcherapi/models.py | Stream.wrap_json | def wrap_json(cls, json):
"""Create a Stream instance for the given json
:param json: the dict with the information of the stream
:type json: :class:`dict` | None
:returns: the new stream instance
:rtype: :class:`Stream` | None
:raises: None
"""
if json is None:
return None
channel = Channel.wrap_json(json.get('channel'))
s = Stream(game=json.get('game'),
channel=channel,
twitchid=json.get('_id'),
viewers=json.get('viewers'),
preview=json.get('preview'))
return s | python | def wrap_json(cls, json):
"""Create a Stream instance for the given json
:param json: the dict with the information of the stream
:type json: :class:`dict` | None
:returns: the new stream instance
:rtype: :class:`Stream` | None
:raises: None
"""
if json is None:
return None
channel = Channel.wrap_json(json.get('channel'))
s = Stream(game=json.get('game'),
channel=channel,
twitchid=json.get('_id'),
viewers=json.get('viewers'),
preview=json.get('preview'))
return s | [
"def",
"wrap_json",
"(",
"cls",
",",
"json",
")",
":",
"if",
"json",
"is",
"None",
":",
"return",
"None",
"channel",
"=",
"Channel",
".",
"wrap_json",
"(",
"json",
".",
"get",
"(",
"'channel'",
")",
")",
"s",
"=",
"Stream",
"(",
"game",
"=",
"json"... | Create a Stream instance for the given json
:param json: the dict with the information of the stream
:type json: :class:`dict` | None
:returns: the new stream instance
:rtype: :class:`Stream` | None
:raises: None | [
"Create",
"a",
"Stream",
"instance",
"for",
"the",
"given",
"json"
] | train | https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/models.py#L298-L315 |
Pytwitcher/pytwitcherapi | src/pytwitcherapi/models.py | User.wrap_get_user | def wrap_get_user(cls, response):
"""Wrap the response from getting a user into an instance
and return it
:param response: The response from getting a user
:type response: :class:`requests.Response`
:returns: the new user instance
:rtype: :class:`list` of :class:`User`
:raises: None
"""
json = response.json()
u = cls.wrap_json(json)
return u | python | def wrap_get_user(cls, response):
"""Wrap the response from getting a user into an instance
and return it
:param response: The response from getting a user
:type response: :class:`requests.Response`
:returns: the new user instance
:rtype: :class:`list` of :class:`User`
:raises: None
"""
json = response.json()
u = cls.wrap_json(json)
return u | [
"def",
"wrap_get_user",
"(",
"cls",
",",
"response",
")",
":",
"json",
"=",
"response",
".",
"json",
"(",
")",
"u",
"=",
"cls",
".",
"wrap_json",
"(",
"json",
")",
"return",
"u"
] | Wrap the response from getting a user into an instance
and return it
:param response: The response from getting a user
:type response: :class:`requests.Response`
:returns: the new user instance
:rtype: :class:`list` of :class:`User`
:raises: None | [
"Wrap",
"the",
"response",
"from",
"getting",
"a",
"user",
"into",
"an",
"instance",
"and",
"return",
"it"
] | train | https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/models.py#L360-L372 |
Pytwitcher/pytwitcherapi | src/pytwitcherapi/models.py | User.wrap_json | def wrap_json(cls, json):
"""Create a User instance for the given json
:param json: the dict with the information of the user
:type json: :class:`dict` | None
:returns: the new user instance
:rtype: :class:`User`
:raises: None
"""
u = User(usertype=json['type'],
name=json['name'],
logo=json['logo'],
twitchid=json['_id'],
displayname=json['display_name'],
bio=json['bio'])
return u | python | def wrap_json(cls, json):
"""Create a User instance for the given json
:param json: the dict with the information of the user
:type json: :class:`dict` | None
:returns: the new user instance
:rtype: :class:`User`
:raises: None
"""
u = User(usertype=json['type'],
name=json['name'],
logo=json['logo'],
twitchid=json['_id'],
displayname=json['display_name'],
bio=json['bio'])
return u | [
"def",
"wrap_json",
"(",
"cls",
",",
"json",
")",
":",
"u",
"=",
"User",
"(",
"usertype",
"=",
"json",
"[",
"'type'",
"]",
",",
"name",
"=",
"json",
"[",
"'name'",
"]",
",",
"logo",
"=",
"json",
"[",
"'logo'",
"]",
",",
"twitchid",
"=",
"json",
... | Create a User instance for the given json
:param json: the dict with the information of the user
:type json: :class:`dict` | None
:returns: the new user instance
:rtype: :class:`User`
:raises: None | [
"Create",
"a",
"User",
"instance",
"for",
"the",
"given",
"json"
] | train | https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/models.py#L375-L390 |
Pytwitcher/pytwitcherapi | src/pytwitcherapi/chat/client.py | _wrap_execute_after | def _wrap_execute_after(funcname):
"""Warp the given method, so it gets executed by the reactor
Wrap a method of :data:`IRCCLient.out_connection`.
The returned function should be assigned to a :class:`irc.client.SimpleIRCClient` class.
:param funcname: the name of a :class:`irc.client.ServerConnection` method
:type funcname: :class:`str`
:returns: a new function, that executes the given one via :class:`irc.schedule.IScheduler.execute_after`
:raises: None
"""
def method(self, *args, **kwargs):
f = getattr(self.out_connection, funcname)
p = functools.partial(f, *args, **kwargs)
self.reactor.scheduler.execute_after(0, p)
method.__name__ = funcname
return method | python | def _wrap_execute_after(funcname):
"""Warp the given method, so it gets executed by the reactor
Wrap a method of :data:`IRCCLient.out_connection`.
The returned function should be assigned to a :class:`irc.client.SimpleIRCClient` class.
:param funcname: the name of a :class:`irc.client.ServerConnection` method
:type funcname: :class:`str`
:returns: a new function, that executes the given one via :class:`irc.schedule.IScheduler.execute_after`
:raises: None
"""
def method(self, *args, **kwargs):
f = getattr(self.out_connection, funcname)
p = functools.partial(f, *args, **kwargs)
self.reactor.scheduler.execute_after(0, p)
method.__name__ = funcname
return method | [
"def",
"_wrap_execute_after",
"(",
"funcname",
")",
":",
"def",
"method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"f",
"=",
"getattr",
"(",
"self",
".",
"out_connection",
",",
"funcname",
")",
"p",
"=",
"functools",
".",
"pa... | Warp the given method, so it gets executed by the reactor
Wrap a method of :data:`IRCCLient.out_connection`.
The returned function should be assigned to a :class:`irc.client.SimpleIRCClient` class.
:param funcname: the name of a :class:`irc.client.ServerConnection` method
:type funcname: :class:`str`
:returns: a new function, that executes the given one via :class:`irc.schedule.IScheduler.execute_after`
:raises: None | [
"Warp",
"the",
"given",
"method",
"so",
"it",
"gets",
"executed",
"by",
"the",
"reactor"
] | train | https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/chat/client.py#L100-L117 |
Pytwitcher/pytwitcherapi | src/pytwitcherapi/chat/client.py | add_serverconnection_methods | def add_serverconnection_methods(cls):
"""Add a bunch of methods to an :class:`irc.client.SimpleIRCClient`
to send commands and messages.
Basically it wraps a bunch of methdos from
:class:`irc.client.ServerConnection` to be
:meth:`irc.schedule.IScheduler.execute_after`.
That way, you can easily send, even if the IRCClient is running in
:class:`IRCClient.process_forever` in another thread.
On the plus side you can use positional and keyword arguments instead of just positional ones.
:param cls: The class to add the methods do.
:type cls: :class:`irc.client.SimpleIRCClient`
:returns: None
"""
methods = ['action', 'admin', 'cap', 'ctcp', 'ctcp_reply',
'globops', 'info', 'invite', 'ison', 'join',
'kick', 'links', 'list', 'lusers', 'mode',
'motd', 'names', 'nick', 'notice', 'oper', 'part',
'part', 'pass_', 'ping', 'pong', 'privmsg',
'privmsg_many', 'quit', 'send_raw', 'squit',
'stats', 'time', 'topic', 'trace', 'user', 'userhost',
'users', 'version', 'wallops', 'who', 'whois', 'whowas']
for m in methods:
method = _wrap_execute_after(m)
f = getattr(irc.client.ServerConnection, m)
method.__doc__ = f.__doc__
setattr(cls, method.__name__, method)
return cls | python | def add_serverconnection_methods(cls):
"""Add a bunch of methods to an :class:`irc.client.SimpleIRCClient`
to send commands and messages.
Basically it wraps a bunch of methdos from
:class:`irc.client.ServerConnection` to be
:meth:`irc.schedule.IScheduler.execute_after`.
That way, you can easily send, even if the IRCClient is running in
:class:`IRCClient.process_forever` in another thread.
On the plus side you can use positional and keyword arguments instead of just positional ones.
:param cls: The class to add the methods do.
:type cls: :class:`irc.client.SimpleIRCClient`
:returns: None
"""
methods = ['action', 'admin', 'cap', 'ctcp', 'ctcp_reply',
'globops', 'info', 'invite', 'ison', 'join',
'kick', 'links', 'list', 'lusers', 'mode',
'motd', 'names', 'nick', 'notice', 'oper', 'part',
'part', 'pass_', 'ping', 'pong', 'privmsg',
'privmsg_many', 'quit', 'send_raw', 'squit',
'stats', 'time', 'topic', 'trace', 'user', 'userhost',
'users', 'version', 'wallops', 'who', 'whois', 'whowas']
for m in methods:
method = _wrap_execute_after(m)
f = getattr(irc.client.ServerConnection, m)
method.__doc__ = f.__doc__
setattr(cls, method.__name__, method)
return cls | [
"def",
"add_serverconnection_methods",
"(",
"cls",
")",
":",
"methods",
"=",
"[",
"'action'",
",",
"'admin'",
",",
"'cap'",
",",
"'ctcp'",
",",
"'ctcp_reply'",
",",
"'globops'",
",",
"'info'",
",",
"'invite'",
",",
"'ison'",
",",
"'join'",
",",
"'kick'",
"... | Add a bunch of methods to an :class:`irc.client.SimpleIRCClient`
to send commands and messages.
Basically it wraps a bunch of methdos from
:class:`irc.client.ServerConnection` to be
:meth:`irc.schedule.IScheduler.execute_after`.
That way, you can easily send, even if the IRCClient is running in
:class:`IRCClient.process_forever` in another thread.
On the plus side you can use positional and keyword arguments instead of just positional ones.
:param cls: The class to add the methods do.
:type cls: :class:`irc.client.SimpleIRCClient`
:returns: None | [
"Add",
"a",
"bunch",
"of",
"methods",
"to",
"an",
":",
"class",
":",
"irc",
".",
"client",
".",
"SimpleIRCClient",
"to",
"send",
"commands",
"and",
"messages",
"."
] | train | https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/chat/client.py#L120-L149 |
Pytwitcher/pytwitcherapi | src/pytwitcherapi/chat/client.py | Reactor.process_forever | def process_forever(self, timeout=0.2):
"""Run an infinite loop, processing data from connections.
This method repeatedly calls process_once.
:param timeout: Parameter to pass to
:meth:`irc.client.Reactor.process_once`
:type timeout: :class:`float`
"""
# This loop should specifically *not* be mutex-locked.
# Otherwise no other thread would ever be able to change
# the shared state of a Reactor object running this function.
log.debug("process_forever(timeout=%s)", timeout)
self._looping.set()
while self._looping.is_set():
self.process_once(timeout) | python | def process_forever(self, timeout=0.2):
"""Run an infinite loop, processing data from connections.
This method repeatedly calls process_once.
:param timeout: Parameter to pass to
:meth:`irc.client.Reactor.process_once`
:type timeout: :class:`float`
"""
# This loop should specifically *not* be mutex-locked.
# Otherwise no other thread would ever be able to change
# the shared state of a Reactor object running this function.
log.debug("process_forever(timeout=%s)", timeout)
self._looping.set()
while self._looping.is_set():
self.process_once(timeout) | [
"def",
"process_forever",
"(",
"self",
",",
"timeout",
"=",
"0.2",
")",
":",
"# This loop should specifically *not* be mutex-locked.",
"# Otherwise no other thread would ever be able to change",
"# the shared state of a Reactor object running this function.",
"log",
".",
"debug",
"("... | Run an infinite loop, processing data from connections.
This method repeatedly calls process_once.
:param timeout: Parameter to pass to
:meth:`irc.client.Reactor.process_once`
:type timeout: :class:`float` | [
"Run",
"an",
"infinite",
"loop",
"processing",
"data",
"from",
"connections",
"."
] | train | https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/chat/client.py#L51-L66 |
Pytwitcher/pytwitcherapi | src/pytwitcherapi/chat/client.py | Reactor.shutdown | def shutdown(self):
"""Disconnect all connections and end the loop
:returns: None
:rtype: None
:raises: None
"""
log.debug('Shutting down %s' % self)
self.disconnect_all()
self._looping.clear() | python | def shutdown(self):
"""Disconnect all connections and end the loop
:returns: None
:rtype: None
:raises: None
"""
log.debug('Shutting down %s' % self)
self.disconnect_all()
self._looping.clear() | [
"def",
"shutdown",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"'Shutting down %s'",
"%",
"self",
")",
"self",
".",
"disconnect_all",
"(",
")",
"self",
".",
"_looping",
".",
"clear",
"(",
")"
] | Disconnect all connections and end the loop
:returns: None
:rtype: None
:raises: None | [
"Disconnect",
"all",
"connections",
"and",
"end",
"the",
"loop"
] | train | https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/chat/client.py#L68-L77 |
Pytwitcher/pytwitcherapi | src/pytwitcherapi/chat/client.py | Reactor3.server | def server(self, ):
"""Creates and returns a ServerConnection
:returns: a server connection
:rtype: :class:`connection.ServerConnection3`
:raises: None
"""
c = connection.ServerConnection3(self)
with self.mutex:
self.connections.append(c)
return c | python | def server(self, ):
"""Creates and returns a ServerConnection
:returns: a server connection
:rtype: :class:`connection.ServerConnection3`
:raises: None
"""
c = connection.ServerConnection3(self)
with self.mutex:
self.connections.append(c)
return c | [
"def",
"server",
"(",
"self",
",",
")",
":",
"c",
"=",
"connection",
".",
"ServerConnection3",
"(",
"self",
")",
"with",
"self",
".",
"mutex",
":",
"self",
".",
"connections",
".",
"append",
"(",
"c",
")",
"return",
"c"
] | Creates and returns a ServerConnection
:returns: a server connection
:rtype: :class:`connection.ServerConnection3`
:raises: None | [
"Creates",
"and",
"returns",
"a",
"ServerConnection"
] | train | https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/chat/client.py#L87-L97 |
tkf/rash | rash/init.py | init_run | def init_run(shell, no_daemon, daemon_options, daemon_outfile):
"""
Configure your shell.
Add the following line in your shell RC file and then you are
ready to go::
eval $(%(prog)s)
To check if your shell is supported, simply run::
%(prog)s --no-daemon
If you want to specify shell other than $SHELL, you can give
--shell option::
eval $(%(prog)s --shell zsh)
By default, this command also starts daemon in background to
automatically index shell history records. To not start daemon,
use --no-daemon option like this::
eval $(%(prog)s --no-daemon)
To see the other methods to launch the daemon process, see
``rash daemon --help``.
"""
import sys
from .__init__ import __version__
init_file = find_init(shell)
if os.path.exists(init_file):
sys.stdout.write(INIT_TEMPLATE.format(
file=init_file, version=__version__))
else:
raise RuntimeError(
"Shell '{0}' is not supported.".format(shell_name(shell)))
if not no_daemon:
from .daemon import start_daemon_in_subprocess
start_daemon_in_subprocess(daemon_options, daemon_outfile) | python | def init_run(shell, no_daemon, daemon_options, daemon_outfile):
"""
Configure your shell.
Add the following line in your shell RC file and then you are
ready to go::
eval $(%(prog)s)
To check if your shell is supported, simply run::
%(prog)s --no-daemon
If you want to specify shell other than $SHELL, you can give
--shell option::
eval $(%(prog)s --shell zsh)
By default, this command also starts daemon in background to
automatically index shell history records. To not start daemon,
use --no-daemon option like this::
eval $(%(prog)s --no-daemon)
To see the other methods to launch the daemon process, see
``rash daemon --help``.
"""
import sys
from .__init__ import __version__
init_file = find_init(shell)
if os.path.exists(init_file):
sys.stdout.write(INIT_TEMPLATE.format(
file=init_file, version=__version__))
else:
raise RuntimeError(
"Shell '{0}' is not supported.".format(shell_name(shell)))
if not no_daemon:
from .daemon import start_daemon_in_subprocess
start_daemon_in_subprocess(daemon_options, daemon_outfile) | [
"def",
"init_run",
"(",
"shell",
",",
"no_daemon",
",",
"daemon_options",
",",
"daemon_outfile",
")",
":",
"import",
"sys",
"from",
".",
"__init__",
"import",
"__version__",
"init_file",
"=",
"find_init",
"(",
"shell",
")",
"if",
"os",
".",
"path",
".",
"e... | Configure your shell.
Add the following line in your shell RC file and then you are
ready to go::
eval $(%(prog)s)
To check if your shell is supported, simply run::
%(prog)s --no-daemon
If you want to specify shell other than $SHELL, you can give
--shell option::
eval $(%(prog)s --shell zsh)
By default, this command also starts daemon in background to
automatically index shell history records. To not start daemon,
use --no-daemon option like this::
eval $(%(prog)s --no-daemon)
To see the other methods to launch the daemon process, see
``rash daemon --help``. | [
"Configure",
"your",
"shell",
"."
] | train | https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/init.py#L37-L77 |
alpha-xone/xone | xone/cache.py | cache_file | def cache_file(symbol, func, has_date, root, date_type='date'):
"""
Data file
Args:
symbol: symbol
func: use function to categorize data
has_date: contains date in data file
root: root path
date_type: parameters pass to utils.cur_time, [date, time, time_path, ...]
Returns:
str: date file
"""
cur_mod = sys.modules[func.__module__]
data_tz = getattr(cur_mod, 'DATA_TZ') if hasattr(cur_mod, 'DATA_TZ') else 'UTC'
cur_dt = utils.cur_time(typ=date_type, tz=data_tz, trading=False)
if has_date:
if hasattr(cur_mod, 'FILE_WITH_DATE'):
file_fmt = getattr(cur_mod, 'FILE_WITH_DATE')
else:
file_fmt = '{root}/{typ}/{symbol}/{cur_dt}.parq'
else:
if hasattr(cur_mod, 'FILE_NO_DATE'):
file_fmt = getattr(cur_mod, 'FILE_NO_DATE')
else:
file_fmt = '{root}/{typ}/{symbol}.parq'
return data_file(
file_fmt=file_fmt, root=root, cur_dt=cur_dt, typ=func.__name__, symbol=symbol
) | python | def cache_file(symbol, func, has_date, root, date_type='date'):
"""
Data file
Args:
symbol: symbol
func: use function to categorize data
has_date: contains date in data file
root: root path
date_type: parameters pass to utils.cur_time, [date, time, time_path, ...]
Returns:
str: date file
"""
cur_mod = sys.modules[func.__module__]
data_tz = getattr(cur_mod, 'DATA_TZ') if hasattr(cur_mod, 'DATA_TZ') else 'UTC'
cur_dt = utils.cur_time(typ=date_type, tz=data_tz, trading=False)
if has_date:
if hasattr(cur_mod, 'FILE_WITH_DATE'):
file_fmt = getattr(cur_mod, 'FILE_WITH_DATE')
else:
file_fmt = '{root}/{typ}/{symbol}/{cur_dt}.parq'
else:
if hasattr(cur_mod, 'FILE_NO_DATE'):
file_fmt = getattr(cur_mod, 'FILE_NO_DATE')
else:
file_fmt = '{root}/{typ}/{symbol}.parq'
return data_file(
file_fmt=file_fmt, root=root, cur_dt=cur_dt, typ=func.__name__, symbol=symbol
) | [
"def",
"cache_file",
"(",
"symbol",
",",
"func",
",",
"has_date",
",",
"root",
",",
"date_type",
"=",
"'date'",
")",
":",
"cur_mod",
"=",
"sys",
".",
"modules",
"[",
"func",
".",
"__module__",
"]",
"data_tz",
"=",
"getattr",
"(",
"cur_mod",
",",
"'DATA... | Data file
Args:
symbol: symbol
func: use function to categorize data
has_date: contains date in data file
root: root path
date_type: parameters pass to utils.cur_time, [date, time, time_path, ...]
Returns:
str: date file | [
"Data",
"file"
] | train | https://github.com/alpha-xone/xone/blob/68534a30f7f1760b220ba58040be3927f7dfbcf4/xone/cache.py#L12-L43 |
alpha-xone/xone | xone/cache.py | update_data | def update_data(func):
"""
Decorator to save data more easily. Use parquet as data format
Args:
func: function to load data from data source
Returns:
wrapped function
"""
default = dict([
(param.name, param.default)
for param in inspect.signature(func).parameters.values()
if param.default != getattr(inspect, '_empty')
])
@wraps(func)
def wrapper(*args, **kwargs):
default.update(kwargs)
kwargs.update(default)
cur_mod = sys.modules[func.__module__]
logger = logs.get_logger(name_or_func=f'{cur_mod.__name__}.{func.__name__}', types='stream')
root_path = cur_mod.DATA_PATH
date_type = kwargs.pop('date_type', 'date')
save_static = kwargs.pop('save_static', True)
save_dynamic = kwargs.pop('save_dynamic', True)
symbol = kwargs.get('symbol')
file_kw = dict(func=func, symbol=symbol, root=root_path, date_type=date_type)
d_file = cache_file(has_date=True, **file_kw)
s_file = cache_file(has_date=False, **file_kw)
cached = kwargs.pop('cached', False)
if cached and save_static and files.exists(s_file):
logger.info(f'Reading data from {s_file} ...')
return pd.read_parquet(s_file)
data = func(*args, **kwargs)
if save_static:
files.create_folder(s_file, is_file=True)
save_data(data=data, file_fmt=s_file, append=False)
logger.info(f'Saved data file to {s_file} ...')
if save_dynamic:
drop_dups = kwargs.pop('drop_dups', None)
files.create_folder(d_file, is_file=True)
save_data(data=data, file_fmt=d_file, append=True, drop_dups=drop_dups)
logger.info(f'Saved data file to {d_file} ...')
return data
return wrapper | python | def update_data(func):
"""
Decorator to save data more easily. Use parquet as data format
Args:
func: function to load data from data source
Returns:
wrapped function
"""
default = dict([
(param.name, param.default)
for param in inspect.signature(func).parameters.values()
if param.default != getattr(inspect, '_empty')
])
@wraps(func)
def wrapper(*args, **kwargs):
default.update(kwargs)
kwargs.update(default)
cur_mod = sys.modules[func.__module__]
logger = logs.get_logger(name_or_func=f'{cur_mod.__name__}.{func.__name__}', types='stream')
root_path = cur_mod.DATA_PATH
date_type = kwargs.pop('date_type', 'date')
save_static = kwargs.pop('save_static', True)
save_dynamic = kwargs.pop('save_dynamic', True)
symbol = kwargs.get('symbol')
file_kw = dict(func=func, symbol=symbol, root=root_path, date_type=date_type)
d_file = cache_file(has_date=True, **file_kw)
s_file = cache_file(has_date=False, **file_kw)
cached = kwargs.pop('cached', False)
if cached and save_static and files.exists(s_file):
logger.info(f'Reading data from {s_file} ...')
return pd.read_parquet(s_file)
data = func(*args, **kwargs)
if save_static:
files.create_folder(s_file, is_file=True)
save_data(data=data, file_fmt=s_file, append=False)
logger.info(f'Saved data file to {s_file} ...')
if save_dynamic:
drop_dups = kwargs.pop('drop_dups', None)
files.create_folder(d_file, is_file=True)
save_data(data=data, file_fmt=d_file, append=True, drop_dups=drop_dups)
logger.info(f'Saved data file to {d_file} ...')
return data
return wrapper | [
"def",
"update_data",
"(",
"func",
")",
":",
"default",
"=",
"dict",
"(",
"[",
"(",
"param",
".",
"name",
",",
"param",
".",
"default",
")",
"for",
"param",
"in",
"inspect",
".",
"signature",
"(",
"func",
")",
".",
"parameters",
".",
"values",
"(",
... | Decorator to save data more easily. Use parquet as data format
Args:
func: function to load data from data source
Returns:
wrapped function | [
"Decorator",
"to",
"save",
"data",
"more",
"easily",
".",
"Use",
"parquet",
"as",
"data",
"format"
] | train | https://github.com/alpha-xone/xone/blob/68534a30f7f1760b220ba58040be3927f7dfbcf4/xone/cache.py#L46-L99 |
alpha-xone/xone | xone/cache.py | save_data | def save_data(data, file_fmt, append=False, drop_dups=None, info=None, **kwargs):
"""
Save data to file
Args:
data: pd.DataFrame
file_fmt: data file format in terms of f-strings
append: if append data to existing data
drop_dups: list, drop duplicates in columns
info: dict, infomation to be hashed and passed to f-strings
**kwargs: additional parameters for f-strings
Examples:
>>> data = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b'])
>>> # save_data(
>>> # data, '{ROOT}/daily/{typ}.parq',
>>> # ROOT='tests/data', typ='earnings'
>>> # )
"""
d_file = data_file(file_fmt=file_fmt, info=info, **kwargs)
if append and files.exists(d_file):
data = pd.DataFrame(pd.concat([pd.read_parquet(d_file), data], sort=False))
if drop_dups is not None:
data.drop_duplicates(subset=utils.tolist(drop_dups), inplace=True)
if not data.empty: data.to_parquet(d_file)
return data | python | def save_data(data, file_fmt, append=False, drop_dups=None, info=None, **kwargs):
"""
Save data to file
Args:
data: pd.DataFrame
file_fmt: data file format in terms of f-strings
append: if append data to existing data
drop_dups: list, drop duplicates in columns
info: dict, infomation to be hashed and passed to f-strings
**kwargs: additional parameters for f-strings
Examples:
>>> data = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b'])
>>> # save_data(
>>> # data, '{ROOT}/daily/{typ}.parq',
>>> # ROOT='tests/data', typ='earnings'
>>> # )
"""
d_file = data_file(file_fmt=file_fmt, info=info, **kwargs)
if append and files.exists(d_file):
data = pd.DataFrame(pd.concat([pd.read_parquet(d_file), data], sort=False))
if drop_dups is not None:
data.drop_duplicates(subset=utils.tolist(drop_dups), inplace=True)
if not data.empty: data.to_parquet(d_file)
return data | [
"def",
"save_data",
"(",
"data",
",",
"file_fmt",
",",
"append",
"=",
"False",
",",
"drop_dups",
"=",
"None",
",",
"info",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"d_file",
"=",
"data_file",
"(",
"file_fmt",
"=",
"file_fmt",
",",
"info",
"=",... | Save data to file
Args:
data: pd.DataFrame
file_fmt: data file format in terms of f-strings
append: if append data to existing data
drop_dups: list, drop duplicates in columns
info: dict, infomation to be hashed and passed to f-strings
**kwargs: additional parameters for f-strings
Examples:
>>> data = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b'])
>>> # save_data(
>>> # data, '{ROOT}/daily/{typ}.parq',
>>> # ROOT='tests/data', typ='earnings'
>>> # ) | [
"Save",
"data",
"to",
"file"
] | train | https://github.com/alpha-xone/xone/blob/68534a30f7f1760b220ba58040be3927f7dfbcf4/xone/cache.py#L102-L128 |
alpha-xone/xone | xone/cache.py | data_file | def data_file(file_fmt, info=None, **kwargs):
"""
Data file name for given infomation
Args:
file_fmt: file format in terms of f-strings
info: dict, to be hashed and then pass to f-string using 'hash_key'
these info will also be passed to f-strings
**kwargs: arguments for f-strings
Returns:
str: data file name
"""
if isinstance(info, dict):
kwargs['hash_key'] = hashlib.sha256(json.dumps(info).encode('utf-8')).hexdigest()
kwargs.update(info)
return utils.fstr(fmt=file_fmt, **kwargs) | python | def data_file(file_fmt, info=None, **kwargs):
"""
Data file name for given infomation
Args:
file_fmt: file format in terms of f-strings
info: dict, to be hashed and then pass to f-string using 'hash_key'
these info will also be passed to f-strings
**kwargs: arguments for f-strings
Returns:
str: data file name
"""
if isinstance(info, dict):
kwargs['hash_key'] = hashlib.sha256(json.dumps(info).encode('utf-8')).hexdigest()
kwargs.update(info)
return utils.fstr(fmt=file_fmt, **kwargs) | [
"def",
"data_file",
"(",
"file_fmt",
",",
"info",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"info",
",",
"dict",
")",
":",
"kwargs",
"[",
"'hash_key'",
"]",
"=",
"hashlib",
".",
"sha256",
"(",
"json",
".",
"dumps",
"(... | Data file name for given infomation
Args:
file_fmt: file format in terms of f-strings
info: dict, to be hashed and then pass to f-string using 'hash_key'
these info will also be passed to f-strings
**kwargs: arguments for f-strings
Returns:
str: data file name | [
"Data",
"file",
"name",
"for",
"given",
"infomation"
] | train | https://github.com/alpha-xone/xone/blob/68534a30f7f1760b220ba58040be3927f7dfbcf4/xone/cache.py#L131-L148 |
alpha-xone/xone | xone/plots.py | plot_multi | def plot_multi(data, cols=None, spacing=.06, color_map=None, plot_kw=None, **kwargs):
"""
Plot data with multiple scaels together
Args:
data: DataFrame of data
cols: columns to be plotted
spacing: spacing between legends
color_map: customized colors in map
plot_kw: kwargs for each plot
**kwargs: kwargs for the first plot
Returns:
ax for plot
Examples:
>>> import pandas as pd
>>> import numpy as np
>>>
>>> idx = range(5)
>>> data = pd.DataFrame(dict(a=np.exp(idx), b=idx), index=idx)
>>> # plot_multi(data=data, cols=['a', 'b'], plot_kw=[dict(style='.-'), dict()])
"""
import matplotlib.pyplot as plt
from pandas import plotting
if cols is None: cols = data.columns
if plot_kw is None: plot_kw = [{}] * len(cols)
if len(cols) == 0: return
num_colors = len(utils.flatten(cols))
# Get default color style from pandas
colors = getattr(getattr(plotting, '_style'), '_get_standard_colors')(num_colors=num_colors)
if color_map is None: color_map = dict()
fig = plt.figure()
ax, lines, labels, c_idx = None, [], [], 0
for n, col in enumerate(cols):
if isinstance(col, (list, tuple)):
ylabel = ' / '.join(cols[n])
color = [
color_map.get(cols[n][_ - c_idx], colors[_ % len(colors)])
for _ in range(c_idx, c_idx + len(cols[n]))
]
c_idx += len(col)
else:
ylabel = col
color = color_map.get(col, colors[c_idx % len(colors)])
c_idx += 1
if 'color' in plot_kw[n]: color = plot_kw[n].pop('color')
if ax is None:
# First y-axes
legend = plot_kw[0].pop('legend', kwargs.pop('legend', False))
ax = data.loc[:, col].plot(
label=col, color=color, legend=legend, zorder=n, **plot_kw[0], **kwargs
)
ax.set_ylabel(ylabel=ylabel)
line, label = ax.get_legend_handles_labels()
ax.spines['left'].set_edgecolor('#D5C4A1')
ax.spines['left'].set_alpha(.5)
else:
# Multiple y-axes
legend = plot_kw[n].pop('legend', False)
ax_new = ax.twinx()
ax_new.spines['right'].set_position(('axes', 1 + spacing * (n - 1)))
data.loc[:, col].plot(
ax=ax_new, label=col, color=color, legend=legend, zorder=n, **plot_kw[n]
)
ax_new.set_ylabel(ylabel=ylabel)
line, label = ax_new.get_legend_handles_labels()
ax_new.spines['right'].set_edgecolor('#D5C4A1')
ax_new.spines['right'].set_alpha(.5)
ax_new.grid(False)
# Proper legend position
lines += line
labels += label
fig.legend(lines, labels, loc=8, prop=dict(), ncol=num_colors).set_zorder(len(cols))
ax.set_xlabel(' \n ')
return ax | python | def plot_multi(data, cols=None, spacing=.06, color_map=None, plot_kw=None, **kwargs):
"""
Plot data with multiple scaels together
Args:
data: DataFrame of data
cols: columns to be plotted
spacing: spacing between legends
color_map: customized colors in map
plot_kw: kwargs for each plot
**kwargs: kwargs for the first plot
Returns:
ax for plot
Examples:
>>> import pandas as pd
>>> import numpy as np
>>>
>>> idx = range(5)
>>> data = pd.DataFrame(dict(a=np.exp(idx), b=idx), index=idx)
>>> # plot_multi(data=data, cols=['a', 'b'], plot_kw=[dict(style='.-'), dict()])
"""
import matplotlib.pyplot as plt
from pandas import plotting
if cols is None: cols = data.columns
if plot_kw is None: plot_kw = [{}] * len(cols)
if len(cols) == 0: return
num_colors = len(utils.flatten(cols))
# Get default color style from pandas
colors = getattr(getattr(plotting, '_style'), '_get_standard_colors')(num_colors=num_colors)
if color_map is None: color_map = dict()
fig = plt.figure()
ax, lines, labels, c_idx = None, [], [], 0
for n, col in enumerate(cols):
if isinstance(col, (list, tuple)):
ylabel = ' / '.join(cols[n])
color = [
color_map.get(cols[n][_ - c_idx], colors[_ % len(colors)])
for _ in range(c_idx, c_idx + len(cols[n]))
]
c_idx += len(col)
else:
ylabel = col
color = color_map.get(col, colors[c_idx % len(colors)])
c_idx += 1
if 'color' in plot_kw[n]: color = plot_kw[n].pop('color')
if ax is None:
# First y-axes
legend = plot_kw[0].pop('legend', kwargs.pop('legend', False))
ax = data.loc[:, col].plot(
label=col, color=color, legend=legend, zorder=n, **plot_kw[0], **kwargs
)
ax.set_ylabel(ylabel=ylabel)
line, label = ax.get_legend_handles_labels()
ax.spines['left'].set_edgecolor('#D5C4A1')
ax.spines['left'].set_alpha(.5)
else:
# Multiple y-axes
legend = plot_kw[n].pop('legend', False)
ax_new = ax.twinx()
ax_new.spines['right'].set_position(('axes', 1 + spacing * (n - 1)))
data.loc[:, col].plot(
ax=ax_new, label=col, color=color, legend=legend, zorder=n, **plot_kw[n]
)
ax_new.set_ylabel(ylabel=ylabel)
line, label = ax_new.get_legend_handles_labels()
ax_new.spines['right'].set_edgecolor('#D5C4A1')
ax_new.spines['right'].set_alpha(.5)
ax_new.grid(False)
# Proper legend position
lines += line
labels += label
fig.legend(lines, labels, loc=8, prop=dict(), ncol=num_colors).set_zorder(len(cols))
ax.set_xlabel(' \n ')
return ax | [
"def",
"plot_multi",
"(",
"data",
",",
"cols",
"=",
"None",
",",
"spacing",
"=",
".06",
",",
"color_map",
"=",
"None",
",",
"plot_kw",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"from",
"pandas... | Plot data with multiple scaels together
Args:
data: DataFrame of data
cols: columns to be plotted
spacing: spacing between legends
color_map: customized colors in map
plot_kw: kwargs for each plot
**kwargs: kwargs for the first plot
Returns:
ax for plot
Examples:
>>> import pandas as pd
>>> import numpy as np
>>>
>>> idx = range(5)
>>> data = pd.DataFrame(dict(a=np.exp(idx), b=idx), index=idx)
>>> # plot_multi(data=data, cols=['a', 'b'], plot_kw=[dict(style='.-'), dict()]) | [
"Plot",
"data",
"with",
"multiple",
"scaels",
"together"
] | train | https://github.com/alpha-xone/xone/blob/68534a30f7f1760b220ba58040be3927f7dfbcf4/xone/plots.py#L4-L87 |
alpha-xone/xone | xone/plots.py | plot_h | def plot_h(data, cols, wspace=.1, plot_kw=None, **kwargs):
"""
Plot horizontally
Args:
data: DataFrame of data
cols: columns to be plotted
wspace: spacing between plots
plot_kw: kwargs for each plot
**kwargs: kwargs for the whole plot
Returns:
axes for plots
Examples:
>>> import pandas as pd
>>> import numpy as np
>>>
>>> idx = range(5)
>>> data = pd.DataFrame(dict(a=np.exp(idx), b=idx), index=idx)
>>> # plot_h(data=data, cols=['a', 'b'], wspace=.2, plot_kw=[dict(style='.-'), dict()])
"""
import matplotlib.pyplot as plt
if plot_kw is None: plot_kw = [dict()] * len(cols)
_, axes = plt.subplots(nrows=1, ncols=len(cols), **kwargs)
plt.subplots_adjust(wspace=wspace)
for n, col in enumerate(cols):
data.loc[:, col].plot(ax=axes[n], **plot_kw[n])
return axes | python | def plot_h(data, cols, wspace=.1, plot_kw=None, **kwargs):
"""
Plot horizontally
Args:
data: DataFrame of data
cols: columns to be plotted
wspace: spacing between plots
plot_kw: kwargs for each plot
**kwargs: kwargs for the whole plot
Returns:
axes for plots
Examples:
>>> import pandas as pd
>>> import numpy as np
>>>
>>> idx = range(5)
>>> data = pd.DataFrame(dict(a=np.exp(idx), b=idx), index=idx)
>>> # plot_h(data=data, cols=['a', 'b'], wspace=.2, plot_kw=[dict(style='.-'), dict()])
"""
import matplotlib.pyplot as plt
if plot_kw is None: plot_kw = [dict()] * len(cols)
_, axes = plt.subplots(nrows=1, ncols=len(cols), **kwargs)
plt.subplots_adjust(wspace=wspace)
for n, col in enumerate(cols):
data.loc[:, col].plot(ax=axes[n], **plot_kw[n])
return axes | [
"def",
"plot_h",
"(",
"data",
",",
"cols",
",",
"wspace",
"=",
".1",
",",
"plot_kw",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"if",
"plot_kw",
"is",
"None",
":",
"plot_kw",
"=",
"[",
"dict"... | Plot horizontally
Args:
data: DataFrame of data
cols: columns to be plotted
wspace: spacing between plots
plot_kw: kwargs for each plot
**kwargs: kwargs for the whole plot
Returns:
axes for plots
Examples:
>>> import pandas as pd
>>> import numpy as np
>>>
>>> idx = range(5)
>>> data = pd.DataFrame(dict(a=np.exp(idx), b=idx), index=idx)
>>> # plot_h(data=data, cols=['a', 'b'], wspace=.2, plot_kw=[dict(style='.-'), dict()]) | [
"Plot",
"horizontally"
] | train | https://github.com/alpha-xone/xone/blob/68534a30f7f1760b220ba58040be3927f7dfbcf4/xone/plots.py#L90-L121 |
tkf/rash | rash/index.py | index_run | def index_run(record_path, keep_json, check_duplicate):
"""
Convert raw JSON records into sqlite3 DB.
Normally RASH launches a daemon that takes care of indexing.
See ``rash daemon --help``.
"""
from .config import ConfigStore
from .indexer import Indexer
cfstore = ConfigStore()
indexer = Indexer(cfstore, check_duplicate, keep_json, record_path)
indexer.index_all() | python | def index_run(record_path, keep_json, check_duplicate):
"""
Convert raw JSON records into sqlite3 DB.
Normally RASH launches a daemon that takes care of indexing.
See ``rash daemon --help``.
"""
from .config import ConfigStore
from .indexer import Indexer
cfstore = ConfigStore()
indexer = Indexer(cfstore, check_duplicate, keep_json, record_path)
indexer.index_all() | [
"def",
"index_run",
"(",
"record_path",
",",
"keep_json",
",",
"check_duplicate",
")",
":",
"from",
".",
"config",
"import",
"ConfigStore",
"from",
".",
"indexer",
"import",
"Indexer",
"cfstore",
"=",
"ConfigStore",
"(",
")",
"indexer",
"=",
"Indexer",
"(",
... | Convert raw JSON records into sqlite3 DB.
Normally RASH launches a daemon that takes care of indexing.
See ``rash daemon --help``. | [
"Convert",
"raw",
"JSON",
"records",
"into",
"sqlite3",
"DB",
"."
] | train | https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/index.py#L17-L29 |
pebble/libpebble2 | libpebble2/services/data_logging.py | DataLoggingService.list | def list(self):
"""
List all available data logging sessions
"""
# We have to open this queue before we make the request, to ensure we don't miss the response.
queue = self._pebble.get_endpoint_queue(DataLogging)
self._pebble.send_packet(DataLogging(data=DataLoggingReportOpenSessions(sessions=[])))
sessions = []
while True:
try:
result = queue.get(timeout=2).data
except TimeoutError:
break
if isinstance(result, DataLoggingDespoolOpenSession):
self._pebble.send_packet(DataLogging(data=DataLoggingACK(
session_id=result.session_id)))
sessions.append(result.__dict__)
queue.close()
return sessions | python | def list(self):
"""
List all available data logging sessions
"""
# We have to open this queue before we make the request, to ensure we don't miss the response.
queue = self._pebble.get_endpoint_queue(DataLogging)
self._pebble.send_packet(DataLogging(data=DataLoggingReportOpenSessions(sessions=[])))
sessions = []
while True:
try:
result = queue.get(timeout=2).data
except TimeoutError:
break
if isinstance(result, DataLoggingDespoolOpenSession):
self._pebble.send_packet(DataLogging(data=DataLoggingACK(
session_id=result.session_id)))
sessions.append(result.__dict__)
queue.close()
return sessions | [
"def",
"list",
"(",
"self",
")",
":",
"# We have to open this queue before we make the request, to ensure we don't miss the response.",
"queue",
"=",
"self",
".",
"_pebble",
".",
"get_endpoint_queue",
"(",
"DataLogging",
")",
"self",
".",
"_pebble",
".",
"send_packet",
"(... | List all available data logging sessions | [
"List",
"all",
"available",
"data",
"logging",
"sessions"
] | train | https://github.com/pebble/libpebble2/blob/23e2eb92cfc084e6f9e8c718711ac994ef606d18/libpebble2/services/data_logging.py#L23-L45 |
pebble/libpebble2 | libpebble2/services/data_logging.py | DataLoggingService.download | def download(self, session_id):
"""
Download a specific session.
Returns (session_info, data)
"""
# We have to open this queue before we make the request, to ensure we don't miss the response.
queue = self._pebble.get_endpoint_queue(DataLogging)
# First, we need to open up all sessions
self._pebble.send_packet(DataLogging(data=DataLoggingReportOpenSessions(sessions=[])))
session = None
while True:
try:
result = queue.get(timeout=2).data
except TimeoutError:
break
if isinstance(result, DataLoggingDespoolOpenSession):
self._pebble.send_packet(DataLogging(data=DataLoggingACK(
session_id=result.session_id)))
if session is None and result.session_id == session_id:
session = result
if session is None:
queue.close()
return (None, None)
# -----------------------------------------------------------------------------
# Request an empty of this session
logger.info("Requesting empty of session {}".format(session_id))
self._pebble.send_packet(DataLogging(data=DataLoggingEmptySession(session_id=session_id)))
data = None
timeout_count = 0
while True:
logger.debug("Looping again. Time: {}".format(datetime.datetime.now()))
try:
result = queue.get(timeout=5).data
timeout_count = 0
except TimeoutError:
logger.debug("Got timeout error Time: {}".format(datetime.datetime.now()))
timeout_count += 1
if timeout_count >= 2:
break
else:
self._pebble.send_packet(DataLogging(data=DataLoggingEmptySession(
session_id=session_id)))
continue
if isinstance(result, DataLoggingDespoolSendData):
if result.session_id != session_id:
self._pebble.send_packet(DataLogging(
data=DataLoggingNACK(session_id=result.session_id)))
else:
logger.info("Received {} bytes of data: {}".format(len(result.data), result))
if data is None:
data = result.data
else:
data += result.data
self._pebble.send_packet(DataLogging(
data=DataLoggingACK(session_id=session_id)))
queue.close()
return (session, data) | python | def download(self, session_id):
"""
Download a specific session.
Returns (session_info, data)
"""
# We have to open this queue before we make the request, to ensure we don't miss the response.
queue = self._pebble.get_endpoint_queue(DataLogging)
# First, we need to open up all sessions
self._pebble.send_packet(DataLogging(data=DataLoggingReportOpenSessions(sessions=[])))
session = None
while True:
try:
result = queue.get(timeout=2).data
except TimeoutError:
break
if isinstance(result, DataLoggingDespoolOpenSession):
self._pebble.send_packet(DataLogging(data=DataLoggingACK(
session_id=result.session_id)))
if session is None and result.session_id == session_id:
session = result
if session is None:
queue.close()
return (None, None)
# -----------------------------------------------------------------------------
# Request an empty of this session
logger.info("Requesting empty of session {}".format(session_id))
self._pebble.send_packet(DataLogging(data=DataLoggingEmptySession(session_id=session_id)))
data = None
timeout_count = 0
while True:
logger.debug("Looping again. Time: {}".format(datetime.datetime.now()))
try:
result = queue.get(timeout=5).data
timeout_count = 0
except TimeoutError:
logger.debug("Got timeout error Time: {}".format(datetime.datetime.now()))
timeout_count += 1
if timeout_count >= 2:
break
else:
self._pebble.send_packet(DataLogging(data=DataLoggingEmptySession(
session_id=session_id)))
continue
if isinstance(result, DataLoggingDespoolSendData):
if result.session_id != session_id:
self._pebble.send_packet(DataLogging(
data=DataLoggingNACK(session_id=result.session_id)))
else:
logger.info("Received {} bytes of data: {}".format(len(result.data), result))
if data is None:
data = result.data
else:
data += result.data
self._pebble.send_packet(DataLogging(
data=DataLoggingACK(session_id=session_id)))
queue.close()
return (session, data) | [
"def",
"download",
"(",
"self",
",",
"session_id",
")",
":",
"# We have to open this queue before we make the request, to ensure we don't miss the response.",
"queue",
"=",
"self",
".",
"_pebble",
".",
"get_endpoint_queue",
"(",
"DataLogging",
")",
"# First, we need to open up ... | Download a specific session.
Returns (session_info, data) | [
"Download",
"a",
"specific",
"session",
".",
"Returns",
"(",
"session_info",
"data",
")"
] | train | https://github.com/pebble/libpebble2/blob/23e2eb92cfc084e6f9e8c718711ac994ef606d18/libpebble2/services/data_logging.py#L48-L113 |
pebble/libpebble2 | libpebble2/services/data_logging.py | DataLoggingService.get_send_enable | def get_send_enable(self):
"""
Return true if sending of sessions is enabled on the watch
"""
# We have to open this queue before we make the request, to ensure we don't miss the response.
queue = self._pebble.get_endpoint_queue(DataLogging)
self._pebble.send_packet(DataLogging(data=DataLoggingGetSendEnableRequest()))
enabled = False
while True:
result = queue.get().data
if isinstance(result, DataLoggingGetSendEnableResponse):
enabled = result.enabled
break
queue.close()
return enabled | python | def get_send_enable(self):
"""
Return true if sending of sessions is enabled on the watch
"""
# We have to open this queue before we make the request, to ensure we don't miss the response.
queue = self._pebble.get_endpoint_queue(DataLogging)
self._pebble.send_packet(DataLogging(data=DataLoggingGetSendEnableRequest()))
enabled = False
while True:
result = queue.get().data
if isinstance(result, DataLoggingGetSendEnableResponse):
enabled = result.enabled
break
queue.close()
return enabled | [
"def",
"get_send_enable",
"(",
"self",
")",
":",
"# We have to open this queue before we make the request, to ensure we don't miss the response.",
"queue",
"=",
"self",
".",
"_pebble",
".",
"get_endpoint_queue",
"(",
"DataLogging",
")",
"self",
".",
"_pebble",
".",
"send_pa... | Return true if sending of sessions is enabled on the watch | [
"Return",
"true",
"if",
"sending",
"of",
"sessions",
"is",
"enabled",
"on",
"the",
"watch"
] | train | https://github.com/pebble/libpebble2/blob/23e2eb92cfc084e6f9e8c718711ac994ef606d18/libpebble2/services/data_logging.py#L116-L133 |
pebble/libpebble2 | libpebble2/services/data_logging.py | DataLoggingService.set_send_enable | def set_send_enable(self, setting):
"""
Set the send enable setting on the watch
"""
self._pebble.send_packet(DataLogging(data=DataLoggingSetSendEnable(enabled=setting))) | python | def set_send_enable(self, setting):
"""
Set the send enable setting on the watch
"""
self._pebble.send_packet(DataLogging(data=DataLoggingSetSendEnable(enabled=setting))) | [
"def",
"set_send_enable",
"(",
"self",
",",
"setting",
")",
":",
"self",
".",
"_pebble",
".",
"send_packet",
"(",
"DataLogging",
"(",
"data",
"=",
"DataLoggingSetSendEnable",
"(",
"enabled",
"=",
"setting",
")",
")",
")"
] | Set the send enable setting on the watch | [
"Set",
"the",
"send",
"enable",
"setting",
"on",
"the",
"watch"
] | train | https://github.com/pebble/libpebble2/blob/23e2eb92cfc084e6f9e8c718711ac994ef606d18/libpebble2/services/data_logging.py#L136-L140 |
tkf/rash | rash/log.py | loglevel | def loglevel(level):
"""
Convert any representation of `level` to an int appropriately.
:type level: int or str
:rtype: int
>>> loglevel('DEBUG') == logging.DEBUG
True
>>> loglevel(10)
10
>>> loglevel(None)
Traceback (most recent call last):
...
ValueError: None is not a proper log level.
"""
if isinstance(level, str):
level = getattr(logging, level.upper())
elif isinstance(level, int):
pass
else:
raise ValueError('{0!r} is not a proper log level.'.format(level))
return level | python | def loglevel(level):
"""
Convert any representation of `level` to an int appropriately.
:type level: int or str
:rtype: int
>>> loglevel('DEBUG') == logging.DEBUG
True
>>> loglevel(10)
10
>>> loglevel(None)
Traceback (most recent call last):
...
ValueError: None is not a proper log level.
"""
if isinstance(level, str):
level = getattr(logging, level.upper())
elif isinstance(level, int):
pass
else:
raise ValueError('{0!r} is not a proper log level.'.format(level))
return level | [
"def",
"loglevel",
"(",
"level",
")",
":",
"if",
"isinstance",
"(",
"level",
",",
"str",
")",
":",
"level",
"=",
"getattr",
"(",
"logging",
",",
"level",
".",
"upper",
"(",
")",
")",
"elif",
"isinstance",
"(",
"level",
",",
"int",
")",
":",
"pass",... | Convert any representation of `level` to an int appropriately.
:type level: int or str
:rtype: int
>>> loglevel('DEBUG') == logging.DEBUG
True
>>> loglevel(10)
10
>>> loglevel(None)
Traceback (most recent call last):
...
ValueError: None is not a proper log level. | [
"Convert",
"any",
"representation",
"of",
"level",
"to",
"an",
"int",
"appropriately",
"."
] | train | https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/log.py#L20-L43 |
tkf/rash | rash/log.py | setup_daemon_log_file | def setup_daemon_log_file(cfstore):
"""
Attach file handler to RASH logger.
:type cfstore: rash.config.ConfigStore
"""
level = loglevel(cfstore.daemon_log_level)
handler = logging.FileHandler(filename=cfstore.daemon_log_path)
handler.setLevel(level)
logger.setLevel(level)
logger.addHandler(handler) | python | def setup_daemon_log_file(cfstore):
"""
Attach file handler to RASH logger.
:type cfstore: rash.config.ConfigStore
"""
level = loglevel(cfstore.daemon_log_level)
handler = logging.FileHandler(filename=cfstore.daemon_log_path)
handler.setLevel(level)
logger.setLevel(level)
logger.addHandler(handler) | [
"def",
"setup_daemon_log_file",
"(",
"cfstore",
")",
":",
"level",
"=",
"loglevel",
"(",
"cfstore",
".",
"daemon_log_level",
")",
"handler",
"=",
"logging",
".",
"FileHandler",
"(",
"filename",
"=",
"cfstore",
".",
"daemon_log_path",
")",
"handler",
".",
"setL... | Attach file handler to RASH logger.
:type cfstore: rash.config.ConfigStore | [
"Attach",
"file",
"handler",
"to",
"RASH",
"logger",
"."
] | train | https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/log.py#L49-L60 |
mathiasertl/xmpp-backends | xmpp_backends/xmlrpclib.py | dumps | def dumps(params, methodname=None, methodresponse=None, encoding=None,
allow_none=0, utf8_encoding='standard'):
"""data [,options] -> marshalled data
Convert an argument tuple or a Fault instance to an XML-RPC
request (or response, if the methodresponse option is used).
In addition to the data object, the following options can be given
as keyword arguments:
methodname: the method name for a methodCall packet
methodresponse: true to create a methodResponse packet.
If this option is used with a tuple, the tuple must be
a singleton (i.e. it can contain only one element).
encoding: the packet encoding (default is UTF-8)
All 8-bit strings in the data structure are assumed to use the
packet encoding. Unicode strings are automatically converted,
where necessary.
"""
assert isinstance(params, TupleType) or isinstance(params, Fault),\
"argument must be tuple or Fault instance"
if isinstance(params, Fault):
methodresponse = 1
elif methodresponse and isinstance(params, TupleType):
assert len(params) == 1, "response tuple must be a singleton"
if not encoding:
encoding = "utf-8"
if FastMarshaller:
m = FastMarshaller(encoding)
else:
m = Marshaller(encoding, allow_none)
data = m.dumps(params)
if encoding != "utf-8":
xmlheader = "<?xml version='1.0' encoding='%s'?>\n" % str(encoding)
else:
xmlheader = "<?xml version='1.0'?>\n" # utf-8 is default
# standard XML-RPC wrappings
if methodname:
# a method call
if not isinstance(methodname, StringType):
methodname = methodname.encode(encoding)
data = (
xmlheader,
"<methodCall>\n"
"<methodName>", methodname, "</methodName>\n",
data,
"</methodCall>\n"
)
elif methodresponse:
# a method response, or a fault structure
data = (
xmlheader,
"<methodResponse>\n",
data,
"</methodResponse>\n"
)
else:
return data # return as is
return string.join(data, "") | python | def dumps(params, methodname=None, methodresponse=None, encoding=None,
allow_none=0, utf8_encoding='standard'):
"""data [,options] -> marshalled data
Convert an argument tuple or a Fault instance to an XML-RPC
request (or response, if the methodresponse option is used).
In addition to the data object, the following options can be given
as keyword arguments:
methodname: the method name for a methodCall packet
methodresponse: true to create a methodResponse packet.
If this option is used with a tuple, the tuple must be
a singleton (i.e. it can contain only one element).
encoding: the packet encoding (default is UTF-8)
All 8-bit strings in the data structure are assumed to use the
packet encoding. Unicode strings are automatically converted,
where necessary.
"""
assert isinstance(params, TupleType) or isinstance(params, Fault),\
"argument must be tuple or Fault instance"
if isinstance(params, Fault):
methodresponse = 1
elif methodresponse and isinstance(params, TupleType):
assert len(params) == 1, "response tuple must be a singleton"
if not encoding:
encoding = "utf-8"
if FastMarshaller:
m = FastMarshaller(encoding)
else:
m = Marshaller(encoding, allow_none)
data = m.dumps(params)
if encoding != "utf-8":
xmlheader = "<?xml version='1.0' encoding='%s'?>\n" % str(encoding)
else:
xmlheader = "<?xml version='1.0'?>\n" # utf-8 is default
# standard XML-RPC wrappings
if methodname:
# a method call
if not isinstance(methodname, StringType):
methodname = methodname.encode(encoding)
data = (
xmlheader,
"<methodCall>\n"
"<methodName>", methodname, "</methodName>\n",
data,
"</methodCall>\n"
)
elif methodresponse:
# a method response, or a fault structure
data = (
xmlheader,
"<methodResponse>\n",
data,
"</methodResponse>\n"
)
else:
return data # return as is
return string.join(data, "") | [
"def",
"dumps",
"(",
"params",
",",
"methodname",
"=",
"None",
",",
"methodresponse",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"allow_none",
"=",
"0",
",",
"utf8_encoding",
"=",
"'standard'",
")",
":",
"assert",
"isinstance",
"(",
"params",
",",
"... | data [,options] -> marshalled data
Convert an argument tuple or a Fault instance to an XML-RPC
request (or response, if the methodresponse option is used).
In addition to the data object, the following options can be given
as keyword arguments:
methodname: the method name for a methodCall packet
methodresponse: true to create a methodResponse packet.
If this option is used with a tuple, the tuple must be
a singleton (i.e. it can contain only one element).
encoding: the packet encoding (default is UTF-8)
All 8-bit strings in the data structure are assumed to use the
packet encoding. Unicode strings are automatically converted,
where necessary. | [
"data",
"[",
"options",
"]",
"-",
">",
"marshalled",
"data"
] | train | https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/xmlrpclib.py#L1139-L1207 |
mathiasertl/xmpp-backends | xmpp_backends/xmlrpclib.py | gzip_encode | def gzip_encode(data):
"""data -> gzip encoded data
Encode data using the gzip content encoding as described in RFC 1952
"""
if not gzip:
raise NotImplementedError
f = StringIO.StringIO()
gzf = gzip.GzipFile(mode="wb", fileobj=f, compresslevel=1)
gzf.write(data)
gzf.close()
encoded = f.getvalue()
f.close()
return encoded | python | def gzip_encode(data):
"""data -> gzip encoded data
Encode data using the gzip content encoding as described in RFC 1952
"""
if not gzip:
raise NotImplementedError
f = StringIO.StringIO()
gzf = gzip.GzipFile(mode="wb", fileobj=f, compresslevel=1)
gzf.write(data)
gzf.close()
encoded = f.getvalue()
f.close()
return encoded | [
"def",
"gzip_encode",
"(",
"data",
")",
":",
"if",
"not",
"gzip",
":",
"raise",
"NotImplementedError",
"f",
"=",
"StringIO",
".",
"StringIO",
"(",
")",
"gzf",
"=",
"gzip",
".",
"GzipFile",
"(",
"mode",
"=",
"\"wb\"",
",",
"fileobj",
"=",
"f",
",",
"c... | data -> gzip encoded data
Encode data using the gzip content encoding as described in RFC 1952 | [
"data",
"-",
">",
"gzip",
"encoded",
"data"
] | train | https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/xmlrpclib.py#L1240-L1253 |
mathiasertl/xmpp-backends | xmpp_backends/xmlrpclib.py | gzip_decode | def gzip_decode(data, max_decode=20971520):
"""gzip encoded data -> unencoded data
Decode data using the gzip content encoding as described in RFC 1952
"""
if not gzip:
raise NotImplementedError
f = StringIO.StringIO(data)
gzf = gzip.GzipFile(mode="rb", fileobj=f)
try:
if max_decode < 0: # no limit
decoded = gzf.read()
else:
decoded = gzf.read(max_decode + 1)
except IOError:
raise ValueError("invalid data")
f.close()
gzf.close()
if max_decode >= 0 and len(decoded) > max_decode:
raise ValueError("max gzipped payload length exceeded")
return decoded | python | def gzip_decode(data, max_decode=20971520):
"""gzip encoded data -> unencoded data
Decode data using the gzip content encoding as described in RFC 1952
"""
if not gzip:
raise NotImplementedError
f = StringIO.StringIO(data)
gzf = gzip.GzipFile(mode="rb", fileobj=f)
try:
if max_decode < 0: # no limit
decoded = gzf.read()
else:
decoded = gzf.read(max_decode + 1)
except IOError:
raise ValueError("invalid data")
f.close()
gzf.close()
if max_decode >= 0 and len(decoded) > max_decode:
raise ValueError("max gzipped payload length exceeded")
return decoded | [
"def",
"gzip_decode",
"(",
"data",
",",
"max_decode",
"=",
"20971520",
")",
":",
"if",
"not",
"gzip",
":",
"raise",
"NotImplementedError",
"f",
"=",
"StringIO",
".",
"StringIO",
"(",
"data",
")",
"gzf",
"=",
"gzip",
".",
"GzipFile",
"(",
"mode",
"=",
"... | gzip encoded data -> unencoded data
Decode data using the gzip content encoding as described in RFC 1952 | [
"gzip",
"encoded",
"data",
"-",
">",
"unencoded",
"data"
] | train | https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/xmlrpclib.py#L1267-L1287 |
staticdev/django-sorting-bootstrap | sorting_bootstrap/templatetags/sorting_tags.py | result_headers | def result_headers(context, cl):
"""
Generates the list column headers.
"""
for i, field_name in enumerate(cl.list_display):
text, attr = label_for_field(field_name, cl.model, return_attr=True)
if attr:
# Potentially not sortable
# if the field is the action checkbox: no sorting and special class
if field_name == 'action_checkbox':
yield {
"text": text,
"class_attrib": mark_safe(' class="action-checkbox-column"'),
"sortable": False,
}
continue
# if other_fields like Edit, Visualize, etc:
# Not sortable
# yield {
# "text": text,
# "class_attrib": format_html(' class="column-{0}"', field_name),
# "sortable": False,
# }
# continue
# OK, it is sortable if we got this far
th_classes = ['sortable', 'column-{0}'.format(field_name)]
ascending = None
is_sorted = False
# Is it currently being sorted on?
if context.get('current_sort_field') == str(i + 1):
is_sorted = True
ascending = False
th_classes.append('sorted descending')
elif context.get('current_sort_field') == '-'+str(i + 1):
is_sorted = True
ascending = True
th_classes.append('sorted ascending')
if 'request' in context:
url = context['request'].path
else:
url = "./"
### TODO: when start using action_checkbox use i instead of i + 1. This +1 is to correct enumerate index
# builds url
url += "?sort_by="
if ascending is False:
url += "-"
url += str(i + 1)
if 'getsortvars' in context:
extra_vars = context['getsortvars']
else:
if 'request' in context:
request = context['request']
getvars = request.GET.copy()
if 'sort_by' in getvars:
del getvars['sort_by']
if len(getvars.keys()) > 0:
context['getsortvars'] = "&%s" % getvars.urlencode()
else:
context['getsortvars'] = ''
extra_vars = context['getsortvars']
# append other vars to url
url += extra_vars
yield {
"text": text,
"url": url,
"sortable": True,
"sorted": is_sorted,
"ascending": ascending,
"class_attrib": format_html(' class="{0}"', ' '.join(th_classes)) if th_classes else '',
} | python | def result_headers(context, cl):
"""
Generates the list column headers.
"""
for i, field_name in enumerate(cl.list_display):
text, attr = label_for_field(field_name, cl.model, return_attr=True)
if attr:
# Potentially not sortable
# if the field is the action checkbox: no sorting and special class
if field_name == 'action_checkbox':
yield {
"text": text,
"class_attrib": mark_safe(' class="action-checkbox-column"'),
"sortable": False,
}
continue
# if other_fields like Edit, Visualize, etc:
# Not sortable
# yield {
# "text": text,
# "class_attrib": format_html(' class="column-{0}"', field_name),
# "sortable": False,
# }
# continue
# OK, it is sortable if we got this far
th_classes = ['sortable', 'column-{0}'.format(field_name)]
ascending = None
is_sorted = False
# Is it currently being sorted on?
if context.get('current_sort_field') == str(i + 1):
is_sorted = True
ascending = False
th_classes.append('sorted descending')
elif context.get('current_sort_field') == '-'+str(i + 1):
is_sorted = True
ascending = True
th_classes.append('sorted ascending')
if 'request' in context:
url = context['request'].path
else:
url = "./"
### TODO: when start using action_checkbox use i instead of i + 1. This +1 is to correct enumerate index
# builds url
url += "?sort_by="
if ascending is False:
url += "-"
url += str(i + 1)
if 'getsortvars' in context:
extra_vars = context['getsortvars']
else:
if 'request' in context:
request = context['request']
getvars = request.GET.copy()
if 'sort_by' in getvars:
del getvars['sort_by']
if len(getvars.keys()) > 0:
context['getsortvars'] = "&%s" % getvars.urlencode()
else:
context['getsortvars'] = ''
extra_vars = context['getsortvars']
# append other vars to url
url += extra_vars
yield {
"text": text,
"url": url,
"sortable": True,
"sorted": is_sorted,
"ascending": ascending,
"class_attrib": format_html(' class="{0}"', ' '.join(th_classes)) if th_classes else '',
} | [
"def",
"result_headers",
"(",
"context",
",",
"cl",
")",
":",
"for",
"i",
",",
"field_name",
"in",
"enumerate",
"(",
"cl",
".",
"list_display",
")",
":",
"text",
",",
"attr",
"=",
"label_for_field",
"(",
"field_name",
",",
"cl",
".",
"model",
",",
"ret... | Generates the list column headers. | [
"Generates",
"the",
"list",
"column",
"headers",
"."
] | train | https://github.com/staticdev/django-sorting-bootstrap/blob/cfdc6e671b1b57aad04e44b041b9df10ee8288d3/sorting_bootstrap/templatetags/sorting_tags.py#L16-L94 |
staticdev/django-sorting-bootstrap | sorting_bootstrap/templatetags/sorting_tags.py | sort_headers | def sort_headers(context, cl):
"""
Displays the headers and data list together
"""
headers = list(result_headers(context, cl))
sorted_fields = False
for h in headers:
if h['sortable'] and h['sorted']:
sorted_fields = True
return {'cl': cl,
'result_headers': headers,
'sorted_fields': sorted_fields} | python | def sort_headers(context, cl):
"""
Displays the headers and data list together
"""
headers = list(result_headers(context, cl))
sorted_fields = False
for h in headers:
if h['sortable'] and h['sorted']:
sorted_fields = True
return {'cl': cl,
'result_headers': headers,
'sorted_fields': sorted_fields} | [
"def",
"sort_headers",
"(",
"context",
",",
"cl",
")",
":",
"headers",
"=",
"list",
"(",
"result_headers",
"(",
"context",
",",
"cl",
")",
")",
"sorted_fields",
"=",
"False",
"for",
"h",
"in",
"headers",
":",
"if",
"h",
"[",
"'sortable'",
"]",
"and",
... | Displays the headers and data list together | [
"Displays",
"the",
"headers",
"and",
"data",
"list",
"together"
] | train | https://github.com/staticdev/django-sorting-bootstrap/blob/cfdc6e671b1b57aad04e44b041b9df10ee8288d3/sorting_bootstrap/templatetags/sorting_tags.py#L98-L109 |
staticdev/django-sorting-bootstrap | sorting_bootstrap/templatetags/sorting_tags.py | sort_link | def sort_link(context, text, sort_field, visible_name=None):
"""Usage: {% sort_link "text" "field_name" %}
Usage: {% sort_link "text" "field_name" "Visible name" %}
"""
sorted_fields = False
ascending = None
class_attrib = 'sortable'
orig_sort_field = sort_field
if context.get('current_sort_field') == sort_field:
sort_field = '-%s' % sort_field
visible_name = '-%s' % (visible_name or orig_sort_field)
sorted_fields = True
ascending = False
class_attrib += ' sorted descending'
elif context.get('current_sort_field') == '-'+sort_field:
visible_name = '%s' % (visible_name or orig_sort_field)
sorted_fields = True
ascending = True
class_attrib += ' sorted ascending'
if visible_name:
if 'request' in context:
request = context['request']
request.session[visible_name] = sort_field
# builds url
if 'request' in context:
url = context['request'].path
else:
url = "./"
url += "?sort_by="
if visible_name is None:
url += sort_field
else:
url += visible_name
if 'getsortvars' in context:
extra_vars = context['getsortvars']
else:
if 'request' in context:
request = context['request']
getvars = request.GET.copy()
if 'sort_by' in getvars:
del getvars['sort_by']
if len(getvars.keys()) > 0:
context['getsortvars'] = "&%s" % getvars.urlencode()
else:
context['getsortvars'] = ''
extra_vars = context['getsortvars']
# append other vars to url
url += extra_vars
return {
'text': text, 'url': url, 'ascending': ascending, 'sorted_fields': sorted_fields, 'class_attrib': class_attrib
} | python | def sort_link(context, text, sort_field, visible_name=None):
"""Usage: {% sort_link "text" "field_name" %}
Usage: {% sort_link "text" "field_name" "Visible name" %}
"""
sorted_fields = False
ascending = None
class_attrib = 'sortable'
orig_sort_field = sort_field
if context.get('current_sort_field') == sort_field:
sort_field = '-%s' % sort_field
visible_name = '-%s' % (visible_name or orig_sort_field)
sorted_fields = True
ascending = False
class_attrib += ' sorted descending'
elif context.get('current_sort_field') == '-'+sort_field:
visible_name = '%s' % (visible_name or orig_sort_field)
sorted_fields = True
ascending = True
class_attrib += ' sorted ascending'
if visible_name:
if 'request' in context:
request = context['request']
request.session[visible_name] = sort_field
# builds url
if 'request' in context:
url = context['request'].path
else:
url = "./"
url += "?sort_by="
if visible_name is None:
url += sort_field
else:
url += visible_name
if 'getsortvars' in context:
extra_vars = context['getsortvars']
else:
if 'request' in context:
request = context['request']
getvars = request.GET.copy()
if 'sort_by' in getvars:
del getvars['sort_by']
if len(getvars.keys()) > 0:
context['getsortvars'] = "&%s" % getvars.urlencode()
else:
context['getsortvars'] = ''
extra_vars = context['getsortvars']
# append other vars to url
url += extra_vars
return {
'text': text, 'url': url, 'ascending': ascending, 'sorted_fields': sorted_fields, 'class_attrib': class_attrib
} | [
"def",
"sort_link",
"(",
"context",
",",
"text",
",",
"sort_field",
",",
"visible_name",
"=",
"None",
")",
":",
"sorted_fields",
"=",
"False",
"ascending",
"=",
"None",
"class_attrib",
"=",
"'sortable'",
"orig_sort_field",
"=",
"sort_field",
"if",
"context",
"... | Usage: {% sort_link "text" "field_name" %}
Usage: {% sort_link "text" "field_name" "Visible name" %} | [
"Usage",
":",
"{",
"%",
"sort_link",
"text",
"field_name",
"%",
"}",
"Usage",
":",
"{",
"%",
"sort_link",
"text",
"field_name",
"Visible",
"name",
"%",
"}"
] | train | https://github.com/staticdev/django-sorting-bootstrap/blob/cfdc6e671b1b57aad04e44b041b9df10ee8288d3/sorting_bootstrap/templatetags/sorting_tags.py#L112-L168 |
staticdev/django-sorting-bootstrap | sorting_bootstrap/templatetags/sorting_tags.py | auto_sort | def auto_sort(parser, token):
"usage: {% auto_sort queryset %}"
try:
tag_name, queryset = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError("{0} tag requires a single argument".format(token.contents.split()[0]))
return SortedQuerysetNode(queryset) | python | def auto_sort(parser, token):
"usage: {% auto_sort queryset %}"
try:
tag_name, queryset = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError("{0} tag requires a single argument".format(token.contents.split()[0]))
return SortedQuerysetNode(queryset) | [
"def",
"auto_sort",
"(",
"parser",
",",
"token",
")",
":",
"try",
":",
"tag_name",
",",
"queryset",
"=",
"token",
".",
"split_contents",
"(",
")",
"except",
"ValueError",
":",
"raise",
"template",
".",
"TemplateSyntaxError",
"(",
"\"{0} tag requires a single arg... | usage: {% auto_sort queryset %} | [
"usage",
":",
"{",
"%",
"auto_sort",
"queryset",
"%",
"}"
] | train | https://github.com/staticdev/django-sorting-bootstrap/blob/cfdc6e671b1b57aad04e44b041b9df10ee8288d3/sorting_bootstrap/templatetags/sorting_tags.py#L175-L181 |
Pytwitcher/pytwitcherapi | src/pytwitcherapi/chat/message.py | Tag.from_str | def from_str(cls, tagstring):
"""Create a tag by parsing the tag of a message
:param tagstring: A tag string described in the irc protocol
:type tagstring: :class:`str`
:returns: A tag
:rtype: :class:`Tag`
:raises: None
"""
m = cls._parse_regexp.match(tagstring)
return cls(name=m.group('name'), value=m.group('value'), vendor=m.group('vendor')) | python | def from_str(cls, tagstring):
"""Create a tag by parsing the tag of a message
:param tagstring: A tag string described in the irc protocol
:type tagstring: :class:`str`
:returns: A tag
:rtype: :class:`Tag`
:raises: None
"""
m = cls._parse_regexp.match(tagstring)
return cls(name=m.group('name'), value=m.group('value'), vendor=m.group('vendor')) | [
"def",
"from_str",
"(",
"cls",
",",
"tagstring",
")",
":",
"m",
"=",
"cls",
".",
"_parse_regexp",
".",
"match",
"(",
"tagstring",
")",
"return",
"cls",
"(",
"name",
"=",
"m",
".",
"group",
"(",
"'name'",
")",
",",
"value",
"=",
"m",
".",
"group",
... | Create a tag by parsing the tag of a message
:param tagstring: A tag string described in the irc protocol
:type tagstring: :class:`str`
:returns: A tag
:rtype: :class:`Tag`
:raises: None | [
"Create",
"a",
"tag",
"by",
"parsing",
"the",
"tag",
"of",
"a",
"message"
] | train | https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/chat/message.py#L61-L71 |
Pytwitcher/pytwitcherapi | src/pytwitcherapi/chat/message.py | Emote.from_str | def from_str(cls, emotestr):
"""Create an emote from the emote tag key
:param emotestr: the tag key, e.g. ``'123:0-4'``
:type emotestr: :class:`str`
:returns: an emote
:rtype: :class:`Emote`
:raises: None
"""
emoteid, occstr = emotestr.split(':')
occurences = []
for occ in occstr.split(','):
start, end = occ.split('-')
occurences.append((int(start), int(end)))
return cls(int(emoteid), occurences) | python | def from_str(cls, emotestr):
"""Create an emote from the emote tag key
:param emotestr: the tag key, e.g. ``'123:0-4'``
:type emotestr: :class:`str`
:returns: an emote
:rtype: :class:`Emote`
:raises: None
"""
emoteid, occstr = emotestr.split(':')
occurences = []
for occ in occstr.split(','):
start, end = occ.split('-')
occurences.append((int(start), int(end)))
return cls(int(emoteid), occurences) | [
"def",
"from_str",
"(",
"cls",
",",
"emotestr",
")",
":",
"emoteid",
",",
"occstr",
"=",
"emotestr",
".",
"split",
"(",
"':'",
")",
"occurences",
"=",
"[",
"]",
"for",
"occ",
"in",
"occstr",
".",
"split",
"(",
"','",
")",
":",
"start",
",",
"end",
... | Create an emote from the emote tag key
:param emotestr: the tag key, e.g. ``'123:0-4'``
:type emotestr: :class:`str`
:returns: an emote
:rtype: :class:`Emote`
:raises: None | [
"Create",
"an",
"emote",
"from",
"the",
"emote",
"tag",
"key"
] | train | https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/chat/message.py#L113-L127 |
Pytwitcher/pytwitcherapi | src/pytwitcherapi/chat/message.py | Message3.from_event | def from_event(cls, event):
"""Create a message from an event
:param event: the event that was received of type ``pubmsg`` or ``privmsg``
:type event: :class:`Event3`
:returns: a message that resembles the event
:rtype: :class:`Message3`
:raises: None
"""
source = Chatter(event.source)
return cls(source, event.target, event.arguments[0], event.tags) | python | def from_event(cls, event):
"""Create a message from an event
:param event: the event that was received of type ``pubmsg`` or ``privmsg``
:type event: :class:`Event3`
:returns: a message that resembles the event
:rtype: :class:`Message3`
:raises: None
"""
source = Chatter(event.source)
return cls(source, event.target, event.arguments[0], event.tags) | [
"def",
"from_event",
"(",
"cls",
",",
"event",
")",
":",
"source",
"=",
"Chatter",
"(",
"event",
".",
"source",
")",
"return",
"cls",
"(",
"source",
",",
"event",
".",
"target",
",",
"event",
".",
"arguments",
"[",
"0",
"]",
",",
"event",
".",
"tag... | Create a message from an event
:param event: the event that was received of type ``pubmsg`` or ``privmsg``
:type event: :class:`Event3`
:returns: a message that resembles the event
:rtype: :class:`Message3`
:raises: None | [
"Create",
"a",
"message",
"from",
"an",
"event"
] | train | https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/chat/message.py#L265-L275 |
Pytwitcher/pytwitcherapi | src/pytwitcherapi/chat/message.py | Message3.set_tags | def set_tags(self, tags):
"""For every known tag, set the appropriate attribute.
Known tags are:
:color: The user color
:emotes: A list of emotes
:subscriber: True, if subscriber
:turbo: True, if turbo user
:user_type: None, mod, staff, global_mod, admin
:param tags: a list of tags
:type tags: :class:`list` of :class:`Tag` | None
:returns: None
:rtype: None
:raises: None
"""
if tags is None:
return
attrmap = {'color': 'color', 'emotes': 'emotes',
'subscriber': 'subscriber',
'turbo': 'turbo', 'user-type': 'user_type'}
for t in tags:
attr = attrmap.get(t.name)
if not attr:
continue
else:
setattr(self, attr, t.value) | python | def set_tags(self, tags):
"""For every known tag, set the appropriate attribute.
Known tags are:
:color: The user color
:emotes: A list of emotes
:subscriber: True, if subscriber
:turbo: True, if turbo user
:user_type: None, mod, staff, global_mod, admin
:param tags: a list of tags
:type tags: :class:`list` of :class:`Tag` | None
:returns: None
:rtype: None
:raises: None
"""
if tags is None:
return
attrmap = {'color': 'color', 'emotes': 'emotes',
'subscriber': 'subscriber',
'turbo': 'turbo', 'user-type': 'user_type'}
for t in tags:
attr = attrmap.get(t.name)
if not attr:
continue
else:
setattr(self, attr, t.value) | [
"def",
"set_tags",
"(",
"self",
",",
"tags",
")",
":",
"if",
"tags",
"is",
"None",
":",
"return",
"attrmap",
"=",
"{",
"'color'",
":",
"'color'",
",",
"'emotes'",
":",
"'emotes'",
",",
"'subscriber'",
":",
"'subscriber'",
",",
"'turbo'",
":",
"'turbo'",
... | For every known tag, set the appropriate attribute.
Known tags are:
:color: The user color
:emotes: A list of emotes
:subscriber: True, if subscriber
:turbo: True, if turbo user
:user_type: None, mod, staff, global_mod, admin
:param tags: a list of tags
:type tags: :class:`list` of :class:`Tag` | None
:returns: None
:rtype: None
:raises: None | [
"For",
"every",
"known",
"tag",
"set",
"the",
"appropriate",
"attribute",
"."
] | train | https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/chat/message.py#L292-L319 |
Pytwitcher/pytwitcherapi | src/pytwitcherapi/chat/message.py | Message3.emotes | def emotes(self, emotes):
"""Set the emotes
:param emotes: the key of the emotes tag
:type emotes: :class:`str`
:returns: None
:rtype: None
:raises: None
"""
if emotes is None:
self._emotes = []
return
es = []
for estr in emotes.split('/'):
es.append(Emote.from_str(estr))
self._emotes = es | python | def emotes(self, emotes):
"""Set the emotes
:param emotes: the key of the emotes tag
:type emotes: :class:`str`
:returns: None
:rtype: None
:raises: None
"""
if emotes is None:
self._emotes = []
return
es = []
for estr in emotes.split('/'):
es.append(Emote.from_str(estr))
self._emotes = es | [
"def",
"emotes",
"(",
"self",
",",
"emotes",
")",
":",
"if",
"emotes",
"is",
"None",
":",
"self",
".",
"_emotes",
"=",
"[",
"]",
"return",
"es",
"=",
"[",
"]",
"for",
"estr",
"in",
"emotes",
".",
"split",
"(",
"'/'",
")",
":",
"es",
".",
"appen... | Set the emotes
:param emotes: the key of the emotes tag
:type emotes: :class:`str`
:returns: None
:rtype: None
:raises: None | [
"Set",
"the",
"emotes"
] | train | https://github.com/Pytwitcher/pytwitcherapi/blob/d53ac5ad5ca113ecb7da542e8cdcbbf8c762b336/src/pytwitcherapi/chat/message.py#L332-L347 |
avalente/appmetrics | appmetrics/statistics.py | sum | def sum(data, start=0):
"""sum(data [, start]) -> value
Return a high-precision sum of the given numeric data. If optional
argument ``start`` is given, it is added to the total. If ``data`` is
empty, ``start`` (defaulting to 0) is returned.
"""
n, d = exact_ratio(start)
T = type(start)
partials = {d: n} # map {denominator: sum of numerators}
# Micro-optimizations.
coerce_types_ = coerce_types
exact_ratio_ = exact_ratio
partials_get = partials.get
# Add numerators for each denominator, and track the "current" type.
for x in data:
T = coerce_types_(T, type(x))
n, d = exact_ratio_(x)
partials[d] = partials_get(d, 0) + n
if None in partials:
assert issubclass(T, (float, Decimal))
assert not isfinite(partials[None])
return T(partials[None])
total = Fraction()
for d, n in sorted(partials.items()):
total += Fraction(n, d)
if issubclass(T, int):
assert total.denominator == 1
return T(total.numerator)
if issubclass(T, Decimal):
return T(total.numerator) / total.denominator
return T(total) | python | def sum(data, start=0):
"""sum(data [, start]) -> value
Return a high-precision sum of the given numeric data. If optional
argument ``start`` is given, it is added to the total. If ``data`` is
empty, ``start`` (defaulting to 0) is returned.
"""
n, d = exact_ratio(start)
T = type(start)
partials = {d: n} # map {denominator: sum of numerators}
# Micro-optimizations.
coerce_types_ = coerce_types
exact_ratio_ = exact_ratio
partials_get = partials.get
# Add numerators for each denominator, and track the "current" type.
for x in data:
T = coerce_types_(T, type(x))
n, d = exact_ratio_(x)
partials[d] = partials_get(d, 0) + n
if None in partials:
assert issubclass(T, (float, Decimal))
assert not isfinite(partials[None])
return T(partials[None])
total = Fraction()
for d, n in sorted(partials.items()):
total += Fraction(n, d)
if issubclass(T, int):
assert total.denominator == 1
return T(total.numerator)
if issubclass(T, Decimal):
return T(total.numerator) / total.denominator
return T(total) | [
"def",
"sum",
"(",
"data",
",",
"start",
"=",
"0",
")",
":",
"n",
",",
"d",
"=",
"exact_ratio",
"(",
"start",
")",
"T",
"=",
"type",
"(",
"start",
")",
"partials",
"=",
"{",
"d",
":",
"n",
"}",
"# map {denominator: sum of numerators}",
"# Micro-optimiz... | sum(data [, start]) -> value
Return a high-precision sum of the given numeric data. If optional
argument ``start`` is given, it is added to the total. If ``data`` is
empty, ``start`` (defaulting to 0) is returned. | [
"sum",
"(",
"data",
"[",
"start",
"]",
")",
"-",
">",
"value"
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L49-L80 |
avalente/appmetrics | appmetrics/statistics.py | exact_ratio | def exact_ratio(x):
"""Convert Real number x exactly to (numerator, denominator) pair.
x is expected to be an int, Fraction, Decimal or float.
"""
try:
try:
# int, Fraction
return x.numerator, x.denominator
except AttributeError:
# float
try:
return x.as_integer_ratio()
except AttributeError:
# Decimal
try:
return decimal_to_ratio(x)
except AttributeError:
msg = "can't convert type '{}' to numerator/denominator"
raise TypeError(msg.format(type(x).__name__))
except (OverflowError, ValueError):
# INF or NAN
return (x, None) | python | def exact_ratio(x):
"""Convert Real number x exactly to (numerator, denominator) pair.
x is expected to be an int, Fraction, Decimal or float.
"""
try:
try:
# int, Fraction
return x.numerator, x.denominator
except AttributeError:
# float
try:
return x.as_integer_ratio()
except AttributeError:
# Decimal
try:
return decimal_to_ratio(x)
except AttributeError:
msg = "can't convert type '{}' to numerator/denominator"
raise TypeError(msg.format(type(x).__name__))
except (OverflowError, ValueError):
# INF or NAN
return (x, None) | [
"def",
"exact_ratio",
"(",
"x",
")",
":",
"try",
":",
"try",
":",
"# int, Fraction",
"return",
"x",
".",
"numerator",
",",
"x",
".",
"denominator",
"except",
"AttributeError",
":",
"# float",
"try",
":",
"return",
"x",
".",
"as_integer_ratio",
"(",
")",
... | Convert Real number x exactly to (numerator, denominator) pair.
x is expected to be an int, Fraction, Decimal or float. | [
"Convert",
"Real",
"number",
"x",
"exactly",
"to",
"(",
"numerator",
"denominator",
")",
"pair",
"."
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L83-L105 |
avalente/appmetrics | appmetrics/statistics.py | decimal_to_ratio | def decimal_to_ratio(d):
"""Convert Decimal d to exact integer ratio (numerator, denominator).
"""
sign, digits, exp = d.as_tuple()
if exp in ('F', 'n', 'N'): # INF, NAN, sNAN
assert not d.is_finite()
raise ValueError
num = 0
for digit in digits:
num = num * 10 + digit
if sign:
num = -num
den = 10 ** -exp
return (num, den) | python | def decimal_to_ratio(d):
"""Convert Decimal d to exact integer ratio (numerator, denominator).
"""
sign, digits, exp = d.as_tuple()
if exp in ('F', 'n', 'N'): # INF, NAN, sNAN
assert not d.is_finite()
raise ValueError
num = 0
for digit in digits:
num = num * 10 + digit
if sign:
num = -num
den = 10 ** -exp
return (num, den) | [
"def",
"decimal_to_ratio",
"(",
"d",
")",
":",
"sign",
",",
"digits",
",",
"exp",
"=",
"d",
".",
"as_tuple",
"(",
")",
"if",
"exp",
"in",
"(",
"'F'",
",",
"'n'",
",",
"'N'",
")",
":",
"# INF, NAN, sNAN",
"assert",
"not",
"d",
".",
"is_finite",
"(",... | Convert Decimal d to exact integer ratio (numerator, denominator). | [
"Convert",
"Decimal",
"d",
"to",
"exact",
"integer",
"ratio",
"(",
"numerator",
"denominator",
")",
"."
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L109-L122 |
avalente/appmetrics | appmetrics/statistics.py | coerce_types | def coerce_types(T1, T2):
"""Coerce types T1 and T2 to a common type.
Coercion is performed according to this table, where "N/A" means
that a TypeError exception is raised.
+----------+-----------+-----------+-----------+----------+
| | int | Fraction | Decimal | float |
+----------+-----------+-----------+-----------+----------+
| int | int | Fraction | Decimal | float |
| Fraction | Fraction | Fraction | N/A | float |
| Decimal | Decimal | N/A | Decimal | float |
| float | float | float | float | float |
+----------+-----------+-----------+-----------+----------+
Subclasses trump their parent class; two subclasses of the same
base class will be coerced to the second of the two.
"""
# Get the common/fast cases out of the way first.
if T1 is T2: return T1
if T1 is int: return T2
if T2 is int: return T1
# Subclasses trump their parent class.
if issubclass(T2, T1): return T2
if issubclass(T1, T2): return T1
# Floats trump everything else.
if issubclass(T2, float): return T2
if issubclass(T1, float): return T1
# Subclasses of the same base class give priority to the second.
if T1.__base__ is T2.__base__: return T2
# Otherwise, just give up.
raise TypeError('cannot coerce types %r and %r' % (T1, T2)) | python | def coerce_types(T1, T2):
"""Coerce types T1 and T2 to a common type.
Coercion is performed according to this table, where "N/A" means
that a TypeError exception is raised.
+----------+-----------+-----------+-----------+----------+
| | int | Fraction | Decimal | float |
+----------+-----------+-----------+-----------+----------+
| int | int | Fraction | Decimal | float |
| Fraction | Fraction | Fraction | N/A | float |
| Decimal | Decimal | N/A | Decimal | float |
| float | float | float | float | float |
+----------+-----------+-----------+-----------+----------+
Subclasses trump their parent class; two subclasses of the same
base class will be coerced to the second of the two.
"""
# Get the common/fast cases out of the way first.
if T1 is T2: return T1
if T1 is int: return T2
if T2 is int: return T1
# Subclasses trump their parent class.
if issubclass(T2, T1): return T2
if issubclass(T1, T2): return T1
# Floats trump everything else.
if issubclass(T2, float): return T2
if issubclass(T1, float): return T1
# Subclasses of the same base class give priority to the second.
if T1.__base__ is T2.__base__: return T2
# Otherwise, just give up.
raise TypeError('cannot coerce types %r and %r' % (T1, T2)) | [
"def",
"coerce_types",
"(",
"T1",
",",
"T2",
")",
":",
"# Get the common/fast cases out of the way first.",
"if",
"T1",
"is",
"T2",
":",
"return",
"T1",
"if",
"T1",
"is",
"int",
":",
"return",
"T2",
"if",
"T2",
"is",
"int",
":",
"return",
"T1",
"# Subclass... | Coerce types T1 and T2 to a common type.
Coercion is performed according to this table, where "N/A" means
that a TypeError exception is raised.
+----------+-----------+-----------+-----------+----------+
| | int | Fraction | Decimal | float |
+----------+-----------+-----------+-----------+----------+
| int | int | Fraction | Decimal | float |
| Fraction | Fraction | Fraction | N/A | float |
| Decimal | Decimal | N/A | Decimal | float |
| float | float | float | float | float |
+----------+-----------+-----------+-----------+----------+
Subclasses trump their parent class; two subclasses of the same
base class will be coerced to the second of the two. | [
"Coerce",
"types",
"T1",
"and",
"T2",
"to",
"a",
"common",
"type",
"."
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L125-L157 |
avalente/appmetrics | appmetrics/statistics.py | counts | def counts(data):
"""
Generate a table of sorted (value, frequency) pairs.
"""
if data is None:
raise TypeError('None is not iterable')
table = collections.Counter(data).most_common()
if not table:
return table
# Extract the values with the highest frequency.
maxfreq = table[0][1]
for i in range(1, len(table)):
if table[i][1] != maxfreq:
table = table[:i]
break
return table | python | def counts(data):
"""
Generate a table of sorted (value, frequency) pairs.
"""
if data is None:
raise TypeError('None is not iterable')
table = collections.Counter(data).most_common()
if not table:
return table
# Extract the values with the highest frequency.
maxfreq = table[0][1]
for i in range(1, len(table)):
if table[i][1] != maxfreq:
table = table[:i]
break
return table | [
"def",
"counts",
"(",
"data",
")",
":",
"if",
"data",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"'None is not iterable'",
")",
"table",
"=",
"collections",
".",
"Counter",
"(",
"data",
")",
".",
"most_common",
"(",
")",
"if",
"not",
"table",
":",
"... | Generate a table of sorted (value, frequency) pairs. | [
"Generate",
"a",
"table",
"of",
"sorted",
"(",
"value",
"frequency",
")",
"pairs",
"."
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L160-L175 |
avalente/appmetrics | appmetrics/statistics.py | mean | def mean(data):
"""Return the sample arithmetic mean of data.
If ``data`` is empty, StatisticsError will be raised.
"""
if iter(data) is data:
data = list(data)
n = len(data)
if n < 1:
raise StatisticsError('mean requires at least one data point')
return sum(data) / n | python | def mean(data):
"""Return the sample arithmetic mean of data.
If ``data`` is empty, StatisticsError will be raised.
"""
if iter(data) is data:
data = list(data)
n = len(data)
if n < 1:
raise StatisticsError('mean requires at least one data point')
return sum(data) / n | [
"def",
"mean",
"(",
"data",
")",
":",
"if",
"iter",
"(",
"data",
")",
"is",
"data",
":",
"data",
"=",
"list",
"(",
"data",
")",
"n",
"=",
"len",
"(",
"data",
")",
"if",
"n",
"<",
"1",
":",
"raise",
"StatisticsError",
"(",
"'mean requires at least o... | Return the sample arithmetic mean of data.
If ``data`` is empty, StatisticsError will be raised. | [
"Return",
"the",
"sample",
"arithmetic",
"mean",
"of",
"data",
"."
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L180-L190 |
avalente/appmetrics | appmetrics/statistics.py | median | def median(data):
"""Return the median (middle value) of numeric data.
When the number of data points is odd, return the middle data point.
When the number of data points is even, the median is interpolated by
taking the average of the two middle values:
"""
data = sorted(data)
n = len(data)
if n == 0:
raise StatisticsError("no median for empty data")
if n % 2 == 1:
return data[n // 2]
else:
i = n // 2
return (data[i - 1] + data[i]) / 2 | python | def median(data):
"""Return the median (middle value) of numeric data.
When the number of data points is odd, return the middle data point.
When the number of data points is even, the median is interpolated by
taking the average of the two middle values:
"""
data = sorted(data)
n = len(data)
if n == 0:
raise StatisticsError("no median for empty data")
if n % 2 == 1:
return data[n // 2]
else:
i = n // 2
return (data[i - 1] + data[i]) / 2 | [
"def",
"median",
"(",
"data",
")",
":",
"data",
"=",
"sorted",
"(",
"data",
")",
"n",
"=",
"len",
"(",
"data",
")",
"if",
"n",
"==",
"0",
":",
"raise",
"StatisticsError",
"(",
"\"no median for empty data\"",
")",
"if",
"n",
"%",
"2",
"==",
"1",
":"... | Return the median (middle value) of numeric data.
When the number of data points is odd, return the middle data point.
When the number of data points is even, the median is interpolated by
taking the average of the two middle values: | [
"Return",
"the",
"median",
"(",
"middle",
"value",
")",
"of",
"numeric",
"data",
"."
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L194-L210 |
avalente/appmetrics | appmetrics/statistics.py | median_low | def median_low(data):
"""Return the low median of numeric data.
When the number of data points is odd, the middle value is returned.
When it is even, the smaller of the two middle values is returned.
"""
data = sorted(data)
n = len(data)
if n == 0:
raise StatisticsError("no median for empty data")
if n % 2 == 1:
return data[n // 2]
else:
return data[n // 2 - 1] | python | def median_low(data):
"""Return the low median of numeric data.
When the number of data points is odd, the middle value is returned.
When it is even, the smaller of the two middle values is returned.
"""
data = sorted(data)
n = len(data)
if n == 0:
raise StatisticsError("no median for empty data")
if n % 2 == 1:
return data[n // 2]
else:
return data[n // 2 - 1] | [
"def",
"median_low",
"(",
"data",
")",
":",
"data",
"=",
"sorted",
"(",
"data",
")",
"n",
"=",
"len",
"(",
"data",
")",
"if",
"n",
"==",
"0",
":",
"raise",
"StatisticsError",
"(",
"\"no median for empty data\"",
")",
"if",
"n",
"%",
"2",
"==",
"1",
... | Return the low median of numeric data.
When the number of data points is odd, the middle value is returned.
When it is even, the smaller of the two middle values is returned. | [
"Return",
"the",
"low",
"median",
"of",
"numeric",
"data",
"."
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L213-L226 |
avalente/appmetrics | appmetrics/statistics.py | median_high | def median_high(data):
"""Return the high median of data.
When the number of data points is odd, the middle value is returned.
When it is even, the larger of the two middle values is returned.
"""
data = sorted(data)
n = len(data)
if n == 0:
raise StatisticsError("no median for empty data")
return data[n // 2] | python | def median_high(data):
"""Return the high median of data.
When the number of data points is odd, the middle value is returned.
When it is even, the larger of the two middle values is returned.
"""
data = sorted(data)
n = len(data)
if n == 0:
raise StatisticsError("no median for empty data")
return data[n // 2] | [
"def",
"median_high",
"(",
"data",
")",
":",
"data",
"=",
"sorted",
"(",
"data",
")",
"n",
"=",
"len",
"(",
"data",
")",
"if",
"n",
"==",
"0",
":",
"raise",
"StatisticsError",
"(",
"\"no median for empty data\"",
")",
"return",
"data",
"[",
"n",
"//",
... | Return the high median of data.
When the number of data points is odd, the middle value is returned.
When it is even, the larger of the two middle values is returned. | [
"Return",
"the",
"high",
"median",
"of",
"data",
"."
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L229-L240 |
avalente/appmetrics | appmetrics/statistics.py | mode | def mode(data):
"""Return the most common data point from discrete or nominal data.
``mode`` assumes discrete data, and returns a single value. This is the
standard treatment of the mode as commonly taught in schools:
If there is not exactly one most common value, ``mode`` will raise
StatisticsError.
"""
# Generate a table of sorted (value, frequency) pairs.
table = counts(data)
if len(table) == 1:
return table[0][0]
elif table:
raise StatisticsError(
'no unique mode; found %d equally common values' % len(table)
)
else:
raise StatisticsError('no mode for empty data') | python | def mode(data):
"""Return the most common data point from discrete or nominal data.
``mode`` assumes discrete data, and returns a single value. This is the
standard treatment of the mode as commonly taught in schools:
If there is not exactly one most common value, ``mode`` will raise
StatisticsError.
"""
# Generate a table of sorted (value, frequency) pairs.
table = counts(data)
if len(table) == 1:
return table[0][0]
elif table:
raise StatisticsError(
'no unique mode; found %d equally common values' % len(table)
)
else:
raise StatisticsError('no mode for empty data') | [
"def",
"mode",
"(",
"data",
")",
":",
"# Generate a table of sorted (value, frequency) pairs.",
"table",
"=",
"counts",
"(",
"data",
")",
"if",
"len",
"(",
"table",
")",
"==",
"1",
":",
"return",
"table",
"[",
"0",
"]",
"[",
"0",
"]",
"elif",
"table",
":... | Return the most common data point from discrete or nominal data.
``mode`` assumes discrete data, and returns a single value. This is the
standard treatment of the mode as commonly taught in schools:
If there is not exactly one most common value, ``mode`` will raise
StatisticsError. | [
"Return",
"the",
"most",
"common",
"data",
"point",
"from",
"discrete",
"or",
"nominal",
"data",
"."
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L243-L261 |
avalente/appmetrics | appmetrics/statistics.py | _ss | def _ss(data, c=None):
"""Return sum of square deviations of sequence data.
If ``c`` is None, the mean is calculated in one pass, and the deviations
from the mean are calculated in a second pass. Otherwise, deviations are
calculated from ``c`` as given. Use the second case with care, as it can
lead to garbage results.
"""
if c is None:
c = mean(data)
ss = sum((x - c) ** 2 for x in data)
# The following sum should mathematically equal zero, but due to rounding
# error may not.
ss -= sum((x - c) for x in data) ** 2 / len(data)
assert not ss < 0, 'negative sum of square deviations: %f' % ss
return ss | python | def _ss(data, c=None):
"""Return sum of square deviations of sequence data.
If ``c`` is None, the mean is calculated in one pass, and the deviations
from the mean are calculated in a second pass. Otherwise, deviations are
calculated from ``c`` as given. Use the second case with care, as it can
lead to garbage results.
"""
if c is None:
c = mean(data)
ss = sum((x - c) ** 2 for x in data)
# The following sum should mathematically equal zero, but due to rounding
# error may not.
ss -= sum((x - c) for x in data) ** 2 / len(data)
assert not ss < 0, 'negative sum of square deviations: %f' % ss
return ss | [
"def",
"_ss",
"(",
"data",
",",
"c",
"=",
"None",
")",
":",
"if",
"c",
"is",
"None",
":",
"c",
"=",
"mean",
"(",
"data",
")",
"ss",
"=",
"sum",
"(",
"(",
"x",
"-",
"c",
")",
"**",
"2",
"for",
"x",
"in",
"data",
")",
"# The following sum shoul... | Return sum of square deviations of sequence data.
If ``c`` is None, the mean is calculated in one pass, and the deviations
from the mean are calculated in a second pass. Otherwise, deviations are
calculated from ``c`` as given. Use the second case with care, as it can
lead to garbage results. | [
"Return",
"sum",
"of",
"square",
"deviations",
"of",
"sequence",
"data",
"."
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L277-L292 |
avalente/appmetrics | appmetrics/statistics.py | variance | def variance(data, xbar=None):
"""Return the sample variance of data.
data should be an iterable of Real-valued numbers, with at least two
values. The optional argument xbar, if given, should be the mean of
the data. If it is missing or None, the mean is automatically calculated.
Use this function when your data is a sample from a population. To
calculate the variance from the entire population, see ``pvariance``.
If you have already calculated the mean of your data, you can pass it as
the optional second argument ``xbar`` to avoid recalculating it:
This function does not check that ``xbar`` is actually the mean of
``data``. Giving arbitrary values for ``xbar`` may lead to invalid or
impossible results.
Decimals and Fractions are supported
"""
if iter(data) is data:
data = list(data)
n = len(data)
if n < 2:
raise StatisticsError('variance requires at least two data points')
ss = _ss(data, xbar)
return ss / (n - 1) | python | def variance(data, xbar=None):
"""Return the sample variance of data.
data should be an iterable of Real-valued numbers, with at least two
values. The optional argument xbar, if given, should be the mean of
the data. If it is missing or None, the mean is automatically calculated.
Use this function when your data is a sample from a population. To
calculate the variance from the entire population, see ``pvariance``.
If you have already calculated the mean of your data, you can pass it as
the optional second argument ``xbar`` to avoid recalculating it:
This function does not check that ``xbar`` is actually the mean of
``data``. Giving arbitrary values for ``xbar`` may lead to invalid or
impossible results.
Decimals and Fractions are supported
"""
if iter(data) is data:
data = list(data)
n = len(data)
if n < 2:
raise StatisticsError('variance requires at least two data points')
ss = _ss(data, xbar)
return ss / (n - 1) | [
"def",
"variance",
"(",
"data",
",",
"xbar",
"=",
"None",
")",
":",
"if",
"iter",
"(",
"data",
")",
"is",
"data",
":",
"data",
"=",
"list",
"(",
"data",
")",
"n",
"=",
"len",
"(",
"data",
")",
"if",
"n",
"<",
"2",
":",
"raise",
"StatisticsError... | Return the sample variance of data.
data should be an iterable of Real-valued numbers, with at least two
values. The optional argument xbar, if given, should be the mean of
the data. If it is missing or None, the mean is automatically calculated.
Use this function when your data is a sample from a population. To
calculate the variance from the entire population, see ``pvariance``.
If you have already calculated the mean of your data, you can pass it as
the optional second argument ``xbar`` to avoid recalculating it:
This function does not check that ``xbar`` is actually the mean of
``data``. Giving arbitrary values for ``xbar`` may lead to invalid or
impossible results.
Decimals and Fractions are supported | [
"Return",
"the",
"sample",
"variance",
"of",
"data",
"."
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L295-L321 |
avalente/appmetrics | appmetrics/statistics.py | pvariance | def pvariance(data, mu=None):
"""Return the population variance of ``data``.
data should be an iterable of Real-valued numbers, with at least one
value. The optional argument mu, if given, should be the mean of
the data. If it is missing or None, the mean is automatically calculated.
Use this function to calculate the variance from the entire population.
To estimate the variance from a sample, the ``variance`` function is
usually a better choice.
If you have already calculated the mean of the data, you can pass it as
the optional second argument to avoid recalculating it:
This function does not check that ``mu`` is actually the mean of ``data``.
Giving arbitrary values for ``mu`` may lead to invalid or impossible
results.
Decimals and Fractions are supported:
"""
if iter(data) is data:
data = list(data)
n = len(data)
if n < 1:
raise StatisticsError('pvariance requires at least one data point')
ss = _ss(data, mu)
return ss / n | python | def pvariance(data, mu=None):
"""Return the population variance of ``data``.
data should be an iterable of Real-valued numbers, with at least one
value. The optional argument mu, if given, should be the mean of
the data. If it is missing or None, the mean is automatically calculated.
Use this function to calculate the variance from the entire population.
To estimate the variance from a sample, the ``variance`` function is
usually a better choice.
If you have already calculated the mean of the data, you can pass it as
the optional second argument to avoid recalculating it:
This function does not check that ``mu`` is actually the mean of ``data``.
Giving arbitrary values for ``mu`` may lead to invalid or impossible
results.
Decimals and Fractions are supported:
"""
if iter(data) is data:
data = list(data)
n = len(data)
if n < 1:
raise StatisticsError('pvariance requires at least one data point')
ss = _ss(data, mu)
return ss / n | [
"def",
"pvariance",
"(",
"data",
",",
"mu",
"=",
"None",
")",
":",
"if",
"iter",
"(",
"data",
")",
"is",
"data",
":",
"data",
"=",
"list",
"(",
"data",
")",
"n",
"=",
"len",
"(",
"data",
")",
"if",
"n",
"<",
"1",
":",
"raise",
"StatisticsError"... | Return the population variance of ``data``.
data should be an iterable of Real-valued numbers, with at least one
value. The optional argument mu, if given, should be the mean of
the data. If it is missing or None, the mean is automatically calculated.
Use this function to calculate the variance from the entire population.
To estimate the variance from a sample, the ``variance`` function is
usually a better choice.
If you have already calculated the mean of the data, you can pass it as
the optional second argument to avoid recalculating it:
This function does not check that ``mu`` is actually the mean of ``data``.
Giving arbitrary values for ``mu`` may lead to invalid or impossible
results.
Decimals and Fractions are supported: | [
"Return",
"the",
"population",
"variance",
"of",
"data",
"."
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L324-L353 |
avalente/appmetrics | appmetrics/statistics.py | stdev | def stdev(data, xbar=None):
"""Return the square root of the sample variance.
See ``variance`` for arguments and other details.
"""
var = variance(data, xbar)
try:
return var.sqrt()
except AttributeError:
return math.sqrt(var) | python | def stdev(data, xbar=None):
"""Return the square root of the sample variance.
See ``variance`` for arguments and other details.
"""
var = variance(data, xbar)
try:
return var.sqrt()
except AttributeError:
return math.sqrt(var) | [
"def",
"stdev",
"(",
"data",
",",
"xbar",
"=",
"None",
")",
":",
"var",
"=",
"variance",
"(",
"data",
",",
"xbar",
")",
"try",
":",
"return",
"var",
".",
"sqrt",
"(",
")",
"except",
"AttributeError",
":",
"return",
"math",
".",
"sqrt",
"(",
"var",
... | Return the square root of the sample variance.
See ``variance`` for arguments and other details. | [
"Return",
"the",
"square",
"root",
"of",
"the",
"sample",
"variance",
"."
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L356-L366 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.