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 |
|---|---|---|---|---|---|---|---|---|---|---|
pletzer/pnumpy | examples/exAverage2d.py | setValues | def setValues(nxG, nyG, iBeg, iEnd, jBeg, jEnd, data):
"""
Set setValues
@param nxG number of global cells in x
@param nyG number of global cells in y
@param iBeg global starting index in x
@param iEnd global ending index in x
@param jBeg global starting index in y
@param jEnd global ending index in y
@param data local array
"""
nxGHalf = nxG/2.
nyGHalf = nyG/2.
nxGQuart = nxGHalf/2.
nyGQuart = nyGHalf/2.
for i in range(data.shape[0]):
iG = iBeg + i
di = iG - nxG
for j in range(data.shape[1]):
jG = jBeg + j
dj = jG - 0.8*nyG
data[i, j] = numpy.floor(1.9*numpy.exp(-di**2/nxGHalf**2 - dj**2/nyGHalf**2)) | python | def setValues(nxG, nyG, iBeg, iEnd, jBeg, jEnd, data):
"""
Set setValues
@param nxG number of global cells in x
@param nyG number of global cells in y
@param iBeg global starting index in x
@param iEnd global ending index in x
@param jBeg global starting index in y
@param jEnd global ending index in y
@param data local array
"""
nxGHalf = nxG/2.
nyGHalf = nyG/2.
nxGQuart = nxGHalf/2.
nyGQuart = nyGHalf/2.
for i in range(data.shape[0]):
iG = iBeg + i
di = iG - nxG
for j in range(data.shape[1]):
jG = jBeg + j
dj = jG - 0.8*nyG
data[i, j] = numpy.floor(1.9*numpy.exp(-di**2/nxGHalf**2 - dj**2/nyGHalf**2)) | [
"def",
"setValues",
"(",
"nxG",
",",
"nyG",
",",
"iBeg",
",",
"iEnd",
",",
"jBeg",
",",
"jEnd",
",",
"data",
")",
":",
"nxGHalf",
"=",
"nxG",
"/",
"2.",
"nyGHalf",
"=",
"nyG",
"/",
"2.",
"nxGQuart",
"=",
"nxGHalf",
"/",
"2.",
"nyGQuart",
"=",
"ny... | Set setValues
@param nxG number of global cells in x
@param nyG number of global cells in y
@param iBeg global starting index in x
@param iEnd global ending index in x
@param jBeg global starting index in y
@param jEnd global ending index in y
@param data local array | [
"Set",
"setValues"
] | train | https://github.com/pletzer/pnumpy/blob/9e6d308be94a42637466b91ab1a7b4d64b4c29ae/examples/exAverage2d.py#L44-L65 |
carpedm20/ndrive | cmdline.py | NdriveTerm.do_ls | def do_ls(self, nothing = ''):
"""list files in current remote directory"""
for d in self.dirs:
self.stdout.write("\033[0;34m" + ('%s\n' % d) + "\033[0m")
for f in self.files:
self.stdout.write('%s\n' % f) | python | def do_ls(self, nothing = ''):
"""list files in current remote directory"""
for d in self.dirs:
self.stdout.write("\033[0;34m" + ('%s\n' % d) + "\033[0m")
for f in self.files:
self.stdout.write('%s\n' % f) | [
"def",
"do_ls",
"(",
"self",
",",
"nothing",
"=",
"''",
")",
":",
"for",
"d",
"in",
"self",
".",
"dirs",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"\"\\033[0;34m\"",
"+",
"(",
"'%s\\n'",
"%",
"d",
")",
"+",
"\"\\033[0m\"",
")",
"for",
"f",
"... | list files in current remote directory | [
"list",
"files",
"in",
"current",
"remote",
"directory"
] | train | https://github.com/carpedm20/ndrive/blob/ac58eaf8a8d46292ad752bb38047f65838b8ad2b/cmdline.py#L42-L48 |
carpedm20/ndrive | cmdline.py | NdriveTerm.do_cd | def do_cd(self, path = '/'):
"""change current working directory"""
path = path[0]
if path == "..":
self.current_path = "/".join(self.current_path[:-1].split("/")[0:-1]) + '/'
elif path == '/':
self.current_path = "/"
else:
if path[-1] == '/':
self.current_path += path
else:
self.current_path += path + '/'
resp = self.n.getList(self.current_path, type=3)
if resp:
self.dirs = []
self.files = []
for f in resp:
name = f['href'].encode('utf-8')
if name[-1] == '/':
self.dirs.append(os.path.basename(name[:-1]))
else:
self.files.append(os.path.basename(name))
self.prompt = "> %s@Ndrive:%s " %(self.id, self.current_path) | python | def do_cd(self, path = '/'):
"""change current working directory"""
path = path[0]
if path == "..":
self.current_path = "/".join(self.current_path[:-1].split("/")[0:-1]) + '/'
elif path == '/':
self.current_path = "/"
else:
if path[-1] == '/':
self.current_path += path
else:
self.current_path += path + '/'
resp = self.n.getList(self.current_path, type=3)
if resp:
self.dirs = []
self.files = []
for f in resp:
name = f['href'].encode('utf-8')
if name[-1] == '/':
self.dirs.append(os.path.basename(name[:-1]))
else:
self.files.append(os.path.basename(name))
self.prompt = "> %s@Ndrive:%s " %(self.id, self.current_path) | [
"def",
"do_cd",
"(",
"self",
",",
"path",
"=",
"'/'",
")",
":",
"path",
"=",
"path",
"[",
"0",
"]",
"if",
"path",
"==",
"\"..\"",
":",
"self",
".",
"current_path",
"=",
"\"/\"",
".",
"join",
"(",
"self",
".",
"current_path",
"[",
":",
"-",
"1",
... | change current working directory | [
"change",
"current",
"working",
"directory"
] | train | https://github.com/carpedm20/ndrive/blob/ac58eaf8a8d46292ad752bb38047f65838b8ad2b/cmdline.py#L84-L112 |
carpedm20/ndrive | cmdline.py | NdriveTerm.do_cat | def do_cat(self, path):
"""display the contents of a file"""
path = path[0]
tmp_file_path = self.TMP_PATH + 'tmp'
if not os.path.exists(self.TMP_PATH):
os.makedirs(self.TMP_PATH)
f = self.n.downloadFile(self.current_path + path, tmp_file_path)
f = open(tmp_file_path, 'r')
self.stdout.write(f.read())
self.stdout.write("\n") | python | def do_cat(self, path):
"""display the contents of a file"""
path = path[0]
tmp_file_path = self.TMP_PATH + 'tmp'
if not os.path.exists(self.TMP_PATH):
os.makedirs(self.TMP_PATH)
f = self.n.downloadFile(self.current_path + path, tmp_file_path)
f = open(tmp_file_path, 'r')
self.stdout.write(f.read())
self.stdout.write("\n") | [
"def",
"do_cat",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"path",
"[",
"0",
"]",
"tmp_file_path",
"=",
"self",
".",
"TMP_PATH",
"+",
"'tmp'",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"TMP_PATH",
")",
":",
"os",
"."... | display the contents of a file | [
"display",
"the",
"contents",
"of",
"a",
"file"
] | train | https://github.com/carpedm20/ndrive/blob/ac58eaf8a8d46292ad752bb38047f65838b8ad2b/cmdline.py#L117-L129 |
carpedm20/ndrive | cmdline.py | NdriveTerm.do_mkdir | def do_mkdir(self, path):
"""create a new directory"""
path = path[0]
self.n.makeDirectory(self.current_path + path)
self.dirs = self.dir_complete() | python | def do_mkdir(self, path):
"""create a new directory"""
path = path[0]
self.n.makeDirectory(self.current_path + path)
self.dirs = self.dir_complete() | [
"def",
"do_mkdir",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"path",
"[",
"0",
"]",
"self",
".",
"n",
".",
"makeDirectory",
"(",
"self",
".",
"current_path",
"+",
"path",
")",
"self",
".",
"dirs",
"=",
"self",
".",
"dir_complete",
"(",
")"
] | create a new directory | [
"create",
"a",
"new",
"directory"
] | train | https://github.com/carpedm20/ndrive/blob/ac58eaf8a8d46292ad752bb38047f65838b8ad2b/cmdline.py#L134-L139 |
carpedm20/ndrive | cmdline.py | NdriveTerm.do_rm | def do_rm(self, path):
path = path[0]
"""delete a file or directory"""
self.n.delete(self.current_path + path)
self.dirs = self.dir_complete()
self.files = self.file_complete() | python | def do_rm(self, path):
path = path[0]
"""delete a file or directory"""
self.n.delete(self.current_path + path)
self.dirs = self.dir_complete()
self.files = self.file_complete() | [
"def",
"do_rm",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"path",
"[",
"0",
"]",
"self",
".",
"n",
".",
"delete",
"(",
"self",
".",
"current_path",
"+",
"path",
")",
"self",
".",
"dirs",
"=",
"self",
".",
"dir_complete",
"(",
")",
"self",
... | delete a file or directory | [
"delete",
"a",
"file",
"or",
"directory"
] | train | https://github.com/carpedm20/ndrive/blob/ac58eaf8a8d46292ad752bb38047f65838b8ad2b/cmdline.py#L141-L147 |
carpedm20/ndrive | cmdline.py | NdriveTerm.do_mv | def do_mv(self, from_path, to_path, nothing = ''):
"""move/rename a file or directory"""
self.n.doMove(self.current_path + from_path,
self.current_path + to_path) | python | def do_mv(self, from_path, to_path, nothing = ''):
"""move/rename a file or directory"""
self.n.doMove(self.current_path + from_path,
self.current_path + to_path) | [
"def",
"do_mv",
"(",
"self",
",",
"from_path",
",",
"to_path",
",",
"nothing",
"=",
"''",
")",
":",
"self",
".",
"n",
".",
"doMove",
"(",
"self",
".",
"current_path",
"+",
"from_path",
",",
"self",
".",
"current_path",
"+",
"to_path",
")"
] | move/rename a file or directory | [
"move",
"/",
"rename",
"a",
"file",
"or",
"directory"
] | train | https://github.com/carpedm20/ndrive/blob/ac58eaf8a8d46292ad752bb38047f65838b8ad2b/cmdline.py#L149-L152 |
carpedm20/ndrive | cmdline.py | NdriveTerm.do_account_info | def do_account_info(self):
"""display account information"""
s, metadata = self.n.getRegisterUserInfo()
pprint.PrettyPrinter(indent=2).pprint(metadata) | python | def do_account_info(self):
"""display account information"""
s, metadata = self.n.getRegisterUserInfo()
pprint.PrettyPrinter(indent=2).pprint(metadata) | [
"def",
"do_account_info",
"(",
"self",
")",
":",
"s",
",",
"metadata",
"=",
"self",
".",
"n",
".",
"getRegisterUserInfo",
"(",
")",
"pprint",
".",
"PrettyPrinter",
"(",
"indent",
"=",
"2",
")",
".",
"pprint",
"(",
"metadata",
")"
] | display account information | [
"display",
"account",
"information"
] | train | https://github.com/carpedm20/ndrive/blob/ac58eaf8a8d46292ad752bb38047f65838b8ad2b/cmdline.py#L157-L160 |
carpedm20/ndrive | cmdline.py | NdriveTerm.do_get | def do_get(self, from_path, to_path):
"""
Copy file from Ndrive to local file and print out out the metadata.
Examples:
Ndrive> get file.txt ~/ndrive-file.txt
"""
to_file = open(os.path.expanduser(to_path), "wb")
self.n.downloadFile(self.current_path + "/" + from_path, to_path) | python | def do_get(self, from_path, to_path):
"""
Copy file from Ndrive to local file and print out out the metadata.
Examples:
Ndrive> get file.txt ~/ndrive-file.txt
"""
to_file = open(os.path.expanduser(to_path), "wb")
self.n.downloadFile(self.current_path + "/" + from_path, to_path) | [
"def",
"do_get",
"(",
"self",
",",
"from_path",
",",
"to_path",
")",
":",
"to_file",
"=",
"open",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"to_path",
")",
",",
"\"wb\"",
")",
"self",
".",
"n",
".",
"downloadFile",
"(",
"self",
".",
"current_pa... | Copy file from Ndrive to local file and print out out the metadata.
Examples:
Ndrive> get file.txt ~/ndrive-file.txt | [
"Copy",
"file",
"from",
"Ndrive",
"to",
"local",
"file",
"and",
"print",
"out",
"out",
"the",
"metadata",
"."
] | train | https://github.com/carpedm20/ndrive/blob/ac58eaf8a8d46292ad752bb38047f65838b8ad2b/cmdline.py#L166-L175 |
carpedm20/ndrive | cmdline.py | NdriveTerm.do_put | def do_put(self, from_path, to_path):
"""
Copy local file to Ndrive
Examples:
Ndrive> put ~/test.txt ndrive-copy-test.txt
"""
from_file = open(os.path.expanduser(from_path), "rb")
self.n.put(self.current_path + "/" + from_path, to_path) | python | def do_put(self, from_path, to_path):
"""
Copy local file to Ndrive
Examples:
Ndrive> put ~/test.txt ndrive-copy-test.txt
"""
from_file = open(os.path.expanduser(from_path), "rb")
self.n.put(self.current_path + "/" + from_path, to_path) | [
"def",
"do_put",
"(",
"self",
",",
"from_path",
",",
"to_path",
")",
":",
"from_file",
"=",
"open",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"from_path",
")",
",",
"\"rb\"",
")",
"self",
".",
"n",
".",
"put",
"(",
"self",
".",
"current_path",
... | Copy local file to Ndrive
Examples:
Ndrive> put ~/test.txt ndrive-copy-test.txt | [
"Copy",
"local",
"file",
"to",
"Ndrive"
] | train | https://github.com/carpedm20/ndrive/blob/ac58eaf8a8d46292ad752bb38047f65838b8ad2b/cmdline.py#L177-L186 |
carpedm20/ndrive | cmdline.py | NdriveTerm.do_search | def do_search(self, string):
"""Search Ndrive for filenames containing the given string."""
results = self.n.doSearch(string, full_path = self.current_path)
if results:
for r in results:
self.stdout.write("%s\n" % r['path']) | python | def do_search(self, string):
"""Search Ndrive for filenames containing the given string."""
results = self.n.doSearch(string, full_path = self.current_path)
if results:
for r in results:
self.stdout.write("%s\n" % r['path']) | [
"def",
"do_search",
"(",
"self",
",",
"string",
")",
":",
"results",
"=",
"self",
".",
"n",
".",
"doSearch",
"(",
"string",
",",
"full_path",
"=",
"self",
".",
"current_path",
")",
"if",
"results",
":",
"for",
"r",
"in",
"results",
":",
"self",
".",
... | Search Ndrive for filenames containing the given string. | [
"Search",
"Ndrive",
"for",
"filenames",
"containing",
"the",
"given",
"string",
"."
] | train | https://github.com/carpedm20/ndrive/blob/ac58eaf8a8d46292ad752bb38047f65838b8ad2b/cmdline.py#L188-L194 |
ikegami-yukino/python-tr | tr/tr.py | tr | def tr(string1, string2, source, option=''):
"""Replace or remove specific characters.
If not given option, then replace all characters in string1 with
the character in the same position in string2.
Following options are available:
c Replace all complemented characters in string1 with
the character in the same position in string2.
d Delete all characters in string1.
s Squeeze all characters in string1.
cs Squeeze all the characters in string2 besides "c" replacement.
ds Delete all characters in string1. Squeeze all characters
in string2.
cd Delete all complemented characters in string1.
Params:
<unicode> string1
<unicode> string2
<unicode> source
<basestring> option
Return:
<unicode> translated_source
"""
if not is_valid_type(source):
raise TypeError('source must be unicode')
from_list = make_char_list(string1)
if option == 's':
from_list = to_unichr(from_list)
return squeeze(from_list, source)
elif 'c' in option:
from_list = to_unichr(from_list)
from_list = [ord(c) for c in set(source) - set(from_list)]
if 'd' in option:
to_list = [None for i in from_list]
else:
to_list = [string2[-1] for i in from_list]
source = translate(from_list, to_list, source)
if 's' in option:
source = squeeze(to_list, source)
return source
elif 'd' in option:
to_list = [None for i in from_list]
source = translate(from_list, to_list, source)
if 's' in option:
to_list = make_char_list(string2)
to_list = to_unichr(to_list)
source = squeeze(to_list, source)
return source
else:
to_list = make_char_list(string2)
length_diff = (len(from_list) - len(to_list))
if length_diff:
to_list += [to_list[-1]] * length_diff
to_list = to_unichr(to_list)
return translate(from_list, to_list, source) | python | def tr(string1, string2, source, option=''):
"""Replace or remove specific characters.
If not given option, then replace all characters in string1 with
the character in the same position in string2.
Following options are available:
c Replace all complemented characters in string1 with
the character in the same position in string2.
d Delete all characters in string1.
s Squeeze all characters in string1.
cs Squeeze all the characters in string2 besides "c" replacement.
ds Delete all characters in string1. Squeeze all characters
in string2.
cd Delete all complemented characters in string1.
Params:
<unicode> string1
<unicode> string2
<unicode> source
<basestring> option
Return:
<unicode> translated_source
"""
if not is_valid_type(source):
raise TypeError('source must be unicode')
from_list = make_char_list(string1)
if option == 's':
from_list = to_unichr(from_list)
return squeeze(from_list, source)
elif 'c' in option:
from_list = to_unichr(from_list)
from_list = [ord(c) for c in set(source) - set(from_list)]
if 'd' in option:
to_list = [None for i in from_list]
else:
to_list = [string2[-1] for i in from_list]
source = translate(from_list, to_list, source)
if 's' in option:
source = squeeze(to_list, source)
return source
elif 'd' in option:
to_list = [None for i in from_list]
source = translate(from_list, to_list, source)
if 's' in option:
to_list = make_char_list(string2)
to_list = to_unichr(to_list)
source = squeeze(to_list, source)
return source
else:
to_list = make_char_list(string2)
length_diff = (len(from_list) - len(to_list))
if length_diff:
to_list += [to_list[-1]] * length_diff
to_list = to_unichr(to_list)
return translate(from_list, to_list, source) | [
"def",
"tr",
"(",
"string1",
",",
"string2",
",",
"source",
",",
"option",
"=",
"''",
")",
":",
"if",
"not",
"is_valid_type",
"(",
"source",
")",
":",
"raise",
"TypeError",
"(",
"'source must be unicode'",
")",
"from_list",
"=",
"make_char_list",
"(",
"str... | Replace or remove specific characters.
If not given option, then replace all characters in string1 with
the character in the same position in string2.
Following options are available:
c Replace all complemented characters in string1 with
the character in the same position in string2.
d Delete all characters in string1.
s Squeeze all characters in string1.
cs Squeeze all the characters in string2 besides "c" replacement.
ds Delete all characters in string1. Squeeze all characters
in string2.
cd Delete all complemented characters in string1.
Params:
<unicode> string1
<unicode> string2
<unicode> source
<basestring> option
Return:
<unicode> translated_source | [
"Replace",
"or",
"remove",
"specific",
"characters",
"."
] | train | https://github.com/ikegami-yukino/python-tr/blob/e74d4bdb505294686e73ac49483c1faafc4d5501/tr/tr.py#L51-L107 |
ClimateImpactLab/DataFS | datafs/services/service.py | DataService.upload | def upload(self, filepath, service_path, remove=False):
'''
"Upload" a file to a service
This copies a file from the local filesystem into the ``DataService``'s
filesystem. If ``remove==True``, the file is moved rather than copied.
If ``filepath`` and ``service_path`` paths are the same, ``upload``
deletes the file if ``remove==True`` and returns.
Parameters
----------
filepath : str
Relative or absolute path to the file to be uploaded on the user's
filesystem
service_path: str
Path to the destination for the file on the ``DataService``'s
filesystem
remove : bool
If true, the file is moved rather than copied
'''
local = OSFS(os.path.dirname(filepath))
# Skip if source and dest are the same
if self.fs.hassyspath(service_path) and (
self.fs.getsyspath(service_path) == local.getsyspath(
os.path.basename(filepath))):
if remove:
os.remove(filepath)
return
if not self.fs.isdir(fs.path.dirname(service_path)):
self.fs.makedir(
fs.path.dirname(service_path),
recursive=True,
allow_recreate=True)
if remove:
fs.utils.movefile(
local,
os.path.basename(filepath),
self.fs,
service_path)
else:
fs.utils.copyfile(
local,
os.path.basename(filepath),
self.fs,
service_path) | python | def upload(self, filepath, service_path, remove=False):
'''
"Upload" a file to a service
This copies a file from the local filesystem into the ``DataService``'s
filesystem. If ``remove==True``, the file is moved rather than copied.
If ``filepath`` and ``service_path`` paths are the same, ``upload``
deletes the file if ``remove==True`` and returns.
Parameters
----------
filepath : str
Relative or absolute path to the file to be uploaded on the user's
filesystem
service_path: str
Path to the destination for the file on the ``DataService``'s
filesystem
remove : bool
If true, the file is moved rather than copied
'''
local = OSFS(os.path.dirname(filepath))
# Skip if source and dest are the same
if self.fs.hassyspath(service_path) and (
self.fs.getsyspath(service_path) == local.getsyspath(
os.path.basename(filepath))):
if remove:
os.remove(filepath)
return
if not self.fs.isdir(fs.path.dirname(service_path)):
self.fs.makedir(
fs.path.dirname(service_path),
recursive=True,
allow_recreate=True)
if remove:
fs.utils.movefile(
local,
os.path.basename(filepath),
self.fs,
service_path)
else:
fs.utils.copyfile(
local,
os.path.basename(filepath),
self.fs,
service_path) | [
"def",
"upload",
"(",
"self",
",",
"filepath",
",",
"service_path",
",",
"remove",
"=",
"False",
")",
":",
"local",
"=",
"OSFS",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"filepath",
")",
")",
"# Skip if source and dest are the same",
"if",
"self",
".",... | "Upload" a file to a service
This copies a file from the local filesystem into the ``DataService``'s
filesystem. If ``remove==True``, the file is moved rather than copied.
If ``filepath`` and ``service_path`` paths are the same, ``upload``
deletes the file if ``remove==True`` and returns.
Parameters
----------
filepath : str
Relative or absolute path to the file to be uploaded on the user's
filesystem
service_path: str
Path to the destination for the file on the ``DataService``'s
filesystem
remove : bool
If true, the file is moved rather than copied | [
"Upload",
"a",
"file",
"to",
"a",
"service"
] | train | https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/services/service.py#L19-L73 |
ClimateImpactLab/DataFS | datafs/core/data_archive.py | DataArchive.get_version_path | def get_version_path(self, version=None):
'''
Returns a storage path for the archive and version
If the archive is versioned, the version number is used as the file
path and the archive path is the directory. If not, the archive path is
used as the file path.
Parameters
----------
version : str or object
Version number to use as file name on versioned archives (default
latest unless ``default_version`` set)
Examples
--------
.. code-block:: python
>>> arch = DataArchive(None, 'arch', None, 'a1', versioned=False)
>>> print(arch.get_version_path())
a1
>>>
>>> ver = DataArchive(None, 'ver', None, 'a2', versioned=True)
>>> print(ver.get_version_path('0.0.0'))
a2/0.0
>>>
>>> print(ver.get_version_path('0.0.1a1'))
a2/0.0.1a1
>>>
>>> print(ver.get_version_path('latest')) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
AttributeError: 'NoneType' object has no attribute 'manager'
'''
version = _process_version(self, version)
if self.versioned:
return fs.path.join(self.archive_path, str(version))
else:
return self.archive_path | python | def get_version_path(self, version=None):
'''
Returns a storage path for the archive and version
If the archive is versioned, the version number is used as the file
path and the archive path is the directory. If not, the archive path is
used as the file path.
Parameters
----------
version : str or object
Version number to use as file name on versioned archives (default
latest unless ``default_version`` set)
Examples
--------
.. code-block:: python
>>> arch = DataArchive(None, 'arch', None, 'a1', versioned=False)
>>> print(arch.get_version_path())
a1
>>>
>>> ver = DataArchive(None, 'ver', None, 'a2', versioned=True)
>>> print(ver.get_version_path('0.0.0'))
a2/0.0
>>>
>>> print(ver.get_version_path('0.0.1a1'))
a2/0.0.1a1
>>>
>>> print(ver.get_version_path('latest')) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
AttributeError: 'NoneType' object has no attribute 'manager'
'''
version = _process_version(self, version)
if self.versioned:
return fs.path.join(self.archive_path, str(version))
else:
return self.archive_path | [
"def",
"get_version_path",
"(",
"self",
",",
"version",
"=",
"None",
")",
":",
"version",
"=",
"_process_version",
"(",
"self",
",",
"version",
")",
"if",
"self",
".",
"versioned",
":",
"return",
"fs",
".",
"path",
".",
"join",
"(",
"self",
".",
"archi... | Returns a storage path for the archive and version
If the archive is versioned, the version number is used as the file
path and the archive path is the directory. If not, the archive path is
used as the file path.
Parameters
----------
version : str or object
Version number to use as file name on versioned archives (default
latest unless ``default_version`` set)
Examples
--------
.. code-block:: python
>>> arch = DataArchive(None, 'arch', None, 'a1', versioned=False)
>>> print(arch.get_version_path())
a1
>>>
>>> ver = DataArchive(None, 'ver', None, 'a2', versioned=True)
>>> print(ver.get_version_path('0.0.0'))
a2/0.0
>>>
>>> print(ver.get_version_path('0.0.1a1'))
a2/0.0.1a1
>>>
>>> print(ver.get_version_path('latest')) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
AttributeError: 'NoneType' object has no attribute 'manager' | [
"Returns",
"a",
"storage",
"path",
"for",
"the",
"archive",
"and",
"version"
] | train | https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/core/data_archive.py#L119-L162 |
ClimateImpactLab/DataFS | datafs/core/data_archive.py | DataArchive.update | def update(
self,
filepath,
cache=False,
remove=False,
bumpversion=None,
prerelease=None,
dependencies=None,
metadata=None,
message=None):
'''
Enter a new version to a DataArchive
Parameters
----------
filepath : str
The path to the file on your local file system
cache : bool
Turn on caching for this archive if not already on before update
remove : bool
removes a file from your local directory
bumpversion : str
Version component to update on write if archive is versioned. Valid
bumpversion values are 'major', 'minor', and 'patch', representing
the three components of the strict version numbering system (e.g.
"1.2.3"). If bumpversion is None the version number is not updated
on write. Either bumpversion or prerelease (or both) must be a
non-None value. If the archive is not versioned, bumpversion is
ignored.
prerelease : str
Prerelease component of archive version to update on write if
archive is versioned. Valid prerelease values are 'alpha' and
'beta'. Either bumpversion or prerelease (or both) must be a
non-None value. If the archive is not versioned, prerelease is
ignored.
metadata : dict
Updates to archive metadata. Pass {key: None} to remove a key from
the archive's metadata.
'''
if metadata is None:
metadata = {}
latest_version = self.get_latest_version()
hashval = self.api.hash_file(filepath)
checksum = hashval['checksum']
algorithm = hashval['algorithm']
if checksum == self.get_latest_hash():
self.update_metadata(metadata)
if remove and os.path.isfile(filepath):
os.remove(filepath)
return
if self.versioned:
if latest_version is None:
latest_version = BumpableVersion()
next_version = latest_version.bump(
kind=bumpversion,
prerelease=prerelease,
inplace=False)
else:
next_version = None
next_path = self.get_version_path(next_version)
if cache:
self.cache(next_version)
if self.is_cached(next_version):
self.authority.upload(filepath, next_path)
self.api.cache.upload(filepath, next_path, remove=remove)
else:
self.authority.upload(filepath, next_path, remove=remove)
self._update_manager(
archive_metadata=metadata,
version_metadata=dict(
checksum=checksum,
algorithm=algorithm,
version=next_version,
dependencies=dependencies,
message=message)) | python | def update(
self,
filepath,
cache=False,
remove=False,
bumpversion=None,
prerelease=None,
dependencies=None,
metadata=None,
message=None):
'''
Enter a new version to a DataArchive
Parameters
----------
filepath : str
The path to the file on your local file system
cache : bool
Turn on caching for this archive if not already on before update
remove : bool
removes a file from your local directory
bumpversion : str
Version component to update on write if archive is versioned. Valid
bumpversion values are 'major', 'minor', and 'patch', representing
the three components of the strict version numbering system (e.g.
"1.2.3"). If bumpversion is None the version number is not updated
on write. Either bumpversion or prerelease (or both) must be a
non-None value. If the archive is not versioned, bumpversion is
ignored.
prerelease : str
Prerelease component of archive version to update on write if
archive is versioned. Valid prerelease values are 'alpha' and
'beta'. Either bumpversion or prerelease (or both) must be a
non-None value. If the archive is not versioned, prerelease is
ignored.
metadata : dict
Updates to archive metadata. Pass {key: None} to remove a key from
the archive's metadata.
'''
if metadata is None:
metadata = {}
latest_version = self.get_latest_version()
hashval = self.api.hash_file(filepath)
checksum = hashval['checksum']
algorithm = hashval['algorithm']
if checksum == self.get_latest_hash():
self.update_metadata(metadata)
if remove and os.path.isfile(filepath):
os.remove(filepath)
return
if self.versioned:
if latest_version is None:
latest_version = BumpableVersion()
next_version = latest_version.bump(
kind=bumpversion,
prerelease=prerelease,
inplace=False)
else:
next_version = None
next_path = self.get_version_path(next_version)
if cache:
self.cache(next_version)
if self.is_cached(next_version):
self.authority.upload(filepath, next_path)
self.api.cache.upload(filepath, next_path, remove=remove)
else:
self.authority.upload(filepath, next_path, remove=remove)
self._update_manager(
archive_metadata=metadata,
version_metadata=dict(
checksum=checksum,
algorithm=algorithm,
version=next_version,
dependencies=dependencies,
message=message)) | [
"def",
"update",
"(",
"self",
",",
"filepath",
",",
"cache",
"=",
"False",
",",
"remove",
"=",
"False",
",",
"bumpversion",
"=",
"None",
",",
"prerelease",
"=",
"None",
",",
"dependencies",
"=",
"None",
",",
"metadata",
"=",
"None",
",",
"message",
"="... | Enter a new version to a DataArchive
Parameters
----------
filepath : str
The path to the file on your local file system
cache : bool
Turn on caching for this archive if not already on before update
remove : bool
removes a file from your local directory
bumpversion : str
Version component to update on write if archive is versioned. Valid
bumpversion values are 'major', 'minor', and 'patch', representing
the three components of the strict version numbering system (e.g.
"1.2.3"). If bumpversion is None the version number is not updated
on write. Either bumpversion or prerelease (or both) must be a
non-None value. If the archive is not versioned, bumpversion is
ignored.
prerelease : str
Prerelease component of archive version to update on write if
archive is versioned. Valid prerelease values are 'alpha' and
'beta'. Either bumpversion or prerelease (or both) must be a
non-None value. If the archive is not versioned, prerelease is
ignored.
metadata : dict
Updates to archive metadata. Pass {key: None} to remove a key from
the archive's metadata. | [
"Enter",
"a",
"new",
"version",
"to",
"a",
"DataArchive"
] | train | https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/core/data_archive.py#L202-L297 |
ClimateImpactLab/DataFS | datafs/core/data_archive.py | DataArchive._get_default_dependencies | def _get_default_dependencies(self):
'''
Get default dependencies for archive
Get default dependencies from requirements file or (if no requirements
file) from previous version
'''
# Get default dependencies from requirements file
default_dependencies = {
k: v for k,
v in self.api.default_versions.items() if k != self.archive_name}
# If no requirements file or is empty:
if len(default_dependencies) == 0:
# Retrieve dependencies from last archive record
history = self.get_history()
if len(history) > 0:
default_dependencies = history[-1].get('dependencies', {})
return default_dependencies | python | def _get_default_dependencies(self):
'''
Get default dependencies for archive
Get default dependencies from requirements file or (if no requirements
file) from previous version
'''
# Get default dependencies from requirements file
default_dependencies = {
k: v for k,
v in self.api.default_versions.items() if k != self.archive_name}
# If no requirements file or is empty:
if len(default_dependencies) == 0:
# Retrieve dependencies from last archive record
history = self.get_history()
if len(history) > 0:
default_dependencies = history[-1].get('dependencies', {})
return default_dependencies | [
"def",
"_get_default_dependencies",
"(",
"self",
")",
":",
"# Get default dependencies from requirements file",
"default_dependencies",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"self",
".",
"api",
".",
"default_versions",
".",
"items",
"(",
")",
"if"... | Get default dependencies for archive
Get default dependencies from requirements file or (if no requirements
file) from previous version | [
"Get",
"default",
"dependencies",
"for",
"archive"
] | train | https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/core/data_archive.py#L299-L321 |
ClimateImpactLab/DataFS | datafs/core/data_archive.py | DataArchive.open | def open(
self,
mode='r',
version=None,
bumpversion=None,
prerelease=None,
dependencies=None,
metadata=None,
message=None,
*args,
**kwargs):
'''
Opens a file for read/write
Parameters
----------
mode : str
Specifies the mode in which the file is opened (default 'r')
version : str
Version number of the file to open (default latest)
bumpversion : str
Version component to update on write if archive is versioned. Valid
bumpversion values are 'major', 'minor', and 'patch', representing
the three components of the strict version numbering system (e.g.
"1.2.3"). If bumpversion is None the version number is not updated
on write. Either bumpversion or prerelease (or both) must be a
non-None value. If the archive is not versioned, bumpversion is
ignored.
prerelease : str
Prerelease component of archive version to update on write if
archive is versioned. Valid prerelease values are 'alpha' and
'beta'. Either bumpversion or prerelease (or both) must be a
non-None value. If the archive is not versioned, prerelease is
ignored.
metadata : dict
Updates to archive metadata. Pass {key: None} to remove a key from
the archive's metadata.
args, kwargs sent to file system opener
'''
if metadata is None:
metadata = {}
latest_version = self.get_latest_version()
version = _process_version(self, version)
version_hash = self.get_version_hash(version)
if self.versioned:
if latest_version is None:
latest_version = BumpableVersion()
next_version = latest_version.bump(
kind=bumpversion,
prerelease=prerelease,
inplace=False)
msg = "Version must be bumped on write. " \
"Provide bumpversion and/or prerelease."
assert next_version > latest_version, msg
read_path = self.get_version_path(version)
write_path = self.get_version_path(next_version)
else:
read_path = self.archive_path
write_path = self.archive_path
next_version = None
# version_check returns true if fp's hash is current as of read
def version_check(chk):
return chk['checksum'] == version_hash
# Updater updates the manager with the latest version number
def updater(checksum, algorithm):
self._update_manager(
archive_metadata=metadata,
version_metadata=dict(
version=next_version,
dependencies=dependencies,
checksum=checksum,
algorithm=algorithm,
message=message))
opener = data_file.open_file(
self.authority,
self.api.cache,
updater,
version_check,
self.api.hash_file,
read_path,
write_path,
mode=mode,
*args,
**kwargs)
with opener as f:
yield f | python | def open(
self,
mode='r',
version=None,
bumpversion=None,
prerelease=None,
dependencies=None,
metadata=None,
message=None,
*args,
**kwargs):
'''
Opens a file for read/write
Parameters
----------
mode : str
Specifies the mode in which the file is opened (default 'r')
version : str
Version number of the file to open (default latest)
bumpversion : str
Version component to update on write if archive is versioned. Valid
bumpversion values are 'major', 'minor', and 'patch', representing
the three components of the strict version numbering system (e.g.
"1.2.3"). If bumpversion is None the version number is not updated
on write. Either bumpversion or prerelease (or both) must be a
non-None value. If the archive is not versioned, bumpversion is
ignored.
prerelease : str
Prerelease component of archive version to update on write if
archive is versioned. Valid prerelease values are 'alpha' and
'beta'. Either bumpversion or prerelease (or both) must be a
non-None value. If the archive is not versioned, prerelease is
ignored.
metadata : dict
Updates to archive metadata. Pass {key: None} to remove a key from
the archive's metadata.
args, kwargs sent to file system opener
'''
if metadata is None:
metadata = {}
latest_version = self.get_latest_version()
version = _process_version(self, version)
version_hash = self.get_version_hash(version)
if self.versioned:
if latest_version is None:
latest_version = BumpableVersion()
next_version = latest_version.bump(
kind=bumpversion,
prerelease=prerelease,
inplace=False)
msg = "Version must be bumped on write. " \
"Provide bumpversion and/or prerelease."
assert next_version > latest_version, msg
read_path = self.get_version_path(version)
write_path = self.get_version_path(next_version)
else:
read_path = self.archive_path
write_path = self.archive_path
next_version = None
# version_check returns true if fp's hash is current as of read
def version_check(chk):
return chk['checksum'] == version_hash
# Updater updates the manager with the latest version number
def updater(checksum, algorithm):
self._update_manager(
archive_metadata=metadata,
version_metadata=dict(
version=next_version,
dependencies=dependencies,
checksum=checksum,
algorithm=algorithm,
message=message))
opener = data_file.open_file(
self.authority,
self.api.cache,
updater,
version_check,
self.api.hash_file,
read_path,
write_path,
mode=mode,
*args,
**kwargs)
with opener as f:
yield f | [
"def",
"open",
"(",
"self",
",",
"mode",
"=",
"'r'",
",",
"version",
"=",
"None",
",",
"bumpversion",
"=",
"None",
",",
"prerelease",
"=",
"None",
",",
"dependencies",
"=",
"None",
",",
"metadata",
"=",
"None",
",",
"message",
"=",
"None",
",",
"*",
... | Opens a file for read/write
Parameters
----------
mode : str
Specifies the mode in which the file is opened (default 'r')
version : str
Version number of the file to open (default latest)
bumpversion : str
Version component to update on write if archive is versioned. Valid
bumpversion values are 'major', 'minor', and 'patch', representing
the three components of the strict version numbering system (e.g.
"1.2.3"). If bumpversion is None the version number is not updated
on write. Either bumpversion or prerelease (or both) must be a
non-None value. If the archive is not versioned, bumpversion is
ignored.
prerelease : str
Prerelease component of archive version to update on write if
archive is versioned. Valid prerelease values are 'alpha' and
'beta'. Either bumpversion or prerelease (or both) must be a
non-None value. If the archive is not versioned, prerelease is
ignored.
metadata : dict
Updates to archive metadata. Pass {key: None} to remove a key from
the archive's metadata.
args, kwargs sent to file system opener | [
"Opens",
"a",
"file",
"for",
"read",
"/",
"write"
] | train | https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/core/data_archive.py#L353-L459 |
ClimateImpactLab/DataFS | datafs/core/data_archive.py | DataArchive.get_local_path | def get_local_path(
self,
version=None,
bumpversion=None,
prerelease=None,
dependencies=None,
metadata=None,
message=None):
'''
Returns a local path for read/write
Parameters
----------
version : str
Version number of the file to retrieve (default latest)
bumpversion : str
Version component to update on write if archive is versioned. Valid
bumpversion values are 'major', 'minor', and 'patch', representing
the three components of the strict version numbering system (e.g.
"1.2.3"). If bumpversion is None the version number is not updated
on write. Either bumpversion or prerelease (or both) must be a
non-None value. If the archive is not versioned, bumpversion is
ignored.
prerelease : str
Prerelease component of archive version to update on write if
archive is versioned. Valid prerelease values are 'alpha' and
'beta'. Either bumpversion or prerelease (or both) must be a
non-None value. If the archive is not versioned, prerelease is
ignored.
metadata : dict
Updates to archive metadata. Pass {key: None} to remove a key from
the archive's metadata.
'''
if metadata is None:
metadata = {}
latest_version = self.get_latest_version()
version = _process_version(self, version)
version_hash = self.get_version_hash(version)
if self.versioned:
if latest_version is None:
latest_version = BumpableVersion()
next_version = latest_version.bump(
kind=bumpversion,
prerelease=prerelease,
inplace=False)
msg = "Version must be bumped on write. " \
"Provide bumpversion and/or prerelease."
assert next_version > latest_version, msg
read_path = self.get_version_path(version)
write_path = self.get_version_path(next_version)
else:
read_path = self.archive_path
write_path = self.archive_path
next_version = None
# version_check returns true if fp's hash is current as of read
def version_check(chk):
return chk['checksum'] == version_hash
# Updater updates the manager with the latest version number
def updater(checksum, algorithm):
self._update_manager(
archive_metadata=metadata,
version_metadata=dict(
version=next_version,
dependencies=dependencies,
checksum=checksum,
algorithm=algorithm,
message=message))
path = data_file.get_local_path(
self.authority,
self.api.cache,
updater,
version_check,
self.api.hash_file,
read_path,
write_path)
with path as fp:
yield fp | python | def get_local_path(
self,
version=None,
bumpversion=None,
prerelease=None,
dependencies=None,
metadata=None,
message=None):
'''
Returns a local path for read/write
Parameters
----------
version : str
Version number of the file to retrieve (default latest)
bumpversion : str
Version component to update on write if archive is versioned. Valid
bumpversion values are 'major', 'minor', and 'patch', representing
the three components of the strict version numbering system (e.g.
"1.2.3"). If bumpversion is None the version number is not updated
on write. Either bumpversion or prerelease (or both) must be a
non-None value. If the archive is not versioned, bumpversion is
ignored.
prerelease : str
Prerelease component of archive version to update on write if
archive is versioned. Valid prerelease values are 'alpha' and
'beta'. Either bumpversion or prerelease (or both) must be a
non-None value. If the archive is not versioned, prerelease is
ignored.
metadata : dict
Updates to archive metadata. Pass {key: None} to remove a key from
the archive's metadata.
'''
if metadata is None:
metadata = {}
latest_version = self.get_latest_version()
version = _process_version(self, version)
version_hash = self.get_version_hash(version)
if self.versioned:
if latest_version is None:
latest_version = BumpableVersion()
next_version = latest_version.bump(
kind=bumpversion,
prerelease=prerelease,
inplace=False)
msg = "Version must be bumped on write. " \
"Provide bumpversion and/or prerelease."
assert next_version > latest_version, msg
read_path = self.get_version_path(version)
write_path = self.get_version_path(next_version)
else:
read_path = self.archive_path
write_path = self.archive_path
next_version = None
# version_check returns true if fp's hash is current as of read
def version_check(chk):
return chk['checksum'] == version_hash
# Updater updates the manager with the latest version number
def updater(checksum, algorithm):
self._update_manager(
archive_metadata=metadata,
version_metadata=dict(
version=next_version,
dependencies=dependencies,
checksum=checksum,
algorithm=algorithm,
message=message))
path = data_file.get_local_path(
self.authority,
self.api.cache,
updater,
version_check,
self.api.hash_file,
read_path,
write_path)
with path as fp:
yield fp | [
"def",
"get_local_path",
"(",
"self",
",",
"version",
"=",
"None",
",",
"bumpversion",
"=",
"None",
",",
"prerelease",
"=",
"None",
",",
"dependencies",
"=",
"None",
",",
"metadata",
"=",
"None",
",",
"message",
"=",
"None",
")",
":",
"if",
"metadata",
... | Returns a local path for read/write
Parameters
----------
version : str
Version number of the file to retrieve (default latest)
bumpversion : str
Version component to update on write if archive is versioned. Valid
bumpversion values are 'major', 'minor', and 'patch', representing
the three components of the strict version numbering system (e.g.
"1.2.3"). If bumpversion is None the version number is not updated
on write. Either bumpversion or prerelease (or both) must be a
non-None value. If the archive is not versioned, bumpversion is
ignored.
prerelease : str
Prerelease component of archive version to update on write if
archive is versioned. Valid prerelease values are 'alpha' and
'beta'. Either bumpversion or prerelease (or both) must be a
non-None value. If the archive is not versioned, prerelease is
ignored.
metadata : dict
Updates to archive metadata. Pass {key: None} to remove a key from
the archive's metadata. | [
"Returns",
"a",
"local",
"path",
"for",
"read",
"/",
"write"
] | train | https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/core/data_archive.py#L462-L556 |
ClimateImpactLab/DataFS | datafs/core/data_archive.py | DataArchive.download | def download(self, filepath, version=None):
'''
Downloads a file from authority to local path
1. First checks in cache to check if file is there and if it is, is it
up to date
2. If it is not up to date, it will download the file to cache
'''
version = _process_version(self, version)
dirname, filename = os.path.split(
os.path.abspath(os.path.expanduser(filepath)))
assert os.path.isdir(dirname), 'Directory not found: "{}"'.format(
dirname)
local = OSFS(dirname)
version_hash = self.get_version_hash(version)
# version_check returns true if fp's hash is current as of read
def version_check(chk):
return chk['checksum'] == version_hash
if os.path.exists(filepath):
if version_check(self.api.hash_file(filepath)):
return
read_path = self.get_version_path(version)
with data_file._choose_read_fs(
self.authority,
self.api.cache,
read_path,
version_check,
self.api.hash_file) as read_fs:
fs.utils.copyfile(
read_fs,
read_path,
local,
filename) | python | def download(self, filepath, version=None):
'''
Downloads a file from authority to local path
1. First checks in cache to check if file is there and if it is, is it
up to date
2. If it is not up to date, it will download the file to cache
'''
version = _process_version(self, version)
dirname, filename = os.path.split(
os.path.abspath(os.path.expanduser(filepath)))
assert os.path.isdir(dirname), 'Directory not found: "{}"'.format(
dirname)
local = OSFS(dirname)
version_hash = self.get_version_hash(version)
# version_check returns true if fp's hash is current as of read
def version_check(chk):
return chk['checksum'] == version_hash
if os.path.exists(filepath):
if version_check(self.api.hash_file(filepath)):
return
read_path = self.get_version_path(version)
with data_file._choose_read_fs(
self.authority,
self.api.cache,
read_path,
version_check,
self.api.hash_file) as read_fs:
fs.utils.copyfile(
read_fs,
read_path,
local,
filename) | [
"def",
"download",
"(",
"self",
",",
"filepath",
",",
"version",
"=",
"None",
")",
":",
"version",
"=",
"_process_version",
"(",
"self",
",",
"version",
")",
"dirname",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"os",
".",
"path",
".... | Downloads a file from authority to local path
1. First checks in cache to check if file is there and if it is, is it
up to date
2. If it is not up to date, it will download the file to cache | [
"Downloads",
"a",
"file",
"from",
"authority",
"to",
"local",
"path"
] | train | https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/core/data_archive.py#L558-L600 |
ClimateImpactLab/DataFS | datafs/core/data_archive.py | DataArchive.delete | def delete(self):
'''
Delete the archive
.. warning::
Deleting an archive will erase all data and metadata permanently.
For help setting user permissions, see
:ref:`Administrative Tools <admin>`
'''
versions = self.get_versions()
self.api.manager.delete_archive_record(self.archive_name)
for version in versions:
if self.authority.fs.exists(self.get_version_path(version)):
self.authority.fs.remove(self.get_version_path(version))
if self.api.cache:
if self.api.cache.fs.exists(self.get_version_path(version)):
self.api.cache.fs.remove(self.get_version_path(version))
if self.authority.fs.exists(self.archive_name):
self.authority.fs.removedir(self.archive_name)
if self.api.cache:
if self.api.cache.fs.exists(self.archive_name):
self.api.cache.fs.removedir(self.archive_name) | python | def delete(self):
'''
Delete the archive
.. warning::
Deleting an archive will erase all data and metadata permanently.
For help setting user permissions, see
:ref:`Administrative Tools <admin>`
'''
versions = self.get_versions()
self.api.manager.delete_archive_record(self.archive_name)
for version in versions:
if self.authority.fs.exists(self.get_version_path(version)):
self.authority.fs.remove(self.get_version_path(version))
if self.api.cache:
if self.api.cache.fs.exists(self.get_version_path(version)):
self.api.cache.fs.remove(self.get_version_path(version))
if self.authority.fs.exists(self.archive_name):
self.authority.fs.removedir(self.archive_name)
if self.api.cache:
if self.api.cache.fs.exists(self.archive_name):
self.api.cache.fs.removedir(self.archive_name) | [
"def",
"delete",
"(",
"self",
")",
":",
"versions",
"=",
"self",
".",
"get_versions",
"(",
")",
"self",
".",
"api",
".",
"manager",
".",
"delete_archive_record",
"(",
"self",
".",
"archive_name",
")",
"for",
"version",
"in",
"versions",
":",
"if",
"self"... | Delete the archive
.. warning::
Deleting an archive will erase all data and metadata permanently.
For help setting user permissions, see
:ref:`Administrative Tools <admin>` | [
"Delete",
"the",
"archive"
] | train | https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/core/data_archive.py#L649-L676 |
ClimateImpactLab/DataFS | datafs/core/data_archive.py | DataArchive.isfile | def isfile(self, version=None, *args, **kwargs):
'''
Check whether the path exists and is a file
'''
version = _process_version(self, version)
path = self.get_version_path(version)
self.authority.fs.isfile(path, *args, **kwargs) | python | def isfile(self, version=None, *args, **kwargs):
'''
Check whether the path exists and is a file
'''
version = _process_version(self, version)
path = self.get_version_path(version)
self.authority.fs.isfile(path, *args, **kwargs) | [
"def",
"isfile",
"(",
"self",
",",
"version",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"version",
"=",
"_process_version",
"(",
"self",
",",
"version",
")",
"path",
"=",
"self",
".",
"get_version_path",
"(",
"version",
")",
"... | Check whether the path exists and is a file | [
"Check",
"whether",
"the",
"path",
"exists",
"and",
"is",
"a",
"file"
] | train | https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/core/data_archive.py#L678-L685 |
ClimateImpactLab/DataFS | datafs/core/data_archive.py | DataArchive.is_cached | def is_cached(self, version=None):
'''
Set the cache property to start/stop file caching for this archive
'''
version = _process_version(self, version)
if self.api.cache and self.api.cache.fs.isfile(
self.get_version_path(version)):
return True
return False | python | def is_cached(self, version=None):
'''
Set the cache property to start/stop file caching for this archive
'''
version = _process_version(self, version)
if self.api.cache and self.api.cache.fs.isfile(
self.get_version_path(version)):
return True
return False | [
"def",
"is_cached",
"(",
"self",
",",
"version",
"=",
"None",
")",
":",
"version",
"=",
"_process_version",
"(",
"self",
",",
"version",
")",
"if",
"self",
".",
"api",
".",
"cache",
"and",
"self",
".",
"api",
".",
"cache",
".",
"fs",
".",
"isfile",
... | Set the cache property to start/stop file caching for this archive | [
"Set",
"the",
"cache",
"property",
"to",
"start",
"/",
"stop",
"file",
"caching",
"for",
"this",
"archive"
] | train | https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/core/data_archive.py#L732-L742 |
ClimateImpactLab/DataFS | datafs/core/data_archive.py | DataArchive.get_dependencies | def get_dependencies(self, version=None):
'''
Parameters
----------
version: str
string representing version number whose dependencies you are
looking up
'''
version = _process_version(self, version)
history = self.get_history()
for v in reversed(history):
if BumpableVersion(v['version']) == version:
return v['dependencies']
raise ValueError('Version {} not found'.format(version)) | python | def get_dependencies(self, version=None):
'''
Parameters
----------
version: str
string representing version number whose dependencies you are
looking up
'''
version = _process_version(self, version)
history = self.get_history()
for v in reversed(history):
if BumpableVersion(v['version']) == version:
return v['dependencies']
raise ValueError('Version {} not found'.format(version)) | [
"def",
"get_dependencies",
"(",
"self",
",",
"version",
"=",
"None",
")",
":",
"version",
"=",
"_process_version",
"(",
"self",
",",
"version",
")",
"history",
"=",
"self",
".",
"get_history",
"(",
")",
"for",
"v",
"in",
"reversed",
"(",
"history",
")",
... | Parameters
----------
version: str
string representing version number whose dependencies you are
looking up | [
"Parameters",
"----------",
"version",
":",
"str",
"string",
"representing",
"version",
"number",
"whose",
"dependencies",
"you",
"are",
"looking",
"up"
] | train | https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/core/data_archive.py#L762-L778 |
ClimateImpactLab/DataFS | datafs/core/data_archive.py | DataArchive.add_tags | def add_tags(self, *tags):
'''
Set tags for a given archive
'''
normed_tags = self.api.manager._normalize_tags(tags)
self.api.manager.add_tags(self.archive_name, normed_tags) | python | def add_tags(self, *tags):
'''
Set tags for a given archive
'''
normed_tags = self.api.manager._normalize_tags(tags)
self.api.manager.add_tags(self.archive_name, normed_tags) | [
"def",
"add_tags",
"(",
"self",
",",
"*",
"tags",
")",
":",
"normed_tags",
"=",
"self",
".",
"api",
".",
"manager",
".",
"_normalize_tags",
"(",
"tags",
")",
"self",
".",
"api",
".",
"manager",
".",
"add_tags",
"(",
"self",
".",
"archive_name",
",",
... | Set tags for a given archive | [
"Set",
"tags",
"for",
"a",
"given",
"archive"
] | train | https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/core/data_archive.py#L803-L808 |
asyncdef/apyio | apyio/__init__.py | open | def open(
file,
mode="r",
buffering=-1,
encoding=None,
errors=None,
newline=None,
closefd=True,
opener=None,
):
r"""Open file and return a stream. Raise OSError upon failure.
file is either a text or byte string giving the name (and the path
if the file isn't in the current working directory) of the file to
be opened or an integer file descriptor of the file to be
wrapped. (If a file descriptor is given, it is closed when the
returned I/O object is closed, unless closefd is set to False.)
mode is an optional string that specifies the mode in which the file is
opened. It defaults to 'r' which means open for reading in text mode. Other
common values are 'w' for writing (truncating the file if it already
exists), 'x' for exclusive creation of a new file, and 'a' for appending
(which on some Unix systems, means that all writes append to the end of the
file regardless of the current seek position). In text mode, if encoding is
not specified the encoding used is platform dependent. (For reading and
writing raw bytes use binary mode and leave encoding unspecified.) The
available modes are:
========= ===============================================================
Character Meaning
--------- ---------------------------------------------------------------
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (deprecated)
========= ===============================================================
The default mode is 'rt' (open for reading text). For binary random
access, the mode 'w+b' opens and truncates the file to 0 bytes, while
'r+b' opens the file without truncation. The 'x' mode implies 'w' and
raises an `FileExistsError` if the file already exists.
Python distinguishes between files opened in binary and text modes,
even when the underlying operating system doesn't. Files opened in
binary mode (appending 'b' to the mode argument) return contents as
bytes objects without any decoding. In text mode (the default, or when
't' is appended to the mode argument), the contents of the file are
returned as strings, the bytes having been first decoded using a
platform-dependent encoding or using the specified encoding if given.
'U' mode is deprecated and will raise an exception in future versions
of Python. It has no effect in Python 3. Use newline to control
universal newlines mode.
buffering is an optional integer used to set the buffering policy.
Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
line buffering (only usable in text mode), and an integer > 1 to indicate
the size of a fixed-size chunk buffer. When no buffering argument is
given, the default buffering policy works as follows:
* Binary files are buffered in fixed-size chunks; the size of the buffer
is chosen using a heuristic trying to determine the underlying device's
"block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
On many systems, the buffer will typically be 4096 or 8192 bytes long.
* "Interactive" text files (files for which isatty() returns True)
use line buffering. Other text files use the policy described above
for binary files.
encoding is the str name of the encoding used to decode or encode the
file. This should only be used in text mode. The default encoding is
platform dependent, but any encoding supported by Python can be
passed. See the codecs module for the list of supported encodings.
errors is an optional string that specifies how encoding errors are to
be handled---this argument should not be used in binary mode. Pass
'strict' to raise a ValueError exception if there is an encoding error
(the default of None has the same effect), or pass 'ignore' to ignore
errors. (Note that ignoring encoding errors can lead to data loss.)
See the documentation for codecs.register for a list of the permitted
encoding error strings.
newline is a string controlling how universal newlines works (it only
applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It
works as follows:
* On input, if newline is None, universal newlines mode is
enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
these are translated into '\n' before being returned to the
caller. If it is '', universal newline mode is enabled, but line
endings are returned to the caller untranslated. If it has any of
the other legal values, input lines are only terminated by the given
string, and the line ending is returned to the caller untranslated.
* On output, if newline is None, any '\n' characters written are
translated to the system default line separator, os.linesep. If
newline is '', no translation takes place. If newline is any of the
other legal values, any '\n' characters written are translated to
the given string.
closedfd is a bool. If closefd is False, the underlying file descriptor
will be kept open when the file is closed. This does not work when a file
name is given and must be True in that case.
The newly created file is non-inheritable.
A custom opener can be used by passing a callable as *opener*. The
underlying file descriptor for the file object is then obtained by calling
*opener* with (*file*, *flags*). *opener* must return an open file
descriptor (passing os.open as *opener* results in functionality similar to
passing None).
open() returns a file object whose type depends on the mode, and
through which the standard file operations such as reading and writing
are performed. When open() is used to open a file in a text mode ('w',
'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
a file in a binary mode, the returned class varies: in read binary
mode, it returns a BufferedReader; in write binary and append binary
modes, it returns a BufferedWriter, and in read/write mode, it returns
a BufferedRandom.
It is also possible to use a string or bytearray as a file for both
reading and writing. For strings StringIO can be used like a file
opened in a text mode, and for bytes a BytesIO can be used like a file
opened in a binary mode.
"""
result = sync_io.open(
file,
mode,
buffering,
encoding,
errors,
newline,
closefd,
opener,
)
return wrap_file(result) | python | def open(
file,
mode="r",
buffering=-1,
encoding=None,
errors=None,
newline=None,
closefd=True,
opener=None,
):
r"""Open file and return a stream. Raise OSError upon failure.
file is either a text or byte string giving the name (and the path
if the file isn't in the current working directory) of the file to
be opened or an integer file descriptor of the file to be
wrapped. (If a file descriptor is given, it is closed when the
returned I/O object is closed, unless closefd is set to False.)
mode is an optional string that specifies the mode in which the file is
opened. It defaults to 'r' which means open for reading in text mode. Other
common values are 'w' for writing (truncating the file if it already
exists), 'x' for exclusive creation of a new file, and 'a' for appending
(which on some Unix systems, means that all writes append to the end of the
file regardless of the current seek position). In text mode, if encoding is
not specified the encoding used is platform dependent. (For reading and
writing raw bytes use binary mode and leave encoding unspecified.) The
available modes are:
========= ===============================================================
Character Meaning
--------- ---------------------------------------------------------------
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (deprecated)
========= ===============================================================
The default mode is 'rt' (open for reading text). For binary random
access, the mode 'w+b' opens and truncates the file to 0 bytes, while
'r+b' opens the file without truncation. The 'x' mode implies 'w' and
raises an `FileExistsError` if the file already exists.
Python distinguishes between files opened in binary and text modes,
even when the underlying operating system doesn't. Files opened in
binary mode (appending 'b' to the mode argument) return contents as
bytes objects without any decoding. In text mode (the default, or when
't' is appended to the mode argument), the contents of the file are
returned as strings, the bytes having been first decoded using a
platform-dependent encoding or using the specified encoding if given.
'U' mode is deprecated and will raise an exception in future versions
of Python. It has no effect in Python 3. Use newline to control
universal newlines mode.
buffering is an optional integer used to set the buffering policy.
Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
line buffering (only usable in text mode), and an integer > 1 to indicate
the size of a fixed-size chunk buffer. When no buffering argument is
given, the default buffering policy works as follows:
* Binary files are buffered in fixed-size chunks; the size of the buffer
is chosen using a heuristic trying to determine the underlying device's
"block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
On many systems, the buffer will typically be 4096 or 8192 bytes long.
* "Interactive" text files (files for which isatty() returns True)
use line buffering. Other text files use the policy described above
for binary files.
encoding is the str name of the encoding used to decode or encode the
file. This should only be used in text mode. The default encoding is
platform dependent, but any encoding supported by Python can be
passed. See the codecs module for the list of supported encodings.
errors is an optional string that specifies how encoding errors are to
be handled---this argument should not be used in binary mode. Pass
'strict' to raise a ValueError exception if there is an encoding error
(the default of None has the same effect), or pass 'ignore' to ignore
errors. (Note that ignoring encoding errors can lead to data loss.)
See the documentation for codecs.register for a list of the permitted
encoding error strings.
newline is a string controlling how universal newlines works (it only
applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It
works as follows:
* On input, if newline is None, universal newlines mode is
enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
these are translated into '\n' before being returned to the
caller. If it is '', universal newline mode is enabled, but line
endings are returned to the caller untranslated. If it has any of
the other legal values, input lines are only terminated by the given
string, and the line ending is returned to the caller untranslated.
* On output, if newline is None, any '\n' characters written are
translated to the system default line separator, os.linesep. If
newline is '', no translation takes place. If newline is any of the
other legal values, any '\n' characters written are translated to
the given string.
closedfd is a bool. If closefd is False, the underlying file descriptor
will be kept open when the file is closed. This does not work when a file
name is given and must be True in that case.
The newly created file is non-inheritable.
A custom opener can be used by passing a callable as *opener*. The
underlying file descriptor for the file object is then obtained by calling
*opener* with (*file*, *flags*). *opener* must return an open file
descriptor (passing os.open as *opener* results in functionality similar to
passing None).
open() returns a file object whose type depends on the mode, and
through which the standard file operations such as reading and writing
are performed. When open() is used to open a file in a text mode ('w',
'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
a file in a binary mode, the returned class varies: in read binary
mode, it returns a BufferedReader; in write binary and append binary
modes, it returns a BufferedWriter, and in read/write mode, it returns
a BufferedRandom.
It is also possible to use a string or bytearray as a file for both
reading and writing. For strings StringIO can be used like a file
opened in a text mode, and for bytes a BytesIO can be used like a file
opened in a binary mode.
"""
result = sync_io.open(
file,
mode,
buffering,
encoding,
errors,
newline,
closefd,
opener,
)
return wrap_file(result) | [
"def",
"open",
"(",
"file",
",",
"mode",
"=",
"\"r\"",
",",
"buffering",
"=",
"-",
"1",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"None",
",",
"newline",
"=",
"None",
",",
"closefd",
"=",
"True",
",",
"opener",
"=",
"None",
",",
")",
":",... | r"""Open file and return a stream. Raise OSError upon failure.
file is either a text or byte string giving the name (and the path
if the file isn't in the current working directory) of the file to
be opened or an integer file descriptor of the file to be
wrapped. (If a file descriptor is given, it is closed when the
returned I/O object is closed, unless closefd is set to False.)
mode is an optional string that specifies the mode in which the file is
opened. It defaults to 'r' which means open for reading in text mode. Other
common values are 'w' for writing (truncating the file if it already
exists), 'x' for exclusive creation of a new file, and 'a' for appending
(which on some Unix systems, means that all writes append to the end of the
file regardless of the current seek position). In text mode, if encoding is
not specified the encoding used is platform dependent. (For reading and
writing raw bytes use binary mode and leave encoding unspecified.) The
available modes are:
========= ===============================================================
Character Meaning
--------- ---------------------------------------------------------------
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (deprecated)
========= ===============================================================
The default mode is 'rt' (open for reading text). For binary random
access, the mode 'w+b' opens and truncates the file to 0 bytes, while
'r+b' opens the file without truncation. The 'x' mode implies 'w' and
raises an `FileExistsError` if the file already exists.
Python distinguishes between files opened in binary and text modes,
even when the underlying operating system doesn't. Files opened in
binary mode (appending 'b' to the mode argument) return contents as
bytes objects without any decoding. In text mode (the default, or when
't' is appended to the mode argument), the contents of the file are
returned as strings, the bytes having been first decoded using a
platform-dependent encoding or using the specified encoding if given.
'U' mode is deprecated and will raise an exception in future versions
of Python. It has no effect in Python 3. Use newline to control
universal newlines mode.
buffering is an optional integer used to set the buffering policy.
Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
line buffering (only usable in text mode), and an integer > 1 to indicate
the size of a fixed-size chunk buffer. When no buffering argument is
given, the default buffering policy works as follows:
* Binary files are buffered in fixed-size chunks; the size of the buffer
is chosen using a heuristic trying to determine the underlying device's
"block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
On many systems, the buffer will typically be 4096 or 8192 bytes long.
* "Interactive" text files (files for which isatty() returns True)
use line buffering. Other text files use the policy described above
for binary files.
encoding is the str name of the encoding used to decode or encode the
file. This should only be used in text mode. The default encoding is
platform dependent, but any encoding supported by Python can be
passed. See the codecs module for the list of supported encodings.
errors is an optional string that specifies how encoding errors are to
be handled---this argument should not be used in binary mode. Pass
'strict' to raise a ValueError exception if there is an encoding error
(the default of None has the same effect), or pass 'ignore' to ignore
errors. (Note that ignoring encoding errors can lead to data loss.)
See the documentation for codecs.register for a list of the permitted
encoding error strings.
newline is a string controlling how universal newlines works (it only
applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It
works as follows:
* On input, if newline is None, universal newlines mode is
enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
these are translated into '\n' before being returned to the
caller. If it is '', universal newline mode is enabled, but line
endings are returned to the caller untranslated. If it has any of
the other legal values, input lines are only terminated by the given
string, and the line ending is returned to the caller untranslated.
* On output, if newline is None, any '\n' characters written are
translated to the system default line separator, os.linesep. If
newline is '', no translation takes place. If newline is any of the
other legal values, any '\n' characters written are translated to
the given string.
closedfd is a bool. If closefd is False, the underlying file descriptor
will be kept open when the file is closed. This does not work when a file
name is given and must be True in that case.
The newly created file is non-inheritable.
A custom opener can be used by passing a callable as *opener*. The
underlying file descriptor for the file object is then obtained by calling
*opener* with (*file*, *flags*). *opener* must return an open file
descriptor (passing os.open as *opener* results in functionality similar to
passing None).
open() returns a file object whose type depends on the mode, and
through which the standard file operations such as reading and writing
are performed. When open() is used to open a file in a text mode ('w',
'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
a file in a binary mode, the returned class varies: in read binary
mode, it returns a BufferedReader; in write binary and append binary
modes, it returns a BufferedWriter, and in read/write mode, it returns
a BufferedRandom.
It is also possible to use a string or bytearray as a file for both
reading and writing. For strings StringIO can be used like a file
opened in a text mode, and for bytes a BytesIO can be used like a file
opened in a binary mode. | [
"r",
"Open",
"file",
"and",
"return",
"a",
"stream",
".",
"Raise",
"OSError",
"upon",
"failure",
"."
] | train | https://github.com/asyncdef/apyio/blob/d6b914929269b8795ca4d6b1ede8a393841cbc29/apyio/__init__.py#L6-L147 |
asyncdef/apyio | apyio/__init__.py | wrap_file | def wrap_file(file_like_obj):
"""Wrap a file like object in an async stream wrapper.
Files generated with `open()` may be one of several types. This
convenience function retruns the stream wrapped in the most appropriate
wrapper for the type. If the stream is already wrapped it is returned
unaltered.
"""
if isinstance(file_like_obj, AsyncIOBaseWrapper):
return file_like_obj
if isinstance(file_like_obj, sync_io.FileIO):
return AsyncFileIOWrapper(file_like_obj)
if isinstance(file_like_obj, sync_io.BufferedRandom):
return AsyncBufferedRandomWrapper(file_like_obj)
if isinstance(file_like_obj, sync_io.BufferedReader):
return AsyncBufferedReaderWrapper(file_like_obj)
if isinstance(file_like_obj, sync_io.BufferedWriter):
return AsyncBufferedWriterWrapper(file_like_obj)
if isinstance(file_like_obj, sync_io.TextIOWrapper):
return AsyncTextIOWrapperWrapper(file_like_obj)
raise TypeError(
'Unrecognized file stream type {}.'.format(file_like_obj.__class__),
) | python | def wrap_file(file_like_obj):
"""Wrap a file like object in an async stream wrapper.
Files generated with `open()` may be one of several types. This
convenience function retruns the stream wrapped in the most appropriate
wrapper for the type. If the stream is already wrapped it is returned
unaltered.
"""
if isinstance(file_like_obj, AsyncIOBaseWrapper):
return file_like_obj
if isinstance(file_like_obj, sync_io.FileIO):
return AsyncFileIOWrapper(file_like_obj)
if isinstance(file_like_obj, sync_io.BufferedRandom):
return AsyncBufferedRandomWrapper(file_like_obj)
if isinstance(file_like_obj, sync_io.BufferedReader):
return AsyncBufferedReaderWrapper(file_like_obj)
if isinstance(file_like_obj, sync_io.BufferedWriter):
return AsyncBufferedWriterWrapper(file_like_obj)
if isinstance(file_like_obj, sync_io.TextIOWrapper):
return AsyncTextIOWrapperWrapper(file_like_obj)
raise TypeError(
'Unrecognized file stream type {}.'.format(file_like_obj.__class__),
) | [
"def",
"wrap_file",
"(",
"file_like_obj",
")",
":",
"if",
"isinstance",
"(",
"file_like_obj",
",",
"AsyncIOBaseWrapper",
")",
":",
"return",
"file_like_obj",
"if",
"isinstance",
"(",
"file_like_obj",
",",
"sync_io",
".",
"FileIO",
")",
":",
"return",
"AsyncFileI... | Wrap a file like object in an async stream wrapper.
Files generated with `open()` may be one of several types. This
convenience function retruns the stream wrapped in the most appropriate
wrapper for the type. If the stream is already wrapped it is returned
unaltered. | [
"Wrap",
"a",
"file",
"like",
"object",
"in",
"an",
"async",
"stream",
"wrapper",
"."
] | train | https://github.com/asyncdef/apyio/blob/d6b914929269b8795ca4d6b1ede8a393841cbc29/apyio/__init__.py#L150-L184 |
asyncdef/apyio | apyio/__init__.py | StringIO | def StringIO(*args, **kwargs):
"""StringIO constructor shim for the async wrapper."""
raw = sync_io.StringIO(*args, **kwargs)
return AsyncStringIOWrapper(raw) | python | def StringIO(*args, **kwargs):
"""StringIO constructor shim for the async wrapper."""
raw = sync_io.StringIO(*args, **kwargs)
return AsyncStringIOWrapper(raw) | [
"def",
"StringIO",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"raw",
"=",
"sync_io",
".",
"StringIO",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"AsyncStringIOWrapper",
"(",
"raw",
")"
] | StringIO constructor shim for the async wrapper. | [
"StringIO",
"constructor",
"shim",
"for",
"the",
"async",
"wrapper",
"."
] | train | https://github.com/asyncdef/apyio/blob/d6b914929269b8795ca4d6b1ede8a393841cbc29/apyio/__init__.py#L882-L885 |
asyncdef/apyio | apyio/__init__.py | BytesIO | def BytesIO(*args, **kwargs):
"""BytesIO constructor shim for the async wrapper."""
raw = sync_io.BytesIO(*args, **kwargs)
return AsyncBytesIOWrapper(raw) | python | def BytesIO(*args, **kwargs):
"""BytesIO constructor shim for the async wrapper."""
raw = sync_io.BytesIO(*args, **kwargs)
return AsyncBytesIOWrapper(raw) | [
"def",
"BytesIO",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"raw",
"=",
"sync_io",
".",
"BytesIO",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"AsyncBytesIOWrapper",
"(",
"raw",
")"
] | BytesIO constructor shim for the async wrapper. | [
"BytesIO",
"constructor",
"shim",
"for",
"the",
"async",
"wrapper",
"."
] | train | https://github.com/asyncdef/apyio/blob/d6b914929269b8795ca4d6b1ede8a393841cbc29/apyio/__init__.py#L888-L891 |
asyncdef/apyio | apyio/__init__.py | AsyncFileIOWrapper.seek | async def seek(self, pos, whence=sync_io.SEEK_SET):
"""Move to new file position.
Argument offset is a byte count. Optional argument whence defaults to
SEEK_SET or 0 (offset from start of file, offset should be >= 0); other
values are SEEK_CUR or 1 (move relative to current position, positive
or negative), and SEEK_END or 2 (move relative to end of file, usually
negative, although many platforms allow seeking beyond the end of a
file).
Note that not all file objects are seekable.
"""
return self._stream.seek(pos, whence) | python | async def seek(self, pos, whence=sync_io.SEEK_SET):
"""Move to new file position.
Argument offset is a byte count. Optional argument whence defaults to
SEEK_SET or 0 (offset from start of file, offset should be >= 0); other
values are SEEK_CUR or 1 (move relative to current position, positive
or negative), and SEEK_END or 2 (move relative to end of file, usually
negative, although many platforms allow seeking beyond the end of a
file).
Note that not all file objects are seekable.
"""
return self._stream.seek(pos, whence) | [
"async",
"def",
"seek",
"(",
"self",
",",
"pos",
",",
"whence",
"=",
"sync_io",
".",
"SEEK_SET",
")",
":",
"return",
"self",
".",
"_stream",
".",
"seek",
"(",
"pos",
",",
"whence",
")"
] | Move to new file position.
Argument offset is a byte count. Optional argument whence defaults to
SEEK_SET or 0 (offset from start of file, offset should be >= 0); other
values are SEEK_CUR or 1 (move relative to current position, positive
or negative), and SEEK_END or 2 (move relative to end of file, usually
negative, although many platforms allow seeking beyond the end of a
file).
Note that not all file objects are seekable. | [
"Move",
"to",
"new",
"file",
"position",
"."
] | train | https://github.com/asyncdef/apyio/blob/d6b914929269b8795ca4d6b1ede8a393841cbc29/apyio/__init__.py#L614-L626 |
cebel/pyctd | src/pyctd/manager/query.py | QueryManager._limit_and_df | def _limit_and_df(self, query, limit, as_df=False):
"""adds a limit (limit==None := no limit) to any query and allow a return as pandas.DataFrame
:param bool as_df: if is set to True results return as pandas.DataFrame
:param `sqlalchemy.orm.query.Query` query: SQL Alchemy query
:param int limit: maximum number of results
:return: query result of pyctd.manager.models.XY objects
"""
if limit:
query = query.limit(limit)
if as_df:
results = read_sql(query.statement, self.engine)
else:
results = query.all()
return results | python | def _limit_and_df(self, query, limit, as_df=False):
"""adds a limit (limit==None := no limit) to any query and allow a return as pandas.DataFrame
:param bool as_df: if is set to True results return as pandas.DataFrame
:param `sqlalchemy.orm.query.Query` query: SQL Alchemy query
:param int limit: maximum number of results
:return: query result of pyctd.manager.models.XY objects
"""
if limit:
query = query.limit(limit)
if as_df:
results = read_sql(query.statement, self.engine)
else:
results = query.all()
return results | [
"def",
"_limit_and_df",
"(",
"self",
",",
"query",
",",
"limit",
",",
"as_df",
"=",
"False",
")",
":",
"if",
"limit",
":",
"query",
"=",
"query",
".",
"limit",
"(",
"limit",
")",
"if",
"as_df",
":",
"results",
"=",
"read_sql",
"(",
"query",
".",
"s... | adds a limit (limit==None := no limit) to any query and allow a return as pandas.DataFrame
:param bool as_df: if is set to True results return as pandas.DataFrame
:param `sqlalchemy.orm.query.Query` query: SQL Alchemy query
:param int limit: maximum number of results
:return: query result of pyctd.manager.models.XY objects | [
"adds",
"a",
"limit",
"(",
"limit",
"==",
"None",
":",
"=",
"no",
"limit",
")",
"to",
"any",
"query",
"and",
"allow",
"a",
"return",
"as",
"pandas",
".",
"DataFrame"
] | train | https://github.com/cebel/pyctd/blob/38ba02adaddb60cef031d3b75516773fe8a046b5/src/pyctd/manager/query.py#L13-L29 |
cebel/pyctd | src/pyctd/manager/query.py | QueryManager._join_gene | def _join_gene(query, gene_name, gene_symbol, gene_id):
"""helper function to add a query join to Gene model
:param `sqlalchemy.orm.query.Query` query: SQL Alchemy query
:param str gene_name: gene name
:param str gene_symbol: gene symbol
:param int gene_id: NCBI Gene identifier
:return: `sqlalchemy.orm.query.Query` object
"""
if gene_name or gene_symbol:
query = query.join(models.Gene)
if gene_symbol:
query = query.filter(models.Gene.gene_symbol.like(gene_symbol))
if gene_name:
query = query.filter(models.Gene.gene_name.like(gene_name))
if gene_id:
query = query.filter(models.Gene.gene_id.like(gene_id))
return query | python | def _join_gene(query, gene_name, gene_symbol, gene_id):
"""helper function to add a query join to Gene model
:param `sqlalchemy.orm.query.Query` query: SQL Alchemy query
:param str gene_name: gene name
:param str gene_symbol: gene symbol
:param int gene_id: NCBI Gene identifier
:return: `sqlalchemy.orm.query.Query` object
"""
if gene_name or gene_symbol:
query = query.join(models.Gene)
if gene_symbol:
query = query.filter(models.Gene.gene_symbol.like(gene_symbol))
if gene_name:
query = query.filter(models.Gene.gene_name.like(gene_name))
if gene_id:
query = query.filter(models.Gene.gene_id.like(gene_id))
return query | [
"def",
"_join_gene",
"(",
"query",
",",
"gene_name",
",",
"gene_symbol",
",",
"gene_id",
")",
":",
"if",
"gene_name",
"or",
"gene_symbol",
":",
"query",
"=",
"query",
".",
"join",
"(",
"models",
".",
"Gene",
")",
"if",
"gene_symbol",
":",
"query",
"=",
... | helper function to add a query join to Gene model
:param `sqlalchemy.orm.query.Query` query: SQL Alchemy query
:param str gene_name: gene name
:param str gene_symbol: gene symbol
:param int gene_id: NCBI Gene identifier
:return: `sqlalchemy.orm.query.Query` object | [
"helper",
"function",
"to",
"add",
"a",
"query",
"join",
"to",
"Gene",
"model"
] | train | https://github.com/cebel/pyctd/blob/38ba02adaddb60cef031d3b75516773fe8a046b5/src/pyctd/manager/query.py#L32-L53 |
cebel/pyctd | src/pyctd/manager/query.py | QueryManager._join_chemical | def _join_chemical(query, cas_rn, chemical_id, chemical_name, chemical_definition):
"""helper function to add a query join to Chemical model
:param `sqlalchemy.orm.query.Query` query: SQL Alchemy query
:param cas_rn:
:param chemical_id:
:param chemical_name:
:param chemical_definition:
:return: `sqlalchemy.orm.query.Query` object
"""
if cas_rn or chemical_id or chemical_name or chemical_definition:
query = query.join(models.Chemical)
if cas_rn:
query = query.filter(models.Chemical.cas_rn.like(cas_rn))
if chemical_id:
query = query.filter(models.Chemical.chemical_id == chemical_id)
if chemical_name:
query = query.filter(models.Chemical.chemical_name.like(chemical_name))
if chemical_definition:
query = query.filter(models.Chemical.definition.like(chemical_definition))
return query | python | def _join_chemical(query, cas_rn, chemical_id, chemical_name, chemical_definition):
"""helper function to add a query join to Chemical model
:param `sqlalchemy.orm.query.Query` query: SQL Alchemy query
:param cas_rn:
:param chemical_id:
:param chemical_name:
:param chemical_definition:
:return: `sqlalchemy.orm.query.Query` object
"""
if cas_rn or chemical_id or chemical_name or chemical_definition:
query = query.join(models.Chemical)
if cas_rn:
query = query.filter(models.Chemical.cas_rn.like(cas_rn))
if chemical_id:
query = query.filter(models.Chemical.chemical_id == chemical_id)
if chemical_name:
query = query.filter(models.Chemical.chemical_name.like(chemical_name))
if chemical_definition:
query = query.filter(models.Chemical.definition.like(chemical_definition))
return query | [
"def",
"_join_chemical",
"(",
"query",
",",
"cas_rn",
",",
"chemical_id",
",",
"chemical_name",
",",
"chemical_definition",
")",
":",
"if",
"cas_rn",
"or",
"chemical_id",
"or",
"chemical_name",
"or",
"chemical_definition",
":",
"query",
"=",
"query",
".",
"join"... | helper function to add a query join to Chemical model
:param `sqlalchemy.orm.query.Query` query: SQL Alchemy query
:param cas_rn:
:param chemical_id:
:param chemical_name:
:param chemical_definition:
:return: `sqlalchemy.orm.query.Query` object | [
"helper",
"function",
"to",
"add",
"a",
"query",
"join",
"to",
"Chemical",
"model",
":",
"param",
"sqlalchemy",
".",
"orm",
".",
"query",
".",
"Query",
"query",
":",
"SQL",
"Alchemy",
"query",
":",
"param",
"cas_rn",
":",
":",
"param",
"chemical_id",
":"... | train | https://github.com/cebel/pyctd/blob/38ba02adaddb60cef031d3b75516773fe8a046b5/src/pyctd/manager/query.py#L56-L81 |
cebel/pyctd | src/pyctd/manager/query.py | QueryManager._join_disease | def _join_disease(query, disease_definition, disease_id, disease_name):
"""helper function to add a query join to Disease model
:param sqlalchemy.orm.query.Query query: SQL Alchemy query
:param disease_definition:
:param str disease_id: see :attr:`models.Disease.disease_id`
:param disease_name:
:rtype: sqlalchemy.orm.query.Query
"""
if disease_definition or disease_id or disease_name:
query = query.join(models.Disease)
if disease_definition:
query = query.filter(models.Disease.definition.like(disease_definition))
if disease_id:
query = query.filter(models.Disease.disease_id == disease_id)
if disease_name:
query = query.filter(models.Disease.disease_name.like(disease_name))
return query | python | def _join_disease(query, disease_definition, disease_id, disease_name):
"""helper function to add a query join to Disease model
:param sqlalchemy.orm.query.Query query: SQL Alchemy query
:param disease_definition:
:param str disease_id: see :attr:`models.Disease.disease_id`
:param disease_name:
:rtype: sqlalchemy.orm.query.Query
"""
if disease_definition or disease_id or disease_name:
query = query.join(models.Disease)
if disease_definition:
query = query.filter(models.Disease.definition.like(disease_definition))
if disease_id:
query = query.filter(models.Disease.disease_id == disease_id)
if disease_name:
query = query.filter(models.Disease.disease_name.like(disease_name))
return query | [
"def",
"_join_disease",
"(",
"query",
",",
"disease_definition",
",",
"disease_id",
",",
"disease_name",
")",
":",
"if",
"disease_definition",
"or",
"disease_id",
"or",
"disease_name",
":",
"query",
"=",
"query",
".",
"join",
"(",
"models",
".",
"Disease",
")"... | helper function to add a query join to Disease model
:param sqlalchemy.orm.query.Query query: SQL Alchemy query
:param disease_definition:
:param str disease_id: see :attr:`models.Disease.disease_id`
:param disease_name:
:rtype: sqlalchemy.orm.query.Query | [
"helper",
"function",
"to",
"add",
"a",
"query",
"join",
"to",
"Disease",
"model",
":",
"param",
"sqlalchemy",
".",
"orm",
".",
"query",
".",
"Query",
"query",
":",
"SQL",
"Alchemy",
"query",
":",
"param",
"disease_definition",
":",
":",
"param",
"str",
... | train | https://github.com/cebel/pyctd/blob/38ba02adaddb60cef031d3b75516773fe8a046b5/src/pyctd/manager/query.py#L84-L105 |
cebel/pyctd | src/pyctd/manager/query.py | QueryManager._join_pathway | def _join_pathway(query, pathway_id, pathway_name):
"""helper function to add a query join to Pathway model
:param `sqlalchemy.orm.query.Query` query: SQL Alchemy query
:param str pathway_id: pathway identifier
:param str pathway_name: pathway name
:return: `sqlalchemy.orm.query.Query` object
"""
if pathway_id or pathway_name:
if pathway_id:
query = query.filter(models.Pathway.pathway_id.like(pathway_id))
if pathway_name:
query = query.filter(models.Pathway.pathway_name.like(pathway_name))
return query | python | def _join_pathway(query, pathway_id, pathway_name):
"""helper function to add a query join to Pathway model
:param `sqlalchemy.orm.query.Query` query: SQL Alchemy query
:param str pathway_id: pathway identifier
:param str pathway_name: pathway name
:return: `sqlalchemy.orm.query.Query` object
"""
if pathway_id or pathway_name:
if pathway_id:
query = query.filter(models.Pathway.pathway_id.like(pathway_id))
if pathway_name:
query = query.filter(models.Pathway.pathway_name.like(pathway_name))
return query | [
"def",
"_join_pathway",
"(",
"query",
",",
"pathway_id",
",",
"pathway_name",
")",
":",
"if",
"pathway_id",
"or",
"pathway_name",
":",
"if",
"pathway_id",
":",
"query",
"=",
"query",
".",
"filter",
"(",
"models",
".",
"Pathway",
".",
"pathway_id",
".",
"li... | helper function to add a query join to Pathway model
:param `sqlalchemy.orm.query.Query` query: SQL Alchemy query
:param str pathway_id: pathway identifier
:param str pathway_name: pathway name
:return: `sqlalchemy.orm.query.Query` object | [
"helper",
"function",
"to",
"add",
"a",
"query",
"join",
"to",
"Pathway",
"model",
":",
"param",
"sqlalchemy",
".",
"orm",
".",
"query",
".",
"Query",
"query",
":",
"SQL",
"Alchemy",
"query",
":",
"param",
"str",
"pathway_id",
":",
"pathway",
"identifier",... | train | https://github.com/cebel/pyctd/blob/38ba02adaddb60cef031d3b75516773fe8a046b5/src/pyctd/manager/query.py#L108-L122 |
cebel/pyctd | src/pyctd/manager/query.py | QueryManager.get_disease | def get_disease(self, disease_name=None, disease_id=None, definition=None, parent_ids=None, tree_numbers=None,
parent_tree_numbers=None, slim_mapping=None, synonym=None, alt_disease_id=None, limit=None,
as_df=False):
"""
Get diseases
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param int limit: maximum number of results
:param str disease_name: disease name
:param str disease_id: disease identifier
:param str definition: definition of disease
:param str parent_ids: parent identifiers, delimiter |
:param str tree_numbers: tree numbers, delimiter |
:param str parent_tree_numbers: parent tree numbers, delimiter
:param str slim_mapping: term derived from the MeSH tree structure for the “Diseases” [C] branch, \
that classifies MEDIC diseases into high-level categories
:param str synonym: disease synonyms
:param str alt_disease_id: alternative disease identifiers
:return: list of :class:`pyctd.manager.models.Disease` object
.. seealso::
:class:`pyctd.manager.models.Disease`
.. todo::
normalize parent_ids, tree_numbers and parent_tree_numbers in :class:`pyctd.manager.models.Disease`
"""
q = self.session.query(models.Disease)
if disease_name:
q = q.filter(models.Disease.disease_name.like(disease_name))
if disease_id:
q = q.filter(models.Disease.disease_id == disease_id)
if definition:
q = q.filter(models.Disease.definition.like(definition))
if parent_ids:
q = q.filter(models.Disease.parent_ids.like(parent_ids))
if tree_numbers:
q = q.filter(models.Disease.tree_numbers.like(tree_numbers))
if parent_tree_numbers:
q = q.filter(models.Disease.parent_tree_numbers.like(parent_tree_numbers))
if slim_mapping:
q = q.join(models.DiseaseSlimmapping).filter(models.DiseaseSlimmapping.slim_mapping.like(slim_mapping))
if synonym:
q = q.join(models.DiseaseSynonym).filter(models.DiseaseSynonym.synonym.like(synonym))
if alt_disease_id:
q = q.join(models.DiseaseAltdiseaseid).filter(models.DiseaseAltdiseaseid.alt_disease_id == alt_disease_id)
return self._limit_and_df(q, limit, as_df) | python | def get_disease(self, disease_name=None, disease_id=None, definition=None, parent_ids=None, tree_numbers=None,
parent_tree_numbers=None, slim_mapping=None, synonym=None, alt_disease_id=None, limit=None,
as_df=False):
"""
Get diseases
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param int limit: maximum number of results
:param str disease_name: disease name
:param str disease_id: disease identifier
:param str definition: definition of disease
:param str parent_ids: parent identifiers, delimiter |
:param str tree_numbers: tree numbers, delimiter |
:param str parent_tree_numbers: parent tree numbers, delimiter
:param str slim_mapping: term derived from the MeSH tree structure for the “Diseases” [C] branch, \
that classifies MEDIC diseases into high-level categories
:param str synonym: disease synonyms
:param str alt_disease_id: alternative disease identifiers
:return: list of :class:`pyctd.manager.models.Disease` object
.. seealso::
:class:`pyctd.manager.models.Disease`
.. todo::
normalize parent_ids, tree_numbers and parent_tree_numbers in :class:`pyctd.manager.models.Disease`
"""
q = self.session.query(models.Disease)
if disease_name:
q = q.filter(models.Disease.disease_name.like(disease_name))
if disease_id:
q = q.filter(models.Disease.disease_id == disease_id)
if definition:
q = q.filter(models.Disease.definition.like(definition))
if parent_ids:
q = q.filter(models.Disease.parent_ids.like(parent_ids))
if tree_numbers:
q = q.filter(models.Disease.tree_numbers.like(tree_numbers))
if parent_tree_numbers:
q = q.filter(models.Disease.parent_tree_numbers.like(parent_tree_numbers))
if slim_mapping:
q = q.join(models.DiseaseSlimmapping).filter(models.DiseaseSlimmapping.slim_mapping.like(slim_mapping))
if synonym:
q = q.join(models.DiseaseSynonym).filter(models.DiseaseSynonym.synonym.like(synonym))
if alt_disease_id:
q = q.join(models.DiseaseAltdiseaseid).filter(models.DiseaseAltdiseaseid.alt_disease_id == alt_disease_id)
return self._limit_and_df(q, limit, as_df) | [
"def",
"get_disease",
"(",
"self",
",",
"disease_name",
"=",
"None",
",",
"disease_id",
"=",
"None",
",",
"definition",
"=",
"None",
",",
"parent_ids",
"=",
"None",
",",
"tree_numbers",
"=",
"None",
",",
"parent_tree_numbers",
"=",
"None",
",",
"slim_mapping... | Get diseases
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param int limit: maximum number of results
:param str disease_name: disease name
:param str disease_id: disease identifier
:param str definition: definition of disease
:param str parent_ids: parent identifiers, delimiter |
:param str tree_numbers: tree numbers, delimiter |
:param str parent_tree_numbers: parent tree numbers, delimiter
:param str slim_mapping: term derived from the MeSH tree structure for the “Diseases” [C] branch, \
that classifies MEDIC diseases into high-level categories
:param str synonym: disease synonyms
:param str alt_disease_id: alternative disease identifiers
:return: list of :class:`pyctd.manager.models.Disease` object
.. seealso::
:class:`pyctd.manager.models.Disease`
.. todo::
normalize parent_ids, tree_numbers and parent_tree_numbers in :class:`pyctd.manager.models.Disease` | [
"Get",
"diseases"
] | train | https://github.com/cebel/pyctd/blob/38ba02adaddb60cef031d3b75516773fe8a046b5/src/pyctd/manager/query.py#L124-L181 |
cebel/pyctd | src/pyctd/manager/query.py | QueryManager.get_gene | def get_gene(self, gene_name=None, gene_symbol=None, gene_id=None, synonym=None, uniprot_id=None,
pharmgkb_id=None, biogrid_id=None, alt_gene_id=None, limit=None, as_df=False):
"""Get genes
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param alt_gene_id:
:param str gene_name: gene name
:param str gene_symbol: HGNC gene symbol
:param int gene_id: NCBI Entrez Gene identifier
:param str synonym: Synonym
:param str uniprot_id: UniProt primary accession number
:param str pharmgkb_id: PharmGKB identifier
:param int biogrid_id: BioGRID identifier
:param int limit: maximum of results
:rtype: list[models.Gene]
"""
q = self.session.query(models.Gene)
if gene_symbol:
q = q.filter(models.Gene.gene_symbol.like(gene_symbol))
if gene_name:
q = q.filter(models.Gene.gene_name.like(gene_name))
if gene_id:
q = q.filter(models.Gene.gene_id.like(gene_id))
if synonym:
q = q.join(models.GeneSynonym).filter(models.GeneSynonym.synonym == synonym)
if uniprot_id:
q = q.join(models.GeneUniprot).filter(models.GeneUniprot.uniprot_id == uniprot_id)
if pharmgkb_id:
q = q.join(models.GenePharmgkb).filter(models.GenePharmgkb.pharmgkb_id == pharmgkb_id)
if biogrid_id:
q = q.join(models.GeneBiogrid).filter(models.GeneBiogrid.biogrid_id == biogrid_id)
if alt_gene_id:
q = q.join(models.GeneAltGeneId.alt_gene_id == alt_gene_id)
return self._limit_and_df(q, limit, as_df) | python | def get_gene(self, gene_name=None, gene_symbol=None, gene_id=None, synonym=None, uniprot_id=None,
pharmgkb_id=None, biogrid_id=None, alt_gene_id=None, limit=None, as_df=False):
"""Get genes
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param alt_gene_id:
:param str gene_name: gene name
:param str gene_symbol: HGNC gene symbol
:param int gene_id: NCBI Entrez Gene identifier
:param str synonym: Synonym
:param str uniprot_id: UniProt primary accession number
:param str pharmgkb_id: PharmGKB identifier
:param int biogrid_id: BioGRID identifier
:param int limit: maximum of results
:rtype: list[models.Gene]
"""
q = self.session.query(models.Gene)
if gene_symbol:
q = q.filter(models.Gene.gene_symbol.like(gene_symbol))
if gene_name:
q = q.filter(models.Gene.gene_name.like(gene_name))
if gene_id:
q = q.filter(models.Gene.gene_id.like(gene_id))
if synonym:
q = q.join(models.GeneSynonym).filter(models.GeneSynonym.synonym == synonym)
if uniprot_id:
q = q.join(models.GeneUniprot).filter(models.GeneUniprot.uniprot_id == uniprot_id)
if pharmgkb_id:
q = q.join(models.GenePharmgkb).filter(models.GenePharmgkb.pharmgkb_id == pharmgkb_id)
if biogrid_id:
q = q.join(models.GeneBiogrid).filter(models.GeneBiogrid.biogrid_id == biogrid_id)
if alt_gene_id:
q = q.join(models.GeneAltGeneId.alt_gene_id == alt_gene_id)
return self._limit_and_df(q, limit, as_df) | [
"def",
"get_gene",
"(",
"self",
",",
"gene_name",
"=",
"None",
",",
"gene_symbol",
"=",
"None",
",",
"gene_id",
"=",
"None",
",",
"synonym",
"=",
"None",
",",
"uniprot_id",
"=",
"None",
",",
"pharmgkb_id",
"=",
"None",
",",
"biogrid_id",
"=",
"None",
"... | Get genes
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param alt_gene_id:
:param str gene_name: gene name
:param str gene_symbol: HGNC gene symbol
:param int gene_id: NCBI Entrez Gene identifier
:param str synonym: Synonym
:param str uniprot_id: UniProt primary accession number
:param str pharmgkb_id: PharmGKB identifier
:param int biogrid_id: BioGRID identifier
:param int limit: maximum of results
:rtype: list[models.Gene] | [
"Get",
"genes"
] | train | https://github.com/cebel/pyctd/blob/38ba02adaddb60cef031d3b75516773fe8a046b5/src/pyctd/manager/query.py#L183-L225 |
cebel/pyctd | src/pyctd/manager/query.py | QueryManager.get_pathway | def get_pathway(self, pathway_name=None, pathway_id=None, limit=None, as_df=False):
"""Get pathway
.. note::
Format of pathway_id is KEGG:X* or REACTOME:X* . X* stands for a sequence of digits
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param str pathway_name: pathway name
:param str pathway_id: KEGG or REACTOME identifier
:param int limit: maximum number of results
:return: list of :class:`pyctd.manager.models.Pathway` objects
.. seealso::
:class:`pyctd.manager.models.Pathway`
"""
q = self.session.query(models.Pathway)
if pathway_name:
q = q.filter(models.Pathway.pathway_name.like(pathway_name))
if pathway_id:
q = q.filter(models.Pathway.pathway_id.like(pathway_id))
return self._limit_and_df(q, limit, as_df) | python | def get_pathway(self, pathway_name=None, pathway_id=None, limit=None, as_df=False):
"""Get pathway
.. note::
Format of pathway_id is KEGG:X* or REACTOME:X* . X* stands for a sequence of digits
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param str pathway_name: pathway name
:param str pathway_id: KEGG or REACTOME identifier
:param int limit: maximum number of results
:return: list of :class:`pyctd.manager.models.Pathway` objects
.. seealso::
:class:`pyctd.manager.models.Pathway`
"""
q = self.session.query(models.Pathway)
if pathway_name:
q = q.filter(models.Pathway.pathway_name.like(pathway_name))
if pathway_id:
q = q.filter(models.Pathway.pathway_id.like(pathway_id))
return self._limit_and_df(q, limit, as_df) | [
"def",
"get_pathway",
"(",
"self",
",",
"pathway_name",
"=",
"None",
",",
"pathway_id",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"as_df",
"=",
"False",
")",
":",
"q",
"=",
"self",
".",
"session",
".",
"query",
"(",
"models",
".",
"Pathway",
")",
... | Get pathway
.. note::
Format of pathway_id is KEGG:X* or REACTOME:X* . X* stands for a sequence of digits
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param str pathway_name: pathway name
:param str pathway_id: KEGG or REACTOME identifier
:param int limit: maximum number of results
:return: list of :class:`pyctd.manager.models.Pathway` objects
.. seealso::
:class:`pyctd.manager.models.Pathway` | [
"Get",
"pathway"
] | train | https://github.com/cebel/pyctd/blob/38ba02adaddb60cef031d3b75516773fe8a046b5/src/pyctd/manager/query.py#L227-L251 |
cebel/pyctd | src/pyctd/manager/query.py | QueryManager.get_chemical | def get_chemical(self, chemical_name=None, chemical_id=None, cas_rn=None, drugbank_id=None, parent_id=None,
parent_tree_number=None, tree_number=None, synonym=None, limit=None, as_df=False):
"""Get chemical
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param str chemical_name: chemical name
:param str chemical_id: cehmical identifier
:param str cas_rn: CAS registry number
:param str drugbank_id: DrugBank identifier
:param str parent_id: identifiers of the parent terms
:param str parent_tree_number: identifiers of the parent nodes
:param str tree_number: identifiers of the chemical's nodes
:param str synonym: chemical synonym
:param int limit: maximum number of results
:return: list of :class:`pyctd.manager.models.Chemical` objects
.. seealso::
:class:`pyctd.manager.models.Chemical`
"""
q = self.session.query(models.Chemical)
if chemical_name:
q = q.filter(models.Chemical.chemical_name.like(chemical_name))
if chemical_id:
q = q.filter(models.Chemical.chemical_id == chemical_id)
if cas_rn:
q = q.filter(models.Chemical.cas_rn == cas_rn)
if drugbank_id:
q = q.join(models.ChemicalDrugbank).filter(models.ChemicalDrugbank.drugbank_id == drugbank_id)
if parent_id:
q = q.join(models.ChemicalParentid).filter(models.ChemicalParentid.parent_id == parent_id)
if tree_number:
q = q.join(models.ChemicalTreenumber) \
.filter(models.ChemicalTreenumber.tree_number == tree_number)
if parent_tree_number:
q = q.join(models.ChemicalParenttreenumber) \
.filter(models.ChemicalParenttreenumber.parent_tree_number == parent_tree_number)
if synonym:
q = q.join(models.ChemicalSynonym).filter(models.ChemicalSynonym.synonym.like(synonym))
return self._limit_and_df(q, limit, as_df) | python | def get_chemical(self, chemical_name=None, chemical_id=None, cas_rn=None, drugbank_id=None, parent_id=None,
parent_tree_number=None, tree_number=None, synonym=None, limit=None, as_df=False):
"""Get chemical
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param str chemical_name: chemical name
:param str chemical_id: cehmical identifier
:param str cas_rn: CAS registry number
:param str drugbank_id: DrugBank identifier
:param str parent_id: identifiers of the parent terms
:param str parent_tree_number: identifiers of the parent nodes
:param str tree_number: identifiers of the chemical's nodes
:param str synonym: chemical synonym
:param int limit: maximum number of results
:return: list of :class:`pyctd.manager.models.Chemical` objects
.. seealso::
:class:`pyctd.manager.models.Chemical`
"""
q = self.session.query(models.Chemical)
if chemical_name:
q = q.filter(models.Chemical.chemical_name.like(chemical_name))
if chemical_id:
q = q.filter(models.Chemical.chemical_id == chemical_id)
if cas_rn:
q = q.filter(models.Chemical.cas_rn == cas_rn)
if drugbank_id:
q = q.join(models.ChemicalDrugbank).filter(models.ChemicalDrugbank.drugbank_id == drugbank_id)
if parent_id:
q = q.join(models.ChemicalParentid).filter(models.ChemicalParentid.parent_id == parent_id)
if tree_number:
q = q.join(models.ChemicalTreenumber) \
.filter(models.ChemicalTreenumber.tree_number == tree_number)
if parent_tree_number:
q = q.join(models.ChemicalParenttreenumber) \
.filter(models.ChemicalParenttreenumber.parent_tree_number == parent_tree_number)
if synonym:
q = q.join(models.ChemicalSynonym).filter(models.ChemicalSynonym.synonym.like(synonym))
return self._limit_and_df(q, limit, as_df) | [
"def",
"get_chemical",
"(",
"self",
",",
"chemical_name",
"=",
"None",
",",
"chemical_id",
"=",
"None",
",",
"cas_rn",
"=",
"None",
",",
"drugbank_id",
"=",
"None",
",",
"parent_id",
"=",
"None",
",",
"parent_tree_number",
"=",
"None",
",",
"tree_number",
... | Get chemical
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param str chemical_name: chemical name
:param str chemical_id: cehmical identifier
:param str cas_rn: CAS registry number
:param str drugbank_id: DrugBank identifier
:param str parent_id: identifiers of the parent terms
:param str parent_tree_number: identifiers of the parent nodes
:param str tree_number: identifiers of the chemical's nodes
:param str synonym: chemical synonym
:param int limit: maximum number of results
:return: list of :class:`pyctd.manager.models.Chemical` objects
.. seealso::
:class:`pyctd.manager.models.Chemical` | [
"Get",
"chemical"
] | train | https://github.com/cebel/pyctd/blob/38ba02adaddb60cef031d3b75516773fe8a046b5/src/pyctd/manager/query.py#L253-L302 |
cebel/pyctd | src/pyctd/manager/query.py | QueryManager.get_chem_gene_interaction_actions | def get_chem_gene_interaction_actions(self, gene_name=None, gene_symbol=None, gene_id=None, limit=None,
cas_rn=None, chemical_id=None, chemical_name=None, organism_id=None,
interaction_sentence=None, chemical_definition=None,
gene_form=None, interaction_action=None, as_df=False):
"""Get all interactions for chemicals on a gene or biological entity (linked to this gene).
Chemicals can interact on different types of biological entities linked to a gene. A list of allowed
entities linked to a gene can be retrieved via the attribute :attr:`~.gene_forms`.
Interactions are classified by a combination of interaction ('affects', 'decreases', 'increases')
and actions ('activity', 'expression', ... ). A complete list of all allowed
interaction_actions can be retrieved via the attribute :attr:`~.interaction_actions`.
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param str interaction_sentence: sentence describing the interactions
:param int organism_id: NCBI TaxTree identifier. Example: 9606 for Human.
:param str chemical_name: chemical name
:param str chemical_id: chemical identifier
:param str cas_rn: CAS registry number
:param str chemical_definition:
:param str gene_symbol: HGNC gene symbol
:param str gene_name: gene name
:param int gene_id: NCBI Entrez Gene identifier
:param str gene_form: gene form
:param str interaction_action: combination of interaction and actions
:param int limit: maximum number of results
:rtype: list[models.ChemGeneIxn]
.. seealso::
:class:`pyctd.manager.models.ChemGeneIxn`
which is linked to:
:class:`pyctd.manager.models.Chemical`
:class:`pyctd.manager.models.Gene`
:class:`pyctd.manager.models.ChemGeneIxnPubmed`
Available interaction_actions and gene_forms
:func:`pyctd.manager.database.Query.interaction_actions`
:func:`pyctd.manager.database.Query.gene_forms`
"""
q = self.session.query(models.ChemGeneIxn)
if organism_id:
q = q.filter(models.ChemGeneIxn.organism_id == organism_id)
if interaction_sentence:
q = q.filter(models.ChemGeneIxn.interaction == interaction_sentence)
if gene_form:
q = q.join(models.ChemGeneIxnGeneForm).filter(models.ChemGeneIxnGeneForm.gene_form == gene_form)
if interaction_action:
q = q.join(models.ChemGeneIxnInteractionAction) \
.filter(models.ChemGeneIxnInteractionAction.interaction_action.like(interaction_action))
q = self._join_gene(query=q, gene_name=gene_name, gene_symbol=gene_symbol, gene_id=gene_id)
q = self._join_chemical(query=q, cas_rn=cas_rn, chemical_id=chemical_id, chemical_name=chemical_name,
chemical_definition=chemical_definition)
return self._limit_and_df(q, limit, as_df) | python | def get_chem_gene_interaction_actions(self, gene_name=None, gene_symbol=None, gene_id=None, limit=None,
cas_rn=None, chemical_id=None, chemical_name=None, organism_id=None,
interaction_sentence=None, chemical_definition=None,
gene_form=None, interaction_action=None, as_df=False):
"""Get all interactions for chemicals on a gene or biological entity (linked to this gene).
Chemicals can interact on different types of biological entities linked to a gene. A list of allowed
entities linked to a gene can be retrieved via the attribute :attr:`~.gene_forms`.
Interactions are classified by a combination of interaction ('affects', 'decreases', 'increases')
and actions ('activity', 'expression', ... ). A complete list of all allowed
interaction_actions can be retrieved via the attribute :attr:`~.interaction_actions`.
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param str interaction_sentence: sentence describing the interactions
:param int organism_id: NCBI TaxTree identifier. Example: 9606 for Human.
:param str chemical_name: chemical name
:param str chemical_id: chemical identifier
:param str cas_rn: CAS registry number
:param str chemical_definition:
:param str gene_symbol: HGNC gene symbol
:param str gene_name: gene name
:param int gene_id: NCBI Entrez Gene identifier
:param str gene_form: gene form
:param str interaction_action: combination of interaction and actions
:param int limit: maximum number of results
:rtype: list[models.ChemGeneIxn]
.. seealso::
:class:`pyctd.manager.models.ChemGeneIxn`
which is linked to:
:class:`pyctd.manager.models.Chemical`
:class:`pyctd.manager.models.Gene`
:class:`pyctd.manager.models.ChemGeneIxnPubmed`
Available interaction_actions and gene_forms
:func:`pyctd.manager.database.Query.interaction_actions`
:func:`pyctd.manager.database.Query.gene_forms`
"""
q = self.session.query(models.ChemGeneIxn)
if organism_id:
q = q.filter(models.ChemGeneIxn.organism_id == organism_id)
if interaction_sentence:
q = q.filter(models.ChemGeneIxn.interaction == interaction_sentence)
if gene_form:
q = q.join(models.ChemGeneIxnGeneForm).filter(models.ChemGeneIxnGeneForm.gene_form == gene_form)
if interaction_action:
q = q.join(models.ChemGeneIxnInteractionAction) \
.filter(models.ChemGeneIxnInteractionAction.interaction_action.like(interaction_action))
q = self._join_gene(query=q, gene_name=gene_name, gene_symbol=gene_symbol, gene_id=gene_id)
q = self._join_chemical(query=q, cas_rn=cas_rn, chemical_id=chemical_id, chemical_name=chemical_name,
chemical_definition=chemical_definition)
return self._limit_and_df(q, limit, as_df) | [
"def",
"get_chem_gene_interaction_actions",
"(",
"self",
",",
"gene_name",
"=",
"None",
",",
"gene_symbol",
"=",
"None",
",",
"gene_id",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"cas_rn",
"=",
"None",
",",
"chemical_id",
"=",
"None",
",",
"chemical_name"... | Get all interactions for chemicals on a gene or biological entity (linked to this gene).
Chemicals can interact on different types of biological entities linked to a gene. A list of allowed
entities linked to a gene can be retrieved via the attribute :attr:`~.gene_forms`.
Interactions are classified by a combination of interaction ('affects', 'decreases', 'increases')
and actions ('activity', 'expression', ... ). A complete list of all allowed
interaction_actions can be retrieved via the attribute :attr:`~.interaction_actions`.
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param str interaction_sentence: sentence describing the interactions
:param int organism_id: NCBI TaxTree identifier. Example: 9606 for Human.
:param str chemical_name: chemical name
:param str chemical_id: chemical identifier
:param str cas_rn: CAS registry number
:param str chemical_definition:
:param str gene_symbol: HGNC gene symbol
:param str gene_name: gene name
:param int gene_id: NCBI Entrez Gene identifier
:param str gene_form: gene form
:param str interaction_action: combination of interaction and actions
:param int limit: maximum number of results
:rtype: list[models.ChemGeneIxn]
.. seealso::
:class:`pyctd.manager.models.ChemGeneIxn`
which is linked to:
:class:`pyctd.manager.models.Chemical`
:class:`pyctd.manager.models.Gene`
:class:`pyctd.manager.models.ChemGeneIxnPubmed`
Available interaction_actions and gene_forms
:func:`pyctd.manager.database.Query.interaction_actions`
:func:`pyctd.manager.database.Query.gene_forms` | [
"Get",
"all",
"interactions",
"for",
"chemicals",
"on",
"a",
"gene",
"or",
"biological",
"entity",
"(",
"linked",
"to",
"this",
"gene",
")",
"."
] | train | https://github.com/cebel/pyctd/blob/38ba02adaddb60cef031d3b75516773fe8a046b5/src/pyctd/manager/query.py#L304-L367 |
cebel/pyctd | src/pyctd/manager/query.py | QueryManager.gene_forms | def gene_forms(self):
"""
:return: List of strings for all available gene forms
:rtype: list[str]
"""
q = self.session.query(distinct(models.ChemGeneIxnGeneForm.gene_form))
return [x[0] for x in q.all()] | python | def gene_forms(self):
"""
:return: List of strings for all available gene forms
:rtype: list[str]
"""
q = self.session.query(distinct(models.ChemGeneIxnGeneForm.gene_form))
return [x[0] for x in q.all()] | [
"def",
"gene_forms",
"(",
"self",
")",
":",
"q",
"=",
"self",
".",
"session",
".",
"query",
"(",
"distinct",
"(",
"models",
".",
"ChemGeneIxnGeneForm",
".",
"gene_form",
")",
")",
"return",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"q",
".",
"all"... | :return: List of strings for all available gene forms
:rtype: list[str] | [
":",
"return",
":",
"List",
"of",
"strings",
"for",
"all",
"available",
"gene",
"forms",
":",
"rtype",
":",
"list",
"[",
"str",
"]"
] | train | https://github.com/cebel/pyctd/blob/38ba02adaddb60cef031d3b75516773fe8a046b5/src/pyctd/manager/query.py#L370-L376 |
cebel/pyctd | src/pyctd/manager/query.py | QueryManager.interaction_actions | def interaction_actions(self):
"""
:return: List of strings for allowed interaction/actions combinations
:rtype: list[str]
"""
r = self.session.query(distinct(models.ChemGeneIxnInteractionAction.interaction_action)).all()
return [x[0] for x in r] | python | def interaction_actions(self):
"""
:return: List of strings for allowed interaction/actions combinations
:rtype: list[str]
"""
r = self.session.query(distinct(models.ChemGeneIxnInteractionAction.interaction_action)).all()
return [x[0] for x in r] | [
"def",
"interaction_actions",
"(",
"self",
")",
":",
"r",
"=",
"self",
".",
"session",
".",
"query",
"(",
"distinct",
"(",
"models",
".",
"ChemGeneIxnInteractionAction",
".",
"interaction_action",
")",
")",
".",
"all",
"(",
")",
"return",
"[",
"x",
"[",
... | :return: List of strings for allowed interaction/actions combinations
:rtype: list[str] | [
":",
"return",
":",
"List",
"of",
"strings",
"for",
"allowed",
"interaction",
"/",
"actions",
"combinations",
":",
"rtype",
":",
"list",
"[",
"str",
"]"
] | train | https://github.com/cebel/pyctd/blob/38ba02adaddb60cef031d3b75516773fe8a046b5/src/pyctd/manager/query.py#L379-L385 |
cebel/pyctd | src/pyctd/manager/query.py | QueryManager.actions | def actions(self):
"""Gets the list of allowed actions
:rtype: list[str]
"""
r = self.session.query(models.Action).all()
return [x.type_name for x in r] | python | def actions(self):
"""Gets the list of allowed actions
:rtype: list[str]
"""
r = self.session.query(models.Action).all()
return [x.type_name for x in r] | [
"def",
"actions",
"(",
"self",
")",
":",
"r",
"=",
"self",
".",
"session",
".",
"query",
"(",
"models",
".",
"Action",
")",
".",
"all",
"(",
")",
"return",
"[",
"x",
".",
"type_name",
"for",
"x",
"in",
"r",
"]"
] | Gets the list of allowed actions
:rtype: list[str] | [
"Gets",
"the",
"list",
"of",
"allowed",
"actions"
] | train | https://github.com/cebel/pyctd/blob/38ba02adaddb60cef031d3b75516773fe8a046b5/src/pyctd/manager/query.py#L388-L394 |
cebel/pyctd | src/pyctd/manager/query.py | QueryManager.get_gene_disease | def get_gene_disease(self, direct_evidence=None, inference_chemical_name=None, inference_score=None,
gene_name=None, gene_symbol=None, gene_id=None, disease_name=None, disease_id=None,
disease_definition=None, limit=None, as_df=False):
"""Get gene–disease associations
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param int gene_id: gene identifier
:param str gene_symbol: gene symbol
:param str gene_name: gene name
:param str direct_evidence: direct evidence
:param str inference_chemical_name: inference_chemical_name
:param float inference_score: inference score
:param str inference_chemical_name: chemical name
:param disease_name: disease name
:param disease_id: disease identifier
:param disease_definition: disease definition
:param int limit: maximum number of results
:return: list of :class:`pyctd.manager.database.models.GeneDisease` objects
.. seealso::
:class:`pyctd.manager.models.GeneDisease`
which is linked to:
:class:`pyctd.manager.models.Chemical`
:class:`pyctd.manager.models.Gene`
"""
q = self.session.query(models.GeneDisease)
if direct_evidence:
q = q.filter(models.GeneDisease.direct_evidence == direct_evidence)
if inference_chemical_name:
q = q.filter(models.GeneDisease.inference_chemical_name == inference_chemical_name)
if inference_score:
q = q.filter(models.GeneDisease.inference_score == inference_score)
q = self._join_disease(query=q, disease_definition=disease_definition, disease_id=disease_id,
disease_name=disease_name)
q = self._join_gene(q, gene_name=gene_name, gene_symbol=gene_symbol, gene_id=gene_id)
return self._limit_and_df(q, limit, as_df) | python | def get_gene_disease(self, direct_evidence=None, inference_chemical_name=None, inference_score=None,
gene_name=None, gene_symbol=None, gene_id=None, disease_name=None, disease_id=None,
disease_definition=None, limit=None, as_df=False):
"""Get gene–disease associations
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param int gene_id: gene identifier
:param str gene_symbol: gene symbol
:param str gene_name: gene name
:param str direct_evidence: direct evidence
:param str inference_chemical_name: inference_chemical_name
:param float inference_score: inference score
:param str inference_chemical_name: chemical name
:param disease_name: disease name
:param disease_id: disease identifier
:param disease_definition: disease definition
:param int limit: maximum number of results
:return: list of :class:`pyctd.manager.database.models.GeneDisease` objects
.. seealso::
:class:`pyctd.manager.models.GeneDisease`
which is linked to:
:class:`pyctd.manager.models.Chemical`
:class:`pyctd.manager.models.Gene`
"""
q = self.session.query(models.GeneDisease)
if direct_evidence:
q = q.filter(models.GeneDisease.direct_evidence == direct_evidence)
if inference_chemical_name:
q = q.filter(models.GeneDisease.inference_chemical_name == inference_chemical_name)
if inference_score:
q = q.filter(models.GeneDisease.inference_score == inference_score)
q = self._join_disease(query=q, disease_definition=disease_definition, disease_id=disease_id,
disease_name=disease_name)
q = self._join_gene(q, gene_name=gene_name, gene_symbol=gene_symbol, gene_id=gene_id)
return self._limit_and_df(q, limit, as_df) | [
"def",
"get_gene_disease",
"(",
"self",
",",
"direct_evidence",
"=",
"None",
",",
"inference_chemical_name",
"=",
"None",
",",
"inference_score",
"=",
"None",
",",
"gene_name",
"=",
"None",
",",
"gene_symbol",
"=",
"None",
",",
"gene_id",
"=",
"None",
",",
"... | Get gene–disease associations
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param int gene_id: gene identifier
:param str gene_symbol: gene symbol
:param str gene_name: gene name
:param str direct_evidence: direct evidence
:param str inference_chemical_name: inference_chemical_name
:param float inference_score: inference score
:param str inference_chemical_name: chemical name
:param disease_name: disease name
:param disease_id: disease identifier
:param disease_definition: disease definition
:param int limit: maximum number of results
:return: list of :class:`pyctd.manager.database.models.GeneDisease` objects
.. seealso::
:class:`pyctd.manager.models.GeneDisease`
which is linked to:
:class:`pyctd.manager.models.Chemical`
:class:`pyctd.manager.models.Gene` | [
"Get",
"gene–disease",
"associations"
] | train | https://github.com/cebel/pyctd/blob/38ba02adaddb60cef031d3b75516773fe8a046b5/src/pyctd/manager/query.py#L404-L447 |
cebel/pyctd | src/pyctd/manager/query.py | QueryManager.direct_evidences | def direct_evidences(self):
"""
:return: All available direct evidences for gene disease correlations
:rtype: list
"""
q = self.session.query(distinct(models.GeneDisease.direct_evidence))
return q.all() | python | def direct_evidences(self):
"""
:return: All available direct evidences for gene disease correlations
:rtype: list
"""
q = self.session.query(distinct(models.GeneDisease.direct_evidence))
return q.all() | [
"def",
"direct_evidences",
"(",
"self",
")",
":",
"q",
"=",
"self",
".",
"session",
".",
"query",
"(",
"distinct",
"(",
"models",
".",
"GeneDisease",
".",
"direct_evidence",
")",
")",
"return",
"q",
".",
"all",
"(",
")"
] | :return: All available direct evidences for gene disease correlations
:rtype: list | [
":",
"return",
":",
"All",
"available",
"direct",
"evidences",
"for",
"gene",
"disease",
"correlations",
":",
"rtype",
":",
"list"
] | train | https://github.com/cebel/pyctd/blob/38ba02adaddb60cef031d3b75516773fe8a046b5/src/pyctd/manager/query.py#L450-L457 |
cebel/pyctd | src/pyctd/manager/query.py | QueryManager.get_disease_pathways | def get_disease_pathways(self, disease_id=None, disease_name=None, pathway_id=None, pathway_name=None,
disease_definition=None, limit=None, as_df=False):
"""Get disease pathway link
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param disease_id:
:param disease_name:
:param pathway_id:
:param pathway_name:
:param disease_definition:
:param int limit: maximum number of results
:return: list of :class:`pyctd.manager.database.models.DiseasePathway` objects
.. seealso::
:class:`pyctd.manager.models.DiseasePathway`
which is linked to:
:class:`pyctd.manager.models.Disease`
:class:`pyctd.manager.models.Pathway`
"""
q = self.session.query(models.DiseasePathway)
q = self._join_disease(query=q, disease_id=disease_id, disease_name=disease_name,
disease_definition=disease_definition)
q = self._join_pathway(query=q, pathway_id=pathway_id, pathway_name=pathway_name)
return self._limit_and_df(q, limit, as_df) | python | def get_disease_pathways(self, disease_id=None, disease_name=None, pathway_id=None, pathway_name=None,
disease_definition=None, limit=None, as_df=False):
"""Get disease pathway link
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param disease_id:
:param disease_name:
:param pathway_id:
:param pathway_name:
:param disease_definition:
:param int limit: maximum number of results
:return: list of :class:`pyctd.manager.database.models.DiseasePathway` objects
.. seealso::
:class:`pyctd.manager.models.DiseasePathway`
which is linked to:
:class:`pyctd.manager.models.Disease`
:class:`pyctd.manager.models.Pathway`
"""
q = self.session.query(models.DiseasePathway)
q = self._join_disease(query=q, disease_id=disease_id, disease_name=disease_name,
disease_definition=disease_definition)
q = self._join_pathway(query=q, pathway_id=pathway_id, pathway_name=pathway_name)
return self._limit_and_df(q, limit, as_df) | [
"def",
"get_disease_pathways",
"(",
"self",
",",
"disease_id",
"=",
"None",
",",
"disease_name",
"=",
"None",
",",
"pathway_id",
"=",
"None",
",",
"pathway_name",
"=",
"None",
",",
"disease_definition",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"as_df",
... | Get disease pathway link
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param disease_id:
:param disease_name:
:param pathway_id:
:param pathway_name:
:param disease_definition:
:param int limit: maximum number of results
:return: list of :class:`pyctd.manager.database.models.DiseasePathway` objects
.. seealso::
:class:`pyctd.manager.models.DiseasePathway`
which is linked to:
:class:`pyctd.manager.models.Disease`
:class:`pyctd.manager.models.Pathway` | [
"Get",
"disease",
"pathway",
"link",
":",
"param",
"bool",
"as_df",
":",
"if",
"set",
"to",
"True",
"result",
"returns",
"as",
"pandas",
".",
"DataFrame",
":",
"param",
"disease_id",
":",
":",
"param",
"disease_name",
":",
":",
"param",
"pathway_id",
":",
... | train | https://github.com/cebel/pyctd/blob/38ba02adaddb60cef031d3b75516773fe8a046b5/src/pyctd/manager/query.py#L459-L487 |
cebel/pyctd | src/pyctd/manager/query.py | QueryManager.get_chemical_diseases | def get_chemical_diseases(self, direct_evidence=None, inference_gene_symbol=None, inference_score=None,
inference_score_operator=None, cas_rn=None, chemical_name=None,
chemical_id=None, chemical_definition=None, disease_definition=None,
disease_id=None, disease_name=None, limit=None, as_df=False):
"""Get chemical–disease associations with inference gene
:param direct_evidence: direct evidence
:param inference_gene_symbol: inference gene symbol
:param inference_score: inference score
:param inference_score_operator: inference score operator
:param cas_rn:
:param chemical_name: chemical name
:param chemical_id:
:param chemical_definition:
:param disease_definition:
:param disease_id:
:param disease_name: disease name
:param int limit: maximum number of results
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:return: list of :class:`pyctd.manager.database.models.ChemicalDisease` objects
.. seealso::
:class:`pyctd.manager.models.ChemicalDisease`
which is linked to:
:class:`pyctd.manager.models.Disease`
:class:`pyctd.manager.models.Chemical`
"""
q = self.session.query(models.ChemicalDisease)
if direct_evidence:
q = q.filter(models.ChemicalDisease.direct_evidence.like(direct_evidence))
if inference_gene_symbol:
q = q.filter(models.ChemicalDisease.inference_gene_symbol.like(inference_gene_symbol))
if inference_score:
if inference_score_operator == ">":
q = q.filter_by(models.ChemicalDisease.inference_score > inference_score)
elif inference_score_operator == "<":
q = q.filter_by(models.ChemicalDisease.inference_score > inference_score)
q = self._join_chemical(q, cas_rn=cas_rn, chemical_id=chemical_id, chemical_name=chemical_name,
chemical_definition=chemical_definition)
q = self._join_disease(q, disease_definition=disease_definition, disease_id=disease_id,
disease_name=disease_name)
return self._limit_and_df(q, limit, as_df) | python | def get_chemical_diseases(self, direct_evidence=None, inference_gene_symbol=None, inference_score=None,
inference_score_operator=None, cas_rn=None, chemical_name=None,
chemical_id=None, chemical_definition=None, disease_definition=None,
disease_id=None, disease_name=None, limit=None, as_df=False):
"""Get chemical–disease associations with inference gene
:param direct_evidence: direct evidence
:param inference_gene_symbol: inference gene symbol
:param inference_score: inference score
:param inference_score_operator: inference score operator
:param cas_rn:
:param chemical_name: chemical name
:param chemical_id:
:param chemical_definition:
:param disease_definition:
:param disease_id:
:param disease_name: disease name
:param int limit: maximum number of results
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:return: list of :class:`pyctd.manager.database.models.ChemicalDisease` objects
.. seealso::
:class:`pyctd.manager.models.ChemicalDisease`
which is linked to:
:class:`pyctd.manager.models.Disease`
:class:`pyctd.manager.models.Chemical`
"""
q = self.session.query(models.ChemicalDisease)
if direct_evidence:
q = q.filter(models.ChemicalDisease.direct_evidence.like(direct_evidence))
if inference_gene_symbol:
q = q.filter(models.ChemicalDisease.inference_gene_symbol.like(inference_gene_symbol))
if inference_score:
if inference_score_operator == ">":
q = q.filter_by(models.ChemicalDisease.inference_score > inference_score)
elif inference_score_operator == "<":
q = q.filter_by(models.ChemicalDisease.inference_score > inference_score)
q = self._join_chemical(q, cas_rn=cas_rn, chemical_id=chemical_id, chemical_name=chemical_name,
chemical_definition=chemical_definition)
q = self._join_disease(q, disease_definition=disease_definition, disease_id=disease_id,
disease_name=disease_name)
return self._limit_and_df(q, limit, as_df) | [
"def",
"get_chemical_diseases",
"(",
"self",
",",
"direct_evidence",
"=",
"None",
",",
"inference_gene_symbol",
"=",
"None",
",",
"inference_score",
"=",
"None",
",",
"inference_score_operator",
"=",
"None",
",",
"cas_rn",
"=",
"None",
",",
"chemical_name",
"=",
... | Get chemical–disease associations with inference gene
:param direct_evidence: direct evidence
:param inference_gene_symbol: inference gene symbol
:param inference_score: inference score
:param inference_score_operator: inference score operator
:param cas_rn:
:param chemical_name: chemical name
:param chemical_id:
:param chemical_definition:
:param disease_definition:
:param disease_id:
:param disease_name: disease name
:param int limit: maximum number of results
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:return: list of :class:`pyctd.manager.database.models.ChemicalDisease` objects
.. seealso::
:class:`pyctd.manager.models.ChemicalDisease`
which is linked to:
:class:`pyctd.manager.models.Disease`
:class:`pyctd.manager.models.Chemical` | [
"Get",
"chemical–disease",
"associations",
"with",
"inference",
"gene",
":",
"param",
"direct_evidence",
":",
"direct",
"evidence",
":",
"param",
"inference_gene_symbol",
":",
"inference",
"gene",
"symbol",
":",
"param",
"inference_score",
":",
"inference",
"score",
... | train | https://github.com/cebel/pyctd/blob/38ba02adaddb60cef031d3b75516773fe8a046b5/src/pyctd/manager/query.py#L489-L538 |
cebel/pyctd | src/pyctd/manager/query.py | QueryManager.get_gene_pathways | def get_gene_pathways(self, gene_name=None, gene_symbol=None, gene_id=None, pathway_id=None,
pathway_name=None, limit=None, as_df=False):
"""Get gene pathway link
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param str gene_name: gene name
:param str gene_symbol: gene symbol
:param int gene_id: NCBI Gene identifier
:param pathway_id:
:param str pathway_name: pathway name
:param int limit: maximum number of results
:return: list of :class:`pyctd.manager.database.models.GenePathway` objects
.. seealso::
:class:`pyctd.manager.models.GenePathway`
which is linked to:
:class:`pyctd.manager.models.Gene`
:class:`pyctd.manager.models.Pathway`
"""
q = self.session.query(models.GenePathway)
q = self._join_gene(q, gene_name=gene_name, gene_symbol=gene_symbol, gene_id=gene_id)
q = self._join_pathway(q, pathway_id=pathway_id, pathway_name=pathway_name)
return self._limit_and_df(q, limit, as_df) | python | def get_gene_pathways(self, gene_name=None, gene_symbol=None, gene_id=None, pathway_id=None,
pathway_name=None, limit=None, as_df=False):
"""Get gene pathway link
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param str gene_name: gene name
:param str gene_symbol: gene symbol
:param int gene_id: NCBI Gene identifier
:param pathway_id:
:param str pathway_name: pathway name
:param int limit: maximum number of results
:return: list of :class:`pyctd.manager.database.models.GenePathway` objects
.. seealso::
:class:`pyctd.manager.models.GenePathway`
which is linked to:
:class:`pyctd.manager.models.Gene`
:class:`pyctd.manager.models.Pathway`
"""
q = self.session.query(models.GenePathway)
q = self._join_gene(q, gene_name=gene_name, gene_symbol=gene_symbol, gene_id=gene_id)
q = self._join_pathway(q, pathway_id=pathway_id, pathway_name=pathway_name)
return self._limit_and_df(q, limit, as_df) | [
"def",
"get_gene_pathways",
"(",
"self",
",",
"gene_name",
"=",
"None",
",",
"gene_symbol",
"=",
"None",
",",
"gene_id",
"=",
"None",
",",
"pathway_id",
"=",
"None",
",",
"pathway_name",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"as_df",
"=",
"False",... | Get gene pathway link
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param str gene_name: gene name
:param str gene_symbol: gene symbol
:param int gene_id: NCBI Gene identifier
:param pathway_id:
:param str pathway_name: pathway name
:param int limit: maximum number of results
:return: list of :class:`pyctd.manager.database.models.GenePathway` objects
.. seealso::
:class:`pyctd.manager.models.GenePathway`
which is linked to:
:class:`pyctd.manager.models.Gene`
:class:`pyctd.manager.models.Pathway` | [
"Get",
"gene",
"pathway",
"link",
":",
"param",
"bool",
"as_df",
":",
"if",
"set",
"to",
"True",
"result",
"returns",
"as",
"pandas",
".",
"DataFrame",
":",
"param",
"str",
"gene_name",
":",
"gene",
"name",
":",
"param",
"str",
"gene_symbol",
":",
"gene"... | train | https://github.com/cebel/pyctd/blob/38ba02adaddb60cef031d3b75516773fe8a046b5/src/pyctd/manager/query.py#L540-L565 |
mattaustin/django-storages-s3upload | s3upload/views.py | S3UploadFormView.get_validate_upload_form_kwargs | def get_validate_upload_form_kwargs(self):
"""
Return the keyword arguments for instantiating the form for validating
the upload.
"""
kwargs = {
'storage': self.get_storage(),
'upload_to': self.get_upload_to(),
'content_type_prefix': self.get_content_type_prefix(),
'process_to': self.get_process_to(),
'processed_key_generator': self.get_processed_key_generator(),
}
# ``data`` may be provided by a POST from the JavaScript if using a
# DropZone form, or as querystrings on a redirect GET request from
# Amazon if not.
data = {
'bucket_name': self._get_bucket_name(),
'key_name': self._get_key_name(),
'etag': self._get_etag(),
}
kwargs.update({'data': data})
return kwargs | python | def get_validate_upload_form_kwargs(self):
"""
Return the keyword arguments for instantiating the form for validating
the upload.
"""
kwargs = {
'storage': self.get_storage(),
'upload_to': self.get_upload_to(),
'content_type_prefix': self.get_content_type_prefix(),
'process_to': self.get_process_to(),
'processed_key_generator': self.get_processed_key_generator(),
}
# ``data`` may be provided by a POST from the JavaScript if using a
# DropZone form, or as querystrings on a redirect GET request from
# Amazon if not.
data = {
'bucket_name': self._get_bucket_name(),
'key_name': self._get_key_name(),
'etag': self._get_etag(),
}
kwargs.update({'data': data})
return kwargs | [
"def",
"get_validate_upload_form_kwargs",
"(",
"self",
")",
":",
"kwargs",
"=",
"{",
"'storage'",
":",
"self",
".",
"get_storage",
"(",
")",
",",
"'upload_to'",
":",
"self",
".",
"get_upload_to",
"(",
")",
",",
"'content_type_prefix'",
":",
"self",
".",
"get... | Return the keyword arguments for instantiating the form for validating
the upload. | [
"Return",
"the",
"keyword",
"arguments",
"for",
"instantiating",
"the",
"form",
"for",
"validating",
"the",
"upload",
"."
] | train | https://github.com/mattaustin/django-storages-s3upload/blob/d4e6b4799aa32de469a00e75732a18716845d6b8/s3upload/views.py#L147-L171 |
snipsco/snipsmanagercore | snipsmanagercore/sound_service.py | SoundService.play | def play(state):
""" Play sound for a given state.
:param state: a State value.
"""
filename = None
if state == SoundService.State.welcome:
filename = "pad_glow_welcome1.wav"
elif state == SoundService.State.goodbye:
filename = "pad_glow_power_off.wav"
elif state == SoundService.State.hotword_detected:
filename = "pad_soft_on.wav"
elif state == SoundService.State.asr_text_captured:
filename = "pad_soft_off.wav"
elif state == SoundService.State.error:
filename = "music_marimba_error_chord_2x.wav"
if filename is not None:
AudioPlayer.play_async("{}/{}".format(ABS_SOUND_DIR, filename)) | python | def play(state):
""" Play sound for a given state.
:param state: a State value.
"""
filename = None
if state == SoundService.State.welcome:
filename = "pad_glow_welcome1.wav"
elif state == SoundService.State.goodbye:
filename = "pad_glow_power_off.wav"
elif state == SoundService.State.hotword_detected:
filename = "pad_soft_on.wav"
elif state == SoundService.State.asr_text_captured:
filename = "pad_soft_off.wav"
elif state == SoundService.State.error:
filename = "music_marimba_error_chord_2x.wav"
if filename is not None:
AudioPlayer.play_async("{}/{}".format(ABS_SOUND_DIR, filename)) | [
"def",
"play",
"(",
"state",
")",
":",
"filename",
"=",
"None",
"if",
"state",
"==",
"SoundService",
".",
"State",
".",
"welcome",
":",
"filename",
"=",
"\"pad_glow_welcome1.wav\"",
"elif",
"state",
"==",
"SoundService",
".",
"State",
".",
"goodbye",
":",
... | Play sound for a given state.
:param state: a State value. | [
"Play",
"sound",
"for",
"a",
"given",
"state",
"."
] | train | https://github.com/snipsco/snipsmanagercore/blob/93eaaa665887f790a30ba86af5ffee394bfd8ede/snipsmanagercore/sound_service.py#L23-L41 |
akissa/spamc | setup.py | get_readme | def get_readme():
"""Generate long description"""
pandoc = None
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
pandoc = os.path.join(path, 'pandoc')
if os.path.isfile(pandoc) and os.access(pandoc, os.X_OK):
break
else:
pandoc = None
try:
if pandoc:
cmd = [pandoc, '-t', 'rst', 'README.md']
long_description = os.popen(' '.join(cmd)).read()
else:
raise ValueError
except BaseException:
long_description = open("README.md").read()
return long_description | python | def get_readme():
"""Generate long description"""
pandoc = None
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
pandoc = os.path.join(path, 'pandoc')
if os.path.isfile(pandoc) and os.access(pandoc, os.X_OK):
break
else:
pandoc = None
try:
if pandoc:
cmd = [pandoc, '-t', 'rst', 'README.md']
long_description = os.popen(' '.join(cmd)).read()
else:
raise ValueError
except BaseException:
long_description = open("README.md").read()
return long_description | [
"def",
"get_readme",
"(",
")",
":",
"pandoc",
"=",
"None",
"for",
"path",
"in",
"os",
".",
"environ",
"[",
"\"PATH\"",
"]",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
":",
"path",
"=",
"path",
".",
"strip",
"(",
"'\"'",
")",
"pandoc",
"=",
"os... | Generate long description | [
"Generate",
"long",
"description"
] | train | https://github.com/akissa/spamc/blob/da50732e276f7ed3d67cb75c31cb017d6a62f066/setup.py#L38-L56 |
akissa/spamc | setup.py | main | def main():
"""Main"""
lic = (
'License :: OSI Approved :: GNU Affero '
'General Public License v3 or later (AGPLv3+)')
version = load_source("version", os.path.join("spamc", "version.py"))
opts = dict(
name="spamc",
version=version.__version__,
description="Python spamassassin spamc client library",
long_description=get_readme(),
keywords="spam spamc spamassassin",
author="Andrew Colin Kissa",
author_email="andrew@topdog.za.net",
url="https://github.com/akissa/spamc",
license="AGPLv3+",
packages=find_packages(exclude=['tests']),
include_package_data=True,
zip_safe=False,
tests_require=TESTS_REQUIRE,
install_requires=INSTALL_REQUIRES,
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules',
'Intended Audience :: Developers',
lic,
'Natural Language :: English',
'Operating System :: OS Independent'],)
setup(**opts) | python | def main():
"""Main"""
lic = (
'License :: OSI Approved :: GNU Affero '
'General Public License v3 or later (AGPLv3+)')
version = load_source("version", os.path.join("spamc", "version.py"))
opts = dict(
name="spamc",
version=version.__version__,
description="Python spamassassin spamc client library",
long_description=get_readme(),
keywords="spam spamc spamassassin",
author="Andrew Colin Kissa",
author_email="andrew@topdog.za.net",
url="https://github.com/akissa/spamc",
license="AGPLv3+",
packages=find_packages(exclude=['tests']),
include_package_data=True,
zip_safe=False,
tests_require=TESTS_REQUIRE,
install_requires=INSTALL_REQUIRES,
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules',
'Intended Audience :: Developers',
lic,
'Natural Language :: English',
'Operating System :: OS Independent'],)
setup(**opts) | [
"def",
"main",
"(",
")",
":",
"lic",
"=",
"(",
"'License :: OSI Approved :: GNU Affero '",
"'General Public License v3 or later (AGPLv3+)'",
")",
"version",
"=",
"load_source",
"(",
"\"version\"",
",",
"os",
".",
"path",
".",
"join",
"(",
"\"spamc\"",
",",
"\"versio... | Main | [
"Main"
] | train | https://github.com/akissa/spamc/blob/da50732e276f7ed3d67cb75c31cb017d6a62f066/setup.py#L59-L91 |
fedora-infra/fedmsg_meta_fedora_infrastructure | fedmsg_meta_fedora_infrastructure/fedocal.py | _casual_timedelta_string | def _casual_timedelta_string(meeting):
""" Return a casual timedelta string.
If a meeting starts in 2 hours, 15 minutes, and 32 seconds from now, then
return just "in 2 hours".
If a meeting starts in 7 minutes and 40 seconds from now, return just "in 7
minutes".
If a meeting starts 56 seconds from now, just return "right now".
"""
now = datetime.datetime.utcnow()
mdate = meeting['meeting_date']
mtime = meeting['meeting_time_start']
dt_string = "%s %s" % (mdate, mtime)
meeting_dt = datetime.datetime.strptime(dt_string, "%Y-%m-%d %H:%M:%S")
relative_td = dateutil.relativedelta.relativedelta(meeting_dt, now)
denominations = ['years', 'months', 'days', 'hours', 'minutes']
for denomination in denominations:
value = getattr(relative_td, denomination)
if value:
# If the value is only one, then strip off the plural suffix.
if value == 1:
denomination = denomination[:-1]
return "in %i %s" % (value, denomination)
return "right now" | python | def _casual_timedelta_string(meeting):
""" Return a casual timedelta string.
If a meeting starts in 2 hours, 15 minutes, and 32 seconds from now, then
return just "in 2 hours".
If a meeting starts in 7 minutes and 40 seconds from now, return just "in 7
minutes".
If a meeting starts 56 seconds from now, just return "right now".
"""
now = datetime.datetime.utcnow()
mdate = meeting['meeting_date']
mtime = meeting['meeting_time_start']
dt_string = "%s %s" % (mdate, mtime)
meeting_dt = datetime.datetime.strptime(dt_string, "%Y-%m-%d %H:%M:%S")
relative_td = dateutil.relativedelta.relativedelta(meeting_dt, now)
denominations = ['years', 'months', 'days', 'hours', 'minutes']
for denomination in denominations:
value = getattr(relative_td, denomination)
if value:
# If the value is only one, then strip off the plural suffix.
if value == 1:
denomination = denomination[:-1]
return "in %i %s" % (value, denomination)
return "right now" | [
"def",
"_casual_timedelta_string",
"(",
"meeting",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"mdate",
"=",
"meeting",
"[",
"'meeting_date'",
"]",
"mtime",
"=",
"meeting",
"[",
"'meeting_time_start'",
"]",
"dt_string",
"=",
"... | Return a casual timedelta string.
If a meeting starts in 2 hours, 15 minutes, and 32 seconds from now, then
return just "in 2 hours".
If a meeting starts in 7 minutes and 40 seconds from now, return just "in 7
minutes".
If a meeting starts 56 seconds from now, just return "right now". | [
"Return",
"a",
"casual",
"timedelta",
"string",
"."
] | train | https://github.com/fedora-infra/fedmsg_meta_fedora_infrastructure/blob/85bf4162692e3042c7dbcc12dfafaca4764b4ae6/fedmsg_meta_fedora_infrastructure/fedocal.py#L48-L77 |
fedora-infra/fedmsg_meta_fedora_infrastructure | fedmsg_meta_fedora_infrastructure/trac.py | repo_name | def repo_name(msg):
""" Compat util to get the repo name from a message. """
try:
# git messages look like this now
path = msg['msg']['commit']['path']
project = path.split('.git')[0][9:]
except KeyError:
# they used to look like this, though
project = msg['msg']['commit']['repo']
return project | python | def repo_name(msg):
""" Compat util to get the repo name from a message. """
try:
# git messages look like this now
path = msg['msg']['commit']['path']
project = path.split('.git')[0][9:]
except KeyError:
# they used to look like this, though
project = msg['msg']['commit']['repo']
return project | [
"def",
"repo_name",
"(",
"msg",
")",
":",
"try",
":",
"# git messages look like this now",
"path",
"=",
"msg",
"[",
"'msg'",
"]",
"[",
"'commit'",
"]",
"[",
"'path'",
"]",
"project",
"=",
"path",
".",
"split",
"(",
"'.git'",
")",
"[",
"0",
"]",
"[",
... | Compat util to get the repo name from a message. | [
"Compat",
"util",
"to",
"get",
"the",
"repo",
"name",
"from",
"a",
"message",
"."
] | train | https://github.com/fedora-infra/fedmsg_meta_fedora_infrastructure/blob/85bf4162692e3042c7dbcc12dfafaca4764b4ae6/fedmsg_meta_fedora_infrastructure/trac.py#L79-L89 |
datasift/datasift-python | datasift/account.py | Account.usage | def usage(self, period=None, start=None, end=None):
""" Get account usage information
:param period: Period is one of either hourly, daily or monthly
:type period: str
:param start: Determines time period of the usage
:type start: int
:param end: Determines time period of the usage
:type end: int
:return: dict of REST API output with headers attached
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`,
:class:`requests.exceptions.HTTPError`
"""
params = {}
if period:
params['period'] = period
if start:
params['start'] = start
if end:
params['end'] = end
return self.request.get('usage', params) | python | def usage(self, period=None, start=None, end=None):
""" Get account usage information
:param period: Period is one of either hourly, daily or monthly
:type period: str
:param start: Determines time period of the usage
:type start: int
:param end: Determines time period of the usage
:type end: int
:return: dict of REST API output with headers attached
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`,
:class:`requests.exceptions.HTTPError`
"""
params = {}
if period:
params['period'] = period
if start:
params['start'] = start
if end:
params['end'] = end
return self.request.get('usage', params) | [
"def",
"usage",
"(",
"self",
",",
"period",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"period",
":",
"params",
"[",
"'period'",
"]",
"=",
"period",
"if",
"start",
":",
"params",
"[",... | Get account usage information
:param period: Period is one of either hourly, daily or monthly
:type period: str
:param start: Determines time period of the usage
:type start: int
:param end: Determines time period of the usage
:type end: int
:return: dict of REST API output with headers attached
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`,
:class:`requests.exceptions.HTTPError` | [
"Get",
"account",
"usage",
"information"
] | train | https://github.com/datasift/datasift-python/blob/bfaca1a47501a18e11065ecf630d9c31df818f65/datasift/account.py#L9-L33 |
cebel/pyctd | src/pyctd/manager/table_conf.py | standard_db_name | def standard_db_name(file_column_name):
"""return a standard name by following rules:
1. find all regular expression partners ((IDs)|(ID)|([A-Z][a-z]+)|([A-Z]{2,}))
2. lower very part and join again with _
This method is only used if values in table[model]['columns'] are str
:param str file_column_name: name of column in file
:return: standard name
:rtype: str
"""
found = id_re.findall(file_column_name)
if not found:
return file_column_name
return '_'.join(x[0].lower() for x in found) | python | def standard_db_name(file_column_name):
"""return a standard name by following rules:
1. find all regular expression partners ((IDs)|(ID)|([A-Z][a-z]+)|([A-Z]{2,}))
2. lower very part and join again with _
This method is only used if values in table[model]['columns'] are str
:param str file_column_name: name of column in file
:return: standard name
:rtype: str
"""
found = id_re.findall(file_column_name)
if not found:
return file_column_name
return '_'.join(x[0].lower() for x in found) | [
"def",
"standard_db_name",
"(",
"file_column_name",
")",
":",
"found",
"=",
"id_re",
".",
"findall",
"(",
"file_column_name",
")",
"if",
"not",
"found",
":",
"return",
"file_column_name",
"return",
"'_'",
".",
"join",
"(",
"x",
"[",
"0",
"]",
".",
"lower",... | return a standard name by following rules:
1. find all regular expression partners ((IDs)|(ID)|([A-Z][a-z]+)|([A-Z]{2,}))
2. lower very part and join again with _
This method is only used if values in table[model]['columns'] are str
:param str file_column_name: name of column in file
:return: standard name
:rtype: str | [
"return",
"a",
"standard",
"name",
"by",
"following",
"rules",
":",
"1",
".",
"find",
"all",
"regular",
"expression",
"partners",
"((",
"IDs",
")",
"|",
"(",
"ID",
")",
"|",
"(",
"[",
"A",
"-",
"Z",
"]",
"[",
"a",
"-",
"z",
"]",
"+",
")",
"|",
... | train | https://github.com/cebel/pyctd/blob/38ba02adaddb60cef031d3b75516773fe8a046b5/src/pyctd/manager/table_conf.py#L11-L26 |
MoseleyBioinformaticsLab/nmrstarlib | nmrstarlib/bmrblex.py | transform_text | def transform_text(input_txt):
"""Transforms text into :py:class:`~collections.deque`, pre-processes
multiline strings.
:param str or bytes input_txt: Input text.
:return: Double-ended queue of single characters and multiline strings.
:rtype: :py:class:`~collections.deque`
"""
if isinstance(input_txt, str):
text = u"{}".format(input_txt)
elif isinstance(input_txt, bytes):
text = input_txt.decode("utf-8")
else:
raise TypeError("Expecting <class 'str'> or <class 'bytes'>, but {} was passed".format(type(input_txt)))
inputq = deque(text.split(u"\n"))
outputq = deque()
while len(inputq) > 0:
line = inputq.popleft()
if line.lstrip().startswith(u"#"):
comment = u"" + line + u"\n"
line = inputq.popleft()
while line.lstrip().startswith(u"#"):
comment += line + u"\n"
line = inputq.popleft()
outputq.append(comment)
for character in line:
outputq.append(character)
elif line.startswith(u";"):
multiline = u""
multiline += line + u"\n"
line = inputq.popleft()
while not line.startswith(u";"):
multiline += line + u"\n"
line = inputq.popleft()
multiline += line[:1]
outputq.append(multiline[1:-1]) # remove STAR syntax from multiline string
for character in line[1:]:
outputq.append(character)
else:
for character in line:
outputq.append(character)
outputq.append(u"\n")
outputq.extend([u"\n", u""]) # end of file signal
return outputq | python | def transform_text(input_txt):
"""Transforms text into :py:class:`~collections.deque`, pre-processes
multiline strings.
:param str or bytes input_txt: Input text.
:return: Double-ended queue of single characters and multiline strings.
:rtype: :py:class:`~collections.deque`
"""
if isinstance(input_txt, str):
text = u"{}".format(input_txt)
elif isinstance(input_txt, bytes):
text = input_txt.decode("utf-8")
else:
raise TypeError("Expecting <class 'str'> or <class 'bytes'>, but {} was passed".format(type(input_txt)))
inputq = deque(text.split(u"\n"))
outputq = deque()
while len(inputq) > 0:
line = inputq.popleft()
if line.lstrip().startswith(u"#"):
comment = u"" + line + u"\n"
line = inputq.popleft()
while line.lstrip().startswith(u"#"):
comment += line + u"\n"
line = inputq.popleft()
outputq.append(comment)
for character in line:
outputq.append(character)
elif line.startswith(u";"):
multiline = u""
multiline += line + u"\n"
line = inputq.popleft()
while not line.startswith(u";"):
multiline += line + u"\n"
line = inputq.popleft()
multiline += line[:1]
outputq.append(multiline[1:-1]) # remove STAR syntax from multiline string
for character in line[1:]:
outputq.append(character)
else:
for character in line:
outputq.append(character)
outputq.append(u"\n")
outputq.extend([u"\n", u""]) # end of file signal
return outputq | [
"def",
"transform_text",
"(",
"input_txt",
")",
":",
"if",
"isinstance",
"(",
"input_txt",
",",
"str",
")",
":",
"text",
"=",
"u\"{}\"",
".",
"format",
"(",
"input_txt",
")",
"elif",
"isinstance",
"(",
"input_txt",
",",
"bytes",
")",
":",
"text",
"=",
... | Transforms text into :py:class:`~collections.deque`, pre-processes
multiline strings.
:param str or bytes input_txt: Input text.
:return: Double-ended queue of single characters and multiline strings.
:rtype: :py:class:`~collections.deque` | [
"Transforms",
"text",
"into",
":",
"py",
":",
"class",
":",
"~collections",
".",
"deque",
"pre",
"-",
"processes",
"multiline",
"strings",
"."
] | train | https://github.com/MoseleyBioinformaticsLab/nmrstarlib/blob/f2adabbca04d5a134ce6ba3211099d1457787ff2/nmrstarlib/bmrblex.py#L37-L94 |
MoseleyBioinformaticsLab/nmrstarlib | nmrstarlib/bmrblex.py | bmrblex | def bmrblex(text):
"""A lexical analyzer for the BMRB NMR-STAR format syntax.
:param text: Input text.
:type text: :py:class:`str` or :py:class:`bytes`
:return: Current token.
:rtype: :py:class:`str`
"""
stream = transform_text(text)
wordchars = (u"abcdfeghijklmnopqrstuvwxyz"
u"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"
u"ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ"
u"ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ"
u"!@$%^&*()_+:;?/>.<,~`|\{[}]-=")
whitespace = u" \t\v\r\n"
comment = u"#"
state = u" "
token = u""
single_line_comment = u""
while len(stream) > 0:
nextnextchar = stream.popleft()
while True:
nextchar = nextnextchar
if len(stream) > 0:
nextnextchar = stream.popleft()
else:
nextnextchar = u""
# Process multiline string, comment, or single line comment
if len(nextchar) > 1:
state = u" "
token = nextchar
break # emit current token
elif nextchar in whitespace and nextnextchar in comment and state not in (u"'", u'"'):
single_line_comment = u""
state = u"#"
if state is None:
token = u"" # past end of file
break
elif state == u" ":
if not nextchar:
state = None
break
elif nextchar in whitespace:
if token:
state = u" "
break # emit current token
else:
continue
elif nextchar in wordchars:
token = nextchar
state = u"a"
elif nextchar == u"'" or nextchar == u'"':
token = nextchar
state = nextchar
else:
token = nextchar
if token:
state = u" "
break # emit current token
else:
continue
# Process single-quoted or double-quoted token
elif state == u"'" or state == u'"':
token += nextchar
if nextchar == state:
if nextnextchar in whitespace:
state = u" "
token = token[1:-1] # remove single or double quotes from the ends
break
# Process single line comment
elif state == u"#":
single_line_comment += nextchar
if nextchar == u"\n":
state = u" "
break
# Process regular (unquoted) token
elif state == u"a":
if not nextchar:
state = None
break
elif nextchar in whitespace:
state = u" "
if token:
break # emit current token
else:
continue
else:
token += nextchar
if nextnextchar:
stream.appendleft(nextnextchar)
yield token
token = u"" | python | def bmrblex(text):
"""A lexical analyzer for the BMRB NMR-STAR format syntax.
:param text: Input text.
:type text: :py:class:`str` or :py:class:`bytes`
:return: Current token.
:rtype: :py:class:`str`
"""
stream = transform_text(text)
wordchars = (u"abcdfeghijklmnopqrstuvwxyz"
u"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"
u"ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ"
u"ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ"
u"!@$%^&*()_+:;?/>.<,~`|\{[}]-=")
whitespace = u" \t\v\r\n"
comment = u"#"
state = u" "
token = u""
single_line_comment = u""
while len(stream) > 0:
nextnextchar = stream.popleft()
while True:
nextchar = nextnextchar
if len(stream) > 0:
nextnextchar = stream.popleft()
else:
nextnextchar = u""
# Process multiline string, comment, or single line comment
if len(nextchar) > 1:
state = u" "
token = nextchar
break # emit current token
elif nextchar in whitespace and nextnextchar in comment and state not in (u"'", u'"'):
single_line_comment = u""
state = u"#"
if state is None:
token = u"" # past end of file
break
elif state == u" ":
if not nextchar:
state = None
break
elif nextchar in whitespace:
if token:
state = u" "
break # emit current token
else:
continue
elif nextchar in wordchars:
token = nextchar
state = u"a"
elif nextchar == u"'" or nextchar == u'"':
token = nextchar
state = nextchar
else:
token = nextchar
if token:
state = u" "
break # emit current token
else:
continue
# Process single-quoted or double-quoted token
elif state == u"'" or state == u'"':
token += nextchar
if nextchar == state:
if nextnextchar in whitespace:
state = u" "
token = token[1:-1] # remove single or double quotes from the ends
break
# Process single line comment
elif state == u"#":
single_line_comment += nextchar
if nextchar == u"\n":
state = u" "
break
# Process regular (unquoted) token
elif state == u"a":
if not nextchar:
state = None
break
elif nextchar in whitespace:
state = u" "
if token:
break # emit current token
else:
continue
else:
token += nextchar
if nextnextchar:
stream.appendleft(nextnextchar)
yield token
token = u"" | [
"def",
"bmrblex",
"(",
"text",
")",
":",
"stream",
"=",
"transform_text",
"(",
"text",
")",
"wordchars",
"=",
"(",
"u\"abcdfeghijklmnopqrstuvwxyz\"",
"u\"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\"",
"u\"ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ\"",
"u\"ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ\"",
"u... | A lexical analyzer for the BMRB NMR-STAR format syntax.
:param text: Input text.
:type text: :py:class:`str` or :py:class:`bytes`
:return: Current token.
:rtype: :py:class:`str` | [
"A",
"lexical",
"analyzer",
"for",
"the",
"BMRB",
"NMR",
"-",
"STAR",
"format",
"syntax",
"."
] | train | https://github.com/MoseleyBioinformaticsLab/nmrstarlib/blob/f2adabbca04d5a134ce6ba3211099d1457787ff2/nmrstarlib/bmrblex.py#L97-L206 |
brunobord/md2ebook | md2ebook/checkers.py | check_dependencies | def check_dependencies():
"""Check external dependecies
Return a tuple with the available generators.
"""
available = []
try:
shell('ebook-convert')
available.append('calibre')
except OSError:
pass
try:
shell('pandoc --help')
available.append('pandoc')
except OSError:
pass
if not available:
sys.exit(error('No generator found, you cannot use md2ebook.'))
check_dependency_epubcheck()
return available | python | def check_dependencies():
"""Check external dependecies
Return a tuple with the available generators.
"""
available = []
try:
shell('ebook-convert')
available.append('calibre')
except OSError:
pass
try:
shell('pandoc --help')
available.append('pandoc')
except OSError:
pass
if not available:
sys.exit(error('No generator found, you cannot use md2ebook.'))
check_dependency_epubcheck()
return available | [
"def",
"check_dependencies",
"(",
")",
":",
"available",
"=",
"[",
"]",
"try",
":",
"shell",
"(",
"'ebook-convert'",
")",
"available",
".",
"append",
"(",
"'calibre'",
")",
"except",
"OSError",
":",
"pass",
"try",
":",
"shell",
"(",
"'pandoc --help'",
")",... | Check external dependecies
Return a tuple with the available generators. | [
"Check",
"external",
"dependecies",
"Return",
"a",
"tuple",
"with",
"the",
"available",
"generators",
"."
] | train | https://github.com/brunobord/md2ebook/blob/31e0d06b77f2d986e6af1115c9e613dfec0591a9/md2ebook/checkers.py#L18-L36 |
lorehov/mongolock | src/mongolock.py | MongoLock.lock | def lock(self, key, owner, timeout=None, expire=None):
"""Lock given `key` to `owner`.
:Parameters:
- `key` - lock name
- `owner` - name of application/component/whatever which asks for lock
- `timeout` (optional) - how long to wait if `key` is locked
- `expire` (optional) - when given, lock will be released after that number of seconds.
Raises `MongoLockTimeout` if can't achieve a lock before timeout.
"""
expire = datetime.utcnow() + timedelta(seconds=expire) if expire else None
try:
self.collection.insert({
'_id': key,
'locked': True,
'owner': owner,
'created': datetime.utcnow(),
'expire': expire
})
return True
except DuplicateKeyError:
start_time = datetime.utcnow()
while True:
if self._try_get_lock(key, owner, expire):
return True
if not timeout or datetime.utcnow() >= start_time + timedelta(seconds=timeout):
return False
time.sleep(self.acquire_retry_step) | python | def lock(self, key, owner, timeout=None, expire=None):
"""Lock given `key` to `owner`.
:Parameters:
- `key` - lock name
- `owner` - name of application/component/whatever which asks for lock
- `timeout` (optional) - how long to wait if `key` is locked
- `expire` (optional) - when given, lock will be released after that number of seconds.
Raises `MongoLockTimeout` if can't achieve a lock before timeout.
"""
expire = datetime.utcnow() + timedelta(seconds=expire) if expire else None
try:
self.collection.insert({
'_id': key,
'locked': True,
'owner': owner,
'created': datetime.utcnow(),
'expire': expire
})
return True
except DuplicateKeyError:
start_time = datetime.utcnow()
while True:
if self._try_get_lock(key, owner, expire):
return True
if not timeout or datetime.utcnow() >= start_time + timedelta(seconds=timeout):
return False
time.sleep(self.acquire_retry_step) | [
"def",
"lock",
"(",
"self",
",",
"key",
",",
"owner",
",",
"timeout",
"=",
"None",
",",
"expire",
"=",
"None",
")",
":",
"expire",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"+",
"timedelta",
"(",
"seconds",
"=",
"expire",
")",
"if",
"expire",
"else... | Lock given `key` to `owner`.
:Parameters:
- `key` - lock name
- `owner` - name of application/component/whatever which asks for lock
- `timeout` (optional) - how long to wait if `key` is locked
- `expire` (optional) - when given, lock will be released after that number of seconds.
Raises `MongoLockTimeout` if can't achieve a lock before timeout. | [
"Lock",
"given",
"key",
"to",
"owner",
"."
] | train | https://github.com/lorehov/mongolock/blob/218c9dfacdc8de04616c0d141a5701c9217a9069/src/mongolock.py#L55-L84 |
lorehov/mongolock | src/mongolock.py | MongoLock.release | def release(self, key, owner):
"""Release lock with given name.
`key` - lock name
`owner` - name of application/component/whatever which held a lock
Raises `MongoLockException` if no such a lock.
"""
status = self.collection.find_and_modify(
{'_id': key, 'owner': owner},
{'locked': False, 'owner': None, 'created': None, 'expire': None}
) | python | def release(self, key, owner):
"""Release lock with given name.
`key` - lock name
`owner` - name of application/component/whatever which held a lock
Raises `MongoLockException` if no such a lock.
"""
status = self.collection.find_and_modify(
{'_id': key, 'owner': owner},
{'locked': False, 'owner': None, 'created': None, 'expire': None}
) | [
"def",
"release",
"(",
"self",
",",
"key",
",",
"owner",
")",
":",
"status",
"=",
"self",
".",
"collection",
".",
"find_and_modify",
"(",
"{",
"'_id'",
":",
"key",
",",
"'owner'",
":",
"owner",
"}",
",",
"{",
"'locked'",
":",
"False",
",",
"'owner'",... | Release lock with given name.
`key` - lock name
`owner` - name of application/component/whatever which held a lock
Raises `MongoLockException` if no such a lock. | [
"Release",
"lock",
"with",
"given",
"name",
".",
"key",
"-",
"lock",
"name",
"owner",
"-",
"name",
"of",
"application",
"/",
"component",
"/",
"whatever",
"which",
"held",
"a",
"lock",
"Raises",
"MongoLockException",
"if",
"no",
"such",
"a",
"lock",
"."
] | train | https://github.com/lorehov/mongolock/blob/218c9dfacdc8de04616c0d141a5701c9217a9069/src/mongolock.py#L86-L95 |
lorehov/mongolock | src/mongolock.py | MongoLock.touch | def touch(self, key, owner, expire=None):
"""Renew lock to avoid expiration. """
lock = self.collection.find_one({'_id': key, 'owner': owner})
if not lock:
raise MongoLockException(u'Can\'t find lock for {key}: {owner}'.format(key=key, owner=owner))
if not lock['expire']:
return
if not expire:
raise MongoLockException(u'Can\'t touch lock without expire for {0}: {1}'.format(key, owner))
expire = datetime.utcnow() + timedelta(seconds=expire)
self.collection.update(
{'_id': key, 'owner': owner},
{'$set': {'expire': expire}}
) | python | def touch(self, key, owner, expire=None):
"""Renew lock to avoid expiration. """
lock = self.collection.find_one({'_id': key, 'owner': owner})
if not lock:
raise MongoLockException(u'Can\'t find lock for {key}: {owner}'.format(key=key, owner=owner))
if not lock['expire']:
return
if not expire:
raise MongoLockException(u'Can\'t touch lock without expire for {0}: {1}'.format(key, owner))
expire = datetime.utcnow() + timedelta(seconds=expire)
self.collection.update(
{'_id': key, 'owner': owner},
{'$set': {'expire': expire}}
) | [
"def",
"touch",
"(",
"self",
",",
"key",
",",
"owner",
",",
"expire",
"=",
"None",
")",
":",
"lock",
"=",
"self",
".",
"collection",
".",
"find_one",
"(",
"{",
"'_id'",
":",
"key",
",",
"'owner'",
":",
"owner",
"}",
")",
"if",
"not",
"lock",
":",... | Renew lock to avoid expiration. | [
"Renew",
"lock",
"to",
"avoid",
"expiration",
"."
] | train | https://github.com/lorehov/mongolock/blob/218c9dfacdc8de04616c0d141a5701c9217a9069/src/mongolock.py#L109-L122 |
ClimateImpactLab/DataFS | datafs/managers/manager_mongo.py | MongoDBManager._get_archive_listing | def _get_archive_listing(self, archive_name):
'''
Return full document for ``{_id:'archive_name'}``
.. note::
MongoDB specific results - do not expose to user
'''
res = self.collection.find_one({'_id': archive_name})
if res is None:
raise KeyError
return res | python | def _get_archive_listing(self, archive_name):
'''
Return full document for ``{_id:'archive_name'}``
.. note::
MongoDB specific results - do not expose to user
'''
res = self.collection.find_one({'_id': archive_name})
if res is None:
raise KeyError
return res | [
"def",
"_get_archive_listing",
"(",
"self",
",",
"archive_name",
")",
":",
"res",
"=",
"self",
".",
"collection",
".",
"find_one",
"(",
"{",
"'_id'",
":",
"archive_name",
"}",
")",
"if",
"res",
"is",
"None",
":",
"raise",
"KeyError",
"return",
"res"
] | Return full document for ``{_id:'archive_name'}``
.. note::
MongoDB specific results - do not expose to user | [
"Return",
"full",
"document",
"for",
"{",
"_id",
":",
"archive_name",
"}"
] | train | https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/managers/manager_mongo.py#L146-L160 |
ClimateImpactLab/DataFS | datafs/managers/manager_mongo.py | MongoDBManager._batch_get_archive_listing | def _batch_get_archive_listing(self, archive_names):
'''
Batched version of :py:meth:`~MongoDBManager._get_archive_listing`
Returns a list of full archive listings from an iterable of archive
names
.. note ::
Invalid archive names will simply not be returned, so the response
may not be the same length as the supplied `archive_names`.
Parameters
----------
archive_names : list
List of archive names
Returns
-------
archive_listings : list
List of archive listings
'''
res = self.collection.find({'_id': {'$in': list(archive_names)}})
if res is None:
res = []
return res | python | def _batch_get_archive_listing(self, archive_names):
'''
Batched version of :py:meth:`~MongoDBManager._get_archive_listing`
Returns a list of full archive listings from an iterable of archive
names
.. note ::
Invalid archive names will simply not be returned, so the response
may not be the same length as the supplied `archive_names`.
Parameters
----------
archive_names : list
List of archive names
Returns
-------
archive_listings : list
List of archive listings
'''
res = self.collection.find({'_id': {'$in': list(archive_names)}})
if res is None:
res = []
return res | [
"def",
"_batch_get_archive_listing",
"(",
"self",
",",
"archive_names",
")",
":",
"res",
"=",
"self",
".",
"collection",
".",
"find",
"(",
"{",
"'_id'",
":",
"{",
"'$in'",
":",
"list",
"(",
"archive_names",
")",
"}",
"}",
")",
"if",
"res",
"is",
"None"... | Batched version of :py:meth:`~MongoDBManager._get_archive_listing`
Returns a list of full archive listings from an iterable of archive
names
.. note ::
Invalid archive names will simply not be returned, so the response
may not be the same length as the supplied `archive_names`.
Parameters
----------
archive_names : list
List of archive names
Returns
-------
archive_listings : list
List of archive listings | [
"Batched",
"version",
"of",
":",
"py",
":",
"meth",
":",
"~MongoDBManager",
".",
"_get_archive_listing"
] | train | https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/managers/manager_mongo.py#L162-L195 |
datasift/datasift-python | datasift/request.py | PartialRequest.build_response | def build_response(self, response, path=None, parser=json_decode_wrapper, async=False):
""" Builds a List or Dict response object.
Wrapper for a response from the DataSift REST API, can be accessed as a list.
:param response: HTTP response to wrap
:type response: :class:`~datasift.requests.DictResponse`
:param parser: optional parser to overload how the data is loaded
:type parser: func
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`~datasift.exceptions.DataSiftApiFailure`, :class:`~datasift.exceptions.AuthException`, :class:`requests.exceptions.HTTPError`, :class:`~datasift.exceptions.RateLimitException`
"""
if async:
response.process = lambda: self.build_response(response.result(), path=path, parser=parser, async=False)
return response
if response.status_code != 204:
try:
data = parser(response.headers, response.text)
except ValueError as e:
raise DataSiftApiFailure(u"Unable to decode returned data: %s" % e)
if "error" in data:
if response.status_code == 401:
raise AuthException(data)
if response.status_code == 403 or response.status_code == 429:
if not response.headers.get("X-RateLimit-Cost"):
raise DataSiftApiException(DictResponse(response, data))
if int(response.headers.get("X-RateLimit-Cost")) > int(response.headers.get("X-RateLimit-Remaining")):
raise RateLimitException(DictResponse(response, data))
raise DataSiftApiException(DictResponse(response, data))
response.raise_for_status()
if isinstance(data, dict):
r = DictResponse(response, data)
elif isinstance(data, (list, map)):
r = ListResponse(response, data)
self.outputmapper.outputmap(r)
return r
else:
# empty dict
return DictResponse(response, {}) | python | def build_response(self, response, path=None, parser=json_decode_wrapper, async=False):
""" Builds a List or Dict response object.
Wrapper for a response from the DataSift REST API, can be accessed as a list.
:param response: HTTP response to wrap
:type response: :class:`~datasift.requests.DictResponse`
:param parser: optional parser to overload how the data is loaded
:type parser: func
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`~datasift.exceptions.DataSiftApiFailure`, :class:`~datasift.exceptions.AuthException`, :class:`requests.exceptions.HTTPError`, :class:`~datasift.exceptions.RateLimitException`
"""
if async:
response.process = lambda: self.build_response(response.result(), path=path, parser=parser, async=False)
return response
if response.status_code != 204:
try:
data = parser(response.headers, response.text)
except ValueError as e:
raise DataSiftApiFailure(u"Unable to decode returned data: %s" % e)
if "error" in data:
if response.status_code == 401:
raise AuthException(data)
if response.status_code == 403 or response.status_code == 429:
if not response.headers.get("X-RateLimit-Cost"):
raise DataSiftApiException(DictResponse(response, data))
if int(response.headers.get("X-RateLimit-Cost")) > int(response.headers.get("X-RateLimit-Remaining")):
raise RateLimitException(DictResponse(response, data))
raise DataSiftApiException(DictResponse(response, data))
response.raise_for_status()
if isinstance(data, dict):
r = DictResponse(response, data)
elif isinstance(data, (list, map)):
r = ListResponse(response, data)
self.outputmapper.outputmap(r)
return r
else:
# empty dict
return DictResponse(response, {}) | [
"def",
"build_response",
"(",
"self",
",",
"response",
",",
"path",
"=",
"None",
",",
"parser",
"=",
"json_decode_wrapper",
",",
"async",
"=",
"False",
")",
":",
"if",
"async",
":",
"response",
".",
"process",
"=",
"lambda",
":",
"self",
".",
"build_resp... | Builds a List or Dict response object.
Wrapper for a response from the DataSift REST API, can be accessed as a list.
:param response: HTTP response to wrap
:type response: :class:`~datasift.requests.DictResponse`
:param parser: optional parser to overload how the data is loaded
:type parser: func
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`~datasift.exceptions.DataSiftApiFailure`, :class:`~datasift.exceptions.AuthException`, :class:`requests.exceptions.HTTPError`, :class:`~datasift.exceptions.RateLimitException` | [
"Builds",
"a",
"List",
"or",
"Dict",
"response",
"object",
"."
] | train | https://github.com/datasift/datasift-python/blob/bfaca1a47501a18e11065ecf630d9c31df818f65/datasift/request.py#L75-L113 |
datasift/datasift-python | datasift/request.py | DataSiftResponse.ratelimits | def ratelimits(self):
""" :returns: Rate Limit headers
:rtype: dict
"""
# can't use a dict comprehension because we want python2.6 support
r = {}
keys = filter(lambda x: x.startswith("x-ratelimit-"), self.headers.keys())
for key in keys:
r[key.replace("x-ratelimit-", "")] = int(self.headers[key])
return r | python | def ratelimits(self):
""" :returns: Rate Limit headers
:rtype: dict
"""
# can't use a dict comprehension because we want python2.6 support
r = {}
keys = filter(lambda x: x.startswith("x-ratelimit-"), self.headers.keys())
for key in keys:
r[key.replace("x-ratelimit-", "")] = int(self.headers[key])
return r | [
"def",
"ratelimits",
"(",
"self",
")",
":",
"# can't use a dict comprehension because we want python2.6 support",
"r",
"=",
"{",
"}",
"keys",
"=",
"filter",
"(",
"lambda",
"x",
":",
"x",
".",
"startswith",
"(",
"\"x-ratelimit-\"",
")",
",",
"self",
".",
"headers... | :returns: Rate Limit headers
:rtype: dict | [
":",
"returns",
":",
"Rate",
"Limit",
"headers",
":",
"rtype",
":",
"dict"
] | train | https://github.com/datasift/datasift-python/blob/bfaca1a47501a18e11065ecf630d9c31df818f65/datasift/request.py#L176-L185 |
ECESeniorDesign/greenhouse_envmgmt | greenhouse_envmgmt/control.py | ControlCluster.compile_instance_masks | def compile_instance_masks(cls):
""" Compiles instance masks into a master mask that is usable by
the IO expander. Also determines whether or not the pump
should be on.
Method is generalized to support multiple IO expanders
for possible future expansion.
"""
# Compute required # of IO expanders needed, clear mask variable.
number_IO_expanders = ((len(cls._list) - 1) / 4) + 1
cls.master_mask = [0, 0] * number_IO_expanders
for ctrlobj in cls:
# Or masks together bank-by-banl
cls.master_mask[ctrlobj.bank] |= ctrlobj.mask
# Handle the pump request seperately
if ctrlobj.pump_request == 1:
cls.master_mask[cls.pump_bank] |= 1 << cls.pump_pin | python | def compile_instance_masks(cls):
""" Compiles instance masks into a master mask that is usable by
the IO expander. Also determines whether or not the pump
should be on.
Method is generalized to support multiple IO expanders
for possible future expansion.
"""
# Compute required # of IO expanders needed, clear mask variable.
number_IO_expanders = ((len(cls._list) - 1) / 4) + 1
cls.master_mask = [0, 0] * number_IO_expanders
for ctrlobj in cls:
# Or masks together bank-by-banl
cls.master_mask[ctrlobj.bank] |= ctrlobj.mask
# Handle the pump request seperately
if ctrlobj.pump_request == 1:
cls.master_mask[cls.pump_bank] |= 1 << cls.pump_pin | [
"def",
"compile_instance_masks",
"(",
"cls",
")",
":",
"# Compute required # of IO expanders needed, clear mask variable.",
"number_IO_expanders",
"=",
"(",
"(",
"len",
"(",
"cls",
".",
"_list",
")",
"-",
"1",
")",
"/",
"4",
")",
"+",
"1",
"cls",
".",
"master_ma... | Compiles instance masks into a master mask that is usable by
the IO expander. Also determines whether or not the pump
should be on.
Method is generalized to support multiple IO expanders
for possible future expansion. | [
"Compiles",
"instance",
"masks",
"into",
"a",
"master",
"mask",
"that",
"is",
"usable",
"by",
"the",
"IO",
"expander",
".",
"Also",
"determines",
"whether",
"or",
"not",
"the",
"pump",
"should",
"be",
"on",
".",
"Method",
"is",
"generalized",
"to",
"suppor... | train | https://github.com/ECESeniorDesign/greenhouse_envmgmt/blob/864e0ce98bfb220f9954026913a5470536de9818/greenhouse_envmgmt/control.py#L44-L60 |
ECESeniorDesign/greenhouse_envmgmt | greenhouse_envmgmt/control.py | ControlCluster.update | def update(self):
""" This method exposes a more simple interface to the IO module
Regardless of what the control instance contains, this method
will transmit the queued IO commands to the IO expander
Usage: plant1Control.update(bus)
"""
ControlCluster.compile_instance_masks()
IO_expander_output(
ControlCluster.bus, self.IOexpander,
self.bank,
ControlCluster.master_mask[self.bank])
if self.bank != ControlCluster.pump_bank:
IO_expander_output(
ControlCluster.bus, self.IOexpander,
ControlCluster.pump_bank,
ControlCluster.master_mask[ControlCluster.pump_bank]) | python | def update(self):
""" This method exposes a more simple interface to the IO module
Regardless of what the control instance contains, this method
will transmit the queued IO commands to the IO expander
Usage: plant1Control.update(bus)
"""
ControlCluster.compile_instance_masks()
IO_expander_output(
ControlCluster.bus, self.IOexpander,
self.bank,
ControlCluster.master_mask[self.bank])
if self.bank != ControlCluster.pump_bank:
IO_expander_output(
ControlCluster.bus, self.IOexpander,
ControlCluster.pump_bank,
ControlCluster.master_mask[ControlCluster.pump_bank]) | [
"def",
"update",
"(",
"self",
")",
":",
"ControlCluster",
".",
"compile_instance_masks",
"(",
")",
"IO_expander_output",
"(",
"ControlCluster",
".",
"bus",
",",
"self",
".",
"IOexpander",
",",
"self",
".",
"bank",
",",
"ControlCluster",
".",
"master_mask",
"["... | This method exposes a more simple interface to the IO module
Regardless of what the control instance contains, this method
will transmit the queued IO commands to the IO expander
Usage: plant1Control.update(bus) | [
"This",
"method",
"exposes",
"a",
"more",
"simple",
"interface",
"to",
"the",
"IO",
"module",
"Regardless",
"of",
"what",
"the",
"control",
"instance",
"contains",
"this",
"method",
"will",
"transmit",
"the",
"queued",
"IO",
"commands",
"to",
"the",
"IO",
"e... | train | https://github.com/ECESeniorDesign/greenhouse_envmgmt/blob/864e0ce98bfb220f9954026913a5470536de9818/greenhouse_envmgmt/control.py#L62-L80 |
ECESeniorDesign/greenhouse_envmgmt | greenhouse_envmgmt/control.py | ControlCluster.form_GPIO_map | def form_GPIO_map(self):
""" This method creates a dictionary to map plant IDs to
GPIO pins are associated in triples.
Each ID gets a light, a fan, and a mist nozzle.
"""
# Compute bank/pins/IOexpander address based on ID
if self.ID == 1:
self.IOexpander = 0x20
self.bank = 0
self.fan = 2
self.light = 3
self.valve = 4
elif self.ID == 2:
self.IOexpander = 0x20
self.bank = 0
self.fan = 5
self.light = 6
self.valve = 7
elif self.ID == 3:
self.IOexpander = 0x20
self.bank = 1
self.fan = 0
self.light = 1
self.valve = 2
elif self.ID == 4:
self.IOexpander = 0x20
self.bank = 1
self.fan = 3
self.light = 5
self.valve = 6
else:
raise InvalidIOMap(
"Mapping not available for ID: " + str(self.ID))
# Check to make sure reserved pins are not requested
if (self.bank == 0) and (min(self.fan, self.light, self.valve) < 2):
raise InvalidIOMap(
"Pins A0 and A1 are reserved for other functions")
self.GPIO_dict = [{'ID': self.ID, 'bank': self.bank,
'fan': self.fan, 'valve': self.valve, 'light': self.light}]
# Append dictionary to class and resort dictionary by ID # if needed
ControlCluster.GPIOdict.append(self.GPIO_dict) | python | def form_GPIO_map(self):
""" This method creates a dictionary to map plant IDs to
GPIO pins are associated in triples.
Each ID gets a light, a fan, and a mist nozzle.
"""
# Compute bank/pins/IOexpander address based on ID
if self.ID == 1:
self.IOexpander = 0x20
self.bank = 0
self.fan = 2
self.light = 3
self.valve = 4
elif self.ID == 2:
self.IOexpander = 0x20
self.bank = 0
self.fan = 5
self.light = 6
self.valve = 7
elif self.ID == 3:
self.IOexpander = 0x20
self.bank = 1
self.fan = 0
self.light = 1
self.valve = 2
elif self.ID == 4:
self.IOexpander = 0x20
self.bank = 1
self.fan = 3
self.light = 5
self.valve = 6
else:
raise InvalidIOMap(
"Mapping not available for ID: " + str(self.ID))
# Check to make sure reserved pins are not requested
if (self.bank == 0) and (min(self.fan, self.light, self.valve) < 2):
raise InvalidIOMap(
"Pins A0 and A1 are reserved for other functions")
self.GPIO_dict = [{'ID': self.ID, 'bank': self.bank,
'fan': self.fan, 'valve': self.valve, 'light': self.light}]
# Append dictionary to class and resort dictionary by ID # if needed
ControlCluster.GPIOdict.append(self.GPIO_dict) | [
"def",
"form_GPIO_map",
"(",
"self",
")",
":",
"# Compute bank/pins/IOexpander address based on ID",
"if",
"self",
".",
"ID",
"==",
"1",
":",
"self",
".",
"IOexpander",
"=",
"0x20",
"self",
".",
"bank",
"=",
"0",
"self",
".",
"fan",
"=",
"2",
"self",
".",
... | This method creates a dictionary to map plant IDs to
GPIO pins are associated in triples.
Each ID gets a light, a fan, and a mist nozzle. | [
"This",
"method",
"creates",
"a",
"dictionary",
"to",
"map",
"plant",
"IDs",
"to",
"GPIO",
"pins",
"are",
"associated",
"in",
"triples",
".",
"Each",
"ID",
"gets",
"a",
"light",
"a",
"fan",
"and",
"a",
"mist",
"nozzle",
"."
] | train | https://github.com/ECESeniorDesign/greenhouse_envmgmt/blob/864e0ce98bfb220f9954026913a5470536de9818/greenhouse_envmgmt/control.py#L82-L125 |
ECESeniorDesign/greenhouse_envmgmt | greenhouse_envmgmt/control.py | ControlCluster.manage_pump | def manage_pump(self, operation):
"""
Updates control module knowledge of pump requests.
If any sensor module requests water, the pump will turn on.
"""
if operation == "on":
self.controls["pump"] = "on"
elif operation == "off":
self.controls["pump"] = "off"
return True | python | def manage_pump(self, operation):
"""
Updates control module knowledge of pump requests.
If any sensor module requests water, the pump will turn on.
"""
if operation == "on":
self.controls["pump"] = "on"
elif operation == "off":
self.controls["pump"] = "off"
return True | [
"def",
"manage_pump",
"(",
"self",
",",
"operation",
")",
":",
"if",
"operation",
"==",
"\"on\"",
":",
"self",
".",
"controls",
"[",
"\"pump\"",
"]",
"=",
"\"on\"",
"elif",
"operation",
"==",
"\"off\"",
":",
"self",
".",
"controls",
"[",
"\"pump\"",
"]",... | Updates control module knowledge of pump requests.
If any sensor module requests water, the pump will turn on. | [
"Updates",
"control",
"module",
"knowledge",
"of",
"pump",
"requests",
".",
"If",
"any",
"sensor",
"module",
"requests",
"water",
"the",
"pump",
"will",
"turn",
"on",
"."
] | train | https://github.com/ECESeniorDesign/greenhouse_envmgmt/blob/864e0ce98bfb220f9954026913a5470536de9818/greenhouse_envmgmt/control.py#L152-L163 |
ECESeniorDesign/greenhouse_envmgmt | greenhouse_envmgmt/control.py | ControlCluster.control | def control(self, on=[], off=[]):
"""
This method serves as the primary interaction point
to the controls interface.
- The 'on' and 'off' arguments can either be a list or a single string.
This allows for both individual device control and batch controls.
Note:
Both the onlist and offlist are optional.
If only one item is being managed, it can be passed as a string.
Usage:
- Turning off all devices:
ctrlobj.control(off="all")
- Turning on all devices:
ctrlobj.control(on="all")
- Turning on the light and fan ONLY (for example)
ctrlobj.control(on=["light", "fan"])
- Turning on the light and turning off the fan (for example)
ctrolobj.control(on="light", off="fan")
"""
controls = {"light", "valve", "fan", "pump"}
def cast_arg(arg):
if type(arg) is str:
if arg == "all":
return controls
else:
return {arg} & controls
else:
return set(arg) & controls
# User has requested individual controls.
for item in cast_arg(on):
self.manage(item, "on")
for item in cast_arg(off):
self.manage(item, "off")
sleep(.01) # Force delay to throttle requests
return self.update() | python | def control(self, on=[], off=[]):
"""
This method serves as the primary interaction point
to the controls interface.
- The 'on' and 'off' arguments can either be a list or a single string.
This allows for both individual device control and batch controls.
Note:
Both the onlist and offlist are optional.
If only one item is being managed, it can be passed as a string.
Usage:
- Turning off all devices:
ctrlobj.control(off="all")
- Turning on all devices:
ctrlobj.control(on="all")
- Turning on the light and fan ONLY (for example)
ctrlobj.control(on=["light", "fan"])
- Turning on the light and turning off the fan (for example)
ctrolobj.control(on="light", off="fan")
"""
controls = {"light", "valve", "fan", "pump"}
def cast_arg(arg):
if type(arg) is str:
if arg == "all":
return controls
else:
return {arg} & controls
else:
return set(arg) & controls
# User has requested individual controls.
for item in cast_arg(on):
self.manage(item, "on")
for item in cast_arg(off):
self.manage(item, "off")
sleep(.01) # Force delay to throttle requests
return self.update() | [
"def",
"control",
"(",
"self",
",",
"on",
"=",
"[",
"]",
",",
"off",
"=",
"[",
"]",
")",
":",
"controls",
"=",
"{",
"\"light\"",
",",
"\"valve\"",
",",
"\"fan\"",
",",
"\"pump\"",
"}",
"def",
"cast_arg",
"(",
"arg",
")",
":",
"if",
"type",
"(",
... | This method serves as the primary interaction point
to the controls interface.
- The 'on' and 'off' arguments can either be a list or a single string.
This allows for both individual device control and batch controls.
Note:
Both the onlist and offlist are optional.
If only one item is being managed, it can be passed as a string.
Usage:
- Turning off all devices:
ctrlobj.control(off="all")
- Turning on all devices:
ctrlobj.control(on="all")
- Turning on the light and fan ONLY (for example)
ctrlobj.control(on=["light", "fan"])
- Turning on the light and turning off the fan (for example)
ctrolobj.control(on="light", off="fan") | [
"This",
"method",
"serves",
"as",
"the",
"primary",
"interaction",
"point",
"to",
"the",
"controls",
"interface",
".",
"-",
"The",
"on",
"and",
"off",
"arguments",
"can",
"either",
"be",
"a",
"list",
"or",
"a",
"single",
"string",
".",
"This",
"allows",
... | train | https://github.com/ECESeniorDesign/greenhouse_envmgmt/blob/864e0ce98bfb220f9954026913a5470536de9818/greenhouse_envmgmt/control.py#L178-L219 |
ECESeniorDesign/greenhouse_envmgmt | greenhouse_envmgmt/control.py | ControlCluster.restore_state | def restore_state(self):
""" Method should be called on obj. initialization
When called, the method will attempt to restore
IO expander and RPi coherence and restore
local knowledge across a possible power failure
"""
current_mask = get_IO_reg(ControlCluster.bus,
self.IOexpander,
self.bank)
if current_mask & (1 << ControlCluster.pump_pin):
self.manage_pump("on")
if current_mask & (1 << self.fan):
self.manage_fan("on")
if current_mask & (1 << self.light):
self.manage_fan("on") | python | def restore_state(self):
""" Method should be called on obj. initialization
When called, the method will attempt to restore
IO expander and RPi coherence and restore
local knowledge across a possible power failure
"""
current_mask = get_IO_reg(ControlCluster.bus,
self.IOexpander,
self.bank)
if current_mask & (1 << ControlCluster.pump_pin):
self.manage_pump("on")
if current_mask & (1 << self.fan):
self.manage_fan("on")
if current_mask & (1 << self.light):
self.manage_fan("on") | [
"def",
"restore_state",
"(",
"self",
")",
":",
"current_mask",
"=",
"get_IO_reg",
"(",
"ControlCluster",
".",
"bus",
",",
"self",
".",
"IOexpander",
",",
"self",
".",
"bank",
")",
"if",
"current_mask",
"&",
"(",
"1",
"<<",
"ControlCluster",
".",
"pump_pin"... | Method should be called on obj. initialization
When called, the method will attempt to restore
IO expander and RPi coherence and restore
local knowledge across a possible power failure | [
"Method",
"should",
"be",
"called",
"on",
"obj",
".",
"initialization",
"When",
"called",
"the",
"method",
"will",
"attempt",
"to",
"restore",
"IO",
"expander",
"and",
"RPi",
"coherence",
"and",
"restore",
"local",
"knowledge",
"across",
"a",
"possible",
"powe... | train | https://github.com/ECESeniorDesign/greenhouse_envmgmt/blob/864e0ce98bfb220f9954026913a5470536de9818/greenhouse_envmgmt/control.py#L221-L235 |
switchboardpy/switchboard | switchboard/models.py | _key | def _key(key=''):
'''
Returns a Datastore key object, prefixed with the NAMESPACE.
'''
if not isinstance(key, datastore.Key):
# Switchboard uses ':' to denote one thing (parent-child) and datastore
# uses it for another, so replace ':' in the datastore version of the
# key.
safe_key = key.replace(':', '|')
key = datastore.Key(os.path.join(NAMESPACE, safe_key))
return key | python | def _key(key=''):
'''
Returns a Datastore key object, prefixed with the NAMESPACE.
'''
if not isinstance(key, datastore.Key):
# Switchboard uses ':' to denote one thing (parent-child) and datastore
# uses it for another, so replace ':' in the datastore version of the
# key.
safe_key = key.replace(':', '|')
key = datastore.Key(os.path.join(NAMESPACE, safe_key))
return key | [
"def",
"_key",
"(",
"key",
"=",
"''",
")",
":",
"if",
"not",
"isinstance",
"(",
"key",
",",
"datastore",
".",
"Key",
")",
":",
"# Switchboard uses ':' to denote one thing (parent-child) and datastore",
"# uses it for another, so replace ':' in the datastore version of the",
... | Returns a Datastore key object, prefixed with the NAMESPACE. | [
"Returns",
"a",
"Datastore",
"key",
"object",
"prefixed",
"with",
"the",
"NAMESPACE",
"."
] | train | https://github.com/switchboardpy/switchboard/blob/074b4838dbe140cb8f89d3c25ae25e70a29f9553/switchboard/models.py#L33-L43 |
switchboardpy/switchboard | switchboard/models.py | Model.get_or_create | def get_or_create(cls, key, defaults={}):
'''
A port of functionality from the Django ORM. Defaults can be passed in
if creating a new document is necessary. Keyword args are used to
lookup the document. Returns a tuple of (object, created), where object
is the retrieved or created object and created is a boolean specifying
whether a new object was created.
'''
instance = cls.get(key)
if not instance:
created = True
data = dict(key=key)
data.update(defaults)
# Do an upsert here instead of a straight create to avoid a race
# condition with another instance creating the same record at
# nearly the same time.
instance = cls.update(data, data, upsert=True)
else:
created = False
return instance, created | python | def get_or_create(cls, key, defaults={}):
'''
A port of functionality from the Django ORM. Defaults can be passed in
if creating a new document is necessary. Keyword args are used to
lookup the document. Returns a tuple of (object, created), where object
is the retrieved or created object and created is a boolean specifying
whether a new object was created.
'''
instance = cls.get(key)
if not instance:
created = True
data = dict(key=key)
data.update(defaults)
# Do an upsert here instead of a straight create to avoid a race
# condition with another instance creating the same record at
# nearly the same time.
instance = cls.update(data, data, upsert=True)
else:
created = False
return instance, created | [
"def",
"get_or_create",
"(",
"cls",
",",
"key",
",",
"defaults",
"=",
"{",
"}",
")",
":",
"instance",
"=",
"cls",
".",
"get",
"(",
"key",
")",
"if",
"not",
"instance",
":",
"created",
"=",
"True",
"data",
"=",
"dict",
"(",
"key",
"=",
"key",
")",... | A port of functionality from the Django ORM. Defaults can be passed in
if creating a new document is necessary. Keyword args are used to
lookup the document. Returns a tuple of (object, created), where object
is the retrieved or created object and created is a boolean specifying
whether a new object was created. | [
"A",
"port",
"of",
"functionality",
"from",
"the",
"Django",
"ORM",
".",
"Defaults",
"can",
"be",
"passed",
"in",
"if",
"creating",
"a",
"new",
"document",
"is",
"necessary",
".",
"Keyword",
"args",
"are",
"used",
"to",
"lookup",
"the",
"document",
".",
... | train | https://github.com/switchboardpy/switchboard/blob/074b4838dbe140cb8f89d3c25ae25e70a29f9553/switchboard/models.py#L102-L121 |
switchboardpy/switchboard | switchboard/models.py | Model.update | def update(cls, spec, updates, upsert=False):
'''
The spec is used to search for the data to update, updates contains the
values to be updated, and upsert specifies whether to do an insert if
the original data is not found.
'''
if 'key' in spec:
previous = cls.get(spec['key'])
else:
previous = None
if previous:
# Update existing data.
current = cls(**previous.__dict__)
elif upsert:
# Create new data.
current = cls(**spec)
else:
current = None
# XXX Should there be any error thrown if this is a noop?
if current:
current.__dict__.update(updates)
current.save()
return current | python | def update(cls, spec, updates, upsert=False):
'''
The spec is used to search for the data to update, updates contains the
values to be updated, and upsert specifies whether to do an insert if
the original data is not found.
'''
if 'key' in spec:
previous = cls.get(spec['key'])
else:
previous = None
if previous:
# Update existing data.
current = cls(**previous.__dict__)
elif upsert:
# Create new data.
current = cls(**spec)
else:
current = None
# XXX Should there be any error thrown if this is a noop?
if current:
current.__dict__.update(updates)
current.save()
return current | [
"def",
"update",
"(",
"cls",
",",
"spec",
",",
"updates",
",",
"upsert",
"=",
"False",
")",
":",
"if",
"'key'",
"in",
"spec",
":",
"previous",
"=",
"cls",
".",
"get",
"(",
"spec",
"[",
"'key'",
"]",
")",
"else",
":",
"previous",
"=",
"None",
"if"... | The spec is used to search for the data to update, updates contains the
values to be updated, and upsert specifies whether to do an insert if
the original data is not found. | [
"The",
"spec",
"is",
"used",
"to",
"search",
"for",
"the",
"data",
"to",
"update",
"updates",
"contains",
"the",
"values",
"to",
"be",
"updated",
"and",
"upsert",
"specifies",
"whether",
"to",
"do",
"an",
"insert",
"if",
"the",
"original",
"data",
"is",
... | train | https://github.com/switchboardpy/switchboard/blob/074b4838dbe140cb8f89d3c25ae25e70a29f9553/switchboard/models.py#L124-L146 |
switchboardpy/switchboard | switchboard/models.py | Model._queryless_all | def _queryless_all(cls):
'''
This is a hack because some datastore implementations don't support
querying. Right now the solution is to drop down to the underlying
native client and query all, which means that this section is ugly.
If it were architected properly, you might be able to do something
like inject an implementation of a NativeClient interface, which would
let Switchboard users write their own NativeClient wrappers that
implement all. However, at this point I'm just happy getting datastore
to work, so quick-and-dirty will suffice.
'''
if hasattr(cls.ds, '_redis'):
r = cls.ds._redis
keys = r.keys()
serializer = cls.ds.child_datastore.serializer
def get_value(k):
value = r.get(k)
return value if value is None else serializer.loads(value)
return [get_value(k) for k in keys]
else:
raise NotImplementedError | python | def _queryless_all(cls):
'''
This is a hack because some datastore implementations don't support
querying. Right now the solution is to drop down to the underlying
native client and query all, which means that this section is ugly.
If it were architected properly, you might be able to do something
like inject an implementation of a NativeClient interface, which would
let Switchboard users write their own NativeClient wrappers that
implement all. However, at this point I'm just happy getting datastore
to work, so quick-and-dirty will suffice.
'''
if hasattr(cls.ds, '_redis'):
r = cls.ds._redis
keys = r.keys()
serializer = cls.ds.child_datastore.serializer
def get_value(k):
value = r.get(k)
return value if value is None else serializer.loads(value)
return [get_value(k) for k in keys]
else:
raise NotImplementedError | [
"def",
"_queryless_all",
"(",
"cls",
")",
":",
"if",
"hasattr",
"(",
"cls",
".",
"ds",
",",
"'_redis'",
")",
":",
"r",
"=",
"cls",
".",
"ds",
".",
"_redis",
"keys",
"=",
"r",
".",
"keys",
"(",
")",
"serializer",
"=",
"cls",
".",
"ds",
".",
"chi... | This is a hack because some datastore implementations don't support
querying. Right now the solution is to drop down to the underlying
native client and query all, which means that this section is ugly.
If it were architected properly, you might be able to do something
like inject an implementation of a NativeClient interface, which would
let Switchboard users write their own NativeClient wrappers that
implement all. However, at this point I'm just happy getting datastore
to work, so quick-and-dirty will suffice. | [
"This",
"is",
"a",
"hack",
"because",
"some",
"datastore",
"implementations",
"don",
"t",
"support",
"querying",
".",
"Right",
"now",
"the",
"solution",
"is",
"to",
"drop",
"down",
"to",
"the",
"underlying",
"native",
"client",
"and",
"query",
"all",
"which"... | train | https://github.com/switchboardpy/switchboard/blob/074b4838dbe140cb8f89d3c25ae25e70a29f9553/switchboard/models.py#L171-L192 |
switchboardpy/switchboard | switchboard/models.py | Switch.remove_condition | def remove_condition(self, manager, condition_set, field_name, condition,
commit=True):
"""
Removes a condition and updates the global ``operator`` switch manager.
If ``commit`` is ``False``, the data will not be written to the
database.
>>> switch = operator['my_switch'] #doctest: +SKIP
>>> cs_id = condition_set.get_id() #doctest: +SKIP
>>> switch.remove_condition(cs_id, 'percent', [0, 50]) #doctest: +SKIP
"""
condition_set = manager.get_condition_set_by_id(condition_set)
namespace = condition_set.get_namespace()
if namespace not in self.value:
return
if field_name not in self.value[namespace]:
return
conditions = self.value[namespace][field_name]
self.value[namespace][field_name] = ([c for c in conditions
if c[1] != condition])
if not self.value[namespace][field_name]:
del self.value[namespace][field_name]
if not self.value[namespace]:
del self.value[namespace]
if commit:
self.save() | python | def remove_condition(self, manager, condition_set, field_name, condition,
commit=True):
"""
Removes a condition and updates the global ``operator`` switch manager.
If ``commit`` is ``False``, the data will not be written to the
database.
>>> switch = operator['my_switch'] #doctest: +SKIP
>>> cs_id = condition_set.get_id() #doctest: +SKIP
>>> switch.remove_condition(cs_id, 'percent', [0, 50]) #doctest: +SKIP
"""
condition_set = manager.get_condition_set_by_id(condition_set)
namespace = condition_set.get_namespace()
if namespace not in self.value:
return
if field_name not in self.value[namespace]:
return
conditions = self.value[namespace][field_name]
self.value[namespace][field_name] = ([c for c in conditions
if c[1] != condition])
if not self.value[namespace][field_name]:
del self.value[namespace][field_name]
if not self.value[namespace]:
del self.value[namespace]
if commit:
self.save() | [
"def",
"remove_condition",
"(",
"self",
",",
"manager",
",",
"condition_set",
",",
"field_name",
",",
"condition",
",",
"commit",
"=",
"True",
")",
":",
"condition_set",
"=",
"manager",
".",
"get_condition_set_by_id",
"(",
"condition_set",
")",
"namespace",
"=",... | Removes a condition and updates the global ``operator`` switch manager.
If ``commit`` is ``False``, the data will not be written to the
database.
>>> switch = operator['my_switch'] #doctest: +SKIP
>>> cs_id = condition_set.get_id() #doctest: +SKIP
>>> switch.remove_condition(cs_id, 'percent', [0, 50]) #doctest: +SKIP | [
"Removes",
"a",
"condition",
"and",
"updates",
"the",
"global",
"operator",
"switch",
"manager",
"."
] | train | https://github.com/switchboardpy/switchboard/blob/074b4838dbe140cb8f89d3c25ae25e70a29f9553/switchboard/models.py#L299-L332 |
switchboardpy/switchboard | switchboard/models.py | Switch.get_active_conditions | def get_active_conditions(self, manager):
'''
Returns a generator which yields groups of lists of conditions.
>>> conditions = switch.get_active_conditions()
>>> for label, set_id, field, value, exc in conditions: #doctest: +SKIP
>>> print ("%(label)s: %(field)s = %(value)s (exclude: %(exc)s)"
>>> % (label, field.label, value, exc)) #doctest: +SKIP
'''
for condition_set in sorted(manager.get_condition_sets(),
key=lambda x: x.get_group_label()):
ns = condition_set.get_namespace()
condition_set_id = condition_set.get_id()
if ns in self.value:
group = condition_set.get_group_label()
for name, field in condition_set.fields.iteritems():
for value in self.value[ns].get(name, []):
try:
yield (condition_set_id, group, field, value[1],
value[0] == EXCLUDE)
except TypeError:
continue | python | def get_active_conditions(self, manager):
'''
Returns a generator which yields groups of lists of conditions.
>>> conditions = switch.get_active_conditions()
>>> for label, set_id, field, value, exc in conditions: #doctest: +SKIP
>>> print ("%(label)s: %(field)s = %(value)s (exclude: %(exc)s)"
>>> % (label, field.label, value, exc)) #doctest: +SKIP
'''
for condition_set in sorted(manager.get_condition_sets(),
key=lambda x: x.get_group_label()):
ns = condition_set.get_namespace()
condition_set_id = condition_set.get_id()
if ns in self.value:
group = condition_set.get_group_label()
for name, field in condition_set.fields.iteritems():
for value in self.value[ns].get(name, []):
try:
yield (condition_set_id, group, field, value[1],
value[0] == EXCLUDE)
except TypeError:
continue | [
"def",
"get_active_conditions",
"(",
"self",
",",
"manager",
")",
":",
"for",
"condition_set",
"in",
"sorted",
"(",
"manager",
".",
"get_condition_sets",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"get_group_label",
"(",
")",
")",
":",
"ns"... | Returns a generator which yields groups of lists of conditions.
>>> conditions = switch.get_active_conditions()
>>> for label, set_id, field, value, exc in conditions: #doctest: +SKIP
>>> print ("%(label)s: %(field)s = %(value)s (exclude: %(exc)s)"
>>> % (label, field.label, value, exc)) #doctest: +SKIP | [
"Returns",
"a",
"generator",
"which",
"yields",
"groups",
"of",
"lists",
"of",
"conditions",
"."
] | train | https://github.com/switchboardpy/switchboard/blob/074b4838dbe140cb8f89d3c25ae25e70a29f9553/switchboard/models.py#L371-L392 |
ampledata/pypirc | pypirc/cmd.py | main | def main():
"""Main loop."""
parser = optparse.OptionParser()
parser.add_option(
'-s', '--server', help='Index Server Name', metavar='SERVER')
parser.add_option(
'-r', '--repository', help='Repository URL', metavar='URL')
parser.add_option(
'-u', '--username', help='User Name', metavar='USERNAME')
parser.add_option(
'-p', '--password', help='Password', metavar='PASSWORD')
options, _ = parser.parse_args()
myrc = pypirc.PyPiRC()
if options.server:
if myrc.servers:
# we're updating
server = myrc.servers.get(options.server, {})
else:
server = {}
if options.repository:
server['repository'] = options.repository
if options.username:
server['username'] = options.username
if options.password:
server['password'] = options.password
myrc.servers[options.server] = server
myrc.save()
if myrc.servers:
pprint.pprint(myrc.servers)
else:
print '.pypirc Empty!' | python | def main():
"""Main loop."""
parser = optparse.OptionParser()
parser.add_option(
'-s', '--server', help='Index Server Name', metavar='SERVER')
parser.add_option(
'-r', '--repository', help='Repository URL', metavar='URL')
parser.add_option(
'-u', '--username', help='User Name', metavar='USERNAME')
parser.add_option(
'-p', '--password', help='Password', metavar='PASSWORD')
options, _ = parser.parse_args()
myrc = pypirc.PyPiRC()
if options.server:
if myrc.servers:
# we're updating
server = myrc.servers.get(options.server, {})
else:
server = {}
if options.repository:
server['repository'] = options.repository
if options.username:
server['username'] = options.username
if options.password:
server['password'] = options.password
myrc.servers[options.server] = server
myrc.save()
if myrc.servers:
pprint.pprint(myrc.servers)
else:
print '.pypirc Empty!' | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"optparse",
".",
"OptionParser",
"(",
")",
"parser",
".",
"add_option",
"(",
"'-s'",
",",
"'--server'",
",",
"help",
"=",
"'Index Server Name'",
",",
"metavar",
"=",
"'SERVER'",
")",
"parser",
".",
"add_option",... | Main loop. | [
"Main",
"loop",
"."
] | train | https://github.com/ampledata/pypirc/blob/c10397a4cf82e40591a075bcc79a5ececcaef4a4/pypirc/cmd.py#L15-L52 |
datasift/datasift-python | datasift/push.py | Push.validate | def validate(self, output_type, output_params):
""" Check that a subscription is defined correctly.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushvalidate
:param output_type: One of DataSift's supported output types, e.g. s3
:type output_type: str
:param output_params: The set of parameters required by the specified output_type for docs on all available connectors see http://dev.datasift.com/docs/push/connectors/
:type output_params: str
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError`
"""
return self.request.post('validate',
dict(output_type=output_type, output_params=output_params)) | python | def validate(self, output_type, output_params):
""" Check that a subscription is defined correctly.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushvalidate
:param output_type: One of DataSift's supported output types, e.g. s3
:type output_type: str
:param output_params: The set of parameters required by the specified output_type for docs on all available connectors see http://dev.datasift.com/docs/push/connectors/
:type output_params: str
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError`
"""
return self.request.post('validate',
dict(output_type=output_type, output_params=output_params)) | [
"def",
"validate",
"(",
"self",
",",
"output_type",
",",
"output_params",
")",
":",
"return",
"self",
".",
"request",
".",
"post",
"(",
"'validate'",
",",
"dict",
"(",
"output_type",
"=",
"output_type",
",",
"output_params",
"=",
"output_params",
")",
")"
] | Check that a subscription is defined correctly.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushvalidate
:param output_type: One of DataSift's supported output types, e.g. s3
:type output_type: str
:param output_params: The set of parameters required by the specified output_type for docs on all available connectors see http://dev.datasift.com/docs/push/connectors/
:type output_params: str
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError` | [
"Check",
"that",
"a",
"subscription",
"is",
"defined",
"correctly",
"."
] | train | https://github.com/datasift/datasift-python/blob/bfaca1a47501a18e11065ecf630d9c31df818f65/datasift/push.py#L6-L20 |
datasift/datasift-python | datasift/push.py | Push.create_from_hash | def create_from_hash(self, stream, name, output_type, output_params,
initial_status=None, start=None, end=None):
""" Create a new push subscription using a live stream.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushcreate
:param stream: The hash of a DataSift stream.
:type stream: str
:param name: The name to give the newly created subscription
:type name: str
:param output_type: One of the supported output types e.g. s3
:type output_type: str
:param output_params: The set of parameters required for the given output type
:type output_params: dict
:param initial_status: The initial status of the subscription, active, paused or waiting_for_start
:type initial_status: str
:param start: Optionally specifies when the subscription should start
:type start: int
:param end: Optionally specifies when the subscription should end
:type end: int
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError`
"""
return self._create(True, stream, name, output_type, output_params, initial_status, start, end) | python | def create_from_hash(self, stream, name, output_type, output_params,
initial_status=None, start=None, end=None):
""" Create a new push subscription using a live stream.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushcreate
:param stream: The hash of a DataSift stream.
:type stream: str
:param name: The name to give the newly created subscription
:type name: str
:param output_type: One of the supported output types e.g. s3
:type output_type: str
:param output_params: The set of parameters required for the given output type
:type output_params: dict
:param initial_status: The initial status of the subscription, active, paused or waiting_for_start
:type initial_status: str
:param start: Optionally specifies when the subscription should start
:type start: int
:param end: Optionally specifies when the subscription should end
:type end: int
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError`
"""
return self._create(True, stream, name, output_type, output_params, initial_status, start, end) | [
"def",
"create_from_hash",
"(",
"self",
",",
"stream",
",",
"name",
",",
"output_type",
",",
"output_params",
",",
"initial_status",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"return",
"self",
".",
"_create",
"(",
"True",... | Create a new push subscription using a live stream.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushcreate
:param stream: The hash of a DataSift stream.
:type stream: str
:param name: The name to give the newly created subscription
:type name: str
:param output_type: One of the supported output types e.g. s3
:type output_type: str
:param output_params: The set of parameters required for the given output type
:type output_params: dict
:param initial_status: The initial status of the subscription, active, paused or waiting_for_start
:type initial_status: str
:param start: Optionally specifies when the subscription should start
:type start: int
:param end: Optionally specifies when the subscription should end
:type end: int
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError` | [
"Create",
"a",
"new",
"push",
"subscription",
"using",
"a",
"live",
"stream",
"."
] | train | https://github.com/datasift/datasift-python/blob/bfaca1a47501a18e11065ecf630d9c31df818f65/datasift/push.py#L43-L67 |
datasift/datasift-python | datasift/push.py | Push.create_from_historics | def create_from_historics(self, historics_id, name, output_type, output_params, initial_status=None, start=None,
end=None):
""" Create a new push subscription using the given Historic ID.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushcreate
:param historics_id: The ID of a Historics query
:type historics_id: str
:param name: The name to give the newly created subscription
:type name: str
:param output_type: One of the supported output types e.g. s3
:type output_type: str
:param output_params: set of parameters required for the given output type, see dev.datasift.com
:type output_params: dict
:param initial_status: The initial status of the subscription, active, paused or waiting_for_start
:type initial_status: str
:param start: Optionally specifies when the subscription should start
:type start: int
:param end: Optionally specifies when the subscription should end
:type end: int
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError`
"""
return self._create(False, historics_id, name, output_type, output_params, initial_status, start, end) | python | def create_from_historics(self, historics_id, name, output_type, output_params, initial_status=None, start=None,
end=None):
""" Create a new push subscription using the given Historic ID.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushcreate
:param historics_id: The ID of a Historics query
:type historics_id: str
:param name: The name to give the newly created subscription
:type name: str
:param output_type: One of the supported output types e.g. s3
:type output_type: str
:param output_params: set of parameters required for the given output type, see dev.datasift.com
:type output_params: dict
:param initial_status: The initial status of the subscription, active, paused or waiting_for_start
:type initial_status: str
:param start: Optionally specifies when the subscription should start
:type start: int
:param end: Optionally specifies when the subscription should end
:type end: int
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError`
"""
return self._create(False, historics_id, name, output_type, output_params, initial_status, start, end) | [
"def",
"create_from_historics",
"(",
"self",
",",
"historics_id",
",",
"name",
",",
"output_type",
",",
"output_params",
",",
"initial_status",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"return",
"self",
".",
"_create",
"("... | Create a new push subscription using the given Historic ID.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushcreate
:param historics_id: The ID of a Historics query
:type historics_id: str
:param name: The name to give the newly created subscription
:type name: str
:param output_type: One of the supported output types e.g. s3
:type output_type: str
:param output_params: set of parameters required for the given output type, see dev.datasift.com
:type output_params: dict
:param initial_status: The initial status of the subscription, active, paused or waiting_for_start
:type initial_status: str
:param start: Optionally specifies when the subscription should start
:type start: int
:param end: Optionally specifies when the subscription should end
:type end: int
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError` | [
"Create",
"a",
"new",
"push",
"subscription",
"using",
"the",
"given",
"Historic",
"ID",
"."
] | train | https://github.com/datasift/datasift-python/blob/bfaca1a47501a18e11065ecf630d9c31df818f65/datasift/push.py#L69-L93 |
datasift/datasift-python | datasift/push.py | Push.pause | def pause(self, subscription_id):
""" Pause a Subscription and buffer the data for up to one hour.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushpause
:param subscription_id: id of an existing Push Subscription.
:type subscription_id: str
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError`
"""
return self.request.post('pause', data=dict(id=subscription_id)) | python | def pause(self, subscription_id):
""" Pause a Subscription and buffer the data for up to one hour.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushpause
:param subscription_id: id of an existing Push Subscription.
:type subscription_id: str
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError`
"""
return self.request.post('pause', data=dict(id=subscription_id)) | [
"def",
"pause",
"(",
"self",
",",
"subscription_id",
")",
":",
"return",
"self",
".",
"request",
".",
"post",
"(",
"'pause'",
",",
"data",
"=",
"dict",
"(",
"id",
"=",
"subscription_id",
")",
")"
] | Pause a Subscription and buffer the data for up to one hour.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushpause
:param subscription_id: id of an existing Push Subscription.
:type subscription_id: str
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError` | [
"Pause",
"a",
"Subscription",
"and",
"buffer",
"the",
"data",
"for",
"up",
"to",
"one",
"hour",
"."
] | train | https://github.com/datasift/datasift-python/blob/bfaca1a47501a18e11065ecf630d9c31df818f65/datasift/push.py#L95-L107 |
datasift/datasift-python | datasift/push.py | Push.resume | def resume(self, subscription_id):
""" Resume a previously paused Subscription.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushresume
:param subscription_id: id of an existing Push Subscription.
:type subscription_id: str
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError`
"""
return self.request.post('resume', data=dict(id=subscription_id)) | python | def resume(self, subscription_id):
""" Resume a previously paused Subscription.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushresume
:param subscription_id: id of an existing Push Subscription.
:type subscription_id: str
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError`
"""
return self.request.post('resume', data=dict(id=subscription_id)) | [
"def",
"resume",
"(",
"self",
",",
"subscription_id",
")",
":",
"return",
"self",
".",
"request",
".",
"post",
"(",
"'resume'",
",",
"data",
"=",
"dict",
"(",
"id",
"=",
"subscription_id",
")",
")"
] | Resume a previously paused Subscription.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushresume
:param subscription_id: id of an existing Push Subscription.
:type subscription_id: str
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError` | [
"Resume",
"a",
"previously",
"paused",
"Subscription",
"."
] | train | https://github.com/datasift/datasift-python/blob/bfaca1a47501a18e11065ecf630d9c31df818f65/datasift/push.py#L109-L121 |
datasift/datasift-python | datasift/push.py | Push.update | def update(self, subscription_id, output_params, name=None):
""" Update the name or output parameters for an existing Subscription.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushupdate
:param subscription_id: id of an existing Push Subscription.
:type subscription_id: str
:param output_params: new output parameters for the subscription, see dev.datasift.com
:type output_params: dict
:param name: optional new name for the Subscription
:type name: str
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError`
"""
params = {'id': subscription_id, 'output_params': output_params}
if name:
params['name'] = name
return self.request.post('update', params) | python | def update(self, subscription_id, output_params, name=None):
""" Update the name or output parameters for an existing Subscription.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushupdate
:param subscription_id: id of an existing Push Subscription.
:type subscription_id: str
:param output_params: new output parameters for the subscription, see dev.datasift.com
:type output_params: dict
:param name: optional new name for the Subscription
:type name: str
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError`
"""
params = {'id': subscription_id, 'output_params': output_params}
if name:
params['name'] = name
return self.request.post('update', params) | [
"def",
"update",
"(",
"self",
",",
"subscription_id",
",",
"output_params",
",",
"name",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'id'",
":",
"subscription_id",
",",
"'output_params'",
":",
"output_params",
"}",
"if",
"name",
":",
"params",
"[",
"'name'... | Update the name or output parameters for an existing Subscription.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushupdate
:param subscription_id: id of an existing Push Subscription.
:type subscription_id: str
:param output_params: new output parameters for the subscription, see dev.datasift.com
:type output_params: dict
:param name: optional new name for the Subscription
:type name: str
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError` | [
"Update",
"the",
"name",
"or",
"output",
"parameters",
"for",
"an",
"existing",
"Subscription",
"."
] | train | https://github.com/datasift/datasift-python/blob/bfaca1a47501a18e11065ecf630d9c31df818f65/datasift/push.py#L123-L141 |
datasift/datasift-python | datasift/push.py | Push.stop | def stop(self, subscription_id):
""" Stop the given subscription from running.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushstop
:param subscription_id: id of an existing Push Subscription.
:type subscription_id: str
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError`
"""
return self.request.post('stop', data=dict(id=subscription_id)) | python | def stop(self, subscription_id):
""" Stop the given subscription from running.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushstop
:param subscription_id: id of an existing Push Subscription.
:type subscription_id: str
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError`
"""
return self.request.post('stop', data=dict(id=subscription_id)) | [
"def",
"stop",
"(",
"self",
",",
"subscription_id",
")",
":",
"return",
"self",
".",
"request",
".",
"post",
"(",
"'stop'",
",",
"data",
"=",
"dict",
"(",
"id",
"=",
"subscription_id",
")",
")"
] | Stop the given subscription from running.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushstop
:param subscription_id: id of an existing Push Subscription.
:type subscription_id: str
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError` | [
"Stop",
"the",
"given",
"subscription",
"from",
"running",
"."
] | train | https://github.com/datasift/datasift-python/blob/bfaca1a47501a18e11065ecf630d9c31df818f65/datasift/push.py#L143-L155 |
datasift/datasift-python | datasift/push.py | Push.delete | def delete(self, subscription_id):
""" Delete the subscription for the given ID.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushdelete
:param subscription_id: id of an existing Push Subscription.
:type subscription_id: str
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError`
"""
return self.request.post('delete', data=dict(id=subscription_id)) | python | def delete(self, subscription_id):
""" Delete the subscription for the given ID.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushdelete
:param subscription_id: id of an existing Push Subscription.
:type subscription_id: str
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError`
"""
return self.request.post('delete', data=dict(id=subscription_id)) | [
"def",
"delete",
"(",
"self",
",",
"subscription_id",
")",
":",
"return",
"self",
".",
"request",
".",
"post",
"(",
"'delete'",
",",
"data",
"=",
"dict",
"(",
"id",
"=",
"subscription_id",
")",
")"
] | Delete the subscription for the given ID.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushdelete
:param subscription_id: id of an existing Push Subscription.
:type subscription_id: str
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError` | [
"Delete",
"the",
"subscription",
"for",
"the",
"given",
"ID",
"."
] | train | https://github.com/datasift/datasift-python/blob/bfaca1a47501a18e11065ecf630d9c31df818f65/datasift/push.py#L157-L169 |
datasift/datasift-python | datasift/push.py | Push.log | def log(self, subscription_id=None, page=None, per_page=None, order_by=None, order_dir=None):
""" Retrieve any messages that have been logged for your subscriptions.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushlog
:param subscription_id: optional id of an existing Push Subscription, restricts logs to a given subscription if supplied.
:type subscription_id: str
:param page: optional page number for pagination
:type page: int
:param per_page: optional number of items per page, default 20
:type per_page: int
:param order_by: field to order by, default request_time
:type order_by: str
:param order_dir: direction to order by, asc or desc, default desc
:type order_dir: str
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError`
"""
params = {}
if subscription_id:
params['id'] = subscription_id
if page:
params['page'] = page
if per_page:
params['per_page'] = per_page
if order_by:
params['order_by'] = order_by
if order_dir:
params['order_dir'] = order_dir
return self.request.get('log', params=params) | python | def log(self, subscription_id=None, page=None, per_page=None, order_by=None, order_dir=None):
""" Retrieve any messages that have been logged for your subscriptions.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushlog
:param subscription_id: optional id of an existing Push Subscription, restricts logs to a given subscription if supplied.
:type subscription_id: str
:param page: optional page number for pagination
:type page: int
:param per_page: optional number of items per page, default 20
:type per_page: int
:param order_by: field to order by, default request_time
:type order_by: str
:param order_dir: direction to order by, asc or desc, default desc
:type order_dir: str
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError`
"""
params = {}
if subscription_id:
params['id'] = subscription_id
if page:
params['page'] = page
if per_page:
params['per_page'] = per_page
if order_by:
params['order_by'] = order_by
if order_dir:
params['order_dir'] = order_dir
return self.request.get('log', params=params) | [
"def",
"log",
"(",
"self",
",",
"subscription_id",
"=",
"None",
",",
"page",
"=",
"None",
",",
"per_page",
"=",
"None",
",",
"order_by",
"=",
"None",
",",
"order_dir",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"subscription_id",
":",
"par... | Retrieve any messages that have been logged for your subscriptions.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushlog
:param subscription_id: optional id of an existing Push Subscription, restricts logs to a given subscription if supplied.
:type subscription_id: str
:param page: optional page number for pagination
:type page: int
:param per_page: optional number of items per page, default 20
:type per_page: int
:param order_by: field to order by, default request_time
:type order_by: str
:param order_dir: direction to order by, asc or desc, default desc
:type order_dir: str
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError` | [
"Retrieve",
"any",
"messages",
"that",
"have",
"been",
"logged",
"for",
"your",
"subscriptions",
"."
] | train | https://github.com/datasift/datasift-python/blob/bfaca1a47501a18e11065ecf630d9c31df818f65/datasift/push.py#L171-L202 |
datasift/datasift-python | datasift/push.py | Push.get | def get(self, subscription_id=None, stream=None, historics_id=None,
page=None, per_page=None, order_by=None, order_dir=None,
include_finished=None):
""" Show details of the Subscriptions belonging to this user.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushget
:param subscription_id: optional id of an existing Push Subscription
:type subscription_id: str
:param hash: optional hash of a live stream
:type hash: str
:param playback_id: optional playback id of a Historics query
:type playback_id: str
:param page: optional page number for pagination
:type page: int
:param per_page: optional number of items per page, default 20
:type per_page: int
:param order_by: field to order by, default request_time
:type order_by: str
:param order_dir: direction to order by, asc or desc, default desc
:type order_dir: str
:param include_finished: boolean indicating if finished Subscriptions for Historics should be included
:type include_finished: bool
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError`
"""
params = {}
if subscription_id:
params['id'] = subscription_id
if stream:
params['hash'] = stream
if historics_id:
params['historics_id'] = historics_id
if page:
params['page'] = page
if per_page:
params['per_page'] = per_page
if order_by:
params['order_by'] = order_by
if order_dir:
params['order_dir'] = order_dir
if include_finished:
params['include_finished'] = 1 if include_finished else 0
return self.request.get('get', params=params) | python | def get(self, subscription_id=None, stream=None, historics_id=None,
page=None, per_page=None, order_by=None, order_dir=None,
include_finished=None):
""" Show details of the Subscriptions belonging to this user.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushget
:param subscription_id: optional id of an existing Push Subscription
:type subscription_id: str
:param hash: optional hash of a live stream
:type hash: str
:param playback_id: optional playback id of a Historics query
:type playback_id: str
:param page: optional page number for pagination
:type page: int
:param per_page: optional number of items per page, default 20
:type per_page: int
:param order_by: field to order by, default request_time
:type order_by: str
:param order_dir: direction to order by, asc or desc, default desc
:type order_dir: str
:param include_finished: boolean indicating if finished Subscriptions for Historics should be included
:type include_finished: bool
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError`
"""
params = {}
if subscription_id:
params['id'] = subscription_id
if stream:
params['hash'] = stream
if historics_id:
params['historics_id'] = historics_id
if page:
params['page'] = page
if per_page:
params['per_page'] = per_page
if order_by:
params['order_by'] = order_by
if order_dir:
params['order_dir'] = order_dir
if include_finished:
params['include_finished'] = 1 if include_finished else 0
return self.request.get('get', params=params) | [
"def",
"get",
"(",
"self",
",",
"subscription_id",
"=",
"None",
",",
"stream",
"=",
"None",
",",
"historics_id",
"=",
"None",
",",
"page",
"=",
"None",
",",
"per_page",
"=",
"None",
",",
"order_by",
"=",
"None",
",",
"order_dir",
"=",
"None",
",",
"i... | Show details of the Subscriptions belonging to this user.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushget
:param subscription_id: optional id of an existing Push Subscription
:type subscription_id: str
:param hash: optional hash of a live stream
:type hash: str
:param playback_id: optional playback id of a Historics query
:type playback_id: str
:param page: optional page number for pagination
:type page: int
:param per_page: optional number of items per page, default 20
:type per_page: int
:param order_by: field to order by, default request_time
:type order_by: str
:param order_dir: direction to order by, asc or desc, default desc
:type order_dir: str
:param include_finished: boolean indicating if finished Subscriptions for Historics should be included
:type include_finished: bool
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.exceptions.DataSiftApiException`, :class:`requests.exceptions.HTTPError` | [
"Show",
"details",
"of",
"the",
"Subscriptions",
"belonging",
"to",
"this",
"user",
"."
] | train | https://github.com/datasift/datasift-python/blob/bfaca1a47501a18e11065ecf630d9c31df818f65/datasift/push.py#L204-L249 |
fedora-infra/fedmsg_meta_fedora_infrastructure | fedmsg_meta_fedora_infrastructure/pagure.py | _get_project | def _get_project(msg, key='project'):
''' Return the project as `foo` or `user/foo` if the project is a
fork.
'''
project = msg[key]['name']
ns = msg[key].get('namespace')
if ns:
project = '/'.join([ns, project])
if msg[key]['parent']:
user = msg[key]['user']['name']
project = '/'.join(['fork', user, project])
return project | python | def _get_project(msg, key='project'):
''' Return the project as `foo` or `user/foo` if the project is a
fork.
'''
project = msg[key]['name']
ns = msg[key].get('namespace')
if ns:
project = '/'.join([ns, project])
if msg[key]['parent']:
user = msg[key]['user']['name']
project = '/'.join(['fork', user, project])
return project | [
"def",
"_get_project",
"(",
"msg",
",",
"key",
"=",
"'project'",
")",
":",
"project",
"=",
"msg",
"[",
"key",
"]",
"[",
"'name'",
"]",
"ns",
"=",
"msg",
"[",
"key",
"]",
".",
"get",
"(",
"'namespace'",
")",
"if",
"ns",
":",
"project",
"=",
"'/'",... | Return the project as `foo` or `user/foo` if the project is a
fork. | [
"Return",
"the",
"project",
"as",
"foo",
"or",
"user",
"/",
"foo",
"if",
"the",
"project",
"is",
"a",
"fork",
"."
] | train | https://github.com/fedora-infra/fedmsg_meta_fedora_infrastructure/blob/85bf4162692e3042c7dbcc12dfafaca4764b4ae6/fedmsg_meta_fedora_infrastructure/pagure.py#L30-L41 |
fedora-infra/fedmsg_meta_fedora_infrastructure | fedmsg_meta_fedora_infrastructure/pagure.py | _git_receive_v1 | def _git_receive_v1(msg, tmpl, **config):
''' Return the subtitle for the first version of pagure git.receive
messages.
'''
repo = _get_project(msg['msg']['commit'], key='repo')
email = msg['msg']['commit']['email']
user = email2fas(email, **config)
summ = msg['msg']['commit']['summary']
whole = msg['msg']['commit']['message']
if summ.strip() != whole.strip():
summ += " (..more)"
branch = msg['msg']['commit']['branch']
if 'refs/heads/' in branch:
branch = branch.replace('refs/heads/', '')
return tmpl.format(user=user or email, repo=repo,
branch=branch, summary=summ) | python | def _git_receive_v1(msg, tmpl, **config):
''' Return the subtitle for the first version of pagure git.receive
messages.
'''
repo = _get_project(msg['msg']['commit'], key='repo')
email = msg['msg']['commit']['email']
user = email2fas(email, **config)
summ = msg['msg']['commit']['summary']
whole = msg['msg']['commit']['message']
if summ.strip() != whole.strip():
summ += " (..more)"
branch = msg['msg']['commit']['branch']
if 'refs/heads/' in branch:
branch = branch.replace('refs/heads/', '')
return tmpl.format(user=user or email, repo=repo,
branch=branch, summary=summ) | [
"def",
"_git_receive_v1",
"(",
"msg",
",",
"tmpl",
",",
"*",
"*",
"config",
")",
":",
"repo",
"=",
"_get_project",
"(",
"msg",
"[",
"'msg'",
"]",
"[",
"'commit'",
"]",
",",
"key",
"=",
"'repo'",
")",
"email",
"=",
"msg",
"[",
"'msg'",
"]",
"[",
"... | Return the subtitle for the first version of pagure git.receive
messages. | [
"Return",
"the",
"subtitle",
"for",
"the",
"first",
"version",
"of",
"pagure",
"git",
".",
"receive",
"messages",
"."
] | train | https://github.com/fedora-infra/fedmsg_meta_fedora_infrastructure/blob/85bf4162692e3042c7dbcc12dfafaca4764b4ae6/fedmsg_meta_fedora_infrastructure/pagure.py#L44-L60 |
fedora-infra/fedmsg_meta_fedora_infrastructure | fedmsg_meta_fedora_infrastructure/pagure.py | _git_receive_v2 | def _git_receive_v2(msg, tmpl):
''' Return the subtitle for the second version of pagure git.receive
messages.
'''
repo = _get_project(msg['msg'], key='repo')
user = msg['msg']['agent']
n_commits = msg['msg']['total_commits']
commit_lbl = 'commit' if str(n_commits) == '1' else 'commits'
branch = msg['msg']['branch']
if 'refs/heads/' in branch:
branch = branch.replace('refs/heads/', '')
return tmpl.format(user=user, repo=repo,
branch=branch, n_commits=n_commits,
commit_lbl=commit_lbl) | python | def _git_receive_v2(msg, tmpl):
''' Return the subtitle for the second version of pagure git.receive
messages.
'''
repo = _get_project(msg['msg'], key='repo')
user = msg['msg']['agent']
n_commits = msg['msg']['total_commits']
commit_lbl = 'commit' if str(n_commits) == '1' else 'commits'
branch = msg['msg']['branch']
if 'refs/heads/' in branch:
branch = branch.replace('refs/heads/', '')
return tmpl.format(user=user, repo=repo,
branch=branch, n_commits=n_commits,
commit_lbl=commit_lbl) | [
"def",
"_git_receive_v2",
"(",
"msg",
",",
"tmpl",
")",
":",
"repo",
"=",
"_get_project",
"(",
"msg",
"[",
"'msg'",
"]",
",",
"key",
"=",
"'repo'",
")",
"user",
"=",
"msg",
"[",
"'msg'",
"]",
"[",
"'agent'",
"]",
"n_commits",
"=",
"msg",
"[",
"'msg... | Return the subtitle for the second version of pagure git.receive
messages. | [
"Return",
"the",
"subtitle",
"for",
"the",
"second",
"version",
"of",
"pagure",
"git",
".",
"receive",
"messages",
"."
] | train | https://github.com/fedora-infra/fedmsg_meta_fedora_infrastructure/blob/85bf4162692e3042c7dbcc12dfafaca4764b4ae6/fedmsg_meta_fedora_infrastructure/pagure.py#L63-L76 |
ClimateImpactLab/DataFS | datafs/managers/manager.py | BaseDataManager.update | def update(self, archive_name, version_metadata):
'''
Register a new version for archive ``archive_name``
.. note ::
need to implement hash checking to prevent duplicate writes
'''
version_metadata['updated'] = self.create_timestamp()
version_metadata['version'] = str(
version_metadata.get('version', None))
if version_metadata.get('message') is not None:
version_metadata['message'] = str(version_metadata['message'])
self._update(archive_name, version_metadata) | python | def update(self, archive_name, version_metadata):
'''
Register a new version for archive ``archive_name``
.. note ::
need to implement hash checking to prevent duplicate writes
'''
version_metadata['updated'] = self.create_timestamp()
version_metadata['version'] = str(
version_metadata.get('version', None))
if version_metadata.get('message') is not None:
version_metadata['message'] = str(version_metadata['message'])
self._update(archive_name, version_metadata) | [
"def",
"update",
"(",
"self",
",",
"archive_name",
",",
"version_metadata",
")",
":",
"version_metadata",
"[",
"'updated'",
"]",
"=",
"self",
".",
"create_timestamp",
"(",
")",
"version_metadata",
"[",
"'version'",
"]",
"=",
"str",
"(",
"version_metadata",
"."... | Register a new version for archive ``archive_name``
.. note ::
need to implement hash checking to prevent duplicate writes | [
"Register",
"a",
"new",
"version",
"for",
"archive",
"archive_name"
] | train | https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/managers/manager.py#L192-L207 |
ClimateImpactLab/DataFS | datafs/managers/manager.py | BaseDataManager.update_metadata | def update_metadata(self, archive_name, archive_metadata):
'''
Update metadata for archive ``archive_name``
'''
required_metadata_keys = self.required_archive_metadata.keys()
for key, val in archive_metadata.items():
if key in required_metadata_keys and val is None:
raise ValueError(
'Cannot remove required metadata attribute "{}"'.format(
key))
self._update_metadata(archive_name, archive_metadata) | python | def update_metadata(self, archive_name, archive_metadata):
'''
Update metadata for archive ``archive_name``
'''
required_metadata_keys = self.required_archive_metadata.keys()
for key, val in archive_metadata.items():
if key in required_metadata_keys and val is None:
raise ValueError(
'Cannot remove required metadata attribute "{}"'.format(
key))
self._update_metadata(archive_name, archive_metadata) | [
"def",
"update_metadata",
"(",
"self",
",",
"archive_name",
",",
"archive_metadata",
")",
":",
"required_metadata_keys",
"=",
"self",
".",
"required_archive_metadata",
".",
"keys",
"(",
")",
"for",
"key",
",",
"val",
"in",
"archive_metadata",
".",
"items",
"(",
... | Update metadata for archive ``archive_name`` | [
"Update",
"metadata",
"for",
"archive",
"archive_name"
] | train | https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/managers/manager.py#L209-L221 |
ClimateImpactLab/DataFS | datafs/managers/manager.py | BaseDataManager.create_archive | def create_archive(
self,
archive_name,
authority_name,
archive_path,
versioned,
raise_on_err=True,
metadata=None,
user_config=None,
tags=None,
helper=False):
'''
Create a new data archive
Returns
-------
archive : object
new :py:class:`~datafs.core.data_archive.DataArchive` object
'''
archive_metadata = self._create_archive_metadata(
archive_name=archive_name,
authority_name=authority_name,
archive_path=archive_path,
versioned=versioned,
raise_on_err=raise_on_err,
metadata=metadata,
user_config=user_config,
tags=tags,
helper=helper)
if raise_on_err:
self._create_archive(
archive_name,
archive_metadata)
else:
self._create_if_not_exists(
archive_name,
archive_metadata)
return self.get_archive(archive_name) | python | def create_archive(
self,
archive_name,
authority_name,
archive_path,
versioned,
raise_on_err=True,
metadata=None,
user_config=None,
tags=None,
helper=False):
'''
Create a new data archive
Returns
-------
archive : object
new :py:class:`~datafs.core.data_archive.DataArchive` object
'''
archive_metadata = self._create_archive_metadata(
archive_name=archive_name,
authority_name=authority_name,
archive_path=archive_path,
versioned=versioned,
raise_on_err=raise_on_err,
metadata=metadata,
user_config=user_config,
tags=tags,
helper=helper)
if raise_on_err:
self._create_archive(
archive_name,
archive_metadata)
else:
self._create_if_not_exists(
archive_name,
archive_metadata)
return self.get_archive(archive_name) | [
"def",
"create_archive",
"(",
"self",
",",
"archive_name",
",",
"authority_name",
",",
"archive_path",
",",
"versioned",
",",
"raise_on_err",
"=",
"True",
",",
"metadata",
"=",
"None",
",",
"user_config",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"helper",... | Create a new data archive
Returns
-------
archive : object
new :py:class:`~datafs.core.data_archive.DataArchive` object | [
"Create",
"a",
"new",
"data",
"archive"
] | train | https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/managers/manager.py#L223-L264 |
ClimateImpactLab/DataFS | datafs/managers/manager.py | BaseDataManager.get_archive | def get_archive(self, archive_name):
'''
Get a data archive given an archive name
Returns
-------
archive_specification : dict
archive_name: name of the archive to be retrieved
authority: name of the archive's authority
archive_path: service path of archive
'''
try:
spec = self._get_archive_spec(archive_name)
return spec
except KeyError:
raise KeyError('Archive "{}" not found'.format(archive_name)) | python | def get_archive(self, archive_name):
'''
Get a data archive given an archive name
Returns
-------
archive_specification : dict
archive_name: name of the archive to be retrieved
authority: name of the archive's authority
archive_path: service path of archive
'''
try:
spec = self._get_archive_spec(archive_name)
return spec
except KeyError:
raise KeyError('Archive "{}" not found'.format(archive_name)) | [
"def",
"get_archive",
"(",
"self",
",",
"archive_name",
")",
":",
"try",
":",
"spec",
"=",
"self",
".",
"_get_archive_spec",
"(",
"archive_name",
")",
"return",
"spec",
"except",
"KeyError",
":",
"raise",
"KeyError",
"(",
"'Archive \"{}\" not found'",
".",
"fo... | Get a data archive given an archive name
Returns
-------
archive_specification : dict
archive_name: name of the archive to be retrieved
authority: name of the archive's authority
archive_path: service path of archive | [
"Get",
"a",
"data",
"archive",
"given",
"an",
"archive",
"name"
] | train | https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/managers/manager.py#L316-L333 |
ClimateImpactLab/DataFS | datafs/managers/manager.py | BaseDataManager.add_tags | def add_tags(self, archive_name, tags):
'''
Add tags to an archive
Parameters
----------
archive_name:s tr
Name of archive
tags: list or tuple of strings
tags to add to the archive
'''
updated_tag_list = list(self._get_tags(archive_name))
for tag in tags:
if tag not in updated_tag_list:
updated_tag_list.append(tag)
self._set_tags(archive_name, updated_tag_list) | python | def add_tags(self, archive_name, tags):
'''
Add tags to an archive
Parameters
----------
archive_name:s tr
Name of archive
tags: list or tuple of strings
tags to add to the archive
'''
updated_tag_list = list(self._get_tags(archive_name))
for tag in tags:
if tag not in updated_tag_list:
updated_tag_list.append(tag)
self._set_tags(archive_name, updated_tag_list) | [
"def",
"add_tags",
"(",
"self",
",",
"archive_name",
",",
"tags",
")",
":",
"updated_tag_list",
"=",
"list",
"(",
"self",
".",
"_get_tags",
"(",
"archive_name",
")",
")",
"for",
"tag",
"in",
"tags",
":",
"if",
"tag",
"not",
"in",
"updated_tag_list",
":",... | Add tags to an archive
Parameters
----------
archive_name:s tr
Name of archive
tags: list or tuple of strings
tags to add to the archive | [
"Add",
"tags",
"to",
"an",
"archive"
] | train | https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/managers/manager.py#L451-L469 |
ClimateImpactLab/DataFS | datafs/managers/manager.py | BaseDataManager.delete_tags | def delete_tags(self, archive_name, tags):
'''
Delete tags from an archive
Parameters
----------
archive_name:s tr
Name of archive
tags: list or tuple of strings
tags to delete from the archive
'''
updated_tag_list = list(self._get_tags(archive_name))
for tag in tags:
if tag in updated_tag_list:
updated_tag_list.remove(tag)
self._set_tags(archive_name, updated_tag_list) | python | def delete_tags(self, archive_name, tags):
'''
Delete tags from an archive
Parameters
----------
archive_name:s tr
Name of archive
tags: list or tuple of strings
tags to delete from the archive
'''
updated_tag_list = list(self._get_tags(archive_name))
for tag in tags:
if tag in updated_tag_list:
updated_tag_list.remove(tag)
self._set_tags(archive_name, updated_tag_list) | [
"def",
"delete_tags",
"(",
"self",
",",
"archive_name",
",",
"tags",
")",
":",
"updated_tag_list",
"=",
"list",
"(",
"self",
".",
"_get_tags",
"(",
"archive_name",
")",
")",
"for",
"tag",
"in",
"tags",
":",
"if",
"tag",
"in",
"updated_tag_list",
":",
"up... | Delete tags from an archive
Parameters
----------
archive_name:s tr
Name of archive
tags: list or tuple of strings
tags to delete from the archive | [
"Delete",
"tags",
"from",
"an",
"archive"
] | train | https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/managers/manager.py#L471-L489 |
ClimateImpactLab/DataFS | datafs/managers/manager.py | BaseDataManager._normalize_tags | def _normalize_tags(self, tags):
'''
Coerces tags to lowercase strings
Parameters
----------
tags: list or tuple of strings
'''
lowered_str_tags = []
for tag in tags:
lowered_str_tags.append(str(tag).lower())
return lowered_str_tags | python | def _normalize_tags(self, tags):
'''
Coerces tags to lowercase strings
Parameters
----------
tags: list or tuple of strings
'''
lowered_str_tags = []
for tag in tags:
lowered_str_tags.append(str(tag).lower())
return lowered_str_tags | [
"def",
"_normalize_tags",
"(",
"self",
",",
"tags",
")",
":",
"lowered_str_tags",
"=",
"[",
"]",
"for",
"tag",
"in",
"tags",
":",
"lowered_str_tags",
".",
"append",
"(",
"str",
"(",
"tag",
")",
".",
"lower",
"(",
")",
")",
"return",
"lowered_str_tags"
] | Coerces tags to lowercase strings
Parameters
----------
tags: list or tuple of strings | [
"Coerces",
"tags",
"to",
"lowercase",
"strings"
] | train | https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/managers/manager.py#L491-L505 |
brunobord/md2ebook | md2ebook/commander.py | Commander.start | def start(self):
"Start the project on the directory"
bookname = self.args.get('--bookname', None)
if not bookname:
bookname = 'book.md'
project_dir = self.args.get('<name>', None)
if not project_dir:
project_dir = join(self.cwd, 'Book')
project_dir = abspath(project_dir)
# create the working dir?
if not exists(project_dir) or self.args['--overwrite']:
if exists(project_dir):
if yesno(warning(
'Are you sure you want to remove `%s`? '
% project_dir)):
shutil.rmtree(project_dir)
else:
sys.exit(error('Operation aborted'))
os.makedirs(project_dir)
os.makedirs(join(project_dir, 'build'))
with codecs.open(
join(project_dir, bookname), 'w', encoding="utf") as fd:
fd.write('''# This is your book
You can start it right now and publish it away!
''')
# What shall we do with the configuration file?
config_file = join(project_dir, 'book.json')
rewrite_config_file = True
if exists(config_file) and not self.args['--overwrite']:
print('A config file already exists. This step is skipped')
rewrite_config_file = False
if rewrite_config_file:
with codecs.open(config_file, 'w', encoding="utf") as fd:
data = {
'files': ['%s' % bookname],
'author': "%s" % ask("What is your name? "),
'title': '%s' % ask("E-book title, please? "),
}
data['fileroot'] = unidecode(data['title']).lower() \
.replace(' ', '-')
# pick a generator
if len(self.generators) == 1:
data['generator'] = self.generators[0]
else:
picked_generator = None
while not picked_generator:
picked_generator = ask(
"Which generator? [%s] "
% ', '.join(self.generators)
)
if picked_generator not in self.generators:
print warning(
'Wrong answer. Please pick one on the list')
picked_generator = None
# fine, we have one.
data['generator'] = picked_generator
json.dump(data, fd, indent=4, encoding="utf")
# Game over
print
sys.exit(
success('Now you can go to `%s` and start editing your book...'
% project_dir)) | python | def start(self):
"Start the project on the directory"
bookname = self.args.get('--bookname', None)
if not bookname:
bookname = 'book.md'
project_dir = self.args.get('<name>', None)
if not project_dir:
project_dir = join(self.cwd, 'Book')
project_dir = abspath(project_dir)
# create the working dir?
if not exists(project_dir) or self.args['--overwrite']:
if exists(project_dir):
if yesno(warning(
'Are you sure you want to remove `%s`? '
% project_dir)):
shutil.rmtree(project_dir)
else:
sys.exit(error('Operation aborted'))
os.makedirs(project_dir)
os.makedirs(join(project_dir, 'build'))
with codecs.open(
join(project_dir, bookname), 'w', encoding="utf") as fd:
fd.write('''# This is your book
You can start it right now and publish it away!
''')
# What shall we do with the configuration file?
config_file = join(project_dir, 'book.json')
rewrite_config_file = True
if exists(config_file) and not self.args['--overwrite']:
print('A config file already exists. This step is skipped')
rewrite_config_file = False
if rewrite_config_file:
with codecs.open(config_file, 'w', encoding="utf") as fd:
data = {
'files': ['%s' % bookname],
'author': "%s" % ask("What is your name? "),
'title': '%s' % ask("E-book title, please? "),
}
data['fileroot'] = unidecode(data['title']).lower() \
.replace(' ', '-')
# pick a generator
if len(self.generators) == 1:
data['generator'] = self.generators[0]
else:
picked_generator = None
while not picked_generator:
picked_generator = ask(
"Which generator? [%s] "
% ', '.join(self.generators)
)
if picked_generator not in self.generators:
print warning(
'Wrong answer. Please pick one on the list')
picked_generator = None
# fine, we have one.
data['generator'] = picked_generator
json.dump(data, fd, indent=4, encoding="utf")
# Game over
print
sys.exit(
success('Now you can go to `%s` and start editing your book...'
% project_dir)) | [
"def",
"start",
"(",
"self",
")",
":",
"bookname",
"=",
"self",
".",
"args",
".",
"get",
"(",
"'--bookname'",
",",
"None",
")",
"if",
"not",
"bookname",
":",
"bookname",
"=",
"'book.md'",
"project_dir",
"=",
"self",
".",
"args",
".",
"get",
"(",
"'<n... | Start the project on the directory | [
"Start",
"the",
"project",
"on",
"the",
"directory"
] | train | https://github.com/brunobord/md2ebook/blob/31e0d06b77f2d986e6af1115c9e613dfec0591a9/md2ebook/commander.py#L46-L110 |
brunobord/md2ebook | md2ebook/commander.py | Commander.build | def build(self):
"Build your book"
config = self.load_config()
html_generator = HTMLGenerator(self.cwd, config)
html_generator.build()
if self.args.get('--generator', None):
generator = self.args.get('--generator')
else:
generator = config.get('generator')
if generator == 'calibre':
EPUBClass = CalibreEPUBGenerator
PDFClass = CalibrePDFGenerator
elif generator == 'pandoc':
EPUBClass = PandocEPUBGenerator
PDFClass = PandocPDFGenerator
else:
raise ConfigurationError(
"Wrong configuration. Please check your config.json file.")
# EPUB Generation
epub_generator = EPUBClass(self.cwd, config, self.args)
epub_generator.build()
# Shall we proceed to the PDF?
if config.get('pdf', False) or self.args['--with-pdf']:
pdf_generator = PDFClass(self.cwd, config, self.args)
pdf_generator.build() | python | def build(self):
"Build your book"
config = self.load_config()
html_generator = HTMLGenerator(self.cwd, config)
html_generator.build()
if self.args.get('--generator', None):
generator = self.args.get('--generator')
else:
generator = config.get('generator')
if generator == 'calibre':
EPUBClass = CalibreEPUBGenerator
PDFClass = CalibrePDFGenerator
elif generator == 'pandoc':
EPUBClass = PandocEPUBGenerator
PDFClass = PandocPDFGenerator
else:
raise ConfigurationError(
"Wrong configuration. Please check your config.json file.")
# EPUB Generation
epub_generator = EPUBClass(self.cwd, config, self.args)
epub_generator.build()
# Shall we proceed to the PDF?
if config.get('pdf', False) or self.args['--with-pdf']:
pdf_generator = PDFClass(self.cwd, config, self.args)
pdf_generator.build() | [
"def",
"build",
"(",
"self",
")",
":",
"config",
"=",
"self",
".",
"load_config",
"(",
")",
"html_generator",
"=",
"HTMLGenerator",
"(",
"self",
".",
"cwd",
",",
"config",
")",
"html_generator",
".",
"build",
"(",
")",
"if",
"self",
".",
"args",
".",
... | Build your book | [
"Build",
"your",
"book"
] | train | https://github.com/brunobord/md2ebook/blob/31e0d06b77f2d986e6af1115c9e613dfec0591a9/md2ebook/commander.py#L113-L141 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.