repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
cenkalti/kuyruk | kuyruk/importer.py | main_module_name | def main_module_name() -> str:
"""Returns main module and module name pair."""
if not hasattr(main_module, '__file__'):
# running from interactive shell
return None
main_filename = os.path.basename(main_module.__file__)
module_name, ext = os.path.splitext(main_filename)
return module_name | python | def main_module_name() -> str:
"""Returns main module and module name pair."""
if not hasattr(main_module, '__file__'):
# running from interactive shell
return None
main_filename = os.path.basename(main_module.__file__)
module_name, ext = os.path.splitext(main_filename)
return module_name | [
"def",
"main_module_name",
"(",
")",
"->",
"str",
":",
"if",
"not",
"hasattr",
"(",
"main_module",
",",
"'__file__'",
")",
":",
"# running from interactive shell",
"return",
"None",
"main_filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"main_module",
... | Returns main module and module name pair. | [
"Returns",
"main",
"module",
"and",
"module",
"name",
"pair",
"."
] | c99d66be9d8fb077610f2fa883d5a1d268b42f04 | https://github.com/cenkalti/kuyruk/blob/c99d66be9d8fb077610f2fa883d5a1d268b42f04/kuyruk/importer.py#L40-L48 | train |
subdownloader/subdownloader | subdownloader/util.py | write_stream | def write_stream(src_file, destination_path):
"""
Write the file-like src_file object to the string dest_path
:param src_file: file-like data to be written
:param destination_path: string of the destionation file
"""
with open(destination_path, 'wb') as destination_file:
shutil.copyfileobj(fsrc=src_file, fdst=destination_file) | python | def write_stream(src_file, destination_path):
"""
Write the file-like src_file object to the string dest_path
:param src_file: file-like data to be written
:param destination_path: string of the destionation file
"""
with open(destination_path, 'wb') as destination_file:
shutil.copyfileobj(fsrc=src_file, fdst=destination_file) | [
"def",
"write_stream",
"(",
"src_file",
",",
"destination_path",
")",
":",
"with",
"open",
"(",
"destination_path",
",",
"'wb'",
")",
"as",
"destination_file",
":",
"shutil",
".",
"copyfileobj",
"(",
"fsrc",
"=",
"src_file",
",",
"fdst",
"=",
"destination_file... | Write the file-like src_file object to the string dest_path
:param src_file: file-like data to be written
:param destination_path: string of the destionation file | [
"Write",
"the",
"file",
"-",
"like",
"src_file",
"object",
"to",
"the",
"string",
"dest_path",
":",
"param",
"src_file",
":",
"file",
"-",
"like",
"data",
"to",
"be",
"written",
":",
"param",
"destination_path",
":",
"string",
"of",
"the",
"destionation",
... | bbccedd11b18d925ad4c062b5eb65981e24d0433 | https://github.com/subdownloader/subdownloader/blob/bbccedd11b18d925ad4c062b5eb65981e24d0433/subdownloader/util.py#L43-L50 | train |
jefflovejapan/drench | drench/switchboard.py | build_dirs | def build_dirs(files):
'''
Build necessary directories based on a list of file paths
'''
for i in files:
if type(i) is list:
build_dirs(i)
continue
else:
if len(i['path']) > 1:
addpath = os.path.join(os.getcwd(), *i['path'][:-1])
subdirs = all_subdirs(os.getcwd())
if addpath and addpath not in subdirs:
os.makedirs(addpath)
print 'just made path', addpath | python | def build_dirs(files):
'''
Build necessary directories based on a list of file paths
'''
for i in files:
if type(i) is list:
build_dirs(i)
continue
else:
if len(i['path']) > 1:
addpath = os.path.join(os.getcwd(), *i['path'][:-1])
subdirs = all_subdirs(os.getcwd())
if addpath and addpath not in subdirs:
os.makedirs(addpath)
print 'just made path', addpath | [
"def",
"build_dirs",
"(",
"files",
")",
":",
"for",
"i",
"in",
"files",
":",
"if",
"type",
"(",
"i",
")",
"is",
"list",
":",
"build_dirs",
"(",
"i",
")",
"continue",
"else",
":",
"if",
"len",
"(",
"i",
"[",
"'path'",
"]",
")",
">",
"1",
":",
... | Build necessary directories based on a list of file paths | [
"Build",
"necessary",
"directories",
"based",
"on",
"a",
"list",
"of",
"file",
"paths"
] | e99a8bf844a61d909d2d57629937ac672810469c | https://github.com/jefflovejapan/drench/blob/e99a8bf844a61d909d2d57629937ac672810469c/drench/switchboard.py#L21-L35 | train |
jefflovejapan/drench | drench/switchboard.py | get_want_file_pos | def get_want_file_pos(file_list):
'''
Ask the user which files in file_list he or she is interested in.
Return indices for the files inside file_list
'''
want_file_pos = []
print '\nFiles contained:\n'
for i in file_list:
print(os.path.join(*i['path']))
while 1:
all_answer = raw_input('\nDo you want all these files? (y/n): ')
if all_answer in ('y', 'n'):
break
if all_answer == 'y':
want_file_pos = range(len(file_list))
return want_file_pos
if all_answer == 'n':
for j, tfile in enumerate(file_list):
while 1:
file_answer = raw_input('Do you want {}? '
'(y/n): '.format(os.path.join
(*tfile['path'])))
if file_answer in ('y', 'n'):
break
if file_answer == 'y':
want_file_pos.append(j)
print "Here are all the files you want:"
for k in want_file_pos:
print os.path.join(*file_list[k]['path'])
return want_file_pos | python | def get_want_file_pos(file_list):
'''
Ask the user which files in file_list he or she is interested in.
Return indices for the files inside file_list
'''
want_file_pos = []
print '\nFiles contained:\n'
for i in file_list:
print(os.path.join(*i['path']))
while 1:
all_answer = raw_input('\nDo you want all these files? (y/n): ')
if all_answer in ('y', 'n'):
break
if all_answer == 'y':
want_file_pos = range(len(file_list))
return want_file_pos
if all_answer == 'n':
for j, tfile in enumerate(file_list):
while 1:
file_answer = raw_input('Do you want {}? '
'(y/n): '.format(os.path.join
(*tfile['path'])))
if file_answer in ('y', 'n'):
break
if file_answer == 'y':
want_file_pos.append(j)
print "Here are all the files you want:"
for k in want_file_pos:
print os.path.join(*file_list[k]['path'])
return want_file_pos | [
"def",
"get_want_file_pos",
"(",
"file_list",
")",
":",
"want_file_pos",
"=",
"[",
"]",
"print",
"'\\nFiles contained:\\n'",
"for",
"i",
"in",
"file_list",
":",
"print",
"(",
"os",
".",
"path",
".",
"join",
"(",
"*",
"i",
"[",
"'path'",
"]",
")",
")",
... | Ask the user which files in file_list he or she is interested in.
Return indices for the files inside file_list | [
"Ask",
"the",
"user",
"which",
"files",
"in",
"file_list",
"he",
"or",
"she",
"is",
"interested",
"in",
".",
"Return",
"indices",
"for",
"the",
"files",
"inside",
"file_list"
] | e99a8bf844a61d909d2d57629937ac672810469c | https://github.com/jefflovejapan/drench/blob/e99a8bf844a61d909d2d57629937ac672810469c/drench/switchboard.py#L38-L68 | train |
jefflovejapan/drench | drench/switchboard.py | get_file_starts | def get_file_starts(file_list):
'''
Return the starting position (in bytes) of a list of files by
iteratively summing their lengths
'''
starts = []
total = 0
for i in file_list:
starts.append(total)
total += i['length']
print starts
return starts | python | def get_file_starts(file_list):
'''
Return the starting position (in bytes) of a list of files by
iteratively summing their lengths
'''
starts = []
total = 0
for i in file_list:
starts.append(total)
total += i['length']
print starts
return starts | [
"def",
"get_file_starts",
"(",
"file_list",
")",
":",
"starts",
"=",
"[",
"]",
"total",
"=",
"0",
"for",
"i",
"in",
"file_list",
":",
"starts",
".",
"append",
"(",
"total",
")",
"total",
"+=",
"i",
"[",
"'length'",
"]",
"print",
"starts",
"return",
"... | Return the starting position (in bytes) of a list of files by
iteratively summing their lengths | [
"Return",
"the",
"starting",
"position",
"(",
"in",
"bytes",
")",
"of",
"a",
"list",
"of",
"files",
"by",
"iteratively",
"summing",
"their",
"lengths"
] | e99a8bf844a61d909d2d57629937ac672810469c | https://github.com/jefflovejapan/drench/blob/e99a8bf844a61d909d2d57629937ac672810469c/drench/switchboard.py#L71-L82 | train |
jefflovejapan/drench | drench/switchboard.py | get_rightmost_index | def get_rightmost_index(byte_index=0, file_starts=[0]):
'''
Retrieve the highest-indexed file that starts at or before byte_index.
'''
i = 1
while i <= len(file_starts):
start = file_starts[-i]
if start <= byte_index:
return len(file_starts) - i
else:
i += 1
else:
raise Exception('byte_index lower than all file_starts') | python | def get_rightmost_index(byte_index=0, file_starts=[0]):
'''
Retrieve the highest-indexed file that starts at or before byte_index.
'''
i = 1
while i <= len(file_starts):
start = file_starts[-i]
if start <= byte_index:
return len(file_starts) - i
else:
i += 1
else:
raise Exception('byte_index lower than all file_starts') | [
"def",
"get_rightmost_index",
"(",
"byte_index",
"=",
"0",
",",
"file_starts",
"=",
"[",
"0",
"]",
")",
":",
"i",
"=",
"1",
"while",
"i",
"<=",
"len",
"(",
"file_starts",
")",
":",
"start",
"=",
"file_starts",
"[",
"-",
"i",
"]",
"if",
"start",
"<=... | Retrieve the highest-indexed file that starts at or before byte_index. | [
"Retrieve",
"the",
"highest",
"-",
"indexed",
"file",
"that",
"starts",
"at",
"or",
"before",
"byte_index",
"."
] | e99a8bf844a61d909d2d57629937ac672810469c | https://github.com/jefflovejapan/drench/blob/e99a8bf844a61d909d2d57629937ac672810469c/drench/switchboard.py#L85-L98 | train |
jefflovejapan/drench | drench/switchboard.py | Switchboard.get_next_want_file | def get_next_want_file(self, byte_index, block):
'''
Returns the leftmost file in the user's list of wanted files
(want_file_pos). If the first file it finds isn't in the list,
it will keep searching until the length of 'block' is exceeded.
'''
while block:
rightmost = get_rightmost_index(byte_index=byte_index,
file_starts=self.file_starts)
if rightmost in self.want_file_pos:
return rightmost, byte_index, block
else:
file_start = (self.file_starts
[rightmost])
file_length = self.file_list[rightmost]['length']
bytes_rem = file_start + file_length - byte_index
if len(block) > bytes_rem:
block = block[bytes_rem:]
byte_index = byte_index + bytes_rem
else:
block = ''
else:
return None | python | def get_next_want_file(self, byte_index, block):
'''
Returns the leftmost file in the user's list of wanted files
(want_file_pos). If the first file it finds isn't in the list,
it will keep searching until the length of 'block' is exceeded.
'''
while block:
rightmost = get_rightmost_index(byte_index=byte_index,
file_starts=self.file_starts)
if rightmost in self.want_file_pos:
return rightmost, byte_index, block
else:
file_start = (self.file_starts
[rightmost])
file_length = self.file_list[rightmost]['length']
bytes_rem = file_start + file_length - byte_index
if len(block) > bytes_rem:
block = block[bytes_rem:]
byte_index = byte_index + bytes_rem
else:
block = ''
else:
return None | [
"def",
"get_next_want_file",
"(",
"self",
",",
"byte_index",
",",
"block",
")",
":",
"while",
"block",
":",
"rightmost",
"=",
"get_rightmost_index",
"(",
"byte_index",
"=",
"byte_index",
",",
"file_starts",
"=",
"self",
".",
"file_starts",
")",
"if",
"rightmos... | Returns the leftmost file in the user's list of wanted files
(want_file_pos). If the first file it finds isn't in the list,
it will keep searching until the length of 'block' is exceeded. | [
"Returns",
"the",
"leftmost",
"file",
"in",
"the",
"user",
"s",
"list",
"of",
"wanted",
"files",
"(",
"want_file_pos",
")",
".",
"If",
"the",
"first",
"file",
"it",
"finds",
"isn",
"t",
"in",
"the",
"list",
"it",
"will",
"keep",
"searching",
"until",
"... | e99a8bf844a61d909d2d57629937ac672810469c | https://github.com/jefflovejapan/drench/blob/e99a8bf844a61d909d2d57629937ac672810469c/drench/switchboard.py#L208-L230 | train |
jefflovejapan/drench | drench/switchboard.py | Switchboard.vis_init | def vis_init(self):
'''
Sends the state of the BTC at the time the visualizer connects,
initializing it.
'''
init_dict = {}
init_dict['kind'] = 'init'
assert len(self.want_file_pos) == len(self.heads_and_tails)
init_dict['want_file_pos'] = self.want_file_pos
init_dict['files'] = self.file_list
init_dict['heads_and_tails'] = self.heads_and_tails
init_dict['num_pieces'] = self.num_pieces
self.broadcast(init_dict) | python | def vis_init(self):
'''
Sends the state of the BTC at the time the visualizer connects,
initializing it.
'''
init_dict = {}
init_dict['kind'] = 'init'
assert len(self.want_file_pos) == len(self.heads_and_tails)
init_dict['want_file_pos'] = self.want_file_pos
init_dict['files'] = self.file_list
init_dict['heads_and_tails'] = self.heads_and_tails
init_dict['num_pieces'] = self.num_pieces
self.broadcast(init_dict) | [
"def",
"vis_init",
"(",
"self",
")",
":",
"init_dict",
"=",
"{",
"}",
"init_dict",
"[",
"'kind'",
"]",
"=",
"'init'",
"assert",
"len",
"(",
"self",
".",
"want_file_pos",
")",
"==",
"len",
"(",
"self",
".",
"heads_and_tails",
")",
"init_dict",
"[",
"'wa... | Sends the state of the BTC at the time the visualizer connects,
initializing it. | [
"Sends",
"the",
"state",
"of",
"the",
"BTC",
"at",
"the",
"time",
"the",
"visualizer",
"connects",
"initializing",
"it",
"."
] | e99a8bf844a61d909d2d57629937ac672810469c | https://github.com/jefflovejapan/drench/blob/e99a8bf844a61d909d2d57629937ac672810469c/drench/switchboard.py#L291-L303 | train |
jefflovejapan/drench | drench/switchboard.py | Switchboard.broadcast | def broadcast(self, data_dict):
'''
Send to the visualizer (if there is one) or enqueue for later
'''
if self.vis_socket:
self.queued_messages.append(data_dict)
self.send_all_updates() | python | def broadcast(self, data_dict):
'''
Send to the visualizer (if there is one) or enqueue for later
'''
if self.vis_socket:
self.queued_messages.append(data_dict)
self.send_all_updates() | [
"def",
"broadcast",
"(",
"self",
",",
"data_dict",
")",
":",
"if",
"self",
".",
"vis_socket",
":",
"self",
".",
"queued_messages",
".",
"append",
"(",
"data_dict",
")",
"self",
".",
"send_all_updates",
"(",
")"
] | Send to the visualizer (if there is one) or enqueue for later | [
"Send",
"to",
"the",
"visualizer",
"(",
"if",
"there",
"is",
"one",
")",
"or",
"enqueue",
"for",
"later"
] | e99a8bf844a61d909d2d57629937ac672810469c | https://github.com/jefflovejapan/drench/blob/e99a8bf844a61d909d2d57629937ac672810469c/drench/switchboard.py#L305-L311 | train |
jefflovejapan/drench | drench/tparser.py | bencode | def bencode(canonical):
'''
Turns a dictionary into a bencoded str with alphabetized keys
e.g., {'spam': 'eggs', 'cow': 'moo'} --> d3:cow3:moo4:spam4:eggse
'''
in_dict = dict(canonical)
def encode_str(in_str):
out_str = str(len(in_str)) + ':' + in_str
return out_str
def encode_int(in_int):
out_str = str('i' + str(in_int) + 'e')
return out_str
def encode_list(in_list):
out_str = 'l'
for item in in_list:
out_str += encode_item(item)
else:
out_str += 'e'
return out_str
def encode_dict(in_dict):
out_str = 'd'
keys = sorted(in_dict.keys())
for key in keys:
val = in_dict[key]
out_str = out_str + encode_item(key) + encode_item(val)
else:
out_str += 'e'
return out_str
def encode_item(x):
if isinstance(x, str):
return encode_str(x)
elif isinstance(x, int):
return encode_int(x)
elif isinstance(x, list):
return encode_list(x)
elif isinstance(x, dict):
return encode_dict(x)
return encode_item(in_dict) | python | def bencode(canonical):
'''
Turns a dictionary into a bencoded str with alphabetized keys
e.g., {'spam': 'eggs', 'cow': 'moo'} --> d3:cow3:moo4:spam4:eggse
'''
in_dict = dict(canonical)
def encode_str(in_str):
out_str = str(len(in_str)) + ':' + in_str
return out_str
def encode_int(in_int):
out_str = str('i' + str(in_int) + 'e')
return out_str
def encode_list(in_list):
out_str = 'l'
for item in in_list:
out_str += encode_item(item)
else:
out_str += 'e'
return out_str
def encode_dict(in_dict):
out_str = 'd'
keys = sorted(in_dict.keys())
for key in keys:
val = in_dict[key]
out_str = out_str + encode_item(key) + encode_item(val)
else:
out_str += 'e'
return out_str
def encode_item(x):
if isinstance(x, str):
return encode_str(x)
elif isinstance(x, int):
return encode_int(x)
elif isinstance(x, list):
return encode_list(x)
elif isinstance(x, dict):
return encode_dict(x)
return encode_item(in_dict) | [
"def",
"bencode",
"(",
"canonical",
")",
":",
"in_dict",
"=",
"dict",
"(",
"canonical",
")",
"def",
"encode_str",
"(",
"in_str",
")",
":",
"out_str",
"=",
"str",
"(",
"len",
"(",
"in_str",
")",
")",
"+",
"':'",
"+",
"in_str",
"return",
"out_str",
"de... | Turns a dictionary into a bencoded str with alphabetized keys
e.g., {'spam': 'eggs', 'cow': 'moo'} --> d3:cow3:moo4:spam4:eggse | [
"Turns",
"a",
"dictionary",
"into",
"a",
"bencoded",
"str",
"with",
"alphabetized",
"keys",
"e",
".",
"g",
".",
"{",
"spam",
":",
"eggs",
"cow",
":",
"moo",
"}",
"--",
">",
"d3",
":",
"cow3",
":",
"moo4",
":",
"spam4",
":",
"eggse"
] | e99a8bf844a61d909d2d57629937ac672810469c | https://github.com/jefflovejapan/drench/blob/e99a8bf844a61d909d2d57629937ac672810469c/drench/tparser.py#L8-L51 | train |
jefflovejapan/drench | drench/tparser.py | bdecode | def bdecode(bstring):
'''
Bdecodes a bencoded string
e.g., d3:cow3:moo4:spam4:eggse -> {'cow': 'moo', 'spam': 'eggs'}
'''
def get_val():
i = reader.next()
if i.isdigit():
str_len = get_len(i)
return get_str(str_len)
if i == 'd':
return get_dict()
if i == 'l':
return get_list()
if i == 'i':
return get_int()
if i == 'e':
return None
def get_len(i=''):
len_str = str(i)
next_char = reader.next()
if next_char == 'e': # The line that collapses the dictionary
return None
while next_char is not ':':
len_str += next_char
next_char = reader.next()
else:
return int(len_str)
def get_dict():
this_dict = {}
while 1:
str_len = get_len()
if str_len is None: # This dict is done
return this_dict
key = get_str(str_len)
val = get_val()
this_dict[key] = val
def get_int():
int_str = ''
i = reader.next()
while i is not 'e':
int_str += i
i = reader.next()
else:
return int(int_str)
def get_str(str_len):
this_str = ''
for i in range(str_len):
this_str += reader.next()
return this_str
def get_list():
this_list = []
while 1:
val = get_val()
if not val:
return this_list
this_list.append(val)
reader = _readchar(bstring)
dict_repr = get_val()
return dict_repr | python | def bdecode(bstring):
'''
Bdecodes a bencoded string
e.g., d3:cow3:moo4:spam4:eggse -> {'cow': 'moo', 'spam': 'eggs'}
'''
def get_val():
i = reader.next()
if i.isdigit():
str_len = get_len(i)
return get_str(str_len)
if i == 'd':
return get_dict()
if i == 'l':
return get_list()
if i == 'i':
return get_int()
if i == 'e':
return None
def get_len(i=''):
len_str = str(i)
next_char = reader.next()
if next_char == 'e': # The line that collapses the dictionary
return None
while next_char is not ':':
len_str += next_char
next_char = reader.next()
else:
return int(len_str)
def get_dict():
this_dict = {}
while 1:
str_len = get_len()
if str_len is None: # This dict is done
return this_dict
key = get_str(str_len)
val = get_val()
this_dict[key] = val
def get_int():
int_str = ''
i = reader.next()
while i is not 'e':
int_str += i
i = reader.next()
else:
return int(int_str)
def get_str(str_len):
this_str = ''
for i in range(str_len):
this_str += reader.next()
return this_str
def get_list():
this_list = []
while 1:
val = get_val()
if not val:
return this_list
this_list.append(val)
reader = _readchar(bstring)
dict_repr = get_val()
return dict_repr | [
"def",
"bdecode",
"(",
"bstring",
")",
":",
"def",
"get_val",
"(",
")",
":",
"i",
"=",
"reader",
".",
"next",
"(",
")",
"if",
"i",
".",
"isdigit",
"(",
")",
":",
"str_len",
"=",
"get_len",
"(",
"i",
")",
"return",
"get_str",
"(",
"str_len",
")",
... | Bdecodes a bencoded string
e.g., d3:cow3:moo4:spam4:eggse -> {'cow': 'moo', 'spam': 'eggs'} | [
"Bdecodes",
"a",
"bencoded",
"string",
"e",
".",
"g",
".",
"d3",
":",
"cow3",
":",
"moo4",
":",
"spam4",
":",
"eggse",
"-",
">",
"{",
"cow",
":",
"moo",
"spam",
":",
"eggs",
"}"
] | e99a8bf844a61d909d2d57629937ac672810469c | https://github.com/jefflovejapan/drench/blob/e99a8bf844a61d909d2d57629937ac672810469c/drench/tparser.py#L54-L120 | train |
jefflovejapan/drench | drench/drench.py | Torrent.build_payload | def build_payload(self):
'''
Builds the payload that will be sent in tracker_request
'''
payload = {}
hashed_info = hashlib.sha1(tparser.bencode(self.torrent_dict['info']))
self.hash_string = hashed_info.digest()
self.peer_id = ('-DR' + VERSION +
''.join(random.sample(ALPHANUM, 13)))
assert len(self.peer_id) == 20
payload['info_hash'] = self.hash_string
payload['peer_id'] = self.peer_id
payload['port'] = self.port
payload['uploaded'] = 0
payload['downloaded'] = 0
payload['left'] = self.length
payload['compact'] = 1
payload['supportcrypto'] = 1
payload['event'] = 'started'
return payload | python | def build_payload(self):
'''
Builds the payload that will be sent in tracker_request
'''
payload = {}
hashed_info = hashlib.sha1(tparser.bencode(self.torrent_dict['info']))
self.hash_string = hashed_info.digest()
self.peer_id = ('-DR' + VERSION +
''.join(random.sample(ALPHANUM, 13)))
assert len(self.peer_id) == 20
payload['info_hash'] = self.hash_string
payload['peer_id'] = self.peer_id
payload['port'] = self.port
payload['uploaded'] = 0
payload['downloaded'] = 0
payload['left'] = self.length
payload['compact'] = 1
payload['supportcrypto'] = 1
payload['event'] = 'started'
return payload | [
"def",
"build_payload",
"(",
"self",
")",
":",
"payload",
"=",
"{",
"}",
"hashed_info",
"=",
"hashlib",
".",
"sha1",
"(",
"tparser",
".",
"bencode",
"(",
"self",
".",
"torrent_dict",
"[",
"'info'",
"]",
")",
")",
"self",
".",
"hash_string",
"=",
"hashe... | Builds the payload that will be sent in tracker_request | [
"Builds",
"the",
"payload",
"that",
"will",
"be",
"sent",
"in",
"tracker_request"
] | e99a8bf844a61d909d2d57629937ac672810469c | https://github.com/jefflovejapan/drench/blob/e99a8bf844a61d909d2d57629937ac672810469c/drench/drench.py#L153-L172 | train |
jefflovejapan/drench | drench/drench.py | Torrent.tracker_request | def tracker_request(self):
'''
Sends the initial request to the tracker, compiling list of all peers
announcing to the tracker
'''
assert self.torrent_dict['info']
payload = self.build_payload()
if self.torrent_dict['announce'].startswith('udp'):
raise Exception('need to deal with UDP')
else:
self.r = requests.get(self.torrent_dict['announce'],
params=payload)
# Decoding response from tracker
self.tracker_response = tparser.bdecode(self.r.content)
self.get_peer_ips() | python | def tracker_request(self):
'''
Sends the initial request to the tracker, compiling list of all peers
announcing to the tracker
'''
assert self.torrent_dict['info']
payload = self.build_payload()
if self.torrent_dict['announce'].startswith('udp'):
raise Exception('need to deal with UDP')
else:
self.r = requests.get(self.torrent_dict['announce'],
params=payload)
# Decoding response from tracker
self.tracker_response = tparser.bdecode(self.r.content)
self.get_peer_ips() | [
"def",
"tracker_request",
"(",
"self",
")",
":",
"assert",
"self",
".",
"torrent_dict",
"[",
"'info'",
"]",
"payload",
"=",
"self",
".",
"build_payload",
"(",
")",
"if",
"self",
".",
"torrent_dict",
"[",
"'announce'",
"]",
".",
"startswith",
"(",
"'udp'",
... | Sends the initial request to the tracker, compiling list of all peers
announcing to the tracker | [
"Sends",
"the",
"initial",
"request",
"to",
"the",
"tracker",
"compiling",
"list",
"of",
"all",
"peers",
"announcing",
"to",
"the",
"tracker"
] | e99a8bf844a61d909d2d57629937ac672810469c | https://github.com/jefflovejapan/drench/blob/e99a8bf844a61d909d2d57629937ac672810469c/drench/drench.py#L175-L193 | train |
jefflovejapan/drench | drench/drench.py | Torrent.get_peer_ips | def get_peer_ips(self):
'''
Generates list of peer IPs from tracker response. Note: not all of
these IPs might be good, which is why we only init peer objects for
the subset that respond to handshake
'''
presponse = [ord(i) for i in self.tracker_response['peers']]
while presponse:
peer_ip = (('.'.join(str(x) for x in presponse[0:4]),
256 * presponse[4] + presponse[5]))
if peer_ip not in self.peer_ips:
self.peer_ips.append(peer_ip)
presponse = presponse[6:] | python | def get_peer_ips(self):
'''
Generates list of peer IPs from tracker response. Note: not all of
these IPs might be good, which is why we only init peer objects for
the subset that respond to handshake
'''
presponse = [ord(i) for i in self.tracker_response['peers']]
while presponse:
peer_ip = (('.'.join(str(x) for x in presponse[0:4]),
256 * presponse[4] + presponse[5]))
if peer_ip not in self.peer_ips:
self.peer_ips.append(peer_ip)
presponse = presponse[6:] | [
"def",
"get_peer_ips",
"(",
"self",
")",
":",
"presponse",
"=",
"[",
"ord",
"(",
"i",
")",
"for",
"i",
"in",
"self",
".",
"tracker_response",
"[",
"'peers'",
"]",
"]",
"while",
"presponse",
":",
"peer_ip",
"=",
"(",
"(",
"'.'",
".",
"join",
"(",
"s... | Generates list of peer IPs from tracker response. Note: not all of
these IPs might be good, which is why we only init peer objects for
the subset that respond to handshake | [
"Generates",
"list",
"of",
"peer",
"IPs",
"from",
"tracker",
"response",
".",
"Note",
":",
"not",
"all",
"of",
"these",
"IPs",
"might",
"be",
"good",
"which",
"is",
"why",
"we",
"only",
"init",
"peer",
"objects",
"for",
"the",
"subset",
"that",
"respond"... | e99a8bf844a61d909d2d57629937ac672810469c | https://github.com/jefflovejapan/drench/blob/e99a8bf844a61d909d2d57629937ac672810469c/drench/drench.py#L195-L207 | train |
jefflovejapan/drench | drench/drench.py | Torrent.handshake_peers | def handshake_peers(self):
'''
pstrlen = length of pstr as one byte
pstr = BitTorrent protocol
reserved = chr(0)*8
info_hash = 20-byte hash above (aka self.hash_string)
peer_id = 20-byte string
'''
pstr = 'BitTorrent protocol'
pstrlen = len(pstr)
info_hash = self.hash_string
peer_id = self.peer_id
packet = ''.join([chr(pstrlen), pstr, chr(0) * 8, info_hash,
peer_id])
print "Here's my packet {}".format(repr(packet))
# TODO -- add some checks in here so that I'm talking
# to a maximum of 30 peers
# TODO -- think about why i'm deleting self.peer_ips.
# What was the point of it? Why won't I need it?
# Think about what we're doing -- using this list to create
# new peer objects. Should make this functional, that way I
# can also call when I get new peers.
for i in self.peer_ips:
if len(self.peer_dict) >= 30:
break
s = socket.socket()
s.setblocking(True)
s.settimeout(0.5)
try:
s.connect(i)
except socket.timeout:
print '{} timed out on connect'.format(s.fileno())
continue
except socket.error:
print '{} threw a socket error'.format(s.fileno())
continue
except:
raise Exception
s.send(packet)
try:
data = s.recv(68) # Peer's handshake - len from docs
if data:
print 'From {} received: {}'.format(s.fileno(), repr(data))
self.initpeer(s)
except:
print '{} timed out on recv'.format(s.fileno())
continue
else:
self.peer_ips = [] | python | def handshake_peers(self):
'''
pstrlen = length of pstr as one byte
pstr = BitTorrent protocol
reserved = chr(0)*8
info_hash = 20-byte hash above (aka self.hash_string)
peer_id = 20-byte string
'''
pstr = 'BitTorrent protocol'
pstrlen = len(pstr)
info_hash = self.hash_string
peer_id = self.peer_id
packet = ''.join([chr(pstrlen), pstr, chr(0) * 8, info_hash,
peer_id])
print "Here's my packet {}".format(repr(packet))
# TODO -- add some checks in here so that I'm talking
# to a maximum of 30 peers
# TODO -- think about why i'm deleting self.peer_ips.
# What was the point of it? Why won't I need it?
# Think about what we're doing -- using this list to create
# new peer objects. Should make this functional, that way I
# can also call when I get new peers.
for i in self.peer_ips:
if len(self.peer_dict) >= 30:
break
s = socket.socket()
s.setblocking(True)
s.settimeout(0.5)
try:
s.connect(i)
except socket.timeout:
print '{} timed out on connect'.format(s.fileno())
continue
except socket.error:
print '{} threw a socket error'.format(s.fileno())
continue
except:
raise Exception
s.send(packet)
try:
data = s.recv(68) # Peer's handshake - len from docs
if data:
print 'From {} received: {}'.format(s.fileno(), repr(data))
self.initpeer(s)
except:
print '{} timed out on recv'.format(s.fileno())
continue
else:
self.peer_ips = [] | [
"def",
"handshake_peers",
"(",
"self",
")",
":",
"pstr",
"=",
"'BitTorrent protocol'",
"pstrlen",
"=",
"len",
"(",
"pstr",
")",
"info_hash",
"=",
"self",
".",
"hash_string",
"peer_id",
"=",
"self",
".",
"peer_id",
"packet",
"=",
"''",
".",
"join",
"(",
"... | pstrlen = length of pstr as one byte
pstr = BitTorrent protocol
reserved = chr(0)*8
info_hash = 20-byte hash above (aka self.hash_string)
peer_id = 20-byte string | [
"pstrlen",
"=",
"length",
"of",
"pstr",
"as",
"one",
"byte",
"pstr",
"=",
"BitTorrent",
"protocol",
"reserved",
"=",
"chr",
"(",
"0",
")",
"*",
"8",
"info_hash",
"=",
"20",
"-",
"byte",
"hash",
"above",
"(",
"aka",
"self",
".",
"hash_string",
")",
"p... | e99a8bf844a61d909d2d57629937ac672810469c | https://github.com/jefflovejapan/drench/blob/e99a8bf844a61d909d2d57629937ac672810469c/drench/drench.py#L211-L262 | train |
jefflovejapan/drench | drench/drench.py | Torrent.initpeer | def initpeer(self, sock):
'''
Creates a new peer object for a nvalid socket and adds it to reactor's
listen list
'''
location_json = requests.request("GET", "http://freegeoip.net/json/"
+ sock.getpeername()[0]).content
location = json.loads(location_json)
tpeer = peer.Peer(sock, self.reactor, self, location)
self.peer_dict[sock] = tpeer
self.reactor.select_list.append(tpeer) | python | def initpeer(self, sock):
'''
Creates a new peer object for a nvalid socket and adds it to reactor's
listen list
'''
location_json = requests.request("GET", "http://freegeoip.net/json/"
+ sock.getpeername()[0]).content
location = json.loads(location_json)
tpeer = peer.Peer(sock, self.reactor, self, location)
self.peer_dict[sock] = tpeer
self.reactor.select_list.append(tpeer) | [
"def",
"initpeer",
"(",
"self",
",",
"sock",
")",
":",
"location_json",
"=",
"requests",
".",
"request",
"(",
"\"GET\"",
",",
"\"http://freegeoip.net/json/\"",
"+",
"sock",
".",
"getpeername",
"(",
")",
"[",
"0",
"]",
")",
".",
"content",
"location",
"=",
... | Creates a new peer object for a nvalid socket and adds it to reactor's
listen list | [
"Creates",
"a",
"new",
"peer",
"object",
"for",
"a",
"nvalid",
"socket",
"and",
"adds",
"it",
"to",
"reactor",
"s",
"listen",
"list"
] | e99a8bf844a61d909d2d57629937ac672810469c | https://github.com/jefflovejapan/drench/blob/e99a8bf844a61d909d2d57629937ac672810469c/drench/drench.py#L264-L274 | train |
jefflovejapan/drench | drench/peer.py | Peer.read | def read(self):
try:
bytes = self.sock.recv(self.max_size)
except:
self.torrent.kill_peer(self)
return
'''
Chain of events:
- process_input
- check save_state and read length, id, and message accordingly
- if we have a piece (really a block), we piece.save it out
inside call to ppiece
- If we've completed a piece we:
- Tell the switchboard to write it out
- init a new piece
'''
if len(bytes) == 0:
print 'Got 0 bytes from fileno {}.'.format(self.fileno())
self.torrent.kill_peer(self)
self.process_input(bytes) | python | def read(self):
try:
bytes = self.sock.recv(self.max_size)
except:
self.torrent.kill_peer(self)
return
'''
Chain of events:
- process_input
- check save_state and read length, id, and message accordingly
- if we have a piece (really a block), we piece.save it out
inside call to ppiece
- If we've completed a piece we:
- Tell the switchboard to write it out
- init a new piece
'''
if len(bytes) == 0:
print 'Got 0 bytes from fileno {}.'.format(self.fileno())
self.torrent.kill_peer(self)
self.process_input(bytes) | [
"def",
"read",
"(",
"self",
")",
":",
"try",
":",
"bytes",
"=",
"self",
".",
"sock",
".",
"recv",
"(",
"self",
".",
"max_size",
")",
"except",
":",
"self",
".",
"torrent",
".",
"kill_peer",
"(",
"self",
")",
"return",
"if",
"len",
"(",
"bytes",
"... | Chain of events:
- process_input
- check save_state and read length, id, and message accordingly
- if we have a piece (really a block), we piece.save it out
inside call to ppiece
- If we've completed a piece we:
- Tell the switchboard to write it out
- init a new piece | [
"Chain",
"of",
"events",
":",
"-",
"process_input",
"-",
"check",
"save_state",
"and",
"read",
"length",
"id",
"and",
"message",
"accordingly",
"-",
"if",
"we",
"have",
"a",
"piece",
"(",
"really",
"a",
"block",
")",
"we",
"piece",
".",
"save",
"it",
"... | e99a8bf844a61d909d2d57629937ac672810469c | https://github.com/jefflovejapan/drench/blob/e99a8bf844a61d909d2d57629937ac672810469c/drench/peer.py#L55-L74 | train |
jefflovejapan/drench | drench/peer.py | Peer.ppiece | def ppiece(self, content):
'''
Process a piece that we've received from a peer, writing it out to
one or more files
'''
piece_index, byte_begin = struct.unpack('!ii', content[0:8])
# TODO -- figure out a better way to catch this error.
# How is piece_index getting swapped out from under me?
if piece_index != self.piece.index:
return
assert byte_begin % REQUEST_SIZE == 0
block_begin = byte_begin / REQUEST_SIZE
block = content[8:]
self.piece.save(index=block_begin, bytes=block)
if self.piece.complete:
piece_bytes = self.piece.get_bytes()
if self.piece.index == self.torrent.last_piece:
piece_bytes = piece_bytes[:self.torrent.last_piece_length]
if hashlib.sha1(piece_bytes).digest() == (self.torrent.torrent_dict
['info']['pieces']
[20 * piece_index:20 *
piece_index + 20]):
print 'hash matches'
# Take care of visualizer stuff
piece_dict = {'kind': 'piece', 'peer': self.sock.getpeername(),
'piece_index': piece_index}
self.torrent.switchboard.broadcast(piece_dict)
print ('writing piece {}. Length is '
'{}').format(repr(piece_bytes)[:10] + '...',
len(piece_bytes))
# Write out
byte_index = piece_index * self.torrent.piece_length
self.piece = self.init_piece()
self.request_all()
self.torrent.switchboard.write(byte_index, piece_bytes)
self.torrent.switchboard.mark_off(piece_index)
print self.torrent.switchboard.bitfield
if self.torrent.switchboard.complete:
print '\nDownload complete\n'
self.reactor.is_running = False
else:
print "Bad data -- hash doesn't match. Discarding piece."
self.piece = self.init_piece()
self.request_all() | python | def ppiece(self, content):
'''
Process a piece that we've received from a peer, writing it out to
one or more files
'''
piece_index, byte_begin = struct.unpack('!ii', content[0:8])
# TODO -- figure out a better way to catch this error.
# How is piece_index getting swapped out from under me?
if piece_index != self.piece.index:
return
assert byte_begin % REQUEST_SIZE == 0
block_begin = byte_begin / REQUEST_SIZE
block = content[8:]
self.piece.save(index=block_begin, bytes=block)
if self.piece.complete:
piece_bytes = self.piece.get_bytes()
if self.piece.index == self.torrent.last_piece:
piece_bytes = piece_bytes[:self.torrent.last_piece_length]
if hashlib.sha1(piece_bytes).digest() == (self.torrent.torrent_dict
['info']['pieces']
[20 * piece_index:20 *
piece_index + 20]):
print 'hash matches'
# Take care of visualizer stuff
piece_dict = {'kind': 'piece', 'peer': self.sock.getpeername(),
'piece_index': piece_index}
self.torrent.switchboard.broadcast(piece_dict)
print ('writing piece {}. Length is '
'{}').format(repr(piece_bytes)[:10] + '...',
len(piece_bytes))
# Write out
byte_index = piece_index * self.torrent.piece_length
self.piece = self.init_piece()
self.request_all()
self.torrent.switchboard.write(byte_index, piece_bytes)
self.torrent.switchboard.mark_off(piece_index)
print self.torrent.switchboard.bitfield
if self.torrent.switchboard.complete:
print '\nDownload complete\n'
self.reactor.is_running = False
else:
print "Bad data -- hash doesn't match. Discarding piece."
self.piece = self.init_piece()
self.request_all() | [
"def",
"ppiece",
"(",
"self",
",",
"content",
")",
":",
"piece_index",
",",
"byte_begin",
"=",
"struct",
".",
"unpack",
"(",
"'!ii'",
",",
"content",
"[",
"0",
":",
"8",
"]",
")",
"# TODO -- figure out a better way to catch this error.",
"# How is piece_index gett... | Process a piece that we've received from a peer, writing it out to
one or more files | [
"Process",
"a",
"piece",
"that",
"we",
"ve",
"received",
"from",
"a",
"peer",
"writing",
"it",
"out",
"to",
"one",
"or",
"more",
"files"
] | e99a8bf844a61d909d2d57629937ac672810469c | https://github.com/jefflovejapan/drench/blob/e99a8bf844a61d909d2d57629937ac672810469c/drench/peer.py#L208-L257 | train |
AustralianSynchrotron/lightflow | lightflow/models/datastore.py | DataStore.is_connected | def is_connected(self):
""" Returns the connection status of the data store.
Returns:
bool: ``True`` if the data store is connected to the MongoDB server.
"""
if self._client is not None:
try:
self._client.server_info()
except ConnectionFailure:
return False
return True
else:
return False | python | def is_connected(self):
""" Returns the connection status of the data store.
Returns:
bool: ``True`` if the data store is connected to the MongoDB server.
"""
if self._client is not None:
try:
self._client.server_info()
except ConnectionFailure:
return False
return True
else:
return False | [
"def",
"is_connected",
"(",
"self",
")",
":",
"if",
"self",
".",
"_client",
"is",
"not",
"None",
":",
"try",
":",
"self",
".",
"_client",
".",
"server_info",
"(",
")",
"except",
"ConnectionFailure",
":",
"return",
"False",
"return",
"True",
"else",
":",
... | Returns the connection status of the data store.
Returns:
bool: ``True`` if the data store is connected to the MongoDB server. | [
"Returns",
"the",
"connection",
"status",
"of",
"the",
"data",
"store",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/datastore.py#L84-L97 | train |
AustralianSynchrotron/lightflow | lightflow/models/datastore.py | DataStore.connect | def connect(self):
""" Establishes a connection to the MongoDB server.
Use the MongoProxy library in order to automatically handle AutoReconnect
exceptions in a graceful and reliable way.
"""
mongodb_args = {
'host': self.host,
'port': self.port,
'username': self._username,
'password': self._password,
'authSource': self._auth_source,
'serverSelectionTimeoutMS': self._connect_timeout
}
if self._auth_mechanism is not None:
mongodb_args['authMechanism'] = self._auth_mechanism
self._client = MongoClient(**mongodb_args)
if self._handle_reconnect:
self._client = MongoClientProxy(self._client) | python | def connect(self):
""" Establishes a connection to the MongoDB server.
Use the MongoProxy library in order to automatically handle AutoReconnect
exceptions in a graceful and reliable way.
"""
mongodb_args = {
'host': self.host,
'port': self.port,
'username': self._username,
'password': self._password,
'authSource': self._auth_source,
'serverSelectionTimeoutMS': self._connect_timeout
}
if self._auth_mechanism is not None:
mongodb_args['authMechanism'] = self._auth_mechanism
self._client = MongoClient(**mongodb_args)
if self._handle_reconnect:
self._client = MongoClientProxy(self._client) | [
"def",
"connect",
"(",
"self",
")",
":",
"mongodb_args",
"=",
"{",
"'host'",
":",
"self",
".",
"host",
",",
"'port'",
":",
"self",
".",
"port",
",",
"'username'",
":",
"self",
".",
"_username",
",",
"'password'",
":",
"self",
".",
"_password",
",",
"... | Establishes a connection to the MongoDB server.
Use the MongoProxy library in order to automatically handle AutoReconnect
exceptions in a graceful and reliable way. | [
"Establishes",
"a",
"connection",
"to",
"the",
"MongoDB",
"server",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/datastore.py#L99-L120 | train |
AustralianSynchrotron/lightflow | lightflow/models/datastore.py | DataStore.exists | def exists(self, workflow_id):
""" Checks whether a document with the specified workflow id already exists.
Args:
workflow_id (str): The workflow id that should be checked.
Raises:
DataStoreNotConnected: If the data store is not connected to the server.
Returns:
bool: ``True`` if a document with the specified workflow id exists.
"""
try:
db = self._client[self.database]
col = db[WORKFLOW_DATA_COLLECTION_NAME]
return col.find_one({"_id": ObjectId(workflow_id)}) is not None
except ConnectionFailure:
raise DataStoreNotConnected() | python | def exists(self, workflow_id):
""" Checks whether a document with the specified workflow id already exists.
Args:
workflow_id (str): The workflow id that should be checked.
Raises:
DataStoreNotConnected: If the data store is not connected to the server.
Returns:
bool: ``True`` if a document with the specified workflow id exists.
"""
try:
db = self._client[self.database]
col = db[WORKFLOW_DATA_COLLECTION_NAME]
return col.find_one({"_id": ObjectId(workflow_id)}) is not None
except ConnectionFailure:
raise DataStoreNotConnected() | [
"def",
"exists",
"(",
"self",
",",
"workflow_id",
")",
":",
"try",
":",
"db",
"=",
"self",
".",
"_client",
"[",
"self",
".",
"database",
"]",
"col",
"=",
"db",
"[",
"WORKFLOW_DATA_COLLECTION_NAME",
"]",
"return",
"col",
".",
"find_one",
"(",
"{",
"\"_i... | Checks whether a document with the specified workflow id already exists.
Args:
workflow_id (str): The workflow id that should be checked.
Raises:
DataStoreNotConnected: If the data store is not connected to the server.
Returns:
bool: ``True`` if a document with the specified workflow id exists. | [
"Checks",
"whether",
"a",
"document",
"with",
"the",
"specified",
"workflow",
"id",
"already",
"exists",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/datastore.py#L139-L157 | train |
AustralianSynchrotron/lightflow | lightflow/models/datastore.py | DataStore.add | def add(self, payload=None):
""" Adds a new document to the data store and returns its id.
Args:
payload (dict): Dictionary of initial data that should be stored
in the new document in the meta section.
Raises:
DataStoreNotConnected: If the data store is not connected to the server.
Returns:
str: The id of the newly created document.
"""
try:
db = self._client[self.database]
col = db[WORKFLOW_DATA_COLLECTION_NAME]
return str(col.insert_one({
DataStoreDocumentSection.Meta:
payload if isinstance(payload, dict) else {},
DataStoreDocumentSection.Data: {}
}).inserted_id)
except ConnectionFailure:
raise DataStoreNotConnected() | python | def add(self, payload=None):
""" Adds a new document to the data store and returns its id.
Args:
payload (dict): Dictionary of initial data that should be stored
in the new document in the meta section.
Raises:
DataStoreNotConnected: If the data store is not connected to the server.
Returns:
str: The id of the newly created document.
"""
try:
db = self._client[self.database]
col = db[WORKFLOW_DATA_COLLECTION_NAME]
return str(col.insert_one({
DataStoreDocumentSection.Meta:
payload if isinstance(payload, dict) else {},
DataStoreDocumentSection.Data: {}
}).inserted_id)
except ConnectionFailure:
raise DataStoreNotConnected() | [
"def",
"add",
"(",
"self",
",",
"payload",
"=",
"None",
")",
":",
"try",
":",
"db",
"=",
"self",
".",
"_client",
"[",
"self",
".",
"database",
"]",
"col",
"=",
"db",
"[",
"WORKFLOW_DATA_COLLECTION_NAME",
"]",
"return",
"str",
"(",
"col",
".",
"insert... | Adds a new document to the data store and returns its id.
Args:
payload (dict): Dictionary of initial data that should be stored
in the new document in the meta section.
Raises:
DataStoreNotConnected: If the data store is not connected to the server.
Returns:
str: The id of the newly created document. | [
"Adds",
"a",
"new",
"document",
"to",
"the",
"data",
"store",
"and",
"returns",
"its",
"id",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/datastore.py#L159-L182 | train |
AustralianSynchrotron/lightflow | lightflow/models/datastore.py | DataStore.remove | def remove(self, workflow_id):
""" Removes a document specified by its id from the data store.
All associated GridFs documents are deleted as well.
Args:
workflow_id (str): The id of the document that represents a workflow run.
Raises:
DataStoreNotConnected: If the data store is not connected to the server.
"""
try:
db = self._client[self.database]
fs = GridFSProxy(GridFS(db.unproxied_object))
for grid_doc in fs.find({"workflow_id": workflow_id},
no_cursor_timeout=True):
fs.delete(grid_doc._id)
col = db[WORKFLOW_DATA_COLLECTION_NAME]
return col.delete_one({"_id": ObjectId(workflow_id)})
except ConnectionFailure:
raise DataStoreNotConnected() | python | def remove(self, workflow_id):
""" Removes a document specified by its id from the data store.
All associated GridFs documents are deleted as well.
Args:
workflow_id (str): The id of the document that represents a workflow run.
Raises:
DataStoreNotConnected: If the data store is not connected to the server.
"""
try:
db = self._client[self.database]
fs = GridFSProxy(GridFS(db.unproxied_object))
for grid_doc in fs.find({"workflow_id": workflow_id},
no_cursor_timeout=True):
fs.delete(grid_doc._id)
col = db[WORKFLOW_DATA_COLLECTION_NAME]
return col.delete_one({"_id": ObjectId(workflow_id)})
except ConnectionFailure:
raise DataStoreNotConnected() | [
"def",
"remove",
"(",
"self",
",",
"workflow_id",
")",
":",
"try",
":",
"db",
"=",
"self",
".",
"_client",
"[",
"self",
".",
"database",
"]",
"fs",
"=",
"GridFSProxy",
"(",
"GridFS",
"(",
"db",
".",
"unproxied_object",
")",
")",
"for",
"grid_doc",
"i... | Removes a document specified by its id from the data store.
All associated GridFs documents are deleted as well.
Args:
workflow_id (str): The id of the document that represents a workflow run.
Raises:
DataStoreNotConnected: If the data store is not connected to the server. | [
"Removes",
"a",
"document",
"specified",
"by",
"its",
"id",
"from",
"the",
"data",
"store",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/datastore.py#L184-L207 | train |
AustralianSynchrotron/lightflow | lightflow/models/datastore.py | DataStore.get | def get(self, workflow_id):
""" Returns the document for the given workflow id.
Args:
workflow_id (str): The id of the document that represents a workflow run.
Raises:
DataStoreNotConnected: If the data store is not connected to the server.
Returns:
DataStoreDocument: The document for the given workflow id.
"""
try:
db = self._client[self.database]
fs = GridFSProxy(GridFS(db.unproxied_object))
return DataStoreDocument(db[WORKFLOW_DATA_COLLECTION_NAME], fs, workflow_id)
except ConnectionFailure:
raise DataStoreNotConnected() | python | def get(self, workflow_id):
""" Returns the document for the given workflow id.
Args:
workflow_id (str): The id of the document that represents a workflow run.
Raises:
DataStoreNotConnected: If the data store is not connected to the server.
Returns:
DataStoreDocument: The document for the given workflow id.
"""
try:
db = self._client[self.database]
fs = GridFSProxy(GridFS(db.unproxied_object))
return DataStoreDocument(db[WORKFLOW_DATA_COLLECTION_NAME], fs, workflow_id)
except ConnectionFailure:
raise DataStoreNotConnected() | [
"def",
"get",
"(",
"self",
",",
"workflow_id",
")",
":",
"try",
":",
"db",
"=",
"self",
".",
"_client",
"[",
"self",
".",
"database",
"]",
"fs",
"=",
"GridFSProxy",
"(",
"GridFS",
"(",
"db",
".",
"unproxied_object",
")",
")",
"return",
"DataStoreDocume... | Returns the document for the given workflow id.
Args:
workflow_id (str): The id of the document that represents a workflow run.
Raises:
DataStoreNotConnected: If the data store is not connected to the server.
Returns:
DataStoreDocument: The document for the given workflow id. | [
"Returns",
"the",
"document",
"for",
"the",
"given",
"workflow",
"id",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/datastore.py#L209-L227 | train |
AustralianSynchrotron/lightflow | lightflow/models/datastore.py | DataStoreDocument.get | def get(self, key, default=None, *, section=DataStoreDocumentSection.Data):
""" Return the field specified by its key from the specified section.
This method access the specified section of the workflow document and returns the
value for the given key.
Args:
key (str): The key pointing to the value that should be retrieved. It supports
MongoDB's dot notation for nested fields.
default: The default value that is returned if the key does not exist.
section (DataStoreDocumentSection): The section from which the data should
be retrieved.
Returns:
object: The value from the field that the specified key is pointing to. If the
key does not exist, the default value is returned. If no default value
is provided and the key does not exist ``None`` is returned.
"""
key_notation = '.'.join([section, key])
try:
return self._decode_value(self._data_from_dotnotation(key_notation, default))
except KeyError:
return None | python | def get(self, key, default=None, *, section=DataStoreDocumentSection.Data):
""" Return the field specified by its key from the specified section.
This method access the specified section of the workflow document and returns the
value for the given key.
Args:
key (str): The key pointing to the value that should be retrieved. It supports
MongoDB's dot notation for nested fields.
default: The default value that is returned if the key does not exist.
section (DataStoreDocumentSection): The section from which the data should
be retrieved.
Returns:
object: The value from the field that the specified key is pointing to. If the
key does not exist, the default value is returned. If no default value
is provided and the key does not exist ``None`` is returned.
"""
key_notation = '.'.join([section, key])
try:
return self._decode_value(self._data_from_dotnotation(key_notation, default))
except KeyError:
return None | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
",",
"*",
",",
"section",
"=",
"DataStoreDocumentSection",
".",
"Data",
")",
":",
"key_notation",
"=",
"'.'",
".",
"join",
"(",
"[",
"section",
",",
"key",
"]",
")",
"try",
":",
"r... | Return the field specified by its key from the specified section.
This method access the specified section of the workflow document and returns the
value for the given key.
Args:
key (str): The key pointing to the value that should be retrieved. It supports
MongoDB's dot notation for nested fields.
default: The default value that is returned if the key does not exist.
section (DataStoreDocumentSection): The section from which the data should
be retrieved.
Returns:
object: The value from the field that the specified key is pointing to. If the
key does not exist, the default value is returned. If no default value
is provided and the key does not exist ``None`` is returned. | [
"Return",
"the",
"field",
"specified",
"by",
"its",
"key",
"from",
"the",
"specified",
"section",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/datastore.py#L248-L270 | train |
AustralianSynchrotron/lightflow | lightflow/models/datastore.py | DataStoreDocument.set | def set(self, key, value, *, section=DataStoreDocumentSection.Data):
""" Store a value under the specified key in the given section of the document.
This method stores a value into the specified section of the workflow data store
document. Any existing value is overridden. Before storing a value, any linked
GridFS document under the specified key is deleted.
Args:
key (str): The key pointing to the value that should be stored/updated.
It supports MongoDB's dot notation for nested fields.
value: The value that should be stored/updated.
section (DataStoreDocumentSection): The section from which the data should
be retrieved.
Returns:
bool: ``True`` if the value could be set/updated, otherwise ``False``.
"""
key_notation = '.'.join([section, key])
try:
self._delete_gridfs_data(self._data_from_dotnotation(key_notation,
default=None))
except KeyError:
logger.info('Adding new field {} to the data store'.format(key_notation))
result = self._collection.update_one(
{"_id": ObjectId(self._workflow_id)},
{
"$set": {
key_notation: self._encode_value(value)
},
"$currentDate": {"lastModified": True}
}
)
return result.modified_count == 1 | python | def set(self, key, value, *, section=DataStoreDocumentSection.Data):
""" Store a value under the specified key in the given section of the document.
This method stores a value into the specified section of the workflow data store
document. Any existing value is overridden. Before storing a value, any linked
GridFS document under the specified key is deleted.
Args:
key (str): The key pointing to the value that should be stored/updated.
It supports MongoDB's dot notation for nested fields.
value: The value that should be stored/updated.
section (DataStoreDocumentSection): The section from which the data should
be retrieved.
Returns:
bool: ``True`` if the value could be set/updated, otherwise ``False``.
"""
key_notation = '.'.join([section, key])
try:
self._delete_gridfs_data(self._data_from_dotnotation(key_notation,
default=None))
except KeyError:
logger.info('Adding new field {} to the data store'.format(key_notation))
result = self._collection.update_one(
{"_id": ObjectId(self._workflow_id)},
{
"$set": {
key_notation: self._encode_value(value)
},
"$currentDate": {"lastModified": True}
}
)
return result.modified_count == 1 | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
",",
"*",
",",
"section",
"=",
"DataStoreDocumentSection",
".",
"Data",
")",
":",
"key_notation",
"=",
"'.'",
".",
"join",
"(",
"[",
"section",
",",
"key",
"]",
")",
"try",
":",
"self",
".",
"_de... | Store a value under the specified key in the given section of the document.
This method stores a value into the specified section of the workflow data store
document. Any existing value is overridden. Before storing a value, any linked
GridFS document under the specified key is deleted.
Args:
key (str): The key pointing to the value that should be stored/updated.
It supports MongoDB's dot notation for nested fields.
value: The value that should be stored/updated.
section (DataStoreDocumentSection): The section from which the data should
be retrieved.
Returns:
bool: ``True`` if the value could be set/updated, otherwise ``False``. | [
"Store",
"a",
"value",
"under",
"the",
"specified",
"key",
"in",
"the",
"given",
"section",
"of",
"the",
"document",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/datastore.py#L272-L306 | train |
AustralianSynchrotron/lightflow | lightflow/models/datastore.py | DataStoreDocument.push | def push(self, key, value, *, section=DataStoreDocumentSection.Data):
""" Appends a value to a list in the specified section of the document.
Args:
key (str): The key pointing to the value that should be stored/updated.
It supports MongoDB's dot notation for nested fields.
value: The value that should be appended to a list in the data store.
section (DataStoreDocumentSection): The section from which the data should
be retrieved.
Returns:
bool: ``True`` if the value could be appended, otherwise ``False``.
"""
key_notation = '.'.join([section, key])
result = self._collection.update_one(
{"_id": ObjectId(self._workflow_id)},
{
"$push": {
key_notation: self._encode_value(value)
},
"$currentDate": {"lastModified": True}
}
)
return result.modified_count == 1 | python | def push(self, key, value, *, section=DataStoreDocumentSection.Data):
""" Appends a value to a list in the specified section of the document.
Args:
key (str): The key pointing to the value that should be stored/updated.
It supports MongoDB's dot notation for nested fields.
value: The value that should be appended to a list in the data store.
section (DataStoreDocumentSection): The section from which the data should
be retrieved.
Returns:
bool: ``True`` if the value could be appended, otherwise ``False``.
"""
key_notation = '.'.join([section, key])
result = self._collection.update_one(
{"_id": ObjectId(self._workflow_id)},
{
"$push": {
key_notation: self._encode_value(value)
},
"$currentDate": {"lastModified": True}
}
)
return result.modified_count == 1 | [
"def",
"push",
"(",
"self",
",",
"key",
",",
"value",
",",
"*",
",",
"section",
"=",
"DataStoreDocumentSection",
".",
"Data",
")",
":",
"key_notation",
"=",
"'.'",
".",
"join",
"(",
"[",
"section",
",",
"key",
"]",
")",
"result",
"=",
"self",
".",
... | Appends a value to a list in the specified section of the document.
Args:
key (str): The key pointing to the value that should be stored/updated.
It supports MongoDB's dot notation for nested fields.
value: The value that should be appended to a list in the data store.
section (DataStoreDocumentSection): The section from which the data should
be retrieved.
Returns:
bool: ``True`` if the value could be appended, otherwise ``False``. | [
"Appends",
"a",
"value",
"to",
"a",
"list",
"in",
"the",
"specified",
"section",
"of",
"the",
"document",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/datastore.py#L308-L331 | train |
AustralianSynchrotron/lightflow | lightflow/models/datastore.py | DataStoreDocument.extend | def extend(self, key, values, *, section=DataStoreDocumentSection.Data):
""" Extends a list in the data store with the elements of values.
Args:
key (str): The key pointing to the value that should be stored/updated.
It supports MongoDB's dot notation for nested fields.
values (list): A list of the values that should be used to extend the list
in the document.
section (DataStoreDocumentSection): The section from which the data should
be retrieved.
Returns:
bool: ``True`` if the list in the database could be extended,
otherwise ``False``.
"""
key_notation = '.'.join([section, key])
if not isinstance(values, list):
return False
result = self._collection.update_one(
{"_id": ObjectId(self._workflow_id)},
{
"$push": {
key_notation: {"$each": self._encode_value(values)}
},
"$currentDate": {"lastModified": True}
}
)
return result.modified_count == 1 | python | def extend(self, key, values, *, section=DataStoreDocumentSection.Data):
""" Extends a list in the data store with the elements of values.
Args:
key (str): The key pointing to the value that should be stored/updated.
It supports MongoDB's dot notation for nested fields.
values (list): A list of the values that should be used to extend the list
in the document.
section (DataStoreDocumentSection): The section from which the data should
be retrieved.
Returns:
bool: ``True`` if the list in the database could be extended,
otherwise ``False``.
"""
key_notation = '.'.join([section, key])
if not isinstance(values, list):
return False
result = self._collection.update_one(
{"_id": ObjectId(self._workflow_id)},
{
"$push": {
key_notation: {"$each": self._encode_value(values)}
},
"$currentDate": {"lastModified": True}
}
)
return result.modified_count == 1 | [
"def",
"extend",
"(",
"self",
",",
"key",
",",
"values",
",",
"*",
",",
"section",
"=",
"DataStoreDocumentSection",
".",
"Data",
")",
":",
"key_notation",
"=",
"'.'",
".",
"join",
"(",
"[",
"section",
",",
"key",
"]",
")",
"if",
"not",
"isinstance",
... | Extends a list in the data store with the elements of values.
Args:
key (str): The key pointing to the value that should be stored/updated.
It supports MongoDB's dot notation for nested fields.
values (list): A list of the values that should be used to extend the list
in the document.
section (DataStoreDocumentSection): The section from which the data should
be retrieved.
Returns:
bool: ``True`` if the list in the database could be extended,
otherwise ``False``. | [
"Extends",
"a",
"list",
"in",
"the",
"data",
"store",
"with",
"the",
"elements",
"of",
"values",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/datastore.py#L333-L361 | train |
AustralianSynchrotron/lightflow | lightflow/models/datastore.py | DataStoreDocument._data_from_dotnotation | def _data_from_dotnotation(self, key, default=None):
""" Returns the MongoDB data from a key using dot notation.
Args:
key (str): The key to the field in the workflow document. Supports MongoDB's
dot notation for embedded fields.
default (object): The default value that is returned if the key
does not exist.
Returns:
object: The data for the specified key or the default value.
"""
if key is None:
raise KeyError('NoneType is not a valid key!')
doc = self._collection.find_one({"_id": ObjectId(self._workflow_id)})
if doc is None:
return default
for k in key.split('.'):
doc = doc[k]
return doc | python | def _data_from_dotnotation(self, key, default=None):
""" Returns the MongoDB data from a key using dot notation.
Args:
key (str): The key to the field in the workflow document. Supports MongoDB's
dot notation for embedded fields.
default (object): The default value that is returned if the key
does not exist.
Returns:
object: The data for the specified key or the default value.
"""
if key is None:
raise KeyError('NoneType is not a valid key!')
doc = self._collection.find_one({"_id": ObjectId(self._workflow_id)})
if doc is None:
return default
for k in key.split('.'):
doc = doc[k]
return doc | [
"def",
"_data_from_dotnotation",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"if",
"key",
"is",
"None",
":",
"raise",
"KeyError",
"(",
"'NoneType is not a valid key!'",
")",
"doc",
"=",
"self",
".",
"_collection",
".",
"find_one",
"(",
... | Returns the MongoDB data from a key using dot notation.
Args:
key (str): The key to the field in the workflow document. Supports MongoDB's
dot notation for embedded fields.
default (object): The default value that is returned if the key
does not exist.
Returns:
object: The data for the specified key or the default value. | [
"Returns",
"the",
"MongoDB",
"data",
"from",
"a",
"key",
"using",
"dot",
"notation",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/datastore.py#L363-L385 | train |
AustralianSynchrotron/lightflow | lightflow/models/datastore.py | DataStoreDocument._encode_value | def _encode_value(self, value):
""" Encodes the value such that it can be stored into MongoDB.
Any primitive types are stored directly into MongoDB, while non-primitive types
are pickled and stored as GridFS objects. The id pointing to a GridFS object
replaces the original value.
Args:
value (object): The object that should be encoded for storing in MongoDB.
Returns:
object: The encoded value ready to be stored in MongoDB.
"""
if isinstance(value, (int, float, str, bool, datetime)):
return value
elif isinstance(value, list):
return [self._encode_value(item) for item in value]
elif isinstance(value, dict):
result = {}
for key, item in value.items():
result[key] = self._encode_value(item)
return result
else:
return self._gridfs.put(Binary(pickle.dumps(value)),
workflow_id=self._workflow_id) | python | def _encode_value(self, value):
""" Encodes the value such that it can be stored into MongoDB.
Any primitive types are stored directly into MongoDB, while non-primitive types
are pickled and stored as GridFS objects. The id pointing to a GridFS object
replaces the original value.
Args:
value (object): The object that should be encoded for storing in MongoDB.
Returns:
object: The encoded value ready to be stored in MongoDB.
"""
if isinstance(value, (int, float, str, bool, datetime)):
return value
elif isinstance(value, list):
return [self._encode_value(item) for item in value]
elif isinstance(value, dict):
result = {}
for key, item in value.items():
result[key] = self._encode_value(item)
return result
else:
return self._gridfs.put(Binary(pickle.dumps(value)),
workflow_id=self._workflow_id) | [
"def",
"_encode_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"int",
",",
"float",
",",
"str",
",",
"bool",
",",
"datetime",
")",
")",
":",
"return",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"list",... | Encodes the value such that it can be stored into MongoDB.
Any primitive types are stored directly into MongoDB, while non-primitive types
are pickled and stored as GridFS objects. The id pointing to a GridFS object
replaces the original value.
Args:
value (object): The object that should be encoded for storing in MongoDB.
Returns:
object: The encoded value ready to be stored in MongoDB. | [
"Encodes",
"the",
"value",
"such",
"that",
"it",
"can",
"be",
"stored",
"into",
"MongoDB",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/datastore.py#L387-L411 | train |
AustralianSynchrotron/lightflow | lightflow/models/datastore.py | DataStoreDocument._decode_value | def _decode_value(self, value):
""" Decodes the value by turning any binary data back into Python objects.
The method searches for ObjectId values, loads the associated binary data from
GridFS and returns the decoded Python object.
Args:
value (object): The value that should be decoded.
Raises:
DataStoreDecodingError: An ObjectId was found but the id is not a valid
GridFS id.
DataStoreDecodeUnknownType: The type of the specified value is unknown.
Returns:
object: The decoded value as a valid Python object.
"""
if isinstance(value, (int, float, str, bool, datetime)):
return value
elif isinstance(value, list):
return [self._decode_value(item) for item in value]
elif isinstance(value, dict):
result = {}
for key, item in value.items():
result[key] = self._decode_value(item)
return result
elif isinstance(value, ObjectId):
if self._gridfs.exists({"_id": value}):
return pickle.loads(self._gridfs.get(value).read())
else:
raise DataStoreGridfsIdInvalid()
else:
raise DataStoreDecodeUnknownType() | python | def _decode_value(self, value):
""" Decodes the value by turning any binary data back into Python objects.
The method searches for ObjectId values, loads the associated binary data from
GridFS and returns the decoded Python object.
Args:
value (object): The value that should be decoded.
Raises:
DataStoreDecodingError: An ObjectId was found but the id is not a valid
GridFS id.
DataStoreDecodeUnknownType: The type of the specified value is unknown.
Returns:
object: The decoded value as a valid Python object.
"""
if isinstance(value, (int, float, str, bool, datetime)):
return value
elif isinstance(value, list):
return [self._decode_value(item) for item in value]
elif isinstance(value, dict):
result = {}
for key, item in value.items():
result[key] = self._decode_value(item)
return result
elif isinstance(value, ObjectId):
if self._gridfs.exists({"_id": value}):
return pickle.loads(self._gridfs.get(value).read())
else:
raise DataStoreGridfsIdInvalid()
else:
raise DataStoreDecodeUnknownType() | [
"def",
"_decode_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"int",
",",
"float",
",",
"str",
",",
"bool",
",",
"datetime",
")",
")",
":",
"return",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"list",... | Decodes the value by turning any binary data back into Python objects.
The method searches for ObjectId values, loads the associated binary data from
GridFS and returns the decoded Python object.
Args:
value (object): The value that should be decoded.
Raises:
DataStoreDecodingError: An ObjectId was found but the id is not a valid
GridFS id.
DataStoreDecodeUnknownType: The type of the specified value is unknown.
Returns:
object: The decoded value as a valid Python object. | [
"Decodes",
"the",
"value",
"by",
"turning",
"any",
"binary",
"data",
"back",
"into",
"Python",
"objects",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/datastore.py#L413-L445 | train |
AustralianSynchrotron/lightflow | lightflow/models/datastore.py | DataStoreDocument._delete_gridfs_data | def _delete_gridfs_data(self, data):
""" Delete all GridFS data that is linked by fields in the specified data.
Args:
data: The data that is parsed for MongoDB ObjectIDs. The linked GridFs object
for any ObjectID is deleted.
"""
if isinstance(data, ObjectId):
if self._gridfs.exists({"_id": data}):
self._gridfs.delete(data)
else:
raise DataStoreGridfsIdInvalid()
elif isinstance(data, list):
for item in data:
self._delete_gridfs_data(item)
elif isinstance(data, dict):
for key, item in data.items():
self._delete_gridfs_data(item) | python | def _delete_gridfs_data(self, data):
""" Delete all GridFS data that is linked by fields in the specified data.
Args:
data: The data that is parsed for MongoDB ObjectIDs. The linked GridFs object
for any ObjectID is deleted.
"""
if isinstance(data, ObjectId):
if self._gridfs.exists({"_id": data}):
self._gridfs.delete(data)
else:
raise DataStoreGridfsIdInvalid()
elif isinstance(data, list):
for item in data:
self._delete_gridfs_data(item)
elif isinstance(data, dict):
for key, item in data.items():
self._delete_gridfs_data(item) | [
"def",
"_delete_gridfs_data",
"(",
"self",
",",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"ObjectId",
")",
":",
"if",
"self",
".",
"_gridfs",
".",
"exists",
"(",
"{",
"\"_id\"",
":",
"data",
"}",
")",
":",
"self",
".",
"_gridfs",
".",
... | Delete all GridFS data that is linked by fields in the specified data.
Args:
data: The data that is parsed for MongoDB ObjectIDs. The linked GridFs object
for any ObjectID is deleted. | [
"Delete",
"all",
"GridFS",
"data",
"that",
"is",
"linked",
"by",
"fields",
"in",
"the",
"specified",
"data",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/datastore.py#L447-L464 | train |
dh1tw/pyhamtools | pyhamtools/callinfo.py | Callinfo.get_homecall | def get_homecall(callsign):
"""Strips off country prefixes (HC2/DH1TW) and activity suffixes (DH1TW/P).
Args:
callsign (str): Amateur Radio callsign
Returns:
str: callsign without country/activity pre/suffixes
Raises:
ValueError: No callsign found in string
Example:
The following code retrieves the home call for "HC2/DH1TW/P"
>>> from pyhamtools import LookupLib, Callinfo
>>> my_lookuplib = LookupLib(lookuptype="countryfile")
>>> cic = Callinfo(my_lookuplib)
>>> cic.get_homecall("HC2/DH1TW/P")
DH1TW
"""
callsign = callsign.upper()
homecall = re.search('[\d]{0,1}[A-Z]{1,2}\d([A-Z]{1,4}|\d{3,3}|\d{1,3}[A-Z])[A-Z]{0,5}', callsign)
if homecall:
homecall = homecall.group(0)
return homecall
else:
raise ValueError | python | def get_homecall(callsign):
"""Strips off country prefixes (HC2/DH1TW) and activity suffixes (DH1TW/P).
Args:
callsign (str): Amateur Radio callsign
Returns:
str: callsign without country/activity pre/suffixes
Raises:
ValueError: No callsign found in string
Example:
The following code retrieves the home call for "HC2/DH1TW/P"
>>> from pyhamtools import LookupLib, Callinfo
>>> my_lookuplib = LookupLib(lookuptype="countryfile")
>>> cic = Callinfo(my_lookuplib)
>>> cic.get_homecall("HC2/DH1TW/P")
DH1TW
"""
callsign = callsign.upper()
homecall = re.search('[\d]{0,1}[A-Z]{1,2}\d([A-Z]{1,4}|\d{3,3}|\d{1,3}[A-Z])[A-Z]{0,5}', callsign)
if homecall:
homecall = homecall.group(0)
return homecall
else:
raise ValueError | [
"def",
"get_homecall",
"(",
"callsign",
")",
":",
"callsign",
"=",
"callsign",
".",
"upper",
"(",
")",
"homecall",
"=",
"re",
".",
"search",
"(",
"'[\\d]{0,1}[A-Z]{1,2}\\d([A-Z]{1,4}|\\d{3,3}|\\d{1,3}[A-Z])[A-Z]{0,5}'",
",",
"callsign",
")",
"if",
"homecall",
":",
... | Strips off country prefixes (HC2/DH1TW) and activity suffixes (DH1TW/P).
Args:
callsign (str): Amateur Radio callsign
Returns:
str: callsign without country/activity pre/suffixes
Raises:
ValueError: No callsign found in string
Example:
The following code retrieves the home call for "HC2/DH1TW/P"
>>> from pyhamtools import LookupLib, Callinfo
>>> my_lookuplib = LookupLib(lookuptype="countryfile")
>>> cic = Callinfo(my_lookuplib)
>>> cic.get_homecall("HC2/DH1TW/P")
DH1TW | [
"Strips",
"off",
"country",
"prefixes",
"(",
"HC2",
"/",
"DH1TW",
")",
"and",
"activity",
"suffixes",
"(",
"DH1TW",
"/",
"P",
")",
"."
] | ee7e4b8732e23c298da10e07163748156c16d0fa | https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/callinfo.py#L50-L79 | train |
dh1tw/pyhamtools | pyhamtools/callinfo.py | Callinfo._iterate_prefix | def _iterate_prefix(self, callsign, timestamp=timestamp_now):
"""truncate call until it corresponds to a Prefix in the database"""
prefix = callsign
if re.search('(VK|AX|VI)9[A-Z]{3}', callsign): #special rule for VK9 calls
if timestamp > datetime(2006,1,1, tzinfo=UTC):
prefix = callsign[0:3]+callsign[4:5]
while len(prefix) > 0:
try:
return self._lookuplib.lookup_prefix(prefix, timestamp)
except KeyError:
prefix = prefix.replace(' ', '')[:-1]
continue
raise KeyError | python | def _iterate_prefix(self, callsign, timestamp=timestamp_now):
"""truncate call until it corresponds to a Prefix in the database"""
prefix = callsign
if re.search('(VK|AX|VI)9[A-Z]{3}', callsign): #special rule for VK9 calls
if timestamp > datetime(2006,1,1, tzinfo=UTC):
prefix = callsign[0:3]+callsign[4:5]
while len(prefix) > 0:
try:
return self._lookuplib.lookup_prefix(prefix, timestamp)
except KeyError:
prefix = prefix.replace(' ', '')[:-1]
continue
raise KeyError | [
"def",
"_iterate_prefix",
"(",
"self",
",",
"callsign",
",",
"timestamp",
"=",
"timestamp_now",
")",
":",
"prefix",
"=",
"callsign",
"if",
"re",
".",
"search",
"(",
"'(VK|AX|VI)9[A-Z]{3}'",
",",
"callsign",
")",
":",
"#special rule for VK9 calls",
"if",
"timesta... | truncate call until it corresponds to a Prefix in the database | [
"truncate",
"call",
"until",
"it",
"corresponds",
"to",
"a",
"Prefix",
"in",
"the",
"database"
] | ee7e4b8732e23c298da10e07163748156c16d0fa | https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/callinfo.py#L81-L95 | train |
dh1tw/pyhamtools | pyhamtools/callinfo.py | Callinfo._dismantle_callsign | def _dismantle_callsign(self, callsign, timestamp=timestamp_now):
""" try to identify the callsign's identity by analyzing it in the following order:
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Raises:
KeyError: Callsign could not be identified
"""
entire_callsign = callsign.upper()
if re.search('[/A-Z0-9\-]{3,15}', entire_callsign): # make sure the call has at least 3 characters
if re.search('\-\d{1,3}$', entire_callsign): # cut off any -10 / -02 appendixes
callsign = re.sub('\-\d{1,3}$', '', entire_callsign)
if re.search('/[A-Z0-9]{1,4}/[A-Z0-9]{1,4}$', callsign):
callsign = re.sub('/[A-Z0-9]{1,4}$', '', callsign) # cut off 2. appendix DH1TW/HC2/P -> DH1TW/HC2
# multiple character appendix (callsign/xxx)
if re.search('[A-Z0-9]{4,10}/[A-Z0-9]{2,4}$', callsign): # case call/xxx, but ignoring /p and /m or /5
appendix = re.search('/[A-Z0-9]{2,4}$', callsign)
appendix = re.sub('/', '', appendix.group(0))
self._logger.debug("appendix: " + appendix)
if appendix == 'MM': # special case Martime Mobile
#self._mm = True
return {
'adif': 999,
'continent': '',
'country': 'MARITIME MOBILE',
'cqz': 0,
'latitude': 0.0,
'longitude': 0.0
}
elif appendix == 'AM': # special case Aeronautic Mobile
return {
'adif': 998,
'continent': '',
'country': 'AIRCAFT MOBILE',
'cqz': 0,
'latitude': 0.0,
'longitude': 0.0
}
elif appendix == 'QRP': # special case QRP
callsign = re.sub('/QRP', '', callsign)
return self._iterate_prefix(callsign, timestamp)
elif appendix == 'QRPP': # special case QRPP
callsign = re.sub('/QRPP', '', callsign)
return self._iterate_prefix(callsign, timestamp)
elif appendix == 'BCN': # filter all beacons
callsign = re.sub('/BCN', '', callsign)
data = self._iterate_prefix(callsign, timestamp).copy()
data[const.BEACON] = True
return data
elif appendix == "LH": # Filter all Lighthouses
callsign = re.sub('/LH', '', callsign)
return self._iterate_prefix(callsign, timestamp)
elif re.search('[A-Z]{3}', appendix): #case of US county(?) contest N3HBX/UAL
callsign = re.sub('/[A-Z]{3}$', '', callsign)
return self._iterate_prefix(callsign, timestamp)
else:
# check if the appendix is a valid country prefix
return self._iterate_prefix(re.sub('/', '', appendix), timestamp)
# Single character appendix (callsign/x)
elif re.search('/[A-Z0-9]$', callsign): # case call/p or /b /m or /5 etc.
appendix = re.search('/[A-Z0-9]$', callsign)
appendix = re.sub('/', '', appendix.group(0))
if appendix == 'B': # special case Beacon
callsign = re.sub('/B', '', callsign)
data = self._iterate_prefix(callsign, timestamp).copy()
data[const.BEACON] = True
return data
elif re.search('\d$', appendix):
area_nr = re.search('\d$', appendix).group(0)
callsign = re.sub('/\d$', '', callsign) #remove /number
if len(re.findall(r'\d+', callsign)) == 1: #call has just on digit e.g. DH1TW
callsign = re.sub('[\d]+', area_nr, callsign)
else: # call has several digits e.g. 7N4AAL
pass # no (two) digit prefix contries known where appendix would change entitiy
return self._iterate_prefix(callsign, timestamp)
else:
return self._iterate_prefix(callsign, timestamp)
# regular callsigns, without prefix or appendix
elif re.match('^[\d]{0,1}[A-Z]{1,2}\d([A-Z]{1,4}|\d{3,3}|\d{1,3}[A-Z])[A-Z]{0,5}$', callsign):
return self._iterate_prefix(callsign, timestamp)
# callsigns with prefixes (xxx/callsign)
elif re.search('^[A-Z0-9]{1,4}/', entire_callsign):
pfx = re.search('^[A-Z0-9]{1,4}/', entire_callsign)
pfx = re.sub('/', '', pfx.group(0))
#make sure that the remaining part is actually a callsign (avoid: OZ/JO81)
rest = re.search('/[A-Z0-9]+', entire_callsign)
rest = re.sub('/', '', rest.group(0))
if re.match('^[\d]{0,1}[A-Z]{1,2}\d([A-Z]{1,4}|\d{3,3}|\d{1,3}[A-Z])[A-Z]{0,5}$', rest):
return self._iterate_prefix(pfx)
if entire_callsign in callsign_exceptions:
return self._iterate_prefix(callsign_exceptions[entire_callsign])
self._logger.debug("Could not decode " + callsign)
raise KeyError("Callsign could not be decoded") | python | def _dismantle_callsign(self, callsign, timestamp=timestamp_now):
""" try to identify the callsign's identity by analyzing it in the following order:
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Raises:
KeyError: Callsign could not be identified
"""
entire_callsign = callsign.upper()
if re.search('[/A-Z0-9\-]{3,15}', entire_callsign): # make sure the call has at least 3 characters
if re.search('\-\d{1,3}$', entire_callsign): # cut off any -10 / -02 appendixes
callsign = re.sub('\-\d{1,3}$', '', entire_callsign)
if re.search('/[A-Z0-9]{1,4}/[A-Z0-9]{1,4}$', callsign):
callsign = re.sub('/[A-Z0-9]{1,4}$', '', callsign) # cut off 2. appendix DH1TW/HC2/P -> DH1TW/HC2
# multiple character appendix (callsign/xxx)
if re.search('[A-Z0-9]{4,10}/[A-Z0-9]{2,4}$', callsign): # case call/xxx, but ignoring /p and /m or /5
appendix = re.search('/[A-Z0-9]{2,4}$', callsign)
appendix = re.sub('/', '', appendix.group(0))
self._logger.debug("appendix: " + appendix)
if appendix == 'MM': # special case Martime Mobile
#self._mm = True
return {
'adif': 999,
'continent': '',
'country': 'MARITIME MOBILE',
'cqz': 0,
'latitude': 0.0,
'longitude': 0.0
}
elif appendix == 'AM': # special case Aeronautic Mobile
return {
'adif': 998,
'continent': '',
'country': 'AIRCAFT MOBILE',
'cqz': 0,
'latitude': 0.0,
'longitude': 0.0
}
elif appendix == 'QRP': # special case QRP
callsign = re.sub('/QRP', '', callsign)
return self._iterate_prefix(callsign, timestamp)
elif appendix == 'QRPP': # special case QRPP
callsign = re.sub('/QRPP', '', callsign)
return self._iterate_prefix(callsign, timestamp)
elif appendix == 'BCN': # filter all beacons
callsign = re.sub('/BCN', '', callsign)
data = self._iterate_prefix(callsign, timestamp).copy()
data[const.BEACON] = True
return data
elif appendix == "LH": # Filter all Lighthouses
callsign = re.sub('/LH', '', callsign)
return self._iterate_prefix(callsign, timestamp)
elif re.search('[A-Z]{3}', appendix): #case of US county(?) contest N3HBX/UAL
callsign = re.sub('/[A-Z]{3}$', '', callsign)
return self._iterate_prefix(callsign, timestamp)
else:
# check if the appendix is a valid country prefix
return self._iterate_prefix(re.sub('/', '', appendix), timestamp)
# Single character appendix (callsign/x)
elif re.search('/[A-Z0-9]$', callsign): # case call/p or /b /m or /5 etc.
appendix = re.search('/[A-Z0-9]$', callsign)
appendix = re.sub('/', '', appendix.group(0))
if appendix == 'B': # special case Beacon
callsign = re.sub('/B', '', callsign)
data = self._iterate_prefix(callsign, timestamp).copy()
data[const.BEACON] = True
return data
elif re.search('\d$', appendix):
area_nr = re.search('\d$', appendix).group(0)
callsign = re.sub('/\d$', '', callsign) #remove /number
if len(re.findall(r'\d+', callsign)) == 1: #call has just on digit e.g. DH1TW
callsign = re.sub('[\d]+', area_nr, callsign)
else: # call has several digits e.g. 7N4AAL
pass # no (two) digit prefix contries known where appendix would change entitiy
return self._iterate_prefix(callsign, timestamp)
else:
return self._iterate_prefix(callsign, timestamp)
# regular callsigns, without prefix or appendix
elif re.match('^[\d]{0,1}[A-Z]{1,2}\d([A-Z]{1,4}|\d{3,3}|\d{1,3}[A-Z])[A-Z]{0,5}$', callsign):
return self._iterate_prefix(callsign, timestamp)
# callsigns with prefixes (xxx/callsign)
elif re.search('^[A-Z0-9]{1,4}/', entire_callsign):
pfx = re.search('^[A-Z0-9]{1,4}/', entire_callsign)
pfx = re.sub('/', '', pfx.group(0))
#make sure that the remaining part is actually a callsign (avoid: OZ/JO81)
rest = re.search('/[A-Z0-9]+', entire_callsign)
rest = re.sub('/', '', rest.group(0))
if re.match('^[\d]{0,1}[A-Z]{1,2}\d([A-Z]{1,4}|\d{3,3}|\d{1,3}[A-Z])[A-Z]{0,5}$', rest):
return self._iterate_prefix(pfx)
if entire_callsign in callsign_exceptions:
return self._iterate_prefix(callsign_exceptions[entire_callsign])
self._logger.debug("Could not decode " + callsign)
raise KeyError("Callsign could not be decoded") | [
"def",
"_dismantle_callsign",
"(",
"self",
",",
"callsign",
",",
"timestamp",
"=",
"timestamp_now",
")",
":",
"entire_callsign",
"=",
"callsign",
".",
"upper",
"(",
")",
"if",
"re",
".",
"search",
"(",
"'[/A-Z0-9\\-]{3,15}'",
",",
"entire_callsign",
")",
":",
... | try to identify the callsign's identity by analyzing it in the following order:
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Raises:
KeyError: Callsign could not be identified | [
"try",
"to",
"identify",
"the",
"callsign",
"s",
"identity",
"by",
"analyzing",
"it",
"in",
"the",
"following",
"order",
":"
] | ee7e4b8732e23c298da10e07163748156c16d0fa | https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/callinfo.py#L112-L222 | train |
dh1tw/pyhamtools | pyhamtools/callinfo.py | Callinfo.get_all | def get_all(self, callsign, timestamp=timestamp_now):
""" Lookup a callsign and return all data available from the underlying database
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
dict: Dictionary containing the callsign specific data
Raises:
KeyError: Callsign could not be identified
Example:
The following code returns all available information from the country-files.com database for the
callsign "DH1TW"
>>> from pyhamtools import LookupLib, Callinfo
>>> my_lookuplib = LookupLib(lookuptype="countryfile")
>>> cic = Callinfo(my_lookuplib)
>>> cic.get_all("DH1TW")
{
'country': 'Fed. Rep. of Germany',
'adif': 230,
'continent': 'EU',
'latitude': 51.0,
'longitude': -10.0,
'cqz': 14,
'ituz': 28
}
Note:
The content of the returned data depends entirely on the injected
:py:class:`LookupLib` (and the used database). While the country-files.com provides
for example the ITU Zone, Clublog doesn't. Consequently, the item "ituz"
would be missing with Clublog (API or XML) :py:class:`LookupLib`.
"""
callsign_data = self._lookup_callsign(callsign, timestamp)
try:
cqz = self._lookuplib.lookup_zone_exception(callsign, timestamp)
callsign_data[const.CQZ] = cqz
except KeyError:
pass
return callsign_data | python | def get_all(self, callsign, timestamp=timestamp_now):
""" Lookup a callsign and return all data available from the underlying database
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
dict: Dictionary containing the callsign specific data
Raises:
KeyError: Callsign could not be identified
Example:
The following code returns all available information from the country-files.com database for the
callsign "DH1TW"
>>> from pyhamtools import LookupLib, Callinfo
>>> my_lookuplib = LookupLib(lookuptype="countryfile")
>>> cic = Callinfo(my_lookuplib)
>>> cic.get_all("DH1TW")
{
'country': 'Fed. Rep. of Germany',
'adif': 230,
'continent': 'EU',
'latitude': 51.0,
'longitude': -10.0,
'cqz': 14,
'ituz': 28
}
Note:
The content of the returned data depends entirely on the injected
:py:class:`LookupLib` (and the used database). While the country-files.com provides
for example the ITU Zone, Clublog doesn't. Consequently, the item "ituz"
would be missing with Clublog (API or XML) :py:class:`LookupLib`.
"""
callsign_data = self._lookup_callsign(callsign, timestamp)
try:
cqz = self._lookuplib.lookup_zone_exception(callsign, timestamp)
callsign_data[const.CQZ] = cqz
except KeyError:
pass
return callsign_data | [
"def",
"get_all",
"(",
"self",
",",
"callsign",
",",
"timestamp",
"=",
"timestamp_now",
")",
":",
"callsign_data",
"=",
"self",
".",
"_lookup_callsign",
"(",
"callsign",
",",
"timestamp",
")",
"try",
":",
"cqz",
"=",
"self",
".",
"_lookuplib",
".",
"lookup... | Lookup a callsign and return all data available from the underlying database
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
dict: Dictionary containing the callsign specific data
Raises:
KeyError: Callsign could not be identified
Example:
The following code returns all available information from the country-files.com database for the
callsign "DH1TW"
>>> from pyhamtools import LookupLib, Callinfo
>>> my_lookuplib = LookupLib(lookuptype="countryfile")
>>> cic = Callinfo(my_lookuplib)
>>> cic.get_all("DH1TW")
{
'country': 'Fed. Rep. of Germany',
'adif': 230,
'continent': 'EU',
'latitude': 51.0,
'longitude': -10.0,
'cqz': 14,
'ituz': 28
}
Note:
The content of the returned data depends entirely on the injected
:py:class:`LookupLib` (and the used database). While the country-files.com provides
for example the ITU Zone, Clublog doesn't. Consequently, the item "ituz"
would be missing with Clublog (API or XML) :py:class:`LookupLib`. | [
"Lookup",
"a",
"callsign",
"and",
"return",
"all",
"data",
"available",
"from",
"the",
"underlying",
"database"
] | ee7e4b8732e23c298da10e07163748156c16d0fa | https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/callinfo.py#L267-L313 | train |
dh1tw/pyhamtools | pyhamtools/callinfo.py | Callinfo.is_valid_callsign | def is_valid_callsign(self, callsign, timestamp=timestamp_now):
""" Checks if a callsign is valid
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
bool: True / False
Example:
The following checks if "DH1TW" is a valid callsign
>>> from pyhamtools import LookupLib, Callinfo
>>> my_lookuplib = LookupLib(lookuptype="countryfile")
>>> cic = Callinfo(my_lookuplib)
>>> cic.is_valid_callsign("DH1TW")
True
"""
try:
if self.get_all(callsign, timestamp):
return True
except KeyError:
return False | python | def is_valid_callsign(self, callsign, timestamp=timestamp_now):
""" Checks if a callsign is valid
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
bool: True / False
Example:
The following checks if "DH1TW" is a valid callsign
>>> from pyhamtools import LookupLib, Callinfo
>>> my_lookuplib = LookupLib(lookuptype="countryfile")
>>> cic = Callinfo(my_lookuplib)
>>> cic.is_valid_callsign("DH1TW")
True
"""
try:
if self.get_all(callsign, timestamp):
return True
except KeyError:
return False | [
"def",
"is_valid_callsign",
"(",
"self",
",",
"callsign",
",",
"timestamp",
"=",
"timestamp_now",
")",
":",
"try",
":",
"if",
"self",
".",
"get_all",
"(",
"callsign",
",",
"timestamp",
")",
":",
"return",
"True",
"except",
"KeyError",
":",
"return",
"False... | Checks if a callsign is valid
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
bool: True / False
Example:
The following checks if "DH1TW" is a valid callsign
>>> from pyhamtools import LookupLib, Callinfo
>>> my_lookuplib = LookupLib(lookuptype="countryfile")
>>> cic = Callinfo(my_lookuplib)
>>> cic.is_valid_callsign("DH1TW")
True | [
"Checks",
"if",
"a",
"callsign",
"is",
"valid"
] | ee7e4b8732e23c298da10e07163748156c16d0fa | https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/callinfo.py#L315-L339 | train |
dh1tw/pyhamtools | pyhamtools/callinfo.py | Callinfo.get_lat_long | def get_lat_long(self, callsign, timestamp=timestamp_now):
""" Returns Latitude and Longitude for a callsign
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
dict: Containing Latitude and Longitude
Raises:
KeyError: No data found for callsign
Example:
The following code returns Latitude & Longitude for "DH1TW"
>>> from pyhamtools import LookupLib, Callinfo
>>> my_lookuplib = LookupLib(lookuptype="countryfile")
>>> cic = Callinfo(my_lookuplib)
>>> cic.get_lat_long("DH1TW")
{
'latitude': 51.0,
'longitude': -10.0
}
Note:
Unfortunately, in most cases the returned Latitude and Longitude are not very precise.
Clublog and Country-files.com use the country's capital coordinates in most cases, if no
dedicated entry in the database exists. Best results will be retrieved with QRZ.com Lookup.
"""
callsign_data = self.get_all(callsign, timestamp=timestamp)
return {
const.LATITUDE: callsign_data[const.LATITUDE],
const.LONGITUDE: callsign_data[const.LONGITUDE]
} | python | def get_lat_long(self, callsign, timestamp=timestamp_now):
""" Returns Latitude and Longitude for a callsign
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
dict: Containing Latitude and Longitude
Raises:
KeyError: No data found for callsign
Example:
The following code returns Latitude & Longitude for "DH1TW"
>>> from pyhamtools import LookupLib, Callinfo
>>> my_lookuplib = LookupLib(lookuptype="countryfile")
>>> cic = Callinfo(my_lookuplib)
>>> cic.get_lat_long("DH1TW")
{
'latitude': 51.0,
'longitude': -10.0
}
Note:
Unfortunately, in most cases the returned Latitude and Longitude are not very precise.
Clublog and Country-files.com use the country's capital coordinates in most cases, if no
dedicated entry in the database exists. Best results will be retrieved with QRZ.com Lookup.
"""
callsign_data = self.get_all(callsign, timestamp=timestamp)
return {
const.LATITUDE: callsign_data[const.LATITUDE],
const.LONGITUDE: callsign_data[const.LONGITUDE]
} | [
"def",
"get_lat_long",
"(",
"self",
",",
"callsign",
",",
"timestamp",
"=",
"timestamp_now",
")",
":",
"callsign_data",
"=",
"self",
".",
"get_all",
"(",
"callsign",
",",
"timestamp",
"=",
"timestamp",
")",
"return",
"{",
"const",
".",
"LATITUDE",
":",
"ca... | Returns Latitude and Longitude for a callsign
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
dict: Containing Latitude and Longitude
Raises:
KeyError: No data found for callsign
Example:
The following code returns Latitude & Longitude for "DH1TW"
>>> from pyhamtools import LookupLib, Callinfo
>>> my_lookuplib = LookupLib(lookuptype="countryfile")
>>> cic = Callinfo(my_lookuplib)
>>> cic.get_lat_long("DH1TW")
{
'latitude': 51.0,
'longitude': -10.0
}
Note:
Unfortunately, in most cases the returned Latitude and Longitude are not very precise.
Clublog and Country-files.com use the country's capital coordinates in most cases, if no
dedicated entry in the database exists. Best results will be retrieved with QRZ.com Lookup. | [
"Returns",
"Latitude",
"and",
"Longitude",
"for",
"a",
"callsign"
] | ee7e4b8732e23c298da10e07163748156c16d0fa | https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/callinfo.py#L341-L376 | train |
dh1tw/pyhamtools | pyhamtools/callinfo.py | Callinfo.get_cqz | def get_cqz(self, callsign, timestamp=timestamp_now):
""" Returns CQ Zone of a callsign
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
int: containing the callsign's CQ Zone
Raises:
KeyError: no CQ Zone found for callsign
"""
return self.get_all(callsign, timestamp)[const.CQZ] | python | def get_cqz(self, callsign, timestamp=timestamp_now):
""" Returns CQ Zone of a callsign
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
int: containing the callsign's CQ Zone
Raises:
KeyError: no CQ Zone found for callsign
"""
return self.get_all(callsign, timestamp)[const.CQZ] | [
"def",
"get_cqz",
"(",
"self",
",",
"callsign",
",",
"timestamp",
"=",
"timestamp_now",
")",
":",
"return",
"self",
".",
"get_all",
"(",
"callsign",
",",
"timestamp",
")",
"[",
"const",
".",
"CQZ",
"]"
] | Returns CQ Zone of a callsign
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
int: containing the callsign's CQ Zone
Raises:
KeyError: no CQ Zone found for callsign | [
"Returns",
"CQ",
"Zone",
"of",
"a",
"callsign"
] | ee7e4b8732e23c298da10e07163748156c16d0fa | https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/callinfo.py#L378-L392 | train |
dh1tw/pyhamtools | pyhamtools/callinfo.py | Callinfo.get_ituz | def get_ituz(self, callsign, timestamp=timestamp_now):
""" Returns ITU Zone of a callsign
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
int: containing the callsign's CQ Zone
Raises:
KeyError: No ITU Zone found for callsign
Note:
Currently, only Country-files.com lookup database contains ITU Zones
"""
return self.get_all(callsign, timestamp)[const.ITUZ] | python | def get_ituz(self, callsign, timestamp=timestamp_now):
""" Returns ITU Zone of a callsign
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
int: containing the callsign's CQ Zone
Raises:
KeyError: No ITU Zone found for callsign
Note:
Currently, only Country-files.com lookup database contains ITU Zones
"""
return self.get_all(callsign, timestamp)[const.ITUZ] | [
"def",
"get_ituz",
"(",
"self",
",",
"callsign",
",",
"timestamp",
"=",
"timestamp_now",
")",
":",
"return",
"self",
".",
"get_all",
"(",
"callsign",
",",
"timestamp",
")",
"[",
"const",
".",
"ITUZ",
"]"
] | Returns ITU Zone of a callsign
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
int: containing the callsign's CQ Zone
Raises:
KeyError: No ITU Zone found for callsign
Note:
Currently, only Country-files.com lookup database contains ITU Zones | [
"Returns",
"ITU",
"Zone",
"of",
"a",
"callsign"
] | ee7e4b8732e23c298da10e07163748156c16d0fa | https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/callinfo.py#L394-L411 | train |
dh1tw/pyhamtools | pyhamtools/callinfo.py | Callinfo.get_country_name | def get_country_name(self, callsign, timestamp=timestamp_now):
""" Returns the country name where the callsign is located
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
str: name of the Country
Raises:
KeyError: No Country found for callsign
Note:
Don't rely on the country name when working with several instances of
py:class:`Callinfo`. Clublog and Country-files.org use slightly different names
for countries. Example:
- Country-files.com: "Fed. Rep. of Germany"
- Clublog: "FEDERAL REPUBLIC OF GERMANY"
"""
return self.get_all(callsign, timestamp)[const.COUNTRY] | python | def get_country_name(self, callsign, timestamp=timestamp_now):
""" Returns the country name where the callsign is located
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
str: name of the Country
Raises:
KeyError: No Country found for callsign
Note:
Don't rely on the country name when working with several instances of
py:class:`Callinfo`. Clublog and Country-files.org use slightly different names
for countries. Example:
- Country-files.com: "Fed. Rep. of Germany"
- Clublog: "FEDERAL REPUBLIC OF GERMANY"
"""
return self.get_all(callsign, timestamp)[const.COUNTRY] | [
"def",
"get_country_name",
"(",
"self",
",",
"callsign",
",",
"timestamp",
"=",
"timestamp_now",
")",
":",
"return",
"self",
".",
"get_all",
"(",
"callsign",
",",
"timestamp",
")",
"[",
"const",
".",
"COUNTRY",
"]"
] | Returns the country name where the callsign is located
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
str: name of the Country
Raises:
KeyError: No Country found for callsign
Note:
Don't rely on the country name when working with several instances of
py:class:`Callinfo`. Clublog and Country-files.org use slightly different names
for countries. Example:
- Country-files.com: "Fed. Rep. of Germany"
- Clublog: "FEDERAL REPUBLIC OF GERMANY" | [
"Returns",
"the",
"country",
"name",
"where",
"the",
"callsign",
"is",
"located"
] | ee7e4b8732e23c298da10e07163748156c16d0fa | https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/callinfo.py#L413-L435 | train |
dh1tw/pyhamtools | pyhamtools/callinfo.py | Callinfo.get_adif_id | def get_adif_id(self, callsign, timestamp=timestamp_now):
""" Returns ADIF id of a callsign's country
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
int: containing the country ADIF id
Raises:
KeyError: No Country found for callsign
"""
return self.get_all(callsign, timestamp)[const.ADIF] | python | def get_adif_id(self, callsign, timestamp=timestamp_now):
""" Returns ADIF id of a callsign's country
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
int: containing the country ADIF id
Raises:
KeyError: No Country found for callsign
"""
return self.get_all(callsign, timestamp)[const.ADIF] | [
"def",
"get_adif_id",
"(",
"self",
",",
"callsign",
",",
"timestamp",
"=",
"timestamp_now",
")",
":",
"return",
"self",
".",
"get_all",
"(",
"callsign",
",",
"timestamp",
")",
"[",
"const",
".",
"ADIF",
"]"
] | Returns ADIF id of a callsign's country
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
int: containing the country ADIF id
Raises:
KeyError: No Country found for callsign | [
"Returns",
"ADIF",
"id",
"of",
"a",
"callsign",
"s",
"country"
] | ee7e4b8732e23c298da10e07163748156c16d0fa | https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/callinfo.py#L437-L451 | train |
dh1tw/pyhamtools | pyhamtools/callinfo.py | Callinfo.get_continent | def get_continent(self, callsign, timestamp=timestamp_now):
""" Returns the continent Identifier of a callsign
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
str: continent identified
Raises:
KeyError: No Continent found for callsign
Note:
The following continent identifiers are used:
- EU: Europe
- NA: North America
- SA: South America
- AS: Asia
- AF: Africa
- OC: Oceania
- AN: Antarctica
"""
return self.get_all(callsign, timestamp)[const.CONTINENT] | python | def get_continent(self, callsign, timestamp=timestamp_now):
""" Returns the continent Identifier of a callsign
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
str: continent identified
Raises:
KeyError: No Continent found for callsign
Note:
The following continent identifiers are used:
- EU: Europe
- NA: North America
- SA: South America
- AS: Asia
- AF: Africa
- OC: Oceania
- AN: Antarctica
"""
return self.get_all(callsign, timestamp)[const.CONTINENT] | [
"def",
"get_continent",
"(",
"self",
",",
"callsign",
",",
"timestamp",
"=",
"timestamp_now",
")",
":",
"return",
"self",
".",
"get_all",
"(",
"callsign",
",",
"timestamp",
")",
"[",
"const",
".",
"CONTINENT",
"]"
] | Returns the continent Identifier of a callsign
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
str: continent identified
Raises:
KeyError: No Continent found for callsign
Note:
The following continent identifiers are used:
- EU: Europe
- NA: North America
- SA: South America
- AS: Asia
- AF: Africa
- OC: Oceania
- AN: Antarctica | [
"Returns",
"the",
"continent",
"Identifier",
"of",
"a",
"callsign"
] | ee7e4b8732e23c298da10e07163748156c16d0fa | https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/callinfo.py#L453-L477 | train |
AustralianSynchrotron/lightflow | lightflow/models/utils.py | find_indices | def find_indices(lst, element):
""" Returns the indices for all occurrences of 'element' in 'lst'.
Args:
lst (list): List to search.
element: Element to find.
Returns:
list: List of indices or values
"""
result = []
offset = -1
while True:
try:
offset = lst.index(element, offset+1)
except ValueError:
return result
result.append(offset) | python | def find_indices(lst, element):
""" Returns the indices for all occurrences of 'element' in 'lst'.
Args:
lst (list): List to search.
element: Element to find.
Returns:
list: List of indices or values
"""
result = []
offset = -1
while True:
try:
offset = lst.index(element, offset+1)
except ValueError:
return result
result.append(offset) | [
"def",
"find_indices",
"(",
"lst",
",",
"element",
")",
":",
"result",
"=",
"[",
"]",
"offset",
"=",
"-",
"1",
"while",
"True",
":",
"try",
":",
"offset",
"=",
"lst",
".",
"index",
"(",
"element",
",",
"offset",
"+",
"1",
")",
"except",
"ValueError... | Returns the indices for all occurrences of 'element' in 'lst'.
Args:
lst (list): List to search.
element: Element to find.
Returns:
list: List of indices or values | [
"Returns",
"the",
"indices",
"for",
"all",
"occurrences",
"of",
"element",
"in",
"lst",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/utils.py#L2-L19 | train |
AustralianSynchrotron/lightflow | lightflow/models/workflow.py | Workflow.from_name | def from_name(cls, name, *, queue=DefaultJobQueueName.Workflow,
clear_data_store=True, arguments=None):
""" Create a workflow object from a workflow script.
Args:
name (str): The name of the workflow script.
queue (str): Name of the queue the workflow should be scheduled to.
clear_data_store (bool): Remove any documents created during the workflow
run in the data store after the run.
arguments (dict): Dictionary of additional arguments that are ingested
into the data store prior to the execution of the workflow.
Returns:
Workflow: A fully initialised workflow object
"""
new_workflow = cls(queue=queue, clear_data_store=clear_data_store)
new_workflow.load(name, arguments=arguments)
return new_workflow | python | def from_name(cls, name, *, queue=DefaultJobQueueName.Workflow,
clear_data_store=True, arguments=None):
""" Create a workflow object from a workflow script.
Args:
name (str): The name of the workflow script.
queue (str): Name of the queue the workflow should be scheduled to.
clear_data_store (bool): Remove any documents created during the workflow
run in the data store after the run.
arguments (dict): Dictionary of additional arguments that are ingested
into the data store prior to the execution of the workflow.
Returns:
Workflow: A fully initialised workflow object
"""
new_workflow = cls(queue=queue, clear_data_store=clear_data_store)
new_workflow.load(name, arguments=arguments)
return new_workflow | [
"def",
"from_name",
"(",
"cls",
",",
"name",
",",
"*",
",",
"queue",
"=",
"DefaultJobQueueName",
".",
"Workflow",
",",
"clear_data_store",
"=",
"True",
",",
"arguments",
"=",
"None",
")",
":",
"new_workflow",
"=",
"cls",
"(",
"queue",
"=",
"queue",
",",
... | Create a workflow object from a workflow script.
Args:
name (str): The name of the workflow script.
queue (str): Name of the queue the workflow should be scheduled to.
clear_data_store (bool): Remove any documents created during the workflow
run in the data store after the run.
arguments (dict): Dictionary of additional arguments that are ingested
into the data store prior to the execution of the workflow.
Returns:
Workflow: A fully initialised workflow object | [
"Create",
"a",
"workflow",
"object",
"from",
"a",
"workflow",
"script",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/workflow.py#L59-L76 | train |
AustralianSynchrotron/lightflow | lightflow/models/workflow.py | Workflow.load | def load(self, name, *, arguments=None, validate_arguments=True, strict_dag=False):
""" Import the workflow script and load all known objects.
The workflow script is treated like a module and imported
into the Python namespace. After the import, the method looks
for instances of known classes and stores a reference for further
use in the workflow object.
Args:
name (str): The name of the workflow script.
arguments (dict): Dictionary of additional arguments that are ingested
into the data store prior to the execution of the workflow.
validate_arguments (bool): Whether to check that all required arguments have
been supplied.
strict_dag (bool): If true then the loaded workflow module must contain an
instance of Dag.
Raises:
WorkflowArgumentError: If the workflow requires arguments to be set that
were not supplied to the workflow.
WorkflowImportError: If the import of the workflow fails.
"""
arguments = {} if arguments is None else arguments
try:
workflow_module = importlib.import_module(name)
dag_present = False
# extract objects of specific types from the workflow module
for key, obj in workflow_module.__dict__.items():
if isinstance(obj, Dag):
self._dags_blueprint[obj.name] = obj
dag_present = True
elif isinstance(obj, Parameters):
self._parameters.extend(obj)
self._name = name
self._docstring = inspect.getdoc(workflow_module)
del sys.modules[name]
if strict_dag and not dag_present:
raise WorkflowImportError(
'Workflow does not include a dag {}'.format(name))
if validate_arguments:
missing_parameters = self._parameters.check_missing(arguments)
if len(missing_parameters) > 0:
raise WorkflowArgumentError(
'The following parameters are required ' +
'by the workflow, but are missing: {}'.format(
', '.join(missing_parameters)))
self._provided_arguments = arguments
except (TypeError, ImportError):
logger.error('Cannot import workflow {}'.format(name))
raise WorkflowImportError('Cannot import workflow {}'.format(name)) | python | def load(self, name, *, arguments=None, validate_arguments=True, strict_dag=False):
""" Import the workflow script and load all known objects.
The workflow script is treated like a module and imported
into the Python namespace. After the import, the method looks
for instances of known classes and stores a reference for further
use in the workflow object.
Args:
name (str): The name of the workflow script.
arguments (dict): Dictionary of additional arguments that are ingested
into the data store prior to the execution of the workflow.
validate_arguments (bool): Whether to check that all required arguments have
been supplied.
strict_dag (bool): If true then the loaded workflow module must contain an
instance of Dag.
Raises:
WorkflowArgumentError: If the workflow requires arguments to be set that
were not supplied to the workflow.
WorkflowImportError: If the import of the workflow fails.
"""
arguments = {} if arguments is None else arguments
try:
workflow_module = importlib.import_module(name)
dag_present = False
# extract objects of specific types from the workflow module
for key, obj in workflow_module.__dict__.items():
if isinstance(obj, Dag):
self._dags_blueprint[obj.name] = obj
dag_present = True
elif isinstance(obj, Parameters):
self._parameters.extend(obj)
self._name = name
self._docstring = inspect.getdoc(workflow_module)
del sys.modules[name]
if strict_dag and not dag_present:
raise WorkflowImportError(
'Workflow does not include a dag {}'.format(name))
if validate_arguments:
missing_parameters = self._parameters.check_missing(arguments)
if len(missing_parameters) > 0:
raise WorkflowArgumentError(
'The following parameters are required ' +
'by the workflow, but are missing: {}'.format(
', '.join(missing_parameters)))
self._provided_arguments = arguments
except (TypeError, ImportError):
logger.error('Cannot import workflow {}'.format(name))
raise WorkflowImportError('Cannot import workflow {}'.format(name)) | [
"def",
"load",
"(",
"self",
",",
"name",
",",
"*",
",",
"arguments",
"=",
"None",
",",
"validate_arguments",
"=",
"True",
",",
"strict_dag",
"=",
"False",
")",
":",
"arguments",
"=",
"{",
"}",
"if",
"arguments",
"is",
"None",
"else",
"arguments",
"try"... | Import the workflow script and load all known objects.
The workflow script is treated like a module and imported
into the Python namespace. After the import, the method looks
for instances of known classes and stores a reference for further
use in the workflow object.
Args:
name (str): The name of the workflow script.
arguments (dict): Dictionary of additional arguments that are ingested
into the data store prior to the execution of the workflow.
validate_arguments (bool): Whether to check that all required arguments have
been supplied.
strict_dag (bool): If true then the loaded workflow module must contain an
instance of Dag.
Raises:
WorkflowArgumentError: If the workflow requires arguments to be set that
were not supplied to the workflow.
WorkflowImportError: If the import of the workflow fails. | [
"Import",
"the",
"workflow",
"script",
"and",
"load",
"all",
"known",
"objects",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/workflow.py#L108-L165 | train |
AustralianSynchrotron/lightflow | lightflow/models/workflow.py | Workflow.run | def run(self, config, data_store, signal_server, workflow_id):
""" Run all autostart dags in the workflow.
Only the dags that are flagged as autostart are started.
Args:
config (Config): Reference to the configuration object from which the
settings for the workflow are retrieved.
data_store (DataStore): A DataStore object that is fully initialised and
connected to the persistent data storage.
signal_server (Server): A signal Server object that receives requests
from dags and tasks.
workflow_id (str): A unique workflow id that represents this workflow run
"""
self._workflow_id = workflow_id
self._celery_app = create_app(config)
# pre-fill the data store with supplied arguments
args = self._parameters.consolidate(self._provided_arguments)
for key, value in args.items():
data_store.get(self._workflow_id).set(key, value)
# start all dags with the autostart flag set to True
for name, dag in self._dags_blueprint.items():
if dag.autostart:
self._queue_dag(name)
# as long as there are dags in the list keep running
while self._dags_running:
if config.workflow_polling_time > 0.0:
sleep(config.workflow_polling_time)
# handle new requests from dags, tasks and the library (e.g. cli, web)
for i in range(MAX_SIGNAL_REQUESTS):
request = signal_server.receive()
if request is None:
break
try:
response = self._handle_request(request)
if response is not None:
signal_server.send(response)
else:
signal_server.restore(request)
except (RequestActionUnknown, RequestFailed):
signal_server.send(Response(success=False, uid=request.uid))
# remove any dags and their result data that finished running
for name, dag in list(self._dags_running.items()):
if dag.ready():
if self._celery_app.conf.result_expires == 0:
dag.forget()
del self._dags_running[name]
elif dag.failed():
self._stop_workflow = True
# remove the signal entry
signal_server.clear()
# delete all entries in the data_store under this workflow id, if requested
if self._clear_data_store:
data_store.remove(self._workflow_id) | python | def run(self, config, data_store, signal_server, workflow_id):
""" Run all autostart dags in the workflow.
Only the dags that are flagged as autostart are started.
Args:
config (Config): Reference to the configuration object from which the
settings for the workflow are retrieved.
data_store (DataStore): A DataStore object that is fully initialised and
connected to the persistent data storage.
signal_server (Server): A signal Server object that receives requests
from dags and tasks.
workflow_id (str): A unique workflow id that represents this workflow run
"""
self._workflow_id = workflow_id
self._celery_app = create_app(config)
# pre-fill the data store with supplied arguments
args = self._parameters.consolidate(self._provided_arguments)
for key, value in args.items():
data_store.get(self._workflow_id).set(key, value)
# start all dags with the autostart flag set to True
for name, dag in self._dags_blueprint.items():
if dag.autostart:
self._queue_dag(name)
# as long as there are dags in the list keep running
while self._dags_running:
if config.workflow_polling_time > 0.0:
sleep(config.workflow_polling_time)
# handle new requests from dags, tasks and the library (e.g. cli, web)
for i in range(MAX_SIGNAL_REQUESTS):
request = signal_server.receive()
if request is None:
break
try:
response = self._handle_request(request)
if response is not None:
signal_server.send(response)
else:
signal_server.restore(request)
except (RequestActionUnknown, RequestFailed):
signal_server.send(Response(success=False, uid=request.uid))
# remove any dags and their result data that finished running
for name, dag in list(self._dags_running.items()):
if dag.ready():
if self._celery_app.conf.result_expires == 0:
dag.forget()
del self._dags_running[name]
elif dag.failed():
self._stop_workflow = True
# remove the signal entry
signal_server.clear()
# delete all entries in the data_store under this workflow id, if requested
if self._clear_data_store:
data_store.remove(self._workflow_id) | [
"def",
"run",
"(",
"self",
",",
"config",
",",
"data_store",
",",
"signal_server",
",",
"workflow_id",
")",
":",
"self",
".",
"_workflow_id",
"=",
"workflow_id",
"self",
".",
"_celery_app",
"=",
"create_app",
"(",
"config",
")",
"# pre-fill the data store with s... | Run all autostart dags in the workflow.
Only the dags that are flagged as autostart are started.
Args:
config (Config): Reference to the configuration object from which the
settings for the workflow are retrieved.
data_store (DataStore): A DataStore object that is fully initialised and
connected to the persistent data storage.
signal_server (Server): A signal Server object that receives requests
from dags and tasks.
workflow_id (str): A unique workflow id that represents this workflow run | [
"Run",
"all",
"autostart",
"dags",
"in",
"the",
"workflow",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/workflow.py#L167-L228 | train |
AustralianSynchrotron/lightflow | lightflow/models/workflow.py | Workflow._queue_dag | def _queue_dag(self, name, *, data=None):
""" Add a new dag to the queue.
If the stop workflow flag is set, no new dag can be queued.
Args:
name (str): The name of the dag that should be queued.
data (MultiTaskData): The data that should be passed on to the new dag.
Raises:
DagNameUnknown: If the specified dag name does not exist
Returns:
str: The name of the queued dag.
"""
if self._stop_workflow:
return None
if name not in self._dags_blueprint:
raise DagNameUnknown()
new_dag = copy.deepcopy(self._dags_blueprint[name])
new_dag.workflow_name = self.name
self._dags_running[new_dag.name] = self._celery_app.send_task(
JobExecPath.Dag, args=(new_dag, self._workflow_id, data),
queue=new_dag.queue, routing_key=new_dag.queue)
return new_dag.name | python | def _queue_dag(self, name, *, data=None):
""" Add a new dag to the queue.
If the stop workflow flag is set, no new dag can be queued.
Args:
name (str): The name of the dag that should be queued.
data (MultiTaskData): The data that should be passed on to the new dag.
Raises:
DagNameUnknown: If the specified dag name does not exist
Returns:
str: The name of the queued dag.
"""
if self._stop_workflow:
return None
if name not in self._dags_blueprint:
raise DagNameUnknown()
new_dag = copy.deepcopy(self._dags_blueprint[name])
new_dag.workflow_name = self.name
self._dags_running[new_dag.name] = self._celery_app.send_task(
JobExecPath.Dag, args=(new_dag, self._workflow_id, data),
queue=new_dag.queue, routing_key=new_dag.queue)
return new_dag.name | [
"def",
"_queue_dag",
"(",
"self",
",",
"name",
",",
"*",
",",
"data",
"=",
"None",
")",
":",
"if",
"self",
".",
"_stop_workflow",
":",
"return",
"None",
"if",
"name",
"not",
"in",
"self",
".",
"_dags_blueprint",
":",
"raise",
"DagNameUnknown",
"(",
")"... | Add a new dag to the queue.
If the stop workflow flag is set, no new dag can be queued.
Args:
name (str): The name of the dag that should be queued.
data (MultiTaskData): The data that should be passed on to the new dag.
Raises:
DagNameUnknown: If the specified dag name does not exist
Returns:
str: The name of the queued dag. | [
"Add",
"a",
"new",
"dag",
"to",
"the",
"queue",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/workflow.py#L230-L257 | train |
AustralianSynchrotron/lightflow | lightflow/models/workflow.py | Workflow._handle_request | def _handle_request(self, request):
""" Handle an incoming request by forwarding it to the appropriate method.
Args:
request (Request): Reference to a request object containing the
incoming request.
Raises:
RequestActionUnknown: If the action specified in the request is not known.
Returns:
Response: A response object containing the response from the method handling
the request.
"""
if request is None:
return Response(success=False, uid=request.uid)
action_map = {
'start_dag': self._handle_start_dag,
'stop_workflow': self._handle_stop_workflow,
'join_dags': self._handle_join_dags,
'stop_dag': self._handle_stop_dag,
'is_dag_stopped': self._handle_is_dag_stopped
}
if request.action in action_map:
return action_map[request.action](request)
else:
raise RequestActionUnknown() | python | def _handle_request(self, request):
""" Handle an incoming request by forwarding it to the appropriate method.
Args:
request (Request): Reference to a request object containing the
incoming request.
Raises:
RequestActionUnknown: If the action specified in the request is not known.
Returns:
Response: A response object containing the response from the method handling
the request.
"""
if request is None:
return Response(success=False, uid=request.uid)
action_map = {
'start_dag': self._handle_start_dag,
'stop_workflow': self._handle_stop_workflow,
'join_dags': self._handle_join_dags,
'stop_dag': self._handle_stop_dag,
'is_dag_stopped': self._handle_is_dag_stopped
}
if request.action in action_map:
return action_map[request.action](request)
else:
raise RequestActionUnknown() | [
"def",
"_handle_request",
"(",
"self",
",",
"request",
")",
":",
"if",
"request",
"is",
"None",
":",
"return",
"Response",
"(",
"success",
"=",
"False",
",",
"uid",
"=",
"request",
".",
"uid",
")",
"action_map",
"=",
"{",
"'start_dag'",
":",
"self",
".... | Handle an incoming request by forwarding it to the appropriate method.
Args:
request (Request): Reference to a request object containing the
incoming request.
Raises:
RequestActionUnknown: If the action specified in the request is not known.
Returns:
Response: A response object containing the response from the method handling
the request. | [
"Handle",
"an",
"incoming",
"request",
"by",
"forwarding",
"it",
"to",
"the",
"appropriate",
"method",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/workflow.py#L259-L287 | train |
AustralianSynchrotron/lightflow | lightflow/models/workflow.py | Workflow._handle_start_dag | def _handle_start_dag(self, request):
""" The handler for the start_dag request.
The start_dag request creates a new dag and adds it to the queue.
Args:
request (Request): Reference to a request object containing the
incoming request. The payload has to contain the
following fields:
'name': the name of the dag that should be started
'data': the data that is passed onto the start tasks
Returns:
Response: A response object containing the following fields:
- dag_name: The name of the started dag.
"""
dag_name = self._queue_dag(name=request.payload['name'],
data=request.payload['data'])
return Response(success=dag_name is not None, uid=request.uid,
payload={'dag_name': dag_name}) | python | def _handle_start_dag(self, request):
""" The handler for the start_dag request.
The start_dag request creates a new dag and adds it to the queue.
Args:
request (Request): Reference to a request object containing the
incoming request. The payload has to contain the
following fields:
'name': the name of the dag that should be started
'data': the data that is passed onto the start tasks
Returns:
Response: A response object containing the following fields:
- dag_name: The name of the started dag.
"""
dag_name = self._queue_dag(name=request.payload['name'],
data=request.payload['data'])
return Response(success=dag_name is not None, uid=request.uid,
payload={'dag_name': dag_name}) | [
"def",
"_handle_start_dag",
"(",
"self",
",",
"request",
")",
":",
"dag_name",
"=",
"self",
".",
"_queue_dag",
"(",
"name",
"=",
"request",
".",
"payload",
"[",
"'name'",
"]",
",",
"data",
"=",
"request",
".",
"payload",
"[",
"'data'",
"]",
")",
"retur... | The handler for the start_dag request.
The start_dag request creates a new dag and adds it to the queue.
Args:
request (Request): Reference to a request object containing the
incoming request. The payload has to contain the
following fields:
'name': the name of the dag that should be started
'data': the data that is passed onto the start tasks
Returns:
Response: A response object containing the following fields:
- dag_name: The name of the started dag. | [
"The",
"handler",
"for",
"the",
"start_dag",
"request",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/workflow.py#L289-L308 | train |
AustralianSynchrotron/lightflow | lightflow/models/workflow.py | Workflow._handle_stop_workflow | def _handle_stop_workflow(self, request):
""" The handler for the stop_workflow request.
The stop_workflow request adds all running dags to the list of dags
that should be stopped and prevents new dags from being started. The dags will
then stop queueing new tasks, which will terminate the dags and in turn the
workflow.
Args:
request (Request): Reference to a request object containing the
incoming request.
Returns:
Response: A response object containing the following fields:
- success: True if the dags were added successfully to the list
of dags that should be stopped.
"""
self._stop_workflow = True
for name, dag in self._dags_running.items():
if name not in self._stop_dags:
self._stop_dags.append(name)
return Response(success=True, uid=request.uid) | python | def _handle_stop_workflow(self, request):
""" The handler for the stop_workflow request.
The stop_workflow request adds all running dags to the list of dags
that should be stopped and prevents new dags from being started. The dags will
then stop queueing new tasks, which will terminate the dags and in turn the
workflow.
Args:
request (Request): Reference to a request object containing the
incoming request.
Returns:
Response: A response object containing the following fields:
- success: True if the dags were added successfully to the list
of dags that should be stopped.
"""
self._stop_workflow = True
for name, dag in self._dags_running.items():
if name not in self._stop_dags:
self._stop_dags.append(name)
return Response(success=True, uid=request.uid) | [
"def",
"_handle_stop_workflow",
"(",
"self",
",",
"request",
")",
":",
"self",
".",
"_stop_workflow",
"=",
"True",
"for",
"name",
",",
"dag",
"in",
"self",
".",
"_dags_running",
".",
"items",
"(",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"_sto... | The handler for the stop_workflow request.
The stop_workflow request adds all running dags to the list of dags
that should be stopped and prevents new dags from being started. The dags will
then stop queueing new tasks, which will terminate the dags and in turn the
workflow.
Args:
request (Request): Reference to a request object containing the
incoming request.
Returns:
Response: A response object containing the following fields:
- success: True if the dags were added successfully to the list
of dags that should be stopped. | [
"The",
"handler",
"for",
"the",
"stop_workflow",
"request",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/workflow.py#L310-L331 | train |
AustralianSynchrotron/lightflow | lightflow/models/workflow.py | Workflow._handle_join_dags | def _handle_join_dags(self, request):
""" The handler for the join_dags request.
If dag names are given in the payload only return a valid Response if none of
the dags specified by the names are running anymore. If no dag names are given,
wait for all dags except one, which by design is the one that issued the request,
to be finished.
Args:
request (Request): Reference to a request object containing the
incoming request.
Returns:
Response: A response object containing the following fields:
- success: True if all dags the request was waiting for have
completed.
"""
if request.payload['names'] is None:
send_response = len(self._dags_running) <= 1
else:
send_response = all([name not in self._dags_running.keys()
for name in request.payload['names']])
if send_response:
return Response(success=True, uid=request.uid)
else:
return None | python | def _handle_join_dags(self, request):
""" The handler for the join_dags request.
If dag names are given in the payload only return a valid Response if none of
the dags specified by the names are running anymore. If no dag names are given,
wait for all dags except one, which by design is the one that issued the request,
to be finished.
Args:
request (Request): Reference to a request object containing the
incoming request.
Returns:
Response: A response object containing the following fields:
- success: True if all dags the request was waiting for have
completed.
"""
if request.payload['names'] is None:
send_response = len(self._dags_running) <= 1
else:
send_response = all([name not in self._dags_running.keys()
for name in request.payload['names']])
if send_response:
return Response(success=True, uid=request.uid)
else:
return None | [
"def",
"_handle_join_dags",
"(",
"self",
",",
"request",
")",
":",
"if",
"request",
".",
"payload",
"[",
"'names'",
"]",
"is",
"None",
":",
"send_response",
"=",
"len",
"(",
"self",
".",
"_dags_running",
")",
"<=",
"1",
"else",
":",
"send_response",
"=",... | The handler for the join_dags request.
If dag names are given in the payload only return a valid Response if none of
the dags specified by the names are running anymore. If no dag names are given,
wait for all dags except one, which by design is the one that issued the request,
to be finished.
Args:
request (Request): Reference to a request object containing the
incoming request.
Returns:
Response: A response object containing the following fields:
- success: True if all dags the request was waiting for have
completed. | [
"The",
"handler",
"for",
"the",
"join_dags",
"request",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/workflow.py#L333-L359 | train |
AustralianSynchrotron/lightflow | lightflow/models/workflow.py | Workflow._handle_stop_dag | def _handle_stop_dag(self, request):
""" The handler for the stop_dag request.
The stop_dag request adds a dag to the list of dags that should be stopped.
The dag will then stop queueing new tasks and will eventually stop running.
Args:
request (Request): Reference to a request object containing the
incoming request. The payload has to contain the
following fields:
'name': the name of the dag that should be stopped
Returns:
Response: A response object containing the following fields:
- success: True if the dag was added successfully to the list
of dags that should be stopped.
"""
if (request.payload['name'] is not None) and \
(request.payload['name'] not in self._stop_dags):
self._stop_dags.append(request.payload['name'])
return Response(success=True, uid=request.uid) | python | def _handle_stop_dag(self, request):
""" The handler for the stop_dag request.
The stop_dag request adds a dag to the list of dags that should be stopped.
The dag will then stop queueing new tasks and will eventually stop running.
Args:
request (Request): Reference to a request object containing the
incoming request. The payload has to contain the
following fields:
'name': the name of the dag that should be stopped
Returns:
Response: A response object containing the following fields:
- success: True if the dag was added successfully to the list
of dags that should be stopped.
"""
if (request.payload['name'] is not None) and \
(request.payload['name'] not in self._stop_dags):
self._stop_dags.append(request.payload['name'])
return Response(success=True, uid=request.uid) | [
"def",
"_handle_stop_dag",
"(",
"self",
",",
"request",
")",
":",
"if",
"(",
"request",
".",
"payload",
"[",
"'name'",
"]",
"is",
"not",
"None",
")",
"and",
"(",
"request",
".",
"payload",
"[",
"'name'",
"]",
"not",
"in",
"self",
".",
"_stop_dags",
"... | The handler for the stop_dag request.
The stop_dag request adds a dag to the list of dags that should be stopped.
The dag will then stop queueing new tasks and will eventually stop running.
Args:
request (Request): Reference to a request object containing the
incoming request. The payload has to contain the
following fields:
'name': the name of the dag that should be stopped
Returns:
Response: A response object containing the following fields:
- success: True if the dag was added successfully to the list
of dags that should be stopped. | [
"The",
"handler",
"for",
"the",
"stop_dag",
"request",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/workflow.py#L361-L381 | train |
AustralianSynchrotron/lightflow | lightflow/models/workflow.py | Workflow._handle_is_dag_stopped | def _handle_is_dag_stopped(self, request):
""" The handler for the dag_stopped request.
The dag_stopped request checks whether a dag is flagged to be terminated.
Args:
request (Request): Reference to a request object containing the
incoming request. The payload has to contain the
following fields:
'dag_name': the name of the dag that should be checked
Returns:
Response: A response object containing the following fields:
- is_stopped: True if the dag is flagged to be stopped.
"""
return Response(success=True,
uid=request.uid,
payload={
'is_stopped': request.payload['dag_name'] in self._stop_dags
}) | python | def _handle_is_dag_stopped(self, request):
""" The handler for the dag_stopped request.
The dag_stopped request checks whether a dag is flagged to be terminated.
Args:
request (Request): Reference to a request object containing the
incoming request. The payload has to contain the
following fields:
'dag_name': the name of the dag that should be checked
Returns:
Response: A response object containing the following fields:
- is_stopped: True if the dag is flagged to be stopped.
"""
return Response(success=True,
uid=request.uid,
payload={
'is_stopped': request.payload['dag_name'] in self._stop_dags
}) | [
"def",
"_handle_is_dag_stopped",
"(",
"self",
",",
"request",
")",
":",
"return",
"Response",
"(",
"success",
"=",
"True",
",",
"uid",
"=",
"request",
".",
"uid",
",",
"payload",
"=",
"{",
"'is_stopped'",
":",
"request",
".",
"payload",
"[",
"'dag_name'",
... | The handler for the dag_stopped request.
The dag_stopped request checks whether a dag is flagged to be terminated.
Args:
request (Request): Reference to a request object containing the
incoming request. The payload has to contain the
following fields:
'dag_name': the name of the dag that should be checked
Returns:
Response: A response object containing the following fields:
- is_stopped: True if the dag is flagged to be stopped. | [
"The",
"handler",
"for",
"the",
"dag_stopped",
"request",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/workflow.py#L383-L402 | train |
AustralianSynchrotron/lightflow | lightflow/queue/worker.py | WorkerLifecycle.stop | def stop(self, consumer):
""" This function is called when the worker received a request to terminate.
Upon the termination of the worker, the workflows for all running jobs are
stopped gracefully.
Args:
consumer (Consumer): Reference to the consumer object that handles messages
from the broker.
"""
stopped_workflows = []
for request in [r for r in consumer.controller.state.active_requests]:
job = AsyncResult(request.id)
workflow_id = job.result['workflow_id']
if workflow_id not in stopped_workflows:
client = Client(
SignalConnection(**consumer.app.user_options['config'].signal,
auto_connect=True),
request_key=workflow_id)
client.send(Request(action='stop_workflow'))
stopped_workflows.append(workflow_id) | python | def stop(self, consumer):
""" This function is called when the worker received a request to terminate.
Upon the termination of the worker, the workflows for all running jobs are
stopped gracefully.
Args:
consumer (Consumer): Reference to the consumer object that handles messages
from the broker.
"""
stopped_workflows = []
for request in [r for r in consumer.controller.state.active_requests]:
job = AsyncResult(request.id)
workflow_id = job.result['workflow_id']
if workflow_id not in stopped_workflows:
client = Client(
SignalConnection(**consumer.app.user_options['config'].signal,
auto_connect=True),
request_key=workflow_id)
client.send(Request(action='stop_workflow'))
stopped_workflows.append(workflow_id) | [
"def",
"stop",
"(",
"self",
",",
"consumer",
")",
":",
"stopped_workflows",
"=",
"[",
"]",
"for",
"request",
"in",
"[",
"r",
"for",
"r",
"in",
"consumer",
".",
"controller",
".",
"state",
".",
"active_requests",
"]",
":",
"job",
"=",
"AsyncResult",
"("... | This function is called when the worker received a request to terminate.
Upon the termination of the worker, the workflows for all running jobs are
stopped gracefully.
Args:
consumer (Consumer): Reference to the consumer object that handles messages
from the broker. | [
"This",
"function",
"is",
"called",
"when",
"the",
"worker",
"received",
"a",
"request",
"to",
"terminate",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/queue/worker.py#L10-L32 | train |
AustralianSynchrotron/lightflow | lightflow/models/task_signal.py | TaskSignal.start_dag | def start_dag(self, dag, *, data=None):
""" Schedule the execution of a dag by sending a signal to the workflow.
Args:
dag (Dag, str): The dag object or the name of the dag that should be started.
data (MultiTaskData): The data that should be passed on to the new dag.
Returns:
str: The name of the successfully started dag.
"""
return self._client.send(
Request(
action='start_dag',
payload={'name': dag.name if isinstance(dag, Dag) else dag,
'data': data if isinstance(data, MultiTaskData) else None}
)
).payload['dag_name'] | python | def start_dag(self, dag, *, data=None):
""" Schedule the execution of a dag by sending a signal to the workflow.
Args:
dag (Dag, str): The dag object or the name of the dag that should be started.
data (MultiTaskData): The data that should be passed on to the new dag.
Returns:
str: The name of the successfully started dag.
"""
return self._client.send(
Request(
action='start_dag',
payload={'name': dag.name if isinstance(dag, Dag) else dag,
'data': data if isinstance(data, MultiTaskData) else None}
)
).payload['dag_name'] | [
"def",
"start_dag",
"(",
"self",
",",
"dag",
",",
"*",
",",
"data",
"=",
"None",
")",
":",
"return",
"self",
".",
"_client",
".",
"send",
"(",
"Request",
"(",
"action",
"=",
"'start_dag'",
",",
"payload",
"=",
"{",
"'name'",
":",
"dag",
".",
"name"... | Schedule the execution of a dag by sending a signal to the workflow.
Args:
dag (Dag, str): The dag object or the name of the dag that should be started.
data (MultiTaskData): The data that should be passed on to the new dag.
Returns:
str: The name of the successfully started dag. | [
"Schedule",
"the",
"execution",
"of",
"a",
"dag",
"by",
"sending",
"a",
"signal",
"to",
"the",
"workflow",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/task_signal.py#L18-L34 | train |
AustralianSynchrotron/lightflow | lightflow/models/task_signal.py | TaskSignal.join_dags | def join_dags(self, names=None):
""" Wait for the specified dags to terminate.
This function blocks until the specified dags terminate. If no dags are specified
wait for all dags of the workflow, except the dag of the task calling this signal,
to terminate.
Args:
names (list): The names of the dags that have to terminate.
Returns:
bool: True if all the signal was sent successfully.
"""
return self._client.send(
Request(
action='join_dags',
payload={'names': names}
)
).success | python | def join_dags(self, names=None):
""" Wait for the specified dags to terminate.
This function blocks until the specified dags terminate. If no dags are specified
wait for all dags of the workflow, except the dag of the task calling this signal,
to terminate.
Args:
names (list): The names of the dags that have to terminate.
Returns:
bool: True if all the signal was sent successfully.
"""
return self._client.send(
Request(
action='join_dags',
payload={'names': names}
)
).success | [
"def",
"join_dags",
"(",
"self",
",",
"names",
"=",
"None",
")",
":",
"return",
"self",
".",
"_client",
".",
"send",
"(",
"Request",
"(",
"action",
"=",
"'join_dags'",
",",
"payload",
"=",
"{",
"'names'",
":",
"names",
"}",
")",
")",
".",
"success"
] | Wait for the specified dags to terminate.
This function blocks until the specified dags terminate. If no dags are specified
wait for all dags of the workflow, except the dag of the task calling this signal,
to terminate.
Args:
names (list): The names of the dags that have to terminate.
Returns:
bool: True if all the signal was sent successfully. | [
"Wait",
"for",
"the",
"specified",
"dags",
"to",
"terminate",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/task_signal.py#L36-L54 | train |
AustralianSynchrotron/lightflow | lightflow/models/task_signal.py | TaskSignal.stop_dag | def stop_dag(self, name=None):
""" Send a stop signal to the specified dag or the dag that hosts this task.
Args:
name str: The name of the dag that should be stopped. If no name is given the
dag that hosts this task is stopped.
Upon receiving the stop signal, the dag will not queue any new tasks and wait
for running tasks to terminate.
Returns:
bool: True if the signal was sent successfully.
"""
return self._client.send(
Request(
action='stop_dag',
payload={'name': name if name is not None else self._dag_name}
)
).success | python | def stop_dag(self, name=None):
""" Send a stop signal to the specified dag or the dag that hosts this task.
Args:
name str: The name of the dag that should be stopped. If no name is given the
dag that hosts this task is stopped.
Upon receiving the stop signal, the dag will not queue any new tasks and wait
for running tasks to terminate.
Returns:
bool: True if the signal was sent successfully.
"""
return self._client.send(
Request(
action='stop_dag',
payload={'name': name if name is not None else self._dag_name}
)
).success | [
"def",
"stop_dag",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"return",
"self",
".",
"_client",
".",
"send",
"(",
"Request",
"(",
"action",
"=",
"'stop_dag'",
",",
"payload",
"=",
"{",
"'name'",
":",
"name",
"if",
"name",
"is",
"not",
"None",
... | Send a stop signal to the specified dag or the dag that hosts this task.
Args:
name str: The name of the dag that should be stopped. If no name is given the
dag that hosts this task is stopped.
Upon receiving the stop signal, the dag will not queue any new tasks and wait
for running tasks to terminate.
Returns:
bool: True if the signal was sent successfully. | [
"Send",
"a",
"stop",
"signal",
"to",
"the",
"specified",
"dag",
"or",
"the",
"dag",
"that",
"hosts",
"this",
"task",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/task_signal.py#L56-L74 | train |
AustralianSynchrotron/lightflow | lightflow/models/task_signal.py | TaskSignal.is_stopped | def is_stopped(self):
""" Check whether the task received a stop signal from the workflow.
Tasks can use the stop flag to gracefully terminate their work. This is
particularly important for long running tasks and tasks that employ an
infinite loop, such as trigger tasks.
Returns:
bool: True if the task should be stopped.
"""
resp = self._client.send(
Request(
action='is_dag_stopped',
payload={'dag_name': self._dag_name}
)
)
return resp.payload['is_stopped'] | python | def is_stopped(self):
""" Check whether the task received a stop signal from the workflow.
Tasks can use the stop flag to gracefully terminate their work. This is
particularly important for long running tasks and tasks that employ an
infinite loop, such as trigger tasks.
Returns:
bool: True if the task should be stopped.
"""
resp = self._client.send(
Request(
action='is_dag_stopped',
payload={'dag_name': self._dag_name}
)
)
return resp.payload['is_stopped'] | [
"def",
"is_stopped",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"_client",
".",
"send",
"(",
"Request",
"(",
"action",
"=",
"'is_dag_stopped'",
",",
"payload",
"=",
"{",
"'dag_name'",
":",
"self",
".",
"_dag_name",
"}",
")",
")",
"return",
"resp"... | Check whether the task received a stop signal from the workflow.
Tasks can use the stop flag to gracefully terminate their work. This is
particularly important for long running tasks and tasks that employ an
infinite loop, such as trigger tasks.
Returns:
bool: True if the task should be stopped. | [
"Check",
"whether",
"the",
"task",
"received",
"a",
"stop",
"signal",
"from",
"the",
"workflow",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/task_signal.py#L90-L106 | train |
AustralianSynchrotron/lightflow | lightflow/queue/event.py | event_stream | def event_stream(app, *, filter_by_prefix=None):
""" Generator function that returns celery events.
This function turns the callback based celery event handling into a generator.
Args:
app: Reference to a celery application object.
filter_by_prefix (str): If not None, only allow events that have a type that
starts with this prefix to yield an generator event.
Returns:
generator: A generator that returns celery events.
"""
q = Queue()
def handle_event(event):
if filter_by_prefix is None or\
(filter_by_prefix is not None and
event['type'].startswith(filter_by_prefix)):
q.put(event)
def receive_events():
with app.connection() as connection:
recv = app.events.Receiver(connection, handlers={
'*': handle_event
})
recv.capture(limit=None, timeout=None, wakeup=True)
t = threading.Thread(target=receive_events)
t.start()
while True:
yield q.get(block=True) | python | def event_stream(app, *, filter_by_prefix=None):
""" Generator function that returns celery events.
This function turns the callback based celery event handling into a generator.
Args:
app: Reference to a celery application object.
filter_by_prefix (str): If not None, only allow events that have a type that
starts with this prefix to yield an generator event.
Returns:
generator: A generator that returns celery events.
"""
q = Queue()
def handle_event(event):
if filter_by_prefix is None or\
(filter_by_prefix is not None and
event['type'].startswith(filter_by_prefix)):
q.put(event)
def receive_events():
with app.connection() as connection:
recv = app.events.Receiver(connection, handlers={
'*': handle_event
})
recv.capture(limit=None, timeout=None, wakeup=True)
t = threading.Thread(target=receive_events)
t.start()
while True:
yield q.get(block=True) | [
"def",
"event_stream",
"(",
"app",
",",
"*",
",",
"filter_by_prefix",
"=",
"None",
")",
":",
"q",
"=",
"Queue",
"(",
")",
"def",
"handle_event",
"(",
"event",
")",
":",
"if",
"filter_by_prefix",
"is",
"None",
"or",
"(",
"filter_by_prefix",
"is",
"not",
... | Generator function that returns celery events.
This function turns the callback based celery event handling into a generator.
Args:
app: Reference to a celery application object.
filter_by_prefix (str): If not None, only allow events that have a type that
starts with this prefix to yield an generator event.
Returns:
generator: A generator that returns celery events. | [
"Generator",
"function",
"that",
"returns",
"celery",
"events",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/queue/event.py#L10-L44 | train |
AustralianSynchrotron/lightflow | lightflow/queue/event.py | create_event_model | def create_event_model(event):
""" Factory function that turns a celery event into an event object.
Args:
event (dict): A dictionary that represents a celery event.
Returns:
object: An event object representing the received event.
Raises:
JobEventTypeUnsupported: If an unsupported celery job event was received.
WorkerEventTypeUnsupported: If an unsupported celery worker event was received.
EventTypeUnknown: If an unknown event type (neither job nor worker) was received.
"""
if event['type'].startswith('task'):
factory = {
JobEventName.Started: JobStartedEvent,
JobEventName.Succeeded: JobSucceededEvent,
JobEventName.Stopped: JobStoppedEvent,
JobEventName.Aborted: JobAbortedEvent
}
if event['type'] in factory:
return factory[event['type']].from_event(event)
else:
raise JobEventTypeUnsupported(
'Unsupported event type {}'.format(event['type']))
elif event['type'].startswith('worker'):
raise WorkerEventTypeUnsupported(
'Unsupported event type {}'.format(event['type']))
else:
raise EventTypeUnknown('Unknown event type {}'.format(event['type'])) | python | def create_event_model(event):
""" Factory function that turns a celery event into an event object.
Args:
event (dict): A dictionary that represents a celery event.
Returns:
object: An event object representing the received event.
Raises:
JobEventTypeUnsupported: If an unsupported celery job event was received.
WorkerEventTypeUnsupported: If an unsupported celery worker event was received.
EventTypeUnknown: If an unknown event type (neither job nor worker) was received.
"""
if event['type'].startswith('task'):
factory = {
JobEventName.Started: JobStartedEvent,
JobEventName.Succeeded: JobSucceededEvent,
JobEventName.Stopped: JobStoppedEvent,
JobEventName.Aborted: JobAbortedEvent
}
if event['type'] in factory:
return factory[event['type']].from_event(event)
else:
raise JobEventTypeUnsupported(
'Unsupported event type {}'.format(event['type']))
elif event['type'].startswith('worker'):
raise WorkerEventTypeUnsupported(
'Unsupported event type {}'.format(event['type']))
else:
raise EventTypeUnknown('Unknown event type {}'.format(event['type'])) | [
"def",
"create_event_model",
"(",
"event",
")",
":",
"if",
"event",
"[",
"'type'",
"]",
".",
"startswith",
"(",
"'task'",
")",
":",
"factory",
"=",
"{",
"JobEventName",
".",
"Started",
":",
"JobStartedEvent",
",",
"JobEventName",
".",
"Succeeded",
":",
"Jo... | Factory function that turns a celery event into an event object.
Args:
event (dict): A dictionary that represents a celery event.
Returns:
object: An event object representing the received event.
Raises:
JobEventTypeUnsupported: If an unsupported celery job event was received.
WorkerEventTypeUnsupported: If an unsupported celery worker event was received.
EventTypeUnknown: If an unknown event type (neither job nor worker) was received. | [
"Factory",
"function",
"that",
"turns",
"a",
"celery",
"event",
"into",
"an",
"event",
"object",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/queue/event.py#L47-L77 | train |
AustralianSynchrotron/lightflow | lightflow/scripts/cli.py | config_required | def config_required(f):
""" Decorator that checks whether a configuration file was set. """
def new_func(obj, *args, **kwargs):
if 'config' not in obj:
click.echo(_style(obj.get('show_color', False),
'Could not find a valid configuration file!',
fg='red', bold=True))
raise click.Abort()
else:
return f(obj, *args, **kwargs)
return update_wrapper(new_func, f) | python | def config_required(f):
""" Decorator that checks whether a configuration file was set. """
def new_func(obj, *args, **kwargs):
if 'config' not in obj:
click.echo(_style(obj.get('show_color', False),
'Could not find a valid configuration file!',
fg='red', bold=True))
raise click.Abort()
else:
return f(obj, *args, **kwargs)
return update_wrapper(new_func, f) | [
"def",
"config_required",
"(",
"f",
")",
":",
"def",
"new_func",
"(",
"obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'config'",
"not",
"in",
"obj",
":",
"click",
".",
"echo",
"(",
"_style",
"(",
"obj",
".",
"get",
"(",
"'show_... | Decorator that checks whether a configuration file was set. | [
"Decorator",
"that",
"checks",
"whether",
"a",
"configuration",
"file",
"was",
"set",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/scripts/cli.py#L30-L40 | train |
AustralianSynchrotron/lightflow | lightflow/scripts/cli.py | ingest_config_obj | def ingest_config_obj(ctx, *, silent=True):
""" Ingest the configuration object into the click context. """
try:
ctx.obj['config'] = Config.from_file(ctx.obj['config_path'])
except ConfigLoadError as err:
click.echo(_style(ctx.obj['show_color'], str(err), fg='red', bold=True))
if not silent:
raise click.Abort() | python | def ingest_config_obj(ctx, *, silent=True):
""" Ingest the configuration object into the click context. """
try:
ctx.obj['config'] = Config.from_file(ctx.obj['config_path'])
except ConfigLoadError as err:
click.echo(_style(ctx.obj['show_color'], str(err), fg='red', bold=True))
if not silent:
raise click.Abort() | [
"def",
"ingest_config_obj",
"(",
"ctx",
",",
"*",
",",
"silent",
"=",
"True",
")",
":",
"try",
":",
"ctx",
".",
"obj",
"[",
"'config'",
"]",
"=",
"Config",
".",
"from_file",
"(",
"ctx",
".",
"obj",
"[",
"'config_path'",
"]",
")",
"except",
"ConfigLoa... | Ingest the configuration object into the click context. | [
"Ingest",
"the",
"configuration",
"object",
"into",
"the",
"click",
"context",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/scripts/cli.py#L43-L50 | train |
AustralianSynchrotron/lightflow | lightflow/scripts/cli.py | cli | def cli(ctx, config, no_color):
""" Command line client for lightflow. A lightweight, high performance pipeline
system for synchrotrons.
Lightflow is being developed at the Australian Synchrotron.
"""
ctx.obj = {
'show_color': not no_color if no_color is not None else True,
'config_path': config
} | python | def cli(ctx, config, no_color):
""" Command line client for lightflow. A lightweight, high performance pipeline
system for synchrotrons.
Lightflow is being developed at the Australian Synchrotron.
"""
ctx.obj = {
'show_color': not no_color if no_color is not None else True,
'config_path': config
} | [
"def",
"cli",
"(",
"ctx",
",",
"config",
",",
"no_color",
")",
":",
"ctx",
".",
"obj",
"=",
"{",
"'show_color'",
":",
"not",
"no_color",
"if",
"no_color",
"is",
"not",
"None",
"else",
"True",
",",
"'config_path'",
":",
"config",
"}"
] | Command line client for lightflow. A lightweight, high performance pipeline
system for synchrotrons.
Lightflow is being developed at the Australian Synchrotron. | [
"Command",
"line",
"client",
"for",
"lightflow",
".",
"A",
"lightweight",
"high",
"performance",
"pipeline",
"system",
"for",
"synchrotrons",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/scripts/cli.py#L58-L67 | train |
AustralianSynchrotron/lightflow | lightflow/scripts/cli.py | config_default | def config_default(dest):
""" Create a default configuration file.
\b
DEST: Path or file name for the configuration file.
"""
conf_path = Path(dest).resolve()
if conf_path.is_dir():
conf_path = conf_path / LIGHTFLOW_CONFIG_NAME
conf_path.write_text(Config.default())
click.echo('Configuration written to {}'.format(conf_path)) | python | def config_default(dest):
""" Create a default configuration file.
\b
DEST: Path or file name for the configuration file.
"""
conf_path = Path(dest).resolve()
if conf_path.is_dir():
conf_path = conf_path / LIGHTFLOW_CONFIG_NAME
conf_path.write_text(Config.default())
click.echo('Configuration written to {}'.format(conf_path)) | [
"def",
"config_default",
"(",
"dest",
")",
":",
"conf_path",
"=",
"Path",
"(",
"dest",
")",
".",
"resolve",
"(",
")",
"if",
"conf_path",
".",
"is_dir",
"(",
")",
":",
"conf_path",
"=",
"conf_path",
"/",
"LIGHTFLOW_CONFIG_NAME",
"conf_path",
".",
"write_tex... | Create a default configuration file.
\b
DEST: Path or file name for the configuration file. | [
"Create",
"a",
"default",
"configuration",
"file",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/scripts/cli.py#L78-L89 | train |
AustralianSynchrotron/lightflow | lightflow/scripts/cli.py | config_list | def config_list(ctx):
""" List the current configuration. """
ingest_config_obj(ctx, silent=False)
click.echo(json.dumps(ctx.obj['config'].to_dict(), indent=4)) | python | def config_list(ctx):
""" List the current configuration. """
ingest_config_obj(ctx, silent=False)
click.echo(json.dumps(ctx.obj['config'].to_dict(), indent=4)) | [
"def",
"config_list",
"(",
"ctx",
")",
":",
"ingest_config_obj",
"(",
"ctx",
",",
"silent",
"=",
"False",
")",
"click",
".",
"echo",
"(",
"json",
".",
"dumps",
"(",
"ctx",
".",
"obj",
"[",
"'config'",
"]",
".",
"to_dict",
"(",
")",
",",
"indent",
"... | List the current configuration. | [
"List",
"the",
"current",
"configuration",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/scripts/cli.py#L94-L97 | train |
AustralianSynchrotron/lightflow | lightflow/scripts/cli.py | config_examples | def config_examples(dest, user_dir):
""" Copy the example workflows to a directory.
\b
DEST: Path to which the examples should be copied.
"""
examples_path = Path(lightflow.__file__).parents[1] / 'examples'
if examples_path.exists():
dest_path = Path(dest).resolve()
if not user_dir:
dest_path = dest_path / 'examples'
if dest_path.exists():
if not click.confirm('Directory already exists. Overwrite existing files?',
default=True, abort=True):
return
else:
dest_path.mkdir()
for example_file in examples_path.glob('*.py'):
shutil.copy(str(example_file), str(dest_path / example_file.name))
click.echo('Copied examples to {}'.format(str(dest_path)))
else:
click.echo('The examples source path does not exist') | python | def config_examples(dest, user_dir):
""" Copy the example workflows to a directory.
\b
DEST: Path to which the examples should be copied.
"""
examples_path = Path(lightflow.__file__).parents[1] / 'examples'
if examples_path.exists():
dest_path = Path(dest).resolve()
if not user_dir:
dest_path = dest_path / 'examples'
if dest_path.exists():
if not click.confirm('Directory already exists. Overwrite existing files?',
default=True, abort=True):
return
else:
dest_path.mkdir()
for example_file in examples_path.glob('*.py'):
shutil.copy(str(example_file), str(dest_path / example_file.name))
click.echo('Copied examples to {}'.format(str(dest_path)))
else:
click.echo('The examples source path does not exist') | [
"def",
"config_examples",
"(",
"dest",
",",
"user_dir",
")",
":",
"examples_path",
"=",
"Path",
"(",
"lightflow",
".",
"__file__",
")",
".",
"parents",
"[",
"1",
"]",
"/",
"'examples'",
"if",
"examples_path",
".",
"exists",
"(",
")",
":",
"dest_path",
"=... | Copy the example workflows to a directory.
\b
DEST: Path to which the examples should be copied. | [
"Copy",
"the",
"example",
"workflows",
"to",
"a",
"directory",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/scripts/cli.py#L104-L127 | train |
AustralianSynchrotron/lightflow | lightflow/scripts/cli.py | workflow_list | def workflow_list(obj):
""" List all available workflows. """
try:
for wf in list_workflows(config=obj['config']):
click.echo('{:23} {}'.format(
_style(obj['show_color'], wf.name, bold=True),
wf.docstring.split('\n')[0] if wf.docstring is not None else ''))
except WorkflowDefinitionError as e:
click.echo(_style(obj['show_color'],
'The graph {} in workflow {} is not a directed acyclic graph'.
format(e.graph_name, e.workflow_name), fg='red', bold=True)) | python | def workflow_list(obj):
""" List all available workflows. """
try:
for wf in list_workflows(config=obj['config']):
click.echo('{:23} {}'.format(
_style(obj['show_color'], wf.name, bold=True),
wf.docstring.split('\n')[0] if wf.docstring is not None else ''))
except WorkflowDefinitionError as e:
click.echo(_style(obj['show_color'],
'The graph {} in workflow {} is not a directed acyclic graph'.
format(e.graph_name, e.workflow_name), fg='red', bold=True)) | [
"def",
"workflow_list",
"(",
"obj",
")",
":",
"try",
":",
"for",
"wf",
"in",
"list_workflows",
"(",
"config",
"=",
"obj",
"[",
"'config'",
"]",
")",
":",
"click",
".",
"echo",
"(",
"'{:23} {}'",
".",
"format",
"(",
"_style",
"(",
"obj",
"[",
"'show_c... | List all available workflows. | [
"List",
"all",
"available",
"workflows",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/scripts/cli.py#L140-L150 | train |
AustralianSynchrotron/lightflow | lightflow/scripts/cli.py | workflow_start | def workflow_start(obj, queue, keep_data, name, workflow_args):
""" Send a workflow to the queue.
\b
NAME: The name of the workflow that should be started.
WORKFLOW_ARGS: Workflow arguments in the form key1=value1 key2=value2.
"""
try:
start_workflow(name=name,
config=obj['config'],
queue=queue,
clear_data_store=not keep_data,
store_args=dict([arg.split('=', maxsplit=1)
for arg in workflow_args]))
except (WorkflowArgumentError, WorkflowImportError) as e:
click.echo(_style(obj['show_color'],
'An error occurred when trying to start the workflow',
fg='red', bold=True))
click.echo('{}'.format(e))
except WorkflowDefinitionError as e:
click.echo(_style(obj['show_color'],
'The graph {} in workflow {} is not a directed acyclic graph'.
format(e.graph_name, e.workflow_name), fg='red', bold=True)) | python | def workflow_start(obj, queue, keep_data, name, workflow_args):
""" Send a workflow to the queue.
\b
NAME: The name of the workflow that should be started.
WORKFLOW_ARGS: Workflow arguments in the form key1=value1 key2=value2.
"""
try:
start_workflow(name=name,
config=obj['config'],
queue=queue,
clear_data_store=not keep_data,
store_args=dict([arg.split('=', maxsplit=1)
for arg in workflow_args]))
except (WorkflowArgumentError, WorkflowImportError) as e:
click.echo(_style(obj['show_color'],
'An error occurred when trying to start the workflow',
fg='red', bold=True))
click.echo('{}'.format(e))
except WorkflowDefinitionError as e:
click.echo(_style(obj['show_color'],
'The graph {} in workflow {} is not a directed acyclic graph'.
format(e.graph_name, e.workflow_name), fg='red', bold=True)) | [
"def",
"workflow_start",
"(",
"obj",
",",
"queue",
",",
"keep_data",
",",
"name",
",",
"workflow_args",
")",
":",
"try",
":",
"start_workflow",
"(",
"name",
"=",
"name",
",",
"config",
"=",
"obj",
"[",
"'config'",
"]",
",",
"queue",
"=",
"queue",
",",
... | Send a workflow to the queue.
\b
NAME: The name of the workflow that should be started.
WORKFLOW_ARGS: Workflow arguments in the form key1=value1 key2=value2. | [
"Send",
"a",
"workflow",
"to",
"the",
"queue",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/scripts/cli.py#L163-L185 | train |
AustralianSynchrotron/lightflow | lightflow/scripts/cli.py | workflow_stop | def workflow_stop(obj, names):
""" Stop one or more running workflows.
\b
NAMES: The names, ids or job ids of the workflows that should be stopped.
Leave empty to stop all running workflows.
"""
if len(names) == 0:
msg = 'Would you like to stop all workflows?'
else:
msg = '\n{}\n\n{}'.format('\n'.join(names),
'Would you like to stop these jobs?')
if click.confirm(msg, default=True, abort=True):
stop_workflow(obj['config'], names=names if len(names) > 0 else None) | python | def workflow_stop(obj, names):
""" Stop one or more running workflows.
\b
NAMES: The names, ids or job ids of the workflows that should be stopped.
Leave empty to stop all running workflows.
"""
if len(names) == 0:
msg = 'Would you like to stop all workflows?'
else:
msg = '\n{}\n\n{}'.format('\n'.join(names),
'Would you like to stop these jobs?')
if click.confirm(msg, default=True, abort=True):
stop_workflow(obj['config'], names=names if len(names) > 0 else None) | [
"def",
"workflow_stop",
"(",
"obj",
",",
"names",
")",
":",
"if",
"len",
"(",
"names",
")",
"==",
"0",
":",
"msg",
"=",
"'Would you like to stop all workflows?'",
"else",
":",
"msg",
"=",
"'\\n{}\\n\\n{}'",
".",
"format",
"(",
"'\\n'",
".",
"join",
"(",
... | Stop one or more running workflows.
\b
NAMES: The names, ids or job ids of the workflows that should be stopped.
Leave empty to stop all running workflows. | [
"Stop",
"one",
"or",
"more",
"running",
"workflows",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/scripts/cli.py#L192-L206 | train |
AustralianSynchrotron/lightflow | lightflow/scripts/cli.py | workflow_status | def workflow_status(obj, details):
""" Show the status of the workflows. """
show_colors = obj['show_color']
config_cli = obj['config'].cli
if details:
temp_form = '{:>{}} {:20} {:25} {:25} {:38} {}'
else:
temp_form = '{:>{}} {:20} {:25} {} {} {}'
click.echo('\n')
click.echo(temp_form.format(
'Status',
12,
'Name',
'Start Time',
'ID' if details else '',
'Job' if details else '',
'Arguments'
))
click.echo('-' * (138 if details else 75))
def print_jobs(jobs, *, label='', color='green'):
for job in jobs:
start_time = job.start_time if job.start_time is not None else 'unknown'
click.echo(temp_form.format(
_style(show_colors, label, fg=color, bold=True),
25 if show_colors else 12,
job.name,
start_time.replace(tzinfo=pytz.utc).astimezone().strftime(
config_cli['time_format']),
job.workflow_id if details else '',
job.id if details else '',
','.join(['{}={}'.format(k, v) for k, v in job.arguments.items()]))
)
# running jobs
print_jobs(list_jobs(config=obj['config'],
status=JobStatus.Active,
filter_by_type=JobType.Workflow),
label='Running', color='green')
# scheduled jobs
print_jobs(list_jobs(config=obj['config'],
status=JobStatus.Scheduled,
filter_by_type=JobType.Workflow),
label='Scheduled', color='blue')
# registered jobs
print_jobs(list_jobs(config=obj['config'],
status=JobStatus.Registered,
filter_by_type=JobType.Workflow),
label='Registered', color='yellow')
# reserved jobs
print_jobs(list_jobs(config=obj['config'],
status=JobStatus.Reserved,
filter_by_type=JobType.Workflow),
label='Reserved', color='yellow') | python | def workflow_status(obj, details):
""" Show the status of the workflows. """
show_colors = obj['show_color']
config_cli = obj['config'].cli
if details:
temp_form = '{:>{}} {:20} {:25} {:25} {:38} {}'
else:
temp_form = '{:>{}} {:20} {:25} {} {} {}'
click.echo('\n')
click.echo(temp_form.format(
'Status',
12,
'Name',
'Start Time',
'ID' if details else '',
'Job' if details else '',
'Arguments'
))
click.echo('-' * (138 if details else 75))
def print_jobs(jobs, *, label='', color='green'):
for job in jobs:
start_time = job.start_time if job.start_time is not None else 'unknown'
click.echo(temp_form.format(
_style(show_colors, label, fg=color, bold=True),
25 if show_colors else 12,
job.name,
start_time.replace(tzinfo=pytz.utc).astimezone().strftime(
config_cli['time_format']),
job.workflow_id if details else '',
job.id if details else '',
','.join(['{}={}'.format(k, v) for k, v in job.arguments.items()]))
)
# running jobs
print_jobs(list_jobs(config=obj['config'],
status=JobStatus.Active,
filter_by_type=JobType.Workflow),
label='Running', color='green')
# scheduled jobs
print_jobs(list_jobs(config=obj['config'],
status=JobStatus.Scheduled,
filter_by_type=JobType.Workflow),
label='Scheduled', color='blue')
# registered jobs
print_jobs(list_jobs(config=obj['config'],
status=JobStatus.Registered,
filter_by_type=JobType.Workflow),
label='Registered', color='yellow')
# reserved jobs
print_jobs(list_jobs(config=obj['config'],
status=JobStatus.Reserved,
filter_by_type=JobType.Workflow),
label='Reserved', color='yellow') | [
"def",
"workflow_status",
"(",
"obj",
",",
"details",
")",
":",
"show_colors",
"=",
"obj",
"[",
"'show_color'",
"]",
"config_cli",
"=",
"obj",
"[",
"'config'",
"]",
".",
"cli",
"if",
"details",
":",
"temp_form",
"=",
"'{:>{}} {:20} {:25} {:25} {:38} {}'",
"el... | Show the status of the workflows. | [
"Show",
"the",
"status",
"of",
"the",
"workflows",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/scripts/cli.py#L213-L272 | train |
AustralianSynchrotron/lightflow | lightflow/scripts/cli.py | worker_start | def worker_start(obj, queues, name, celery_args):
""" Start a worker process.
\b
CELERY_ARGS: Additional Celery worker command line arguments.
"""
try:
start_worker(queues=queues.split(','),
config=obj['config'],
name=name,
celery_args=celery_args)
except DataStoreNotConnected:
click.echo(_style(obj['show_color'],
'Cannot connect to the Data Store server. Is the server running?',
fg='red', bold=True)) | python | def worker_start(obj, queues, name, celery_args):
""" Start a worker process.
\b
CELERY_ARGS: Additional Celery worker command line arguments.
"""
try:
start_worker(queues=queues.split(','),
config=obj['config'],
name=name,
celery_args=celery_args)
except DataStoreNotConnected:
click.echo(_style(obj['show_color'],
'Cannot connect to the Data Store server. Is the server running?',
fg='red', bold=True)) | [
"def",
"worker_start",
"(",
"obj",
",",
"queues",
",",
"name",
",",
"celery_args",
")",
":",
"try",
":",
"start_worker",
"(",
"queues",
"=",
"queues",
".",
"split",
"(",
"','",
")",
",",
"config",
"=",
"obj",
"[",
"'config'",
"]",
",",
"name",
"=",
... | Start a worker process.
\b
CELERY_ARGS: Additional Celery worker command line arguments. | [
"Start",
"a",
"worker",
"process",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/scripts/cli.py#L292-L306 | train |
AustralianSynchrotron/lightflow | lightflow/scripts/cli.py | worker_stop | def worker_stop(obj, worker_ids):
""" Stop running workers.
\b
WORKER_IDS: The IDs of the worker that should be stopped or none to stop them all.
"""
if len(worker_ids) == 0:
msg = 'Would you like to stop all workers?'
else:
msg = '\n{}\n\n{}'.format('\n'.join(worker_ids),
'Would you like to stop these workers?')
if click.confirm(msg, default=True, abort=True):
stop_worker(obj['config'],
worker_ids=list(worker_ids) if len(worker_ids) > 0 else None) | python | def worker_stop(obj, worker_ids):
""" Stop running workers.
\b
WORKER_IDS: The IDs of the worker that should be stopped or none to stop them all.
"""
if len(worker_ids) == 0:
msg = 'Would you like to stop all workers?'
else:
msg = '\n{}\n\n{}'.format('\n'.join(worker_ids),
'Would you like to stop these workers?')
if click.confirm(msg, default=True, abort=True):
stop_worker(obj['config'],
worker_ids=list(worker_ids) if len(worker_ids) > 0 else None) | [
"def",
"worker_stop",
"(",
"obj",
",",
"worker_ids",
")",
":",
"if",
"len",
"(",
"worker_ids",
")",
"==",
"0",
":",
"msg",
"=",
"'Would you like to stop all workers?'",
"else",
":",
"msg",
"=",
"'\\n{}\\n\\n{}'",
".",
"format",
"(",
"'\\n'",
".",
"join",
"... | Stop running workers.
\b
WORKER_IDS: The IDs of the worker that should be stopped or none to stop them all. | [
"Stop",
"running",
"workers",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/scripts/cli.py#L313-L327 | train |
AustralianSynchrotron/lightflow | lightflow/scripts/cli.py | worker_status | def worker_status(obj, filter_queues, details):
""" Show the status of all running workers. """
show_colors = obj['show_color']
f_queues = filter_queues.split(',') if filter_queues is not None else None
workers = list_workers(config=obj['config'], filter_by_queues=f_queues)
if len(workers) == 0:
click.echo('No workers are running at the moment.')
return
for ws in workers:
click.echo('{} {}'.format(_style(show_colors, 'Worker:', fg='blue', bold=True),
_style(show_colors, ws.name, fg='blue')))
click.echo('{:23} {}'.format(_style(show_colors, '> pid:', bold=True), ws.pid))
if details:
click.echo('{:23} {}'.format(_style(show_colors, '> concurrency:', bold=True),
ws.concurrency))
click.echo('{:23} {}'.format(_style(show_colors, '> processes:', bold=True),
', '.join(str(p) for p in ws.process_pids)))
click.echo('{:23} {}://{}:{}/{}'.format(_style(show_colors, '> broker:',
bold=True),
ws.broker.transport,
ws.broker.hostname,
ws.broker.port,
ws.broker.virtual_host))
click.echo('{:23} {}'.format(_style(show_colors, '> queues:', bold=True),
', '.join([q.name for q in ws.queues])))
if details:
click.echo('{:23} {}'.format(_style(show_colors, '> job count:', bold=True),
ws.job_count))
jobs = list_jobs(config=obj['config'], filter_by_worker=ws.name)
click.echo('{:23} [{}]'.format(_style(show_colors, '> jobs:', bold=True),
len(jobs) if len(jobs) > 0 else 'No tasks'))
for job in jobs:
click.echo('{:15} {} {}'.format(
'',
_style(show_colors, '{}'.format(job.name),
bold=True, fg=JOB_COLOR[job.type]),
_style(show_colors, '({}) [{}] <{}> on {}'.format(
job.type, job.workflow_id, job.id, job.worker_pid),
fg=JOB_COLOR[job.type])))
click.echo('\n') | python | def worker_status(obj, filter_queues, details):
""" Show the status of all running workers. """
show_colors = obj['show_color']
f_queues = filter_queues.split(',') if filter_queues is not None else None
workers = list_workers(config=obj['config'], filter_by_queues=f_queues)
if len(workers) == 0:
click.echo('No workers are running at the moment.')
return
for ws in workers:
click.echo('{} {}'.format(_style(show_colors, 'Worker:', fg='blue', bold=True),
_style(show_colors, ws.name, fg='blue')))
click.echo('{:23} {}'.format(_style(show_colors, '> pid:', bold=True), ws.pid))
if details:
click.echo('{:23} {}'.format(_style(show_colors, '> concurrency:', bold=True),
ws.concurrency))
click.echo('{:23} {}'.format(_style(show_colors, '> processes:', bold=True),
', '.join(str(p) for p in ws.process_pids)))
click.echo('{:23} {}://{}:{}/{}'.format(_style(show_colors, '> broker:',
bold=True),
ws.broker.transport,
ws.broker.hostname,
ws.broker.port,
ws.broker.virtual_host))
click.echo('{:23} {}'.format(_style(show_colors, '> queues:', bold=True),
', '.join([q.name for q in ws.queues])))
if details:
click.echo('{:23} {}'.format(_style(show_colors, '> job count:', bold=True),
ws.job_count))
jobs = list_jobs(config=obj['config'], filter_by_worker=ws.name)
click.echo('{:23} [{}]'.format(_style(show_colors, '> jobs:', bold=True),
len(jobs) if len(jobs) > 0 else 'No tasks'))
for job in jobs:
click.echo('{:15} {} {}'.format(
'',
_style(show_colors, '{}'.format(job.name),
bold=True, fg=JOB_COLOR[job.type]),
_style(show_colors, '({}) [{}] <{}> on {}'.format(
job.type, job.workflow_id, job.id, job.worker_pid),
fg=JOB_COLOR[job.type])))
click.echo('\n') | [
"def",
"worker_status",
"(",
"obj",
",",
"filter_queues",
",",
"details",
")",
":",
"show_colors",
"=",
"obj",
"[",
"'show_color'",
"]",
"f_queues",
"=",
"filter_queues",
".",
"split",
"(",
"','",
")",
"if",
"filter_queues",
"is",
"not",
"None",
"else",
"N... | Show the status of all running workers. | [
"Show",
"the",
"status",
"of",
"all",
"running",
"workers",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/scripts/cli.py#L336-L384 | train |
AustralianSynchrotron/lightflow | lightflow/scripts/cli.py | monitor | def monitor(ctx, details):
""" Show the worker and workflow event stream. """
ingest_config_obj(ctx, silent=False)
show_colors = ctx.obj['show_color']
event_display = {
JobEventName.Started: {'color': 'blue', 'label': 'started'},
JobEventName.Succeeded: {'color': 'green', 'label': 'succeeded'},
JobEventName.Stopped: {'color': 'yellow', 'label': 'stopped'},
JobEventName.Aborted: {'color': 'red', 'label': 'aborted'}
}
click.echo('\n')
click.echo('{:>10} {:>12} {:25} {:18} {:16} {:28} {}'.format(
'Status',
'Type',
'Name',
'Duration (sec)',
'Queue' if details else '',
'Workflow ID' if details else '',
'Worker' if details else ''))
click.echo('-' * (136 if details else 65))
for event in workflow_events(ctx.obj['config']):
evt_disp = event_display[event.event]
click.echo('{:>{}} {:>{}} {:25} {:18} {:16} {:28} {}'.format(
_style(show_colors, evt_disp['label'], fg=evt_disp['color']),
20 if show_colors else 10,
_style(show_colors, event.type, bold=True, fg=JOB_COLOR[event.type]),
24 if show_colors else 12,
event.name,
'{0:.3f}'.format(event.duration) if event.duration is not None else '',
event.queue if details else '',
event.workflow_id if details else '',
event.hostname if details else '')) | python | def monitor(ctx, details):
""" Show the worker and workflow event stream. """
ingest_config_obj(ctx, silent=False)
show_colors = ctx.obj['show_color']
event_display = {
JobEventName.Started: {'color': 'blue', 'label': 'started'},
JobEventName.Succeeded: {'color': 'green', 'label': 'succeeded'},
JobEventName.Stopped: {'color': 'yellow', 'label': 'stopped'},
JobEventName.Aborted: {'color': 'red', 'label': 'aborted'}
}
click.echo('\n')
click.echo('{:>10} {:>12} {:25} {:18} {:16} {:28} {}'.format(
'Status',
'Type',
'Name',
'Duration (sec)',
'Queue' if details else '',
'Workflow ID' if details else '',
'Worker' if details else ''))
click.echo('-' * (136 if details else 65))
for event in workflow_events(ctx.obj['config']):
evt_disp = event_display[event.event]
click.echo('{:>{}} {:>{}} {:25} {:18} {:16} {:28} {}'.format(
_style(show_colors, evt_disp['label'], fg=evt_disp['color']),
20 if show_colors else 10,
_style(show_colors, event.type, bold=True, fg=JOB_COLOR[event.type]),
24 if show_colors else 12,
event.name,
'{0:.3f}'.format(event.duration) if event.duration is not None else '',
event.queue if details else '',
event.workflow_id if details else '',
event.hostname if details else '')) | [
"def",
"monitor",
"(",
"ctx",
",",
"details",
")",
":",
"ingest_config_obj",
"(",
"ctx",
",",
"silent",
"=",
"False",
")",
"show_colors",
"=",
"ctx",
".",
"obj",
"[",
"'show_color'",
"]",
"event_display",
"=",
"{",
"JobEventName",
".",
"Started",
":",
"{... | Show the worker and workflow event stream. | [
"Show",
"the",
"worker",
"and",
"workflow",
"event",
"stream",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/scripts/cli.py#L390-L426 | train |
AustralianSynchrotron/lightflow | lightflow/scripts/cli.py | ext | def ext(obj, ext_name, ext_args):
""" Run an extension by its name.
\b
EXT_NAME: The name of the extension.
EXT_ARGS: Arguments that are passed to the extension.
"""
try:
mod = import_module('lightflow_{}.__main__'.format(ext_name))
mod.main(ext_args)
except ImportError as err:
click.echo(_style(obj['show_color'],
'An error occurred when trying to call the extension',
fg='red', bold=True))
click.echo('{}'.format(err)) | python | def ext(obj, ext_name, ext_args):
""" Run an extension by its name.
\b
EXT_NAME: The name of the extension.
EXT_ARGS: Arguments that are passed to the extension.
"""
try:
mod = import_module('lightflow_{}.__main__'.format(ext_name))
mod.main(ext_args)
except ImportError as err:
click.echo(_style(obj['show_color'],
'An error occurred when trying to call the extension',
fg='red', bold=True))
click.echo('{}'.format(err)) | [
"def",
"ext",
"(",
"obj",
",",
"ext_name",
",",
"ext_args",
")",
":",
"try",
":",
"mod",
"=",
"import_module",
"(",
"'lightflow_{}.__main__'",
".",
"format",
"(",
"ext_name",
")",
")",
"mod",
".",
"main",
"(",
"ext_args",
")",
"except",
"ImportError",
"a... | Run an extension by its name.
\b
EXT_NAME: The name of the extension.
EXT_ARGS: Arguments that are passed to the extension. | [
"Run",
"an",
"extension",
"by",
"its",
"name",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/scripts/cli.py#L433-L447 | train |
AustralianSynchrotron/lightflow | lightflow/scripts/cli.py | _style | def _style(enabled, text, **kwargs):
""" Helper function to enable/disable styled output text.
Args:
enable (bool): Turn on or off styling.
text (string): The string that should be styled.
kwargs (dict): Parameters that are passed through to click.style
Returns:
string: The input with either the styling applied (enabled=True)
or just the text (enabled=False)
"""
if enabled:
return click.style(text, **kwargs)
else:
return text | python | def _style(enabled, text, **kwargs):
""" Helper function to enable/disable styled output text.
Args:
enable (bool): Turn on or off styling.
text (string): The string that should be styled.
kwargs (dict): Parameters that are passed through to click.style
Returns:
string: The input with either the styling applied (enabled=True)
or just the text (enabled=False)
"""
if enabled:
return click.style(text, **kwargs)
else:
return text | [
"def",
"_style",
"(",
"enabled",
",",
"text",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"enabled",
":",
"return",
"click",
".",
"style",
"(",
"text",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"return",
"text"
] | Helper function to enable/disable styled output text.
Args:
enable (bool): Turn on or off styling.
text (string): The string that should be styled.
kwargs (dict): Parameters that are passed through to click.style
Returns:
string: The input with either the styling applied (enabled=True)
or just the text (enabled=False) | [
"Helper",
"function",
"to",
"enable",
"/",
"disable",
"styled",
"output",
"text",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/scripts/cli.py#L450-L465 | train |
dh1tw/pyhamtools | pyhamtools/utils.py | freq_to_band | def freq_to_band(freq):
"""converts a Frequency [kHz] into the band and mode according to the IARU bandplan
Note:
**DEPRECATION NOTICE**
This function has been moved to pyhamtools.frequency with PyHamTools 0.4.1
Please don't use this module/function anymore. It will be removed soon.
"""
band = None
mode = None
if ((freq >= 135) and (freq <= 138)):
band = 2190
mode = const.CW
elif ((freq >= 1800) and (freq <= 2000)):
band = 160
if ((freq >= 1800) and (freq < 1838)):
mode = const.CW
elif ((freq >= 1838) and (freq < 1840)):
mode = const.DIGITAL
elif ((freq >= 1840) and (freq < 2000)):
mode = const.LSB
elif ((freq >= 3500) and (freq <= 4000)):
band = 80
if ((freq >= 3500) and (freq < 3580)):
mode = const.CW
elif ((freq >= 3580) and (freq < 3600)):
mode = const.DIGITAL
elif ((freq >= 3600) and (freq < 4000)):
mode = const.LSB
elif ((freq >= 5000) and (freq <= 5500)):
band = 60
elif ((freq >= 7000) and (freq <= 7300)):
band = 40
if ((freq >= 7000) and (freq < 7040)):
mode = const.CW
elif ((freq >= 7040) and (freq < 7050)):
mode = const.DIGITAL
elif ((freq >= 7050) and (freq < 7300)):
mode = const.LSB
elif ((freq >= 10100) and (freq <= 10150)):
band = 30
if ((freq >= 10100) and (freq < 10140)):
mode = const.CW
elif ((freq >= 10140) and (freq < 10150)):
mode = const.DIGITAL
elif ((freq >= 14000) and (freq <= 14350)):
band = 20
if ((freq >= 14000) and (freq < 14070)):
mode = const.CW
elif ((freq >= 14070) and (freq < 14099)):
mode = const.DIGITAL
elif ((freq >= 14100) and (freq < 14350)):
mode = const.USB
elif ((freq >= 18068) and (freq <= 18268)):
band = 17
if ((freq >= 18068) and (freq < 18095)):
mode = const.CW
elif ((freq >= 18095) and (freq < 18110)):
mode = const.DIGITAL
elif ((freq >= 18110) and (freq < 18268)):
mode = const.USB
elif ((freq >= 21000) and (freq <= 21450)):
band = 15
if ((freq >= 21000) and (freq < 21070)):
mode = const.CW
elif ((freq >= 21070) and (freq < 21150)):
mode = const.DIGITAL
elif ((freq >= 21150) and (freq < 21450)):
mode = const.USB
elif ((freq >= 24890) and (freq <= 24990)):
band = 12
if ((freq >= 24890) and (freq < 24915)):
mode = const.CW
elif ((freq >= 24915) and (freq < 24930)):
mode = const.DIGITAL
elif ((freq >= 24930) and (freq < 24990)):
mode = const.USB
elif ((freq >= 28000) and (freq <= 29700)):
band = 10
if ((freq >= 28000) and (freq < 28070)):
mode = const.CW
elif ((freq >= 28070) and (freq < 28190)):
mode = const.DIGITAL
elif ((freq >= 28300) and (freq < 29700)):
mode = const.USB
elif ((freq >= 50000) and (freq <= 54000)):
band = 6
if ((freq >= 50000) and (freq < 50100)):
mode = const.CW
elif ((freq >= 50100) and (freq < 50500)):
mode = const.USB
elif ((freq >= 50500) and (freq < 51000)):
mode = const.DIGITAL
elif ((freq >= 70000) and (freq <= 71000)):
band = 4
mode = None
elif ((freq >= 144000) and (freq <= 148000)):
band = 2
if ((freq >= 144000) and (freq < 144150)):
mode = const.CW
elif ((freq >= 144150) and (freq < 144400)):
mode = const.USB
elif ((freq >= 144400) and (freq < 148000)):
mode = None
elif ((freq >= 220000) and (freq <= 226000)):
band = 1.25 #1.25m
mode = None
elif ((freq >= 420000) and (freq <= 470000)):
band = 0.7 #70cm
mode = None
elif ((freq >= 902000) and (freq <= 928000)):
band = 0.33 #33cm US
mode = None
elif ((freq >= 1200000) and (freq <= 1300000)):
band = 0.23 #23cm
mode = None
elif ((freq >= 2390000) and (freq <= 2450000)):
band = 0.13 #13cm
mode = None
elif ((freq >= 3300000) and (freq <= 3500000)):
band = 0.09 #9cm
mode = None
elif ((freq >= 5650000) and (freq <= 5850000)):
band = 0.053 #5.3cm
mode = None
elif ((freq >= 10000000) and (freq <= 10500000)):
band = 0.03 #3cm
mode = None
elif ((freq >= 24000000) and (freq <= 24050000)):
band = 0.0125 #1,25cm
mode = None
elif ((freq >= 47000000) and (freq <= 47200000)):
band = 0.0063 #6,3mm
mode = None
else:
raise KeyError
return {"band": band, "mode": mode} | python | def freq_to_band(freq):
"""converts a Frequency [kHz] into the band and mode according to the IARU bandplan
Note:
**DEPRECATION NOTICE**
This function has been moved to pyhamtools.frequency with PyHamTools 0.4.1
Please don't use this module/function anymore. It will be removed soon.
"""
band = None
mode = None
if ((freq >= 135) and (freq <= 138)):
band = 2190
mode = const.CW
elif ((freq >= 1800) and (freq <= 2000)):
band = 160
if ((freq >= 1800) and (freq < 1838)):
mode = const.CW
elif ((freq >= 1838) and (freq < 1840)):
mode = const.DIGITAL
elif ((freq >= 1840) and (freq < 2000)):
mode = const.LSB
elif ((freq >= 3500) and (freq <= 4000)):
band = 80
if ((freq >= 3500) and (freq < 3580)):
mode = const.CW
elif ((freq >= 3580) and (freq < 3600)):
mode = const.DIGITAL
elif ((freq >= 3600) and (freq < 4000)):
mode = const.LSB
elif ((freq >= 5000) and (freq <= 5500)):
band = 60
elif ((freq >= 7000) and (freq <= 7300)):
band = 40
if ((freq >= 7000) and (freq < 7040)):
mode = const.CW
elif ((freq >= 7040) and (freq < 7050)):
mode = const.DIGITAL
elif ((freq >= 7050) and (freq < 7300)):
mode = const.LSB
elif ((freq >= 10100) and (freq <= 10150)):
band = 30
if ((freq >= 10100) and (freq < 10140)):
mode = const.CW
elif ((freq >= 10140) and (freq < 10150)):
mode = const.DIGITAL
elif ((freq >= 14000) and (freq <= 14350)):
band = 20
if ((freq >= 14000) and (freq < 14070)):
mode = const.CW
elif ((freq >= 14070) and (freq < 14099)):
mode = const.DIGITAL
elif ((freq >= 14100) and (freq < 14350)):
mode = const.USB
elif ((freq >= 18068) and (freq <= 18268)):
band = 17
if ((freq >= 18068) and (freq < 18095)):
mode = const.CW
elif ((freq >= 18095) and (freq < 18110)):
mode = const.DIGITAL
elif ((freq >= 18110) and (freq < 18268)):
mode = const.USB
elif ((freq >= 21000) and (freq <= 21450)):
band = 15
if ((freq >= 21000) and (freq < 21070)):
mode = const.CW
elif ((freq >= 21070) and (freq < 21150)):
mode = const.DIGITAL
elif ((freq >= 21150) and (freq < 21450)):
mode = const.USB
elif ((freq >= 24890) and (freq <= 24990)):
band = 12
if ((freq >= 24890) and (freq < 24915)):
mode = const.CW
elif ((freq >= 24915) and (freq < 24930)):
mode = const.DIGITAL
elif ((freq >= 24930) and (freq < 24990)):
mode = const.USB
elif ((freq >= 28000) and (freq <= 29700)):
band = 10
if ((freq >= 28000) and (freq < 28070)):
mode = const.CW
elif ((freq >= 28070) and (freq < 28190)):
mode = const.DIGITAL
elif ((freq >= 28300) and (freq < 29700)):
mode = const.USB
elif ((freq >= 50000) and (freq <= 54000)):
band = 6
if ((freq >= 50000) and (freq < 50100)):
mode = const.CW
elif ((freq >= 50100) and (freq < 50500)):
mode = const.USB
elif ((freq >= 50500) and (freq < 51000)):
mode = const.DIGITAL
elif ((freq >= 70000) and (freq <= 71000)):
band = 4
mode = None
elif ((freq >= 144000) and (freq <= 148000)):
band = 2
if ((freq >= 144000) and (freq < 144150)):
mode = const.CW
elif ((freq >= 144150) and (freq < 144400)):
mode = const.USB
elif ((freq >= 144400) and (freq < 148000)):
mode = None
elif ((freq >= 220000) and (freq <= 226000)):
band = 1.25 #1.25m
mode = None
elif ((freq >= 420000) and (freq <= 470000)):
band = 0.7 #70cm
mode = None
elif ((freq >= 902000) and (freq <= 928000)):
band = 0.33 #33cm US
mode = None
elif ((freq >= 1200000) and (freq <= 1300000)):
band = 0.23 #23cm
mode = None
elif ((freq >= 2390000) and (freq <= 2450000)):
band = 0.13 #13cm
mode = None
elif ((freq >= 3300000) and (freq <= 3500000)):
band = 0.09 #9cm
mode = None
elif ((freq >= 5650000) and (freq <= 5850000)):
band = 0.053 #5.3cm
mode = None
elif ((freq >= 10000000) and (freq <= 10500000)):
band = 0.03 #3cm
mode = None
elif ((freq >= 24000000) and (freq <= 24050000)):
band = 0.0125 #1,25cm
mode = None
elif ((freq >= 47000000) and (freq <= 47200000)):
band = 0.0063 #6,3mm
mode = None
else:
raise KeyError
return {"band": band, "mode": mode} | [
"def",
"freq_to_band",
"(",
"freq",
")",
":",
"band",
"=",
"None",
"mode",
"=",
"None",
"if",
"(",
"(",
"freq",
">=",
"135",
")",
"and",
"(",
"freq",
"<=",
"138",
")",
")",
":",
"band",
"=",
"2190",
"mode",
"=",
"const",
".",
"CW",
"elif",
"(",... | converts a Frequency [kHz] into the band and mode according to the IARU bandplan
Note:
**DEPRECATION NOTICE**
This function has been moved to pyhamtools.frequency with PyHamTools 0.4.1
Please don't use this module/function anymore. It will be removed soon. | [
"converts",
"a",
"Frequency",
"[",
"kHz",
"]",
"into",
"the",
"band",
"and",
"mode",
"according",
"to",
"the",
"IARU",
"bandplan"
] | ee7e4b8732e23c298da10e07163748156c16d0fa | https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/utils.py#L4-L143 | train |
AustralianSynchrotron/lightflow | lightflow/queue/app.py | create_app | def create_app(config):
""" Create a fully configured Celery application object.
Args:
config (Config): A reference to a lightflow configuration object.
Returns:
Celery: A fully configured Celery application object.
"""
# configure the celery logging system with the lightflow settings
setup_logging.connect(partial(_initialize_logging, config), weak=False)
task_postrun.connect(partial(_cleanup_workflow, config), weak=False)
# patch Celery to use cloudpickle instead of pickle for serialisation
patch_celery()
# create the main celery app and load the configuration
app = Celery('lightflow')
app.conf.update(**config.celery)
# overwrite user supplied settings to make sure celery works with lightflow
app.conf.update(
task_serializer='pickle',
accept_content=['pickle'],
result_serializer='pickle',
task_default_queue=DefaultJobQueueName.Task
)
if isinstance(app.conf.include, list):
app.conf.include.extend(LIGHTFLOW_INCLUDE)
else:
if len(app.conf.include) > 0:
raise ConfigOverwriteError(
'The content in the include config will be overwritten')
app.conf.include = LIGHTFLOW_INCLUDE
return app | python | def create_app(config):
""" Create a fully configured Celery application object.
Args:
config (Config): A reference to a lightflow configuration object.
Returns:
Celery: A fully configured Celery application object.
"""
# configure the celery logging system with the lightflow settings
setup_logging.connect(partial(_initialize_logging, config), weak=False)
task_postrun.connect(partial(_cleanup_workflow, config), weak=False)
# patch Celery to use cloudpickle instead of pickle for serialisation
patch_celery()
# create the main celery app and load the configuration
app = Celery('lightflow')
app.conf.update(**config.celery)
# overwrite user supplied settings to make sure celery works with lightflow
app.conf.update(
task_serializer='pickle',
accept_content=['pickle'],
result_serializer='pickle',
task_default_queue=DefaultJobQueueName.Task
)
if isinstance(app.conf.include, list):
app.conf.include.extend(LIGHTFLOW_INCLUDE)
else:
if len(app.conf.include) > 0:
raise ConfigOverwriteError(
'The content in the include config will be overwritten')
app.conf.include = LIGHTFLOW_INCLUDE
return app | [
"def",
"create_app",
"(",
"config",
")",
":",
"# configure the celery logging system with the lightflow settings",
"setup_logging",
".",
"connect",
"(",
"partial",
"(",
"_initialize_logging",
",",
"config",
")",
",",
"weak",
"=",
"False",
")",
"task_postrun",
".",
"co... | Create a fully configured Celery application object.
Args:
config (Config): A reference to a lightflow configuration object.
Returns:
Celery: A fully configured Celery application object. | [
"Create",
"a",
"fully",
"configured",
"Celery",
"application",
"object",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/queue/app.py#L16-L53 | train |
AustralianSynchrotron/lightflow | lightflow/queue/app.py | _cleanup_workflow | def _cleanup_workflow(config, task_id, args, **kwargs):
""" Cleanup the results of a workflow when it finished.
Connects to the postrun signal of Celery. If the signal was sent by a workflow,
remove the result from the result backend.
Args:
task_id (str): The id of the task.
args (tuple): The arguments the task was started with.
**kwargs: Keyword arguments from the hook.
"""
from lightflow.models import Workflow
if isinstance(args[0], Workflow):
if config.celery['result_expires'] == 0:
AsyncResult(task_id).forget() | python | def _cleanup_workflow(config, task_id, args, **kwargs):
""" Cleanup the results of a workflow when it finished.
Connects to the postrun signal of Celery. If the signal was sent by a workflow,
remove the result from the result backend.
Args:
task_id (str): The id of the task.
args (tuple): The arguments the task was started with.
**kwargs: Keyword arguments from the hook.
"""
from lightflow.models import Workflow
if isinstance(args[0], Workflow):
if config.celery['result_expires'] == 0:
AsyncResult(task_id).forget() | [
"def",
"_cleanup_workflow",
"(",
"config",
",",
"task_id",
",",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"lightflow",
".",
"models",
"import",
"Workflow",
"if",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"Workflow",
")",
":",
"if",
"confi... | Cleanup the results of a workflow when it finished.
Connects to the postrun signal of Celery. If the signal was sent by a workflow,
remove the result from the result backend.
Args:
task_id (str): The id of the task.
args (tuple): The arguments the task was started with.
**kwargs: Keyword arguments from the hook. | [
"Cleanup",
"the",
"results",
"of",
"a",
"workflow",
"when",
"it",
"finished",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/queue/app.py#L70-L84 | train |
AustralianSynchrotron/lightflow | lightflow/queue/jobs.py | execute_workflow | def execute_workflow(self, workflow, workflow_id=None):
""" Celery task (aka job) that runs a workflow on a worker.
This celery task starts, manages and monitors the dags that make up a workflow.
Args:
self (Task): Reference to itself, the celery task object.
workflow (Workflow): Reference to the workflow object that is being used to
start, manage and monitor dags.
workflow_id (string): If a workflow ID is provided the workflow run will use
this ID, if not a new ID will be auto generated.
"""
start_time = datetime.utcnow()
logger.info('Running workflow <{}>'.format(workflow.name))
data_store = DataStore(**self.app.user_options['config'].data_store,
auto_connect=True)
# create a unique workflow id for this run
if data_store.exists(workflow_id):
logger.info('Using existing workflow ID: {}'.format(workflow_id))
else:
workflow_id = data_store.add(payload={
'name': workflow.name,
'queue': workflow.queue,
'start_time': start_time
})
logger.info('Created workflow ID: {}'.format(workflow_id))
# send custom celery event that the workflow has been started
self.send_event(JobEventName.Started,
job_type=JobType.Workflow,
name=workflow.name,
queue=workflow.queue,
time=start_time,
workflow_id=workflow_id,
duration=None)
# create server for inter-task messaging
signal_server = Server(SignalConnection(**self.app.user_options['config'].signal,
auto_connect=True),
request_key=workflow_id)
# store job specific meta information wth the job
self.update_state(meta={'name': workflow.name,
'type': JobType.Workflow,
'workflow_id': workflow_id,
'queue': workflow.queue,
'start_time': start_time,
'arguments': workflow.provided_arguments})
# run the DAGs in the workflow
workflow.run(config=self.app.user_options['config'],
data_store=data_store,
signal_server=signal_server,
workflow_id=workflow_id)
end_time = datetime.utcnow()
duration = (end_time - start_time).total_seconds()
# update data store with provenance information
store_doc = data_store.get(workflow_id)
store_doc.set(key='end_time', value=end_time,
section=DataStoreDocumentSection.Meta)
store_doc.set(key='duration', value=duration,
section=DataStoreDocumentSection.Meta)
# send custom celery event that the workflow has succeeded
event_name = JobEventName.Succeeded if not workflow.is_stopped \
else JobEventName.Aborted
self.send_event(event_name,
job_type=JobType.Workflow,
name=workflow.name,
queue=workflow.queue,
time=end_time,
workflow_id=workflow_id,
duration=duration)
logger.info('Finished workflow <{}>'.format(workflow.name)) | python | def execute_workflow(self, workflow, workflow_id=None):
""" Celery task (aka job) that runs a workflow on a worker.
This celery task starts, manages and monitors the dags that make up a workflow.
Args:
self (Task): Reference to itself, the celery task object.
workflow (Workflow): Reference to the workflow object that is being used to
start, manage and monitor dags.
workflow_id (string): If a workflow ID is provided the workflow run will use
this ID, if not a new ID will be auto generated.
"""
start_time = datetime.utcnow()
logger.info('Running workflow <{}>'.format(workflow.name))
data_store = DataStore(**self.app.user_options['config'].data_store,
auto_connect=True)
# create a unique workflow id for this run
if data_store.exists(workflow_id):
logger.info('Using existing workflow ID: {}'.format(workflow_id))
else:
workflow_id = data_store.add(payload={
'name': workflow.name,
'queue': workflow.queue,
'start_time': start_time
})
logger.info('Created workflow ID: {}'.format(workflow_id))
# send custom celery event that the workflow has been started
self.send_event(JobEventName.Started,
job_type=JobType.Workflow,
name=workflow.name,
queue=workflow.queue,
time=start_time,
workflow_id=workflow_id,
duration=None)
# create server for inter-task messaging
signal_server = Server(SignalConnection(**self.app.user_options['config'].signal,
auto_connect=True),
request_key=workflow_id)
# store job specific meta information wth the job
self.update_state(meta={'name': workflow.name,
'type': JobType.Workflow,
'workflow_id': workflow_id,
'queue': workflow.queue,
'start_time': start_time,
'arguments': workflow.provided_arguments})
# run the DAGs in the workflow
workflow.run(config=self.app.user_options['config'],
data_store=data_store,
signal_server=signal_server,
workflow_id=workflow_id)
end_time = datetime.utcnow()
duration = (end_time - start_time).total_seconds()
# update data store with provenance information
store_doc = data_store.get(workflow_id)
store_doc.set(key='end_time', value=end_time,
section=DataStoreDocumentSection.Meta)
store_doc.set(key='duration', value=duration,
section=DataStoreDocumentSection.Meta)
# send custom celery event that the workflow has succeeded
event_name = JobEventName.Succeeded if not workflow.is_stopped \
else JobEventName.Aborted
self.send_event(event_name,
job_type=JobType.Workflow,
name=workflow.name,
queue=workflow.queue,
time=end_time,
workflow_id=workflow_id,
duration=duration)
logger.info('Finished workflow <{}>'.format(workflow.name)) | [
"def",
"execute_workflow",
"(",
"self",
",",
"workflow",
",",
"workflow_id",
"=",
"None",
")",
":",
"start_time",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"logger",
".",
"info",
"(",
"'Running workflow <{}>'",
".",
"format",
"(",
"workflow",
".",
"name",
... | Celery task (aka job) that runs a workflow on a worker.
This celery task starts, manages and monitors the dags that make up a workflow.
Args:
self (Task): Reference to itself, the celery task object.
workflow (Workflow): Reference to the workflow object that is being used to
start, manage and monitor dags.
workflow_id (string): If a workflow ID is provided the workflow run will use
this ID, if not a new ID will be auto generated. | [
"Celery",
"task",
"(",
"aka",
"job",
")",
"that",
"runs",
"a",
"workflow",
"on",
"a",
"worker",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/queue/jobs.py#L17-L96 | train |
AustralianSynchrotron/lightflow | lightflow/queue/jobs.py | execute_dag | def execute_dag(self, dag, workflow_id, data=None):
""" Celery task that runs a single dag on a worker.
This celery task starts, manages and monitors the individual tasks of a dag.
Args:
self (Task): Reference to itself, the celery task object.
dag (Dag): Reference to a Dag object that is being used to start, manage and
monitor tasks.
workflow_id (string): The unique ID of the workflow run that started this dag.
data (MultiTaskData): An optional MultiTaskData object that is being passed to
the first tasks in the dag. This allows the transfer of
data from dag to dag.
"""
start_time = datetime.utcnow()
logger.info('Running DAG <{}>'.format(dag.name))
store_doc = DataStore(**self.app.user_options['config'].data_store,
auto_connect=True).get(workflow_id)
store_loc = 'log.{}'.format(dag.name)
# update data store with provenance information
store_doc.set(key='{}.start_time'.format(store_loc), value=start_time,
section=DataStoreDocumentSection.Meta)
# send custom celery event that the dag has been started
self.send_event(JobEventName.Started,
job_type=JobType.Dag,
name=dag.name,
queue=dag.queue,
time=start_time,
workflow_id=workflow_id,
duration=None)
# store job specific meta information wth the job
self.update_state(meta={'name': dag.name,
'queue': dag.queue,
'type': JobType.Dag,
'workflow_id': workflow_id})
# run the tasks in the DAG
signal = DagSignal(Client(SignalConnection(**self.app.user_options['config'].signal,
auto_connect=True),
request_key=workflow_id), dag.name)
dag.run(config=self.app.user_options['config'],
workflow_id=workflow_id,
signal=signal,
data=data)
end_time = datetime.utcnow()
duration = (end_time - start_time).total_seconds()
# update data store with provenance information
store_doc.set(key='{}.end_time'.format(store_loc), value=end_time,
section=DataStoreDocumentSection.Meta)
store_doc.set(key='{}.duration'.format(store_loc), value=duration,
section=DataStoreDocumentSection.Meta)
# send custom celery event that the dag has succeeded
event_name = JobEventName.Succeeded if not signal.is_stopped else JobEventName.Aborted
self.send_event(event_name,
job_type=JobType.Dag,
name=dag.name,
queue=dag.queue,
time=end_time,
workflow_id=workflow_id,
duration=duration)
logger.info('Finished DAG <{}>'.format(dag.name)) | python | def execute_dag(self, dag, workflow_id, data=None):
""" Celery task that runs a single dag on a worker.
This celery task starts, manages and monitors the individual tasks of a dag.
Args:
self (Task): Reference to itself, the celery task object.
dag (Dag): Reference to a Dag object that is being used to start, manage and
monitor tasks.
workflow_id (string): The unique ID of the workflow run that started this dag.
data (MultiTaskData): An optional MultiTaskData object that is being passed to
the first tasks in the dag. This allows the transfer of
data from dag to dag.
"""
start_time = datetime.utcnow()
logger.info('Running DAG <{}>'.format(dag.name))
store_doc = DataStore(**self.app.user_options['config'].data_store,
auto_connect=True).get(workflow_id)
store_loc = 'log.{}'.format(dag.name)
# update data store with provenance information
store_doc.set(key='{}.start_time'.format(store_loc), value=start_time,
section=DataStoreDocumentSection.Meta)
# send custom celery event that the dag has been started
self.send_event(JobEventName.Started,
job_type=JobType.Dag,
name=dag.name,
queue=dag.queue,
time=start_time,
workflow_id=workflow_id,
duration=None)
# store job specific meta information wth the job
self.update_state(meta={'name': dag.name,
'queue': dag.queue,
'type': JobType.Dag,
'workflow_id': workflow_id})
# run the tasks in the DAG
signal = DagSignal(Client(SignalConnection(**self.app.user_options['config'].signal,
auto_connect=True),
request_key=workflow_id), dag.name)
dag.run(config=self.app.user_options['config'],
workflow_id=workflow_id,
signal=signal,
data=data)
end_time = datetime.utcnow()
duration = (end_time - start_time).total_seconds()
# update data store with provenance information
store_doc.set(key='{}.end_time'.format(store_loc), value=end_time,
section=DataStoreDocumentSection.Meta)
store_doc.set(key='{}.duration'.format(store_loc), value=duration,
section=DataStoreDocumentSection.Meta)
# send custom celery event that the dag has succeeded
event_name = JobEventName.Succeeded if not signal.is_stopped else JobEventName.Aborted
self.send_event(event_name,
job_type=JobType.Dag,
name=dag.name,
queue=dag.queue,
time=end_time,
workflow_id=workflow_id,
duration=duration)
logger.info('Finished DAG <{}>'.format(dag.name)) | [
"def",
"execute_dag",
"(",
"self",
",",
"dag",
",",
"workflow_id",
",",
"data",
"=",
"None",
")",
":",
"start_time",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"logger",
".",
"info",
"(",
"'Running DAG <{}>'",
".",
"format",
"(",
"dag",
".",
"name",
")"... | Celery task that runs a single dag on a worker.
This celery task starts, manages and monitors the individual tasks of a dag.
Args:
self (Task): Reference to itself, the celery task object.
dag (Dag): Reference to a Dag object that is being used to start, manage and
monitor tasks.
workflow_id (string): The unique ID of the workflow run that started this dag.
data (MultiTaskData): An optional MultiTaskData object that is being passed to
the first tasks in the dag. This allows the transfer of
data from dag to dag. | [
"Celery",
"task",
"that",
"runs",
"a",
"single",
"dag",
"on",
"a",
"worker",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/queue/jobs.py#L100-L168 | train |
AustralianSynchrotron/lightflow | lightflow/queue/jobs.py | execute_task | def execute_task(self, task, workflow_id, data=None):
""" Celery task that runs a single task on a worker.
Args:
self (Task): Reference to itself, the celery task object.
task (BaseTask): Reference to the task object that performs the work
in its run() method.
workflow_id (string): The unique ID of the workflow run that started this task.
data (MultiTaskData): An optional MultiTaskData object that contains the data
that has been passed down from upstream tasks.
"""
start_time = datetime.utcnow()
store_doc = DataStore(**self.app.user_options['config'].data_store,
auto_connect=True).get(workflow_id)
store_loc = 'log.{}.tasks.{}'.format(task.dag_name, task.name)
def handle_callback(message, event_type, exc=None):
msg = '{}: {}'.format(message, str(exc)) if exc is not None else message
# set the logging level
if event_type == JobEventName.Stopped:
logger.warning(msg)
elif event_type == JobEventName.Aborted:
logger.error(msg)
else:
logger.info(msg)
current_time = datetime.utcnow()
# store provenance information about a task
if event_type != JobEventName.Started:
duration = (current_time - start_time).total_seconds()
store_doc.set(key='{}.end_time'.format(store_loc),
value=current_time,
section=DataStoreDocumentSection.Meta)
store_doc.set(key='{}.duration'.format(store_loc),
value=duration,
section=DataStoreDocumentSection.Meta)
else:
# store provenance information about a task
store_doc.set(key='{}.start_time'.format(store_loc),
value=start_time,
section=DataStoreDocumentSection.Meta)
store_doc.set(key='{}.worker'.format(store_loc),
value=self.request.hostname,
section=DataStoreDocumentSection.Meta)
store_doc.set(key='{}.queue'.format(store_loc),
value=task.queue,
section=DataStoreDocumentSection.Meta)
duration = None
# send custom celery event
self.send_event(event_type,
job_type=JobType.Task,
name=task.name,
queue=task.queue,
time=current_time,
workflow_id=workflow_id,
duration=duration)
# store job specific meta information wth the job
self.update_state(meta={'name': task.name,
'queue': task.queue,
'type': JobType.Task,
'workflow_id': workflow_id})
# send start celery event
handle_callback('Start task <{}>'.format(task.name), JobEventName.Started)
# run the task and capture the result
return task._run(
data=data,
store=store_doc,
signal=TaskSignal(Client(
SignalConnection(**self.app.user_options['config'].signal, auto_connect=True),
request_key=workflow_id),
task.dag_name),
context=TaskContext(task.name, task.dag_name, task.workflow_name,
workflow_id, self.request.hostname),
success_callback=partial(handle_callback,
message='Complete task <{}>'.format(task.name),
event_type=JobEventName.Succeeded),
stop_callback=partial(handle_callback,
message='Stop task <{}>'.format(task.name),
event_type=JobEventName.Stopped),
abort_callback=partial(handle_callback,
message='Abort workflow <{}> by task <{}>'.format(
task.workflow_name, task.name),
event_type=JobEventName.Aborted)) | python | def execute_task(self, task, workflow_id, data=None):
""" Celery task that runs a single task on a worker.
Args:
self (Task): Reference to itself, the celery task object.
task (BaseTask): Reference to the task object that performs the work
in its run() method.
workflow_id (string): The unique ID of the workflow run that started this task.
data (MultiTaskData): An optional MultiTaskData object that contains the data
that has been passed down from upstream tasks.
"""
start_time = datetime.utcnow()
store_doc = DataStore(**self.app.user_options['config'].data_store,
auto_connect=True).get(workflow_id)
store_loc = 'log.{}.tasks.{}'.format(task.dag_name, task.name)
def handle_callback(message, event_type, exc=None):
msg = '{}: {}'.format(message, str(exc)) if exc is not None else message
# set the logging level
if event_type == JobEventName.Stopped:
logger.warning(msg)
elif event_type == JobEventName.Aborted:
logger.error(msg)
else:
logger.info(msg)
current_time = datetime.utcnow()
# store provenance information about a task
if event_type != JobEventName.Started:
duration = (current_time - start_time).total_seconds()
store_doc.set(key='{}.end_time'.format(store_loc),
value=current_time,
section=DataStoreDocumentSection.Meta)
store_doc.set(key='{}.duration'.format(store_loc),
value=duration,
section=DataStoreDocumentSection.Meta)
else:
# store provenance information about a task
store_doc.set(key='{}.start_time'.format(store_loc),
value=start_time,
section=DataStoreDocumentSection.Meta)
store_doc.set(key='{}.worker'.format(store_loc),
value=self.request.hostname,
section=DataStoreDocumentSection.Meta)
store_doc.set(key='{}.queue'.format(store_loc),
value=task.queue,
section=DataStoreDocumentSection.Meta)
duration = None
# send custom celery event
self.send_event(event_type,
job_type=JobType.Task,
name=task.name,
queue=task.queue,
time=current_time,
workflow_id=workflow_id,
duration=duration)
# store job specific meta information wth the job
self.update_state(meta={'name': task.name,
'queue': task.queue,
'type': JobType.Task,
'workflow_id': workflow_id})
# send start celery event
handle_callback('Start task <{}>'.format(task.name), JobEventName.Started)
# run the task and capture the result
return task._run(
data=data,
store=store_doc,
signal=TaskSignal(Client(
SignalConnection(**self.app.user_options['config'].signal, auto_connect=True),
request_key=workflow_id),
task.dag_name),
context=TaskContext(task.name, task.dag_name, task.workflow_name,
workflow_id, self.request.hostname),
success_callback=partial(handle_callback,
message='Complete task <{}>'.format(task.name),
event_type=JobEventName.Succeeded),
stop_callback=partial(handle_callback,
message='Stop task <{}>'.format(task.name),
event_type=JobEventName.Stopped),
abort_callback=partial(handle_callback,
message='Abort workflow <{}> by task <{}>'.format(
task.workflow_name, task.name),
event_type=JobEventName.Aborted)) | [
"def",
"execute_task",
"(",
"self",
",",
"task",
",",
"workflow_id",
",",
"data",
"=",
"None",
")",
":",
"start_time",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"store_doc",
"=",
"DataStore",
"(",
"*",
"*",
"self",
".",
"app",
".",
"user_options",
"[",... | Celery task that runs a single task on a worker.
Args:
self (Task): Reference to itself, the celery task object.
task (BaseTask): Reference to the task object that performs the work
in its run() method.
workflow_id (string): The unique ID of the workflow run that started this task.
data (MultiTaskData): An optional MultiTaskData object that contains the data
that has been passed down from upstream tasks. | [
"Celery",
"task",
"that",
"runs",
"a",
"single",
"task",
"on",
"a",
"worker",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/queue/jobs.py#L172-L265 | train |
AustralianSynchrotron/lightflow | lightflow/queue/models.py | BrokerStats.from_celery | def from_celery(cls, broker_dict):
""" Create a BrokerStats object from the dictionary returned by celery.
Args:
broker_dict (dict): The dictionary as returned by celery.
Returns:
BrokerStats: A fully initialized BrokerStats object.
"""
return BrokerStats(
hostname=broker_dict['hostname'],
port=broker_dict['port'],
transport=broker_dict['transport'],
virtual_host=broker_dict['virtual_host']
) | python | def from_celery(cls, broker_dict):
""" Create a BrokerStats object from the dictionary returned by celery.
Args:
broker_dict (dict): The dictionary as returned by celery.
Returns:
BrokerStats: A fully initialized BrokerStats object.
"""
return BrokerStats(
hostname=broker_dict['hostname'],
port=broker_dict['port'],
transport=broker_dict['transport'],
virtual_host=broker_dict['virtual_host']
) | [
"def",
"from_celery",
"(",
"cls",
",",
"broker_dict",
")",
":",
"return",
"BrokerStats",
"(",
"hostname",
"=",
"broker_dict",
"[",
"'hostname'",
"]",
",",
"port",
"=",
"broker_dict",
"[",
"'port'",
"]",
",",
"transport",
"=",
"broker_dict",
"[",
"'transport'... | Create a BrokerStats object from the dictionary returned by celery.
Args:
broker_dict (dict): The dictionary as returned by celery.
Returns:
BrokerStats: A fully initialized BrokerStats object. | [
"Create",
"a",
"BrokerStats",
"object",
"from",
"the",
"dictionary",
"returned",
"by",
"celery",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/queue/models.py#L22-L36 | train |
AustralianSynchrotron/lightflow | lightflow/queue/models.py | BrokerStats.to_dict | def to_dict(self):
""" Return a dictionary of the broker stats.
Returns:
dict: Dictionary of the stats.
"""
return {
'hostname': self.hostname,
'port': self.port,
'transport': self.transport,
'virtual_host': self.virtual_host
} | python | def to_dict(self):
""" Return a dictionary of the broker stats.
Returns:
dict: Dictionary of the stats.
"""
return {
'hostname': self.hostname,
'port': self.port,
'transport': self.transport,
'virtual_host': self.virtual_host
} | [
"def",
"to_dict",
"(",
"self",
")",
":",
"return",
"{",
"'hostname'",
":",
"self",
".",
"hostname",
",",
"'port'",
":",
"self",
".",
"port",
",",
"'transport'",
":",
"self",
".",
"transport",
",",
"'virtual_host'",
":",
"self",
".",
"virtual_host",
"}"
] | Return a dictionary of the broker stats.
Returns:
dict: Dictionary of the stats. | [
"Return",
"a",
"dictionary",
"of",
"the",
"broker",
"stats",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/queue/models.py#L38-L49 | train |
AustralianSynchrotron/lightflow | lightflow/queue/models.py | WorkerStats.from_celery | def from_celery(cls, name, worker_dict, queues):
""" Create a WorkerStats object from the dictionary returned by celery.
Args:
name (str): The name of the worker.
worker_dict (dict): The dictionary as returned by celery.
queues (list): A list of QueueStats objects that represent the queues this
worker is listening on.
Returns:
WorkerStats: A fully initialized WorkerStats object.
"""
return WorkerStats(
name=name,
broker=BrokerStats.from_celery(worker_dict['broker']),
pid=worker_dict['pid'],
process_pids=worker_dict['pool']['processes'],
concurrency=worker_dict['pool']['max-concurrency'],
job_count=worker_dict['pool']['writes']['total'],
queues=queues
) | python | def from_celery(cls, name, worker_dict, queues):
""" Create a WorkerStats object from the dictionary returned by celery.
Args:
name (str): The name of the worker.
worker_dict (dict): The dictionary as returned by celery.
queues (list): A list of QueueStats objects that represent the queues this
worker is listening on.
Returns:
WorkerStats: A fully initialized WorkerStats object.
"""
return WorkerStats(
name=name,
broker=BrokerStats.from_celery(worker_dict['broker']),
pid=worker_dict['pid'],
process_pids=worker_dict['pool']['processes'],
concurrency=worker_dict['pool']['max-concurrency'],
job_count=worker_dict['pool']['writes']['total'],
queues=queues
) | [
"def",
"from_celery",
"(",
"cls",
",",
"name",
",",
"worker_dict",
",",
"queues",
")",
":",
"return",
"WorkerStats",
"(",
"name",
"=",
"name",
",",
"broker",
"=",
"BrokerStats",
".",
"from_celery",
"(",
"worker_dict",
"[",
"'broker'",
"]",
")",
",",
"pid... | Create a WorkerStats object from the dictionary returned by celery.
Args:
name (str): The name of the worker.
worker_dict (dict): The dictionary as returned by celery.
queues (list): A list of QueueStats objects that represent the queues this
worker is listening on.
Returns:
WorkerStats: A fully initialized WorkerStats object. | [
"Create",
"a",
"WorkerStats",
"object",
"from",
"the",
"dictionary",
"returned",
"by",
"celery",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/queue/models.py#L114-L134 | train |
AustralianSynchrotron/lightflow | lightflow/queue/models.py | WorkerStats.to_dict | def to_dict(self):
""" Return a dictionary of the worker stats.
Returns:
dict: Dictionary of the stats.
"""
return {
'name': self.name,
'broker': self.broker.to_dict(),
'pid': self.pid,
'process_pids': self.process_pids,
'concurrency': self.concurrency,
'job_count': self.job_count,
'queues': [q.to_dict() for q in self.queues]
} | python | def to_dict(self):
""" Return a dictionary of the worker stats.
Returns:
dict: Dictionary of the stats.
"""
return {
'name': self.name,
'broker': self.broker.to_dict(),
'pid': self.pid,
'process_pids': self.process_pids,
'concurrency': self.concurrency,
'job_count': self.job_count,
'queues': [q.to_dict() for q in self.queues]
} | [
"def",
"to_dict",
"(",
"self",
")",
":",
"return",
"{",
"'name'",
":",
"self",
".",
"name",
",",
"'broker'",
":",
"self",
".",
"broker",
".",
"to_dict",
"(",
")",
",",
"'pid'",
":",
"self",
".",
"pid",
",",
"'process_pids'",
":",
"self",
".",
"proc... | Return a dictionary of the worker stats.
Returns:
dict: Dictionary of the stats. | [
"Return",
"a",
"dictionary",
"of",
"the",
"worker",
"stats",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/queue/models.py#L136-L150 | train |
AustralianSynchrotron/lightflow | lightflow/queue/models.py | JobStats.from_celery | def from_celery(cls, worker_name, job_dict, celery_app):
""" Create a JobStats object from the dictionary returned by celery.
Args:
worker_name (str): The name of the worker this jobs runs on.
job_dict (dict): The dictionary as returned by celery.
celery_app: Reference to a celery application object.
Returns:
JobStats: A fully initialized JobStats object.
"""
if not isinstance(job_dict, dict) or 'id' not in job_dict:
raise JobStatInvalid('The job description is missing important fields.')
async_result = AsyncResult(id=job_dict['id'], app=celery_app)
a_info = async_result.info if isinstance(async_result.info, dict) else None
return JobStats(
name=a_info.get('name', '') if a_info is not None else '',
job_id=job_dict['id'],
job_type=a_info.get('type', '') if a_info is not None else '',
workflow_id=a_info.get('workflow_id', '') if a_info is not None else '',
queue=a_info.get('queue', '') if a_info is not None else '',
start_time=a_info.get('start_time', None) if a_info is not None else None,
arguments=a_info.get('arguments', {}) if a_info is not None else {},
acknowledged=job_dict['acknowledged'],
func_name=job_dict['type'],
hostname=job_dict['hostname'],
worker_name=worker_name,
worker_pid=job_dict['worker_pid'],
routing_key=job_dict['delivery_info']['routing_key']
) | python | def from_celery(cls, worker_name, job_dict, celery_app):
""" Create a JobStats object from the dictionary returned by celery.
Args:
worker_name (str): The name of the worker this jobs runs on.
job_dict (dict): The dictionary as returned by celery.
celery_app: Reference to a celery application object.
Returns:
JobStats: A fully initialized JobStats object.
"""
if not isinstance(job_dict, dict) or 'id' not in job_dict:
raise JobStatInvalid('The job description is missing important fields.')
async_result = AsyncResult(id=job_dict['id'], app=celery_app)
a_info = async_result.info if isinstance(async_result.info, dict) else None
return JobStats(
name=a_info.get('name', '') if a_info is not None else '',
job_id=job_dict['id'],
job_type=a_info.get('type', '') if a_info is not None else '',
workflow_id=a_info.get('workflow_id', '') if a_info is not None else '',
queue=a_info.get('queue', '') if a_info is not None else '',
start_time=a_info.get('start_time', None) if a_info is not None else None,
arguments=a_info.get('arguments', {}) if a_info is not None else {},
acknowledged=job_dict['acknowledged'],
func_name=job_dict['type'],
hostname=job_dict['hostname'],
worker_name=worker_name,
worker_pid=job_dict['worker_pid'],
routing_key=job_dict['delivery_info']['routing_key']
) | [
"def",
"from_celery",
"(",
"cls",
",",
"worker_name",
",",
"job_dict",
",",
"celery_app",
")",
":",
"if",
"not",
"isinstance",
"(",
"job_dict",
",",
"dict",
")",
"or",
"'id'",
"not",
"in",
"job_dict",
":",
"raise",
"JobStatInvalid",
"(",
"'The job descriptio... | Create a JobStats object from the dictionary returned by celery.
Args:
worker_name (str): The name of the worker this jobs runs on.
job_dict (dict): The dictionary as returned by celery.
celery_app: Reference to a celery application object.
Returns:
JobStats: A fully initialized JobStats object. | [
"Create",
"a",
"JobStats",
"object",
"from",
"the",
"dictionary",
"returned",
"by",
"celery",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/queue/models.py#L188-L219 | train |
AustralianSynchrotron/lightflow | lightflow/queue/models.py | JobStats.to_dict | def to_dict(self):
""" Return a dictionary of the job stats.
Returns:
dict: Dictionary of the stats.
"""
return {
'name': self.name,
'id': self.id,
'type': self.type,
'workflow_id': self.workflow_id,
'queue': self.queue,
'start_time': self.start_time,
'arguments': self.arguments,
'acknowledged': self.acknowledged,
'func_name': self.func_name,
'hostname': self.hostname,
'worker_name': self.worker_name,
'worker_pid': self.worker_pid,
'routing_key': self.routing_key
} | python | def to_dict(self):
""" Return a dictionary of the job stats.
Returns:
dict: Dictionary of the stats.
"""
return {
'name': self.name,
'id': self.id,
'type': self.type,
'workflow_id': self.workflow_id,
'queue': self.queue,
'start_time': self.start_time,
'arguments': self.arguments,
'acknowledged': self.acknowledged,
'func_name': self.func_name,
'hostname': self.hostname,
'worker_name': self.worker_name,
'worker_pid': self.worker_pid,
'routing_key': self.routing_key
} | [
"def",
"to_dict",
"(",
"self",
")",
":",
"return",
"{",
"'name'",
":",
"self",
".",
"name",
",",
"'id'",
":",
"self",
".",
"id",
",",
"'type'",
":",
"self",
".",
"type",
",",
"'workflow_id'",
":",
"self",
".",
"workflow_id",
",",
"'queue'",
":",
"s... | Return a dictionary of the job stats.
Returns:
dict: Dictionary of the stats. | [
"Return",
"a",
"dictionary",
"of",
"the",
"job",
"stats",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/queue/models.py#L221-L241 | train |
AustralianSynchrotron/lightflow | lightflow/queue/models.py | JobEvent.from_event | def from_event(cls, event):
""" Create a JobEvent object from the event dictionary returned by celery.
Args:
event (dict): The dictionary as returned by celery.
Returns:
JobEvent: A fully initialized JobEvent object.
"""
return cls(
uuid=event['uuid'],
job_type=event['job_type'],
event_type=event['type'],
queue=event['queue'],
hostname=event['hostname'],
pid=event['pid'],
name=event['name'],
workflow_id=event['workflow_id'],
event_time=event['time'],
duration=event['duration']
) | python | def from_event(cls, event):
""" Create a JobEvent object from the event dictionary returned by celery.
Args:
event (dict): The dictionary as returned by celery.
Returns:
JobEvent: A fully initialized JobEvent object.
"""
return cls(
uuid=event['uuid'],
job_type=event['job_type'],
event_type=event['type'],
queue=event['queue'],
hostname=event['hostname'],
pid=event['pid'],
name=event['name'],
workflow_id=event['workflow_id'],
event_time=event['time'],
duration=event['duration']
) | [
"def",
"from_event",
"(",
"cls",
",",
"event",
")",
":",
"return",
"cls",
"(",
"uuid",
"=",
"event",
"[",
"'uuid'",
"]",
",",
"job_type",
"=",
"event",
"[",
"'job_type'",
"]",
",",
"event_type",
"=",
"event",
"[",
"'type'",
"]",
",",
"queue",
"=",
... | Create a JobEvent object from the event dictionary returned by celery.
Args:
event (dict): The dictionary as returned by celery.
Returns:
JobEvent: A fully initialized JobEvent object. | [
"Create",
"a",
"JobEvent",
"object",
"from",
"the",
"event",
"dictionary",
"returned",
"by",
"celery",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/queue/models.py#L273-L293 | train |
AustralianSynchrotron/lightflow | lightflow/workflows.py | start_workflow | def start_workflow(name, config, *, queue=DefaultJobQueueName.Workflow,
clear_data_store=True, store_args=None):
""" Start a single workflow by sending it to the workflow queue.
Args:
name (str): The name of the workflow that should be started. Refers to the
name of the workflow file without the .py extension.
config (Config): Reference to the configuration object from which the
settings for the workflow are retrieved.
queue (str): Name of the queue the workflow should be scheduled to.
clear_data_store (bool): Remove any documents created during the workflow
run in the data store after the run.
store_args (dict): Dictionary of additional arguments that are ingested into the
data store prior to the execution of the workflow.
Returns:
str: The ID of the workflow job.
Raises:
WorkflowArgumentError: If the workflow requires arguments to be set in store_args
that were not supplied to the workflow.
WorkflowImportError: If the import of the workflow fails.
"""
try:
wf = Workflow.from_name(name,
queue=queue,
clear_data_store=clear_data_store,
arguments=store_args)
except DirectedAcyclicGraphInvalid as e:
raise WorkflowDefinitionError(workflow_name=name,
graph_name=e.graph_name)
celery_app = create_app(config)
result = celery_app.send_task(JobExecPath.Workflow,
args=(wf,), queue=queue, routing_key=queue)
return result.id | python | def start_workflow(name, config, *, queue=DefaultJobQueueName.Workflow,
clear_data_store=True, store_args=None):
""" Start a single workflow by sending it to the workflow queue.
Args:
name (str): The name of the workflow that should be started. Refers to the
name of the workflow file without the .py extension.
config (Config): Reference to the configuration object from which the
settings for the workflow are retrieved.
queue (str): Name of the queue the workflow should be scheduled to.
clear_data_store (bool): Remove any documents created during the workflow
run in the data store after the run.
store_args (dict): Dictionary of additional arguments that are ingested into the
data store prior to the execution of the workflow.
Returns:
str: The ID of the workflow job.
Raises:
WorkflowArgumentError: If the workflow requires arguments to be set in store_args
that were not supplied to the workflow.
WorkflowImportError: If the import of the workflow fails.
"""
try:
wf = Workflow.from_name(name,
queue=queue,
clear_data_store=clear_data_store,
arguments=store_args)
except DirectedAcyclicGraphInvalid as e:
raise WorkflowDefinitionError(workflow_name=name,
graph_name=e.graph_name)
celery_app = create_app(config)
result = celery_app.send_task(JobExecPath.Workflow,
args=(wf,), queue=queue, routing_key=queue)
return result.id | [
"def",
"start_workflow",
"(",
"name",
",",
"config",
",",
"*",
",",
"queue",
"=",
"DefaultJobQueueName",
".",
"Workflow",
",",
"clear_data_store",
"=",
"True",
",",
"store_args",
"=",
"None",
")",
":",
"try",
":",
"wf",
"=",
"Workflow",
".",
"from_name",
... | Start a single workflow by sending it to the workflow queue.
Args:
name (str): The name of the workflow that should be started. Refers to the
name of the workflow file without the .py extension.
config (Config): Reference to the configuration object from which the
settings for the workflow are retrieved.
queue (str): Name of the queue the workflow should be scheduled to.
clear_data_store (bool): Remove any documents created during the workflow
run in the data store after the run.
store_args (dict): Dictionary of additional arguments that are ingested into the
data store prior to the execution of the workflow.
Returns:
str: The ID of the workflow job.
Raises:
WorkflowArgumentError: If the workflow requires arguments to be set in store_args
that were not supplied to the workflow.
WorkflowImportError: If the import of the workflow fails. | [
"Start",
"a",
"single",
"workflow",
"by",
"sending",
"it",
"to",
"the",
"workflow",
"queue",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/workflows.py#L16-L49 | train |
AustralianSynchrotron/lightflow | lightflow/workflows.py | stop_workflow | def stop_workflow(config, *, names=None):
""" Stop one or more workflows.
Args:
config (Config): Reference to the configuration object from which the
settings for the workflow are retrieved.
names (list): List of workflow names, workflow ids or workflow job ids for the
workflows that should be stopped. If all workflows should be
stopped, set it to None.
Returns:
tuple: A tuple of the workflow jobs that were successfully stopped and the ones
that could not be stopped.
"""
jobs = list_jobs(config, filter_by_type=JobType.Workflow)
if names is not None:
filtered_jobs = []
for job in jobs:
if (job.id in names) or (job.name in names) or (job.workflow_id in names):
filtered_jobs.append(job)
else:
filtered_jobs = jobs
success = []
failed = []
for job in filtered_jobs:
client = Client(SignalConnection(**config.signal, auto_connect=True),
request_key=job.workflow_id)
if client.send(Request(action='stop_workflow')).success:
success.append(job)
else:
failed.append(job)
return success, failed | python | def stop_workflow(config, *, names=None):
""" Stop one or more workflows.
Args:
config (Config): Reference to the configuration object from which the
settings for the workflow are retrieved.
names (list): List of workflow names, workflow ids or workflow job ids for the
workflows that should be stopped. If all workflows should be
stopped, set it to None.
Returns:
tuple: A tuple of the workflow jobs that were successfully stopped and the ones
that could not be stopped.
"""
jobs = list_jobs(config, filter_by_type=JobType.Workflow)
if names is not None:
filtered_jobs = []
for job in jobs:
if (job.id in names) or (job.name in names) or (job.workflow_id in names):
filtered_jobs.append(job)
else:
filtered_jobs = jobs
success = []
failed = []
for job in filtered_jobs:
client = Client(SignalConnection(**config.signal, auto_connect=True),
request_key=job.workflow_id)
if client.send(Request(action='stop_workflow')).success:
success.append(job)
else:
failed.append(job)
return success, failed | [
"def",
"stop_workflow",
"(",
"config",
",",
"*",
",",
"names",
"=",
"None",
")",
":",
"jobs",
"=",
"list_jobs",
"(",
"config",
",",
"filter_by_type",
"=",
"JobType",
".",
"Workflow",
")",
"if",
"names",
"is",
"not",
"None",
":",
"filtered_jobs",
"=",
"... | Stop one or more workflows.
Args:
config (Config): Reference to the configuration object from which the
settings for the workflow are retrieved.
names (list): List of workflow names, workflow ids or workflow job ids for the
workflows that should be stopped. If all workflows should be
stopped, set it to None.
Returns:
tuple: A tuple of the workflow jobs that were successfully stopped and the ones
that could not be stopped. | [
"Stop",
"one",
"or",
"more",
"workflows",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/workflows.py#L52-L87 | train |
AustralianSynchrotron/lightflow | lightflow/workflows.py | list_workflows | def list_workflows(config):
""" List all available workflows.
Returns a list of all workflows that are available from the paths specified
in the config. A workflow is defined as a Python file with at least one DAG.
Args:
config (Config): Reference to the configuration object from which the
settings are retrieved.
Returns:
list: A list of workflows.
"""
workflows = []
for path in config.workflows:
filenames = glob.glob(os.path.join(os.path.abspath(path), '*.py'))
for filename in filenames:
module_name = os.path.splitext(os.path.basename(filename))[0]
workflow = Workflow()
try:
workflow.load(module_name, validate_arguments=False, strict_dag=True)
workflows.append(workflow)
except DirectedAcyclicGraphInvalid as e:
raise WorkflowDefinitionError(workflow_name=module_name,
graph_name=e.graph_name)
except WorkflowImportError:
continue
return workflows | python | def list_workflows(config):
""" List all available workflows.
Returns a list of all workflows that are available from the paths specified
in the config. A workflow is defined as a Python file with at least one DAG.
Args:
config (Config): Reference to the configuration object from which the
settings are retrieved.
Returns:
list: A list of workflows.
"""
workflows = []
for path in config.workflows:
filenames = glob.glob(os.path.join(os.path.abspath(path), '*.py'))
for filename in filenames:
module_name = os.path.splitext(os.path.basename(filename))[0]
workflow = Workflow()
try:
workflow.load(module_name, validate_arguments=False, strict_dag=True)
workflows.append(workflow)
except DirectedAcyclicGraphInvalid as e:
raise WorkflowDefinitionError(workflow_name=module_name,
graph_name=e.graph_name)
except WorkflowImportError:
continue
return workflows | [
"def",
"list_workflows",
"(",
"config",
")",
":",
"workflows",
"=",
"[",
"]",
"for",
"path",
"in",
"config",
".",
"workflows",
":",
"filenames",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"abspath",
... | List all available workflows.
Returns a list of all workflows that are available from the paths specified
in the config. A workflow is defined as a Python file with at least one DAG.
Args:
config (Config): Reference to the configuration object from which the
settings are retrieved.
Returns:
list: A list of workflows. | [
"List",
"all",
"available",
"workflows",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/workflows.py#L90-L119 | train |
AustralianSynchrotron/lightflow | lightflow/workflows.py | list_jobs | def list_jobs(config, *, status=JobStatus.Active,
filter_by_type=None, filter_by_worker=None):
""" Return a list of Celery jobs.
Args:
config (Config): Reference to the configuration object from which the
settings are retrieved.
status (JobStatus): The status of the jobs that should be returned.
filter_by_type (list): Restrict the returned jobs to the types in this list.
filter_by_worker (list): Only return jobs that were registered, reserved or are
running on the workers given in this list of worker names. Using
this option will increase the performance.
Returns:
list: A list of JobStats.
"""
celery_app = create_app(config)
# option to filter by the worker (improves performance)
if filter_by_worker is not None:
inspect = celery_app.control.inspect(
destination=filter_by_worker if isinstance(filter_by_worker, list)
else [filter_by_worker])
else:
inspect = celery_app.control.inspect()
# get active, registered or reserved jobs
if status == JobStatus.Active:
job_map = inspect.active()
elif status == JobStatus.Registered:
job_map = inspect.registered()
elif status == JobStatus.Reserved:
job_map = inspect.reserved()
elif status == JobStatus.Scheduled:
job_map = inspect.scheduled()
else:
job_map = None
if job_map is None:
return []
result = []
for worker_name, jobs in job_map.items():
for job in jobs:
try:
job_stats = JobStats.from_celery(worker_name, job, celery_app)
if (filter_by_type is None) or (job_stats.type == filter_by_type):
result.append(job_stats)
except JobStatInvalid:
pass
return result | python | def list_jobs(config, *, status=JobStatus.Active,
filter_by_type=None, filter_by_worker=None):
""" Return a list of Celery jobs.
Args:
config (Config): Reference to the configuration object from which the
settings are retrieved.
status (JobStatus): The status of the jobs that should be returned.
filter_by_type (list): Restrict the returned jobs to the types in this list.
filter_by_worker (list): Only return jobs that were registered, reserved or are
running on the workers given in this list of worker names. Using
this option will increase the performance.
Returns:
list: A list of JobStats.
"""
celery_app = create_app(config)
# option to filter by the worker (improves performance)
if filter_by_worker is not None:
inspect = celery_app.control.inspect(
destination=filter_by_worker if isinstance(filter_by_worker, list)
else [filter_by_worker])
else:
inspect = celery_app.control.inspect()
# get active, registered or reserved jobs
if status == JobStatus.Active:
job_map = inspect.active()
elif status == JobStatus.Registered:
job_map = inspect.registered()
elif status == JobStatus.Reserved:
job_map = inspect.reserved()
elif status == JobStatus.Scheduled:
job_map = inspect.scheduled()
else:
job_map = None
if job_map is None:
return []
result = []
for worker_name, jobs in job_map.items():
for job in jobs:
try:
job_stats = JobStats.from_celery(worker_name, job, celery_app)
if (filter_by_type is None) or (job_stats.type == filter_by_type):
result.append(job_stats)
except JobStatInvalid:
pass
return result | [
"def",
"list_jobs",
"(",
"config",
",",
"*",
",",
"status",
"=",
"JobStatus",
".",
"Active",
",",
"filter_by_type",
"=",
"None",
",",
"filter_by_worker",
"=",
"None",
")",
":",
"celery_app",
"=",
"create_app",
"(",
"config",
")",
"# option to filter by the wor... | Return a list of Celery jobs.
Args:
config (Config): Reference to the configuration object from which the
settings are retrieved.
status (JobStatus): The status of the jobs that should be returned.
filter_by_type (list): Restrict the returned jobs to the types in this list.
filter_by_worker (list): Only return jobs that were registered, reserved or are
running on the workers given in this list of worker names. Using
this option will increase the performance.
Returns:
list: A list of JobStats. | [
"Return",
"a",
"list",
"of",
"Celery",
"jobs",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/workflows.py#L122-L174 | train |
AustralianSynchrotron/lightflow | lightflow/workflows.py | events | def events(config):
""" Return a generator that yields workflow events.
For every workflow event that is sent from celery this generator yields an event
object.
Args:
config (Config): Reference to the configuration object from which the
settings are retrieved.
Returns:
generator: A generator that returns workflow events.
"""
celery_app = create_app(config)
for event in event_stream(celery_app, filter_by_prefix='task'):
try:
yield create_event_model(event)
except JobEventTypeUnsupported:
pass | python | def events(config):
""" Return a generator that yields workflow events.
For every workflow event that is sent from celery this generator yields an event
object.
Args:
config (Config): Reference to the configuration object from which the
settings are retrieved.
Returns:
generator: A generator that returns workflow events.
"""
celery_app = create_app(config)
for event in event_stream(celery_app, filter_by_prefix='task'):
try:
yield create_event_model(event)
except JobEventTypeUnsupported:
pass | [
"def",
"events",
"(",
"config",
")",
":",
"celery_app",
"=",
"create_app",
"(",
"config",
")",
"for",
"event",
"in",
"event_stream",
"(",
"celery_app",
",",
"filter_by_prefix",
"=",
"'task'",
")",
":",
"try",
":",
"yield",
"create_event_model",
"(",
"event",... | Return a generator that yields workflow events.
For every workflow event that is sent from celery this generator yields an event
object.
Args:
config (Config): Reference to the configuration object from which the
settings are retrieved.
Returns:
generator: A generator that returns workflow events. | [
"Return",
"a",
"generator",
"that",
"yields",
"workflow",
"events",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/workflows.py#L177-L197 | train |
AustralianSynchrotron/lightflow | lightflow/tasks/bash_task.py | BashTaskOutputReader.run | def run(self):
""" Drain the process output streams. """
read_stdout = partial(self._read_output, stream=self._process.stdout,
callback=self._callback_stdout,
output_file=self._stdout_file)
read_stderr = partial(self._read_output, stream=self._process.stderr,
callback=self._callback_stderr,
output_file=self._stderr_file)
# capture the process output as long as the process is active
try:
while self._process.poll() is None:
result_stdout = read_stdout()
result_stderr = read_stderr()
if not result_stdout and not result_stderr:
sleep(self._refresh_time)
# read remaining lines
while read_stdout():
pass
while read_stderr():
pass
except (StopTask, AbortWorkflow) as exc:
self._exc_obj = exc | python | def run(self):
""" Drain the process output streams. """
read_stdout = partial(self._read_output, stream=self._process.stdout,
callback=self._callback_stdout,
output_file=self._stdout_file)
read_stderr = partial(self._read_output, stream=self._process.stderr,
callback=self._callback_stderr,
output_file=self._stderr_file)
# capture the process output as long as the process is active
try:
while self._process.poll() is None:
result_stdout = read_stdout()
result_stderr = read_stderr()
if not result_stdout and not result_stderr:
sleep(self._refresh_time)
# read remaining lines
while read_stdout():
pass
while read_stderr():
pass
except (StopTask, AbortWorkflow) as exc:
self._exc_obj = exc | [
"def",
"run",
"(",
"self",
")",
":",
"read_stdout",
"=",
"partial",
"(",
"self",
".",
"_read_output",
",",
"stream",
"=",
"self",
".",
"_process",
".",
"stdout",
",",
"callback",
"=",
"self",
".",
"_callback_stdout",
",",
"output_file",
"=",
"self",
".",... | Drain the process output streams. | [
"Drain",
"the",
"process",
"output",
"streams",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/tasks/bash_task.py#L64-L91 | train |
AustralianSynchrotron/lightflow | lightflow/tasks/bash_task.py | BashTaskOutputReader._read_output | def _read_output(self, stream, callback, output_file):
""" Read the output of the process, executed the callback and save the output.
Args:
stream: A file object pointing to the output stream that should be read.
callback(callable, None): A callback function that is called for each new
line of output.
output_file: A file object to which the full output is written.
Returns:
bool: True if a line was read from the output, otherwise False.
"""
if (callback is None and output_file is None) or stream.closed:
return False
line = stream.readline()
if line:
if callback is not None:
callback(line.decode(),
self._data, self._store, self._signal, self._context)
if output_file is not None:
output_file.write(line)
return True
else:
return False | python | def _read_output(self, stream, callback, output_file):
""" Read the output of the process, executed the callback and save the output.
Args:
stream: A file object pointing to the output stream that should be read.
callback(callable, None): A callback function that is called for each new
line of output.
output_file: A file object to which the full output is written.
Returns:
bool: True if a line was read from the output, otherwise False.
"""
if (callback is None and output_file is None) or stream.closed:
return False
line = stream.readline()
if line:
if callback is not None:
callback(line.decode(),
self._data, self._store, self._signal, self._context)
if output_file is not None:
output_file.write(line)
return True
else:
return False | [
"def",
"_read_output",
"(",
"self",
",",
"stream",
",",
"callback",
",",
"output_file",
")",
":",
"if",
"(",
"callback",
"is",
"None",
"and",
"output_file",
"is",
"None",
")",
"or",
"stream",
".",
"closed",
":",
"return",
"False",
"line",
"=",
"stream",
... | Read the output of the process, executed the callback and save the output.
Args:
stream: A file object pointing to the output stream that should be read.
callback(callable, None): A callback function that is called for each new
line of output.
output_file: A file object to which the full output is written.
Returns:
bool: True if a line was read from the output, otherwise False. | [
"Read",
"the",
"output",
"of",
"the",
"process",
"executed",
"the",
"callback",
"and",
"save",
"the",
"output",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/tasks/bash_task.py#L93-L119 | train |
AustralianSynchrotron/lightflow | lightflow/tasks/bash_task.py | BashTask.run | def run(self, data, store, signal, context, **kwargs):
""" The main run method of the Python task.
Args:
data (:class:`.MultiTaskData`): The data object that has been passed from the
predecessor task.
store (:class:`.DataStoreDocument`): The persistent data store object that allows the
task to store data for access across the current workflow run.
signal (TaskSignal): The signal object for tasks. It wraps the construction
and sending of signals into easy to use methods.
context (TaskContext): The context in which the tasks runs.
Returns:
Action (Action): An Action object containing the data that should be passed on
to the next task and optionally a list of successor tasks that
should be executed.
"""
params = self.params.eval(data, store, exclude=['command'])
capture_stdout = self._callback_stdout is not None or params.capture_stdout
capture_stderr = self._callback_stderr is not None or params.capture_stderr
stdout_file = TemporaryFile() if params.capture_stdout else None
stderr_file = TemporaryFile() if params.capture_stderr else None
stdout = PIPE if capture_stdout else None
stderr = PIPE if capture_stderr else None
# change the user or group under which the process should run
if params.user is not None or params.group is not None:
pre_exec = self._run_as(params.user, params.group)
else:
pre_exec = None
# call the command
proc = Popen(self.params.eval_single('command', data, store),
cwd=params.cwd, shell=True, env=params.env,
preexec_fn=pre_exec, stdout=stdout, stderr=stderr,
stdin=PIPE if params.stdin is not None else None)
# if input is available, send it to the process
if params.stdin is not None:
proc.stdin.write(params.stdin.encode(sys.getfilesystemencoding()))
# send a notification that the process has been started
try:
if self._callback_process is not None:
self._callback_process(proc.pid, data, store, signal, context)
except (StopTask, AbortWorkflow):
proc.terminate()
raise
# send the output handling to a thread
if capture_stdout or capture_stderr:
output_reader = BashTaskOutputReader(proc, stdout_file, stderr_file,
self._callback_stdout,
self._callback_stderr,
params.refresh_time,
data, store, signal, context)
output_reader.start()
else:
output_reader = None
# wait for the process to complete and watch for a stop signal
while proc.poll() is None or\
(output_reader is not None and output_reader.is_alive()):
sleep(params.refresh_time)
if signal.is_stopped:
proc.terminate()
if output_reader is not None:
output_reader.join()
data = output_reader.data
# if a stop or abort exception was raised, stop the bash process and re-raise
if output_reader.exc_obj is not None:
if proc.poll() is None:
proc.terminate()
raise output_reader.exc_obj
# send a notification that the process has completed
if self._callback_end is not None:
if stdout_file is not None:
stdout_file.seek(0)
if stderr_file is not None:
stderr_file.seek(0)
self._callback_end(proc.returncode, stdout_file, stderr_file,
data, store, signal, context)
if stdout_file is not None:
stdout_file.close()
if stderr_file is not None:
stderr_file.close()
return Action(data) | python | def run(self, data, store, signal, context, **kwargs):
""" The main run method of the Python task.
Args:
data (:class:`.MultiTaskData`): The data object that has been passed from the
predecessor task.
store (:class:`.DataStoreDocument`): The persistent data store object that allows the
task to store data for access across the current workflow run.
signal (TaskSignal): The signal object for tasks. It wraps the construction
and sending of signals into easy to use methods.
context (TaskContext): The context in which the tasks runs.
Returns:
Action (Action): An Action object containing the data that should be passed on
to the next task and optionally a list of successor tasks that
should be executed.
"""
params = self.params.eval(data, store, exclude=['command'])
capture_stdout = self._callback_stdout is not None or params.capture_stdout
capture_stderr = self._callback_stderr is not None or params.capture_stderr
stdout_file = TemporaryFile() if params.capture_stdout else None
stderr_file = TemporaryFile() if params.capture_stderr else None
stdout = PIPE if capture_stdout else None
stderr = PIPE if capture_stderr else None
# change the user or group under which the process should run
if params.user is not None or params.group is not None:
pre_exec = self._run_as(params.user, params.group)
else:
pre_exec = None
# call the command
proc = Popen(self.params.eval_single('command', data, store),
cwd=params.cwd, shell=True, env=params.env,
preexec_fn=pre_exec, stdout=stdout, stderr=stderr,
stdin=PIPE if params.stdin is not None else None)
# if input is available, send it to the process
if params.stdin is not None:
proc.stdin.write(params.stdin.encode(sys.getfilesystemencoding()))
# send a notification that the process has been started
try:
if self._callback_process is not None:
self._callback_process(proc.pid, data, store, signal, context)
except (StopTask, AbortWorkflow):
proc.terminate()
raise
# send the output handling to a thread
if capture_stdout or capture_stderr:
output_reader = BashTaskOutputReader(proc, stdout_file, stderr_file,
self._callback_stdout,
self._callback_stderr,
params.refresh_time,
data, store, signal, context)
output_reader.start()
else:
output_reader = None
# wait for the process to complete and watch for a stop signal
while proc.poll() is None or\
(output_reader is not None and output_reader.is_alive()):
sleep(params.refresh_time)
if signal.is_stopped:
proc.terminate()
if output_reader is not None:
output_reader.join()
data = output_reader.data
# if a stop or abort exception was raised, stop the bash process and re-raise
if output_reader.exc_obj is not None:
if proc.poll() is None:
proc.terminate()
raise output_reader.exc_obj
# send a notification that the process has completed
if self._callback_end is not None:
if stdout_file is not None:
stdout_file.seek(0)
if stderr_file is not None:
stderr_file.seek(0)
self._callback_end(proc.returncode, stdout_file, stderr_file,
data, store, signal, context)
if stdout_file is not None:
stdout_file.close()
if stderr_file is not None:
stderr_file.close()
return Action(data) | [
"def",
"run",
"(",
"self",
",",
"data",
",",
"store",
",",
"signal",
",",
"context",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"self",
".",
"params",
".",
"eval",
"(",
"data",
",",
"store",
",",
"exclude",
"=",
"[",
"'command'",
"]",
")",... | The main run method of the Python task.
Args:
data (:class:`.MultiTaskData`): The data object that has been passed from the
predecessor task.
store (:class:`.DataStoreDocument`): The persistent data store object that allows the
task to store data for access across the current workflow run.
signal (TaskSignal): The signal object for tasks. It wraps the construction
and sending of signals into easy to use methods.
context (TaskContext): The context in which the tasks runs.
Returns:
Action (Action): An Action object containing the data that should be passed on
to the next task and optionally a list of successor tasks that
should be executed. | [
"The",
"main",
"run",
"method",
"of",
"the",
"Python",
"task",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/tasks/bash_task.py#L293-L389 | train |
AustralianSynchrotron/lightflow | lightflow/tasks/bash_task.py | BashTask._run_as | def _run_as(user, group):
""" Function wrapper that sets the user and group for the process """
def wrapper():
if user is not None:
os.setuid(user)
if group is not None:
os.setgid(group)
return wrapper | python | def _run_as(user, group):
""" Function wrapper that sets the user and group for the process """
def wrapper():
if user is not None:
os.setuid(user)
if group is not None:
os.setgid(group)
return wrapper | [
"def",
"_run_as",
"(",
"user",
",",
"group",
")",
":",
"def",
"wrapper",
"(",
")",
":",
"if",
"user",
"is",
"not",
"None",
":",
"os",
".",
"setuid",
"(",
"user",
")",
"if",
"group",
"is",
"not",
"None",
":",
"os",
".",
"setgid",
"(",
"group",
"... | Function wrapper that sets the user and group for the process | [
"Function",
"wrapper",
"that",
"sets",
"the",
"user",
"and",
"group",
"for",
"the",
"process"
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/tasks/bash_task.py#L392-L399 | train |
AustralianSynchrotron/lightflow | lightflow/models/parameters.py | Option.convert | def convert(self, value):
""" Convert the specified value to the type of the option.
Args:
value: The value that should be converted.
Returns:
The value with the type given by the option.
"""
if self._type is str:
return str(value)
elif self._type is int:
try:
return int(value)
except (UnicodeError, ValueError):
raise WorkflowArgumentError('Cannot convert {} to int'.format(value))
elif self._type is float:
try:
return float(value)
except (UnicodeError, ValueError):
raise WorkflowArgumentError('Cannot convert {} to float'.format(value))
elif self._type is bool:
if isinstance(value, bool):
return bool(value)
value = value.lower()
if value in ('true', '1', 'yes', 'y'):
return True
elif value in ('false', '0', 'no', 'n'):
return False
raise WorkflowArgumentError('Cannot convert {} to bool'.format(value))
else:
return value | python | def convert(self, value):
""" Convert the specified value to the type of the option.
Args:
value: The value that should be converted.
Returns:
The value with the type given by the option.
"""
if self._type is str:
return str(value)
elif self._type is int:
try:
return int(value)
except (UnicodeError, ValueError):
raise WorkflowArgumentError('Cannot convert {} to int'.format(value))
elif self._type is float:
try:
return float(value)
except (UnicodeError, ValueError):
raise WorkflowArgumentError('Cannot convert {} to float'.format(value))
elif self._type is bool:
if isinstance(value, bool):
return bool(value)
value = value.lower()
if value in ('true', '1', 'yes', 'y'):
return True
elif value in ('false', '0', 'no', 'n'):
return False
raise WorkflowArgumentError('Cannot convert {} to bool'.format(value))
else:
return value | [
"def",
"convert",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"_type",
"is",
"str",
":",
"return",
"str",
"(",
"value",
")",
"elif",
"self",
".",
"_type",
"is",
"int",
":",
"try",
":",
"return",
"int",
"(",
"value",
")",
"except",
"("... | Convert the specified value to the type of the option.
Args:
value: The value that should be converted.
Returns:
The value with the type given by the option. | [
"Convert",
"the",
"specified",
"value",
"to",
"the",
"type",
"of",
"the",
"option",
"."
] | dc53dbc1d961e20fb144273baca258060705c03e | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/parameters.py#L62-L93 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.