ngram
listlengths 0
67.8k
|
|---|
[
"ConfigParser def configLoader(filename): if os.path.exists(filename): _config = ConfigParser() _config.read(filename) return _config._sections else: return",
"os import sys from ConfigParser import ConfigParser def configLoader(filename): if os.path.exists(filename): _config =",
"import ConfigParser def configLoader(filename): if os.path.exists(filename): _config = ConfigParser() _config.read(filename) return _config._sections else:",
"def configLoader(filename): if os.path.exists(filename): _config = ConfigParser() _config.read(filename) return _config._sections else: return False",
"import os import sys from ConfigParser import ConfigParser def configLoader(filename): if os.path.exists(filename): _config",
"<filename>iot/rmq/config.py<gh_stars>0 import os import sys from ConfigParser import ConfigParser def configLoader(filename): if os.path.exists(filename):",
"ConfigParser import ConfigParser def configLoader(filename): if os.path.exists(filename): _config = ConfigParser() _config.read(filename) return _config._sections",
"import sys from ConfigParser import ConfigParser def configLoader(filename): if os.path.exists(filename): _config = ConfigParser()",
"from ConfigParser import ConfigParser def configLoader(filename): if os.path.exists(filename): _config = ConfigParser() _config.read(filename) return",
"sys from ConfigParser import ConfigParser def configLoader(filename): if os.path.exists(filename): _config = ConfigParser() _config.read(filename)"
] |
[
"self.shuffle() def shuffle(self): counter = self.mines for idx1 in range(self.size): for idx2 in",
"epoch -= 1 def checking(self): idx1 = 0 idx2 = 0 # searching",
"0: if idx2 - 1 >= 0: neighbours.append([idx1-1, idx2-1]) if idx2 + 1",
"epoch = 1000 while epoch > 0: idx1, idx2, idx3, idx4 = sample([num",
"idx1, idx2, idx3, idx4 = sample([num for num in range(self.size)], 4) self.field[idx1][idx2], self.field[idx3][idx4]",
"= neighbour[0], neighbour[1] if self.field[n_idx1][n_idx2] != '*': self.field[n_idx1][n_idx2] += 1 idx2 += 1",
"= 0 idx1 += 1 return self.field def __repr__(self): text = '' for",
"if idx2 - 1 >= 0: neighbours.append([idx1+1, idx2-1]) if idx2 + 1 <",
"1000 while epoch > 0: idx1, idx2, idx3, idx4 = sample([num for num",
"idx1 in range(self.size) and idx2 in range(self.size): neighbours = [] if idx1-1 >=",
"< self.size: neighbours.append([idx1+1, idx2+1]) neighbours.append([idx1+1, idx2]) if idx2 - 1 >= 0: neighbours.append([idx1,",
"0: idx1, idx2, idx3, idx4 = sample([num for num in range(self.size)], 4) self.field[idx1][idx2],",
"class MineMap: def __init__(self, size=9, mine_coefficient=0.1): self.size = size self.field = [[0 for",
"self.mines = int((self.size**2) * mine_coefficient) self.shuffle() def shuffle(self): counter = self.mines for idx1",
"range(self.size)] for _ in range(self.size)] self.mines = int((self.size**2) * mine_coefficient) self.shuffle() def shuffle(self):",
"def __repr__(self): text = '' for string in self.field: text += ' '.join([str(elem)",
"'*': for neighbour in neighbours: n_idx1, n_idx2 = neighbour[0], neighbour[1] if self.field[n_idx1][n_idx2] !=",
"for idx1 in range(self.size): for idx2 in range(self.size): if counter > 0: self.field[idx1][idx2]",
"idx2 > self.size-1: idx2 = 0 idx1 += 1 return self.field def __repr__(self):",
"'*' counter -= 1 epoch = 1000 while epoch > 0: idx1, idx2,",
"self.field def __repr__(self): text = '' for string in self.field: text += '",
"n_idx1, n_idx2 = neighbour[0], neighbour[1] if self.field[n_idx1][n_idx2] != '*': self.field[n_idx1][n_idx2] += 1 idx2",
"idx1 in range(self.size): for idx2 in range(self.size): if counter > 0: self.field[idx1][idx2] =",
"neighbour[0], neighbour[1] if self.field[n_idx1][n_idx2] != '*': self.field[n_idx1][n_idx2] += 1 idx2 += 1 if",
"= [] if idx1-1 >= 0: if idx2 - 1 >= 0: neighbours.append([idx1-1,",
"neighbours while idx1 in range(self.size) and idx2 in range(self.size): neighbours = [] if",
"int((self.size**2) * mine_coefficient) self.shuffle() def shuffle(self): counter = self.mines for idx1 in range(self.size):",
"= \\ self.field[idx3][idx4], self.field[idx1][idx2] epoch -= 1 def checking(self): idx1 = 0 idx2",
"self.field[idx1][idx2] = '*' counter -= 1 epoch = 1000 while epoch > 0:",
"for _ in range(self.size)] self.mines = int((self.size**2) * mine_coefficient) self.shuffle() def shuffle(self): counter",
"+= ' '.join([str(elem) for elem in string]) text += '\\n' return text def",
"range(self.size): for idx2 in range(self.size): if counter > 0: self.field[idx1][idx2] = '*' counter",
"neighbours.append([idx1-1, idx2+1]) neighbours.append([idx1-1, idx2]) if idx1+1 < self.size: if idx2 - 1 >=",
"self.size: if idx2 - 1 >= 0: neighbours.append([idx1+1, idx2-1]) if idx2 + 1",
"text += ' '.join([str(elem) for elem in string]) text += '\\n' return text",
"if idx2 + 1 < self.size: neighbours.append([idx1-1, idx2+1]) neighbours.append([idx1-1, idx2]) if idx1+1 <",
"idx1-1 >= 0: if idx2 - 1 >= 0: neighbours.append([idx1-1, idx2-1]) if idx2",
"text = '' for string in self.field: text += ' '.join([str(elem) for elem",
">= 0: neighbours.append([idx1, idx2-1]) if idx2 + 1 < self.size: neighbours.append([idx1, idx2+1]) #",
"'' for string in self.field: text += ' '.join([str(elem) for elem in string])",
"idx3, idx4 = sample([num for num in range(self.size)], 4) self.field[idx1][idx2], self.field[idx3][idx4] = \\",
"< self.size: if idx2 - 1 >= 0: neighbours.append([idx1+1, idx2-1]) if idx2 +",
"idx2-1]) if idx2 + 1 < self.size: neighbours.append([idx1, idx2+1]) # checking neighbours if",
"self.mines for idx1 in range(self.size): for idx2 in range(self.size): if counter > 0:",
"self.field[idx1][idx2] == '*': for neighbour in neighbours: n_idx1, n_idx2 = neighbour[0], neighbour[1] if",
"idx1 += 1 return self.field def __repr__(self): text = '' for string in",
"neighbours.append([idx1-1, idx2-1]) if idx2 + 1 < self.size: neighbours.append([idx1-1, idx2+1]) neighbours.append([idx1-1, idx2]) if",
"self.field[idx1][idx2], self.field[idx3][idx4] = \\ self.field[idx3][idx4], self.field[idx1][idx2] epoch -= 1 def checking(self): idx1 =",
"* mine_coefficient) self.shuffle() def shuffle(self): counter = self.mines for idx1 in range(self.size): for",
"-= 1 epoch = 1000 while epoch > 0: idx1, idx2, idx3, idx4",
"idx2, idx3, idx4 = sample([num for num in range(self.size)], 4) self.field[idx1][idx2], self.field[idx3][idx4] =",
"self.size = size self.field = [[0 for _ in range(self.size)] for _ in",
"> 0: idx1, idx2, idx3, idx4 = sample([num for num in range(self.size)], 4)",
"n_idx2 = neighbour[0], neighbour[1] if self.field[n_idx1][n_idx2] != '*': self.field[n_idx1][n_idx2] += 1 idx2 +=",
"in range(self.size)] for _ in range(self.size)] self.mines = int((self.size**2) * mine_coefficient) self.shuffle() def",
">= 0: if idx2 - 1 >= 0: neighbours.append([idx1-1, idx2-1]) if idx2 +",
"self.size: neighbours.append([idx1+1, idx2+1]) neighbours.append([idx1+1, idx2]) if idx2 - 1 >= 0: neighbours.append([idx1, idx2-1])",
"- 1 >= 0: neighbours.append([idx1+1, idx2-1]) if idx2 + 1 < self.size: neighbours.append([idx1+1,",
"idx2]) if idx1+1 < self.size: if idx2 - 1 >= 0: neighbours.append([idx1+1, idx2-1])",
"+= 1 if idx2 > self.size-1: idx2 = 0 idx1 += 1 return",
"1 < self.size: neighbours.append([idx1, idx2+1]) # checking neighbours if self.field[idx1][idx2] == '*': for",
"= 1000 while epoch > 0: idx1, idx2, idx3, idx4 = sample([num for",
"_ in range(self.size)] self.mines = int((self.size**2) * mine_coefficient) self.shuffle() def shuffle(self): counter =",
"'.join([str(elem) for elem in string]) text += '\\n' return text def __int__(self): return",
"string]) text += '\\n' return text def __int__(self): return self.mines def main(): new_map",
"+= '\\n' return text def __int__(self): return self.mines def main(): new_map = MineMap()",
"< self.size: neighbours.append([idx1, idx2+1]) # checking neighbours if self.field[idx1][idx2] == '*': for neighbour",
"+ 1 < self.size: neighbours.append([idx1, idx2+1]) # checking neighbours if self.field[idx1][idx2] == '*':",
"1 >= 0: neighbours.append([idx1+1, idx2-1]) if idx2 + 1 < self.size: neighbours.append([idx1+1, idx2+1])",
"= '*' counter -= 1 epoch = 1000 while epoch > 0: idx1,",
"== '*': for neighbour in neighbours: n_idx1, n_idx2 = neighbour[0], neighbour[1] if self.field[n_idx1][n_idx2]",
"idx2 + 1 < self.size: neighbours.append([idx1, idx2+1]) # checking neighbours if self.field[idx1][idx2] ==",
"0 idx1 += 1 return self.field def __repr__(self): text = '' for string",
"while idx1 in range(self.size) and idx2 in range(self.size): neighbours = [] if idx1-1",
"\\ self.field[idx3][idx4], self.field[idx1][idx2] epoch -= 1 def checking(self): idx1 = 0 idx2 =",
"import sample n = 9 class MineMap: def __init__(self, size=9, mine_coefficient=0.1): self.size =",
"1 < self.size: neighbours.append([idx1-1, idx2+1]) neighbours.append([idx1-1, idx2]) if idx1+1 < self.size: if idx2",
"__int__(self): return self.mines def main(): new_map = MineMap() new_map.checking() print(new_map, '\\n', int(new_map), sep='')",
"idx1+1 < self.size: if idx2 - 1 >= 0: neighbours.append([idx1+1, idx2-1]) if idx2",
"idx4 = sample([num for num in range(self.size)], 4) self.field[idx1][idx2], self.field[idx3][idx4] = \\ self.field[idx3][idx4],",
"-= 1 def checking(self): idx1 = 0 idx2 = 0 # searching neighbours",
"in range(self.size): for idx2 in range(self.size): if counter > 0: self.field[idx1][idx2] = '*'",
"new_map = MineMap() new_map.checking() print(new_map, '\\n', int(new_map), sep='') if __name__ == '__main__': main()",
"while epoch > 0: idx1, idx2, idx3, idx4 = sample([num for num in",
"# searching neighbours while idx1 in range(self.size) and idx2 in range(self.size): neighbours =",
"size=9, mine_coefficient=0.1): self.size = size self.field = [[0 for _ in range(self.size)] for",
"0 # searching neighbours while idx1 in range(self.size) and idx2 in range(self.size): neighbours",
"sample([num for num in range(self.size)], 4) self.field[idx1][idx2], self.field[idx3][idx4] = \\ self.field[idx3][idx4], self.field[idx1][idx2] epoch",
"> self.size-1: idx2 = 0 idx1 += 1 return self.field def __repr__(self): text",
"in range(self.size) and idx2 in range(self.size): neighbours = [] if idx1-1 >= 0:",
"self.field[idx3][idx4] = \\ self.field[idx3][idx4], self.field[idx1][idx2] epoch -= 1 def checking(self): idx1 = 0",
"+ 1 < self.size: neighbours.append([idx1+1, idx2+1]) neighbours.append([idx1+1, idx2]) if idx2 - 1 >=",
"for elem in string]) text += '\\n' return text def __int__(self): return self.mines",
"__repr__(self): text = '' for string in self.field: text += ' '.join([str(elem) for",
">= 0: neighbours.append([idx1-1, idx2-1]) if idx2 + 1 < self.size: neighbours.append([idx1-1, idx2+1]) neighbours.append([idx1-1,",
"shuffle(self): counter = self.mines for idx1 in range(self.size): for idx2 in range(self.size): if",
"neighbour in neighbours: n_idx1, n_idx2 = neighbour[0], neighbour[1] if self.field[n_idx1][n_idx2] != '*': self.field[n_idx1][n_idx2]",
"from random import sample n = 9 class MineMap: def __init__(self, size=9, mine_coefficient=0.1):",
"in range(self.size): neighbours = [] if idx1-1 >= 0: if idx2 - 1",
"text def __int__(self): return self.mines def main(): new_map = MineMap() new_map.checking() print(new_map, '\\n',",
"- 1 >= 0: neighbours.append([idx1-1, idx2-1]) if idx2 + 1 < self.size: neighbours.append([idx1-1,",
"in string]) text += '\\n' return text def __int__(self): return self.mines def main():",
"neighbours.append([idx1, idx2-1]) if idx2 + 1 < self.size: neighbours.append([idx1, idx2+1]) # checking neighbours",
"= sample([num for num in range(self.size)], 4) self.field[idx1][idx2], self.field[idx3][idx4] = \\ self.field[idx3][idx4], self.field[idx1][idx2]",
"counter -= 1 epoch = 1000 while epoch > 0: idx1, idx2, idx3,",
"string in self.field: text += ' '.join([str(elem) for elem in string]) text +=",
"self.field = [[0 for _ in range(self.size)] for _ in range(self.size)] self.mines =",
">= 0: neighbours.append([idx1+1, idx2-1]) if idx2 + 1 < self.size: neighbours.append([idx1+1, idx2+1]) neighbours.append([idx1+1,",
"idx2 - 1 >= 0: neighbours.append([idx1+1, idx2-1]) if idx2 + 1 < self.size:",
"neighbours.append([idx1-1, idx2]) if idx1+1 < self.size: if idx2 - 1 >= 0: neighbours.append([idx1+1,",
"if idx2 > self.size-1: idx2 = 0 idx1 += 1 return self.field def",
"idx2 + 1 < self.size: neighbours.append([idx1-1, idx2+1]) neighbours.append([idx1-1, idx2]) if idx1+1 < self.size:",
"_ in range(self.size)] for _ in range(self.size)] self.mines = int((self.size**2) * mine_coefficient) self.shuffle()",
"size self.field = [[0 for _ in range(self.size)] for _ in range(self.size)] self.mines",
"= '' for string in self.field: text += ' '.join([str(elem) for elem in",
"MineMap: def __init__(self, size=9, mine_coefficient=0.1): self.size = size self.field = [[0 for _",
"idx2-1]) if idx2 + 1 < self.size: neighbours.append([idx1+1, idx2+1]) neighbours.append([idx1+1, idx2]) if idx2",
"neighbours.append([idx1+1, idx2]) if idx2 - 1 >= 0: neighbours.append([idx1, idx2-1]) if idx2 +",
"- 1 >= 0: neighbours.append([idx1, idx2-1]) if idx2 + 1 < self.size: neighbours.append([idx1,",
"1 def checking(self): idx1 = 0 idx2 = 0 # searching neighbours while",
"0: neighbours.append([idx1+1, idx2-1]) if idx2 + 1 < self.size: neighbours.append([idx1+1, idx2+1]) neighbours.append([idx1+1, idx2])",
"in neighbours: n_idx1, n_idx2 = neighbour[0], neighbour[1] if self.field[n_idx1][n_idx2] != '*': self.field[n_idx1][n_idx2] +=",
"__init__(self, size=9, mine_coefficient=0.1): self.size = size self.field = [[0 for _ in range(self.size)]",
"neighbours = [] if idx1-1 >= 0: if idx2 - 1 >= 0:",
"checking(self): idx1 = 0 idx2 = 0 # searching neighbours while idx1 in",
"0: neighbours.append([idx1-1, idx2-1]) if idx2 + 1 < self.size: neighbours.append([idx1-1, idx2+1]) neighbours.append([idx1-1, idx2])",
"' '.join([str(elem) for elem in string]) text += '\\n' return text def __int__(self):",
"self.field[idx1][idx2] epoch -= 1 def checking(self): idx1 = 0 idx2 = 0 #",
"in range(self.size)], 4) self.field[idx1][idx2], self.field[idx3][idx4] = \\ self.field[idx3][idx4], self.field[idx1][idx2] epoch -= 1 def",
"0: neighbours.append([idx1, idx2-1]) if idx2 + 1 < self.size: neighbours.append([idx1, idx2+1]) # checking",
"return self.field def __repr__(self): text = '' for string in self.field: text +=",
"!= '*': self.field[n_idx1][n_idx2] += 1 idx2 += 1 if idx2 > self.size-1: idx2",
"if self.field[n_idx1][n_idx2] != '*': self.field[n_idx1][n_idx2] += 1 idx2 += 1 if idx2 >",
"n = 9 class MineMap: def __init__(self, size=9, mine_coefficient=0.1): self.size = size self.field",
"def shuffle(self): counter = self.mines for idx1 in range(self.size): for idx2 in range(self.size):",
"4) self.field[idx1][idx2], self.field[idx3][idx4] = \\ self.field[idx3][idx4], self.field[idx1][idx2] epoch -= 1 def checking(self): idx1",
"in range(self.size): if counter > 0: self.field[idx1][idx2] = '*' counter -= 1 epoch",
"self.size-1: idx2 = 0 idx1 += 1 return self.field def __repr__(self): text =",
"def main(): new_map = MineMap() new_map.checking() print(new_map, '\\n', int(new_map), sep='') if __name__ ==",
"range(self.size): neighbours = [] if idx1-1 >= 0: if idx2 - 1 >=",
"epoch > 0: idx1, idx2, idx3, idx4 = sample([num for num in range(self.size)],",
"main(): new_map = MineMap() new_map.checking() print(new_map, '\\n', int(new_map), sep='') if __name__ == '__main__':",
"idx2]) if idx2 - 1 >= 0: neighbours.append([idx1, idx2-1]) if idx2 + 1",
"checking neighbours if self.field[idx1][idx2] == '*': for neighbour in neighbours: n_idx1, n_idx2 =",
"return self.mines def main(): new_map = MineMap() new_map.checking() print(new_map, '\\n', int(new_map), sep='') if",
"1 epoch = 1000 while epoch > 0: idx1, idx2, idx3, idx4 =",
"in self.field: text += ' '.join([str(elem) for elem in string]) text += '\\n'",
"1 >= 0: neighbours.append([idx1-1, idx2-1]) if idx2 + 1 < self.size: neighbours.append([idx1-1, idx2+1])",
"= int((self.size**2) * mine_coefficient) self.shuffle() def shuffle(self): counter = self.mines for idx1 in",
"text += '\\n' return text def __int__(self): return self.mines def main(): new_map =",
"0 idx2 = 0 # searching neighbours while idx1 in range(self.size) and idx2",
"mine_coefficient=0.1): self.size = size self.field = [[0 for _ in range(self.size)] for _",
"sample n = 9 class MineMap: def __init__(self, size=9, mine_coefficient=0.1): self.size = size",
"= 0 # searching neighbours while idx1 in range(self.size) and idx2 in range(self.size):",
"if counter > 0: self.field[idx1][idx2] = '*' counter -= 1 epoch = 1000",
"and idx2 in range(self.size): neighbours = [] if idx1-1 >= 0: if idx2",
"neighbours: n_idx1, n_idx2 = neighbour[0], neighbour[1] if self.field[n_idx1][n_idx2] != '*': self.field[n_idx1][n_idx2] += 1",
"1 return self.field def __repr__(self): text = '' for string in self.field: text",
"range(self.size): if counter > 0: self.field[idx1][idx2] = '*' counter -= 1 epoch =",
"idx2 += 1 if idx2 > self.size-1: idx2 = 0 idx1 += 1",
"if idx1-1 >= 0: if idx2 - 1 >= 0: neighbours.append([idx1-1, idx2-1]) if",
"return text def __int__(self): return self.mines def main(): new_map = MineMap() new_map.checking() print(new_map,",
"= 0 idx2 = 0 # searching neighbours while idx1 in range(self.size) and",
"0: self.field[idx1][idx2] = '*' counter -= 1 epoch = 1000 while epoch >",
"for string in self.field: text += ' '.join([str(elem) for elem in string]) text",
"self.field[idx3][idx4], self.field[idx1][idx2] epoch -= 1 def checking(self): idx1 = 0 idx2 = 0",
"def __init__(self, size=9, mine_coefficient=0.1): self.size = size self.field = [[0 for _ in",
"'*': self.field[n_idx1][n_idx2] += 1 idx2 += 1 if idx2 > self.size-1: idx2 =",
"idx2-1]) if idx2 + 1 < self.size: neighbours.append([idx1-1, idx2+1]) neighbours.append([idx1-1, idx2]) if idx1+1",
"idx2 in range(self.size): if counter > 0: self.field[idx1][idx2] = '*' counter -= 1",
"self.mines def main(): new_map = MineMap() new_map.checking() print(new_map, '\\n', int(new_map), sep='') if __name__",
"1 idx2 += 1 if idx2 > self.size-1: idx2 = 0 idx1 +=",
"idx2+1]) neighbours.append([idx1-1, idx2]) if idx1+1 < self.size: if idx2 - 1 >= 0:",
"if idx1+1 < self.size: if idx2 - 1 >= 0: neighbours.append([idx1+1, idx2-1]) if",
"[[0 for _ in range(self.size)] for _ in range(self.size)] self.mines = int((self.size**2) *",
"for idx2 in range(self.size): if counter > 0: self.field[idx1][idx2] = '*' counter -=",
"> 0: self.field[idx1][idx2] = '*' counter -= 1 epoch = 1000 while epoch",
"idx2 in range(self.size): neighbours = [] if idx1-1 >= 0: if idx2 -",
"in range(self.size)] self.mines = int((self.size**2) * mine_coefficient) self.shuffle() def shuffle(self): counter = self.mines",
"idx2 - 1 >= 0: neighbours.append([idx1-1, idx2-1]) if idx2 + 1 < self.size:",
"idx2 + 1 < self.size: neighbours.append([idx1+1, idx2+1]) neighbours.append([idx1+1, idx2]) if idx2 - 1",
"self.field[n_idx1][n_idx2] != '*': self.field[n_idx1][n_idx2] += 1 idx2 += 1 if idx2 > self.size-1:",
"num in range(self.size)], 4) self.field[idx1][idx2], self.field[idx3][idx4] = \\ self.field[idx3][idx4], self.field[idx1][idx2] epoch -= 1",
"= self.mines for idx1 in range(self.size): for idx2 in range(self.size): if counter >",
"neighbour[1] if self.field[n_idx1][n_idx2] != '*': self.field[n_idx1][n_idx2] += 1 idx2 += 1 if idx2",
"= size self.field = [[0 for _ in range(self.size)] for _ in range(self.size)]",
"< self.size: neighbours.append([idx1-1, idx2+1]) neighbours.append([idx1-1, idx2]) if idx1+1 < self.size: if idx2 -",
"9 class MineMap: def __init__(self, size=9, mine_coefficient=0.1): self.size = size self.field = [[0",
"idx1 = 0 idx2 = 0 # searching neighbours while idx1 in range(self.size)",
"for neighbour in neighbours: n_idx1, n_idx2 = neighbour[0], neighbour[1] if self.field[n_idx1][n_idx2] != '*':",
"for _ in range(self.size)] for _ in range(self.size)] self.mines = int((self.size**2) * mine_coefficient)",
"if idx2 - 1 >= 0: neighbours.append([idx1, idx2-1]) if idx2 + 1 <",
"idx2 = 0 # searching neighbours while idx1 in range(self.size) and idx2 in",
"for num in range(self.size)], 4) self.field[idx1][idx2], self.field[idx3][idx4] = \\ self.field[idx3][idx4], self.field[idx1][idx2] epoch -=",
"+= 1 return self.field def __repr__(self): text = '' for string in self.field:",
"= [[0 for _ in range(self.size)] for _ in range(self.size)] self.mines = int((self.size**2)",
"counter > 0: self.field[idx1][idx2] = '*' counter -= 1 epoch = 1000 while",
"idx2 - 1 >= 0: neighbours.append([idx1, idx2-1]) if idx2 + 1 < self.size:",
"if idx2 + 1 < self.size: neighbours.append([idx1, idx2+1]) # checking neighbours if self.field[idx1][idx2]",
"# checking neighbours if self.field[idx1][idx2] == '*': for neighbour in neighbours: n_idx1, n_idx2",
"idx2+1]) neighbours.append([idx1+1, idx2]) if idx2 - 1 >= 0: neighbours.append([idx1, idx2-1]) if idx2",
"+= 1 idx2 += 1 if idx2 > self.size-1: idx2 = 0 idx1",
"neighbours.append([idx1, idx2+1]) # checking neighbours if self.field[idx1][idx2] == '*': for neighbour in neighbours:",
"counter = self.mines for idx1 in range(self.size): for idx2 in range(self.size): if counter",
"+ 1 < self.size: neighbours.append([idx1-1, idx2+1]) neighbours.append([idx1-1, idx2]) if idx1+1 < self.size: if",
"idx2 = 0 idx1 += 1 return self.field def __repr__(self): text = ''",
"range(self.size) and idx2 in range(self.size): neighbours = [] if idx1-1 >= 0: if",
"neighbours.append([idx1+1, idx2-1]) if idx2 + 1 < self.size: neighbours.append([idx1+1, idx2+1]) neighbours.append([idx1+1, idx2]) if",
"neighbours.append([idx1+1, idx2+1]) neighbours.append([idx1+1, idx2]) if idx2 - 1 >= 0: neighbours.append([idx1, idx2-1]) if",
"elem in string]) text += '\\n' return text def __int__(self): return self.mines def",
"[] if idx1-1 >= 0: if idx2 - 1 >= 0: neighbours.append([idx1-1, idx2-1])",
"if idx2 + 1 < self.size: neighbours.append([idx1+1, idx2+1]) neighbours.append([idx1+1, idx2]) if idx2 -",
"self.field: text += ' '.join([str(elem) for elem in string]) text += '\\n' return",
"searching neighbours while idx1 in range(self.size) and idx2 in range(self.size): neighbours = []",
"def checking(self): idx1 = 0 idx2 = 0 # searching neighbours while idx1",
"if self.field[idx1][idx2] == '*': for neighbour in neighbours: n_idx1, n_idx2 = neighbour[0], neighbour[1]",
"self.size: neighbours.append([idx1-1, idx2+1]) neighbours.append([idx1-1, idx2]) if idx1+1 < self.size: if idx2 - 1",
"self.size: neighbours.append([idx1, idx2+1]) # checking neighbours if self.field[idx1][idx2] == '*': for neighbour in",
"neighbours if self.field[idx1][idx2] == '*': for neighbour in neighbours: n_idx1, n_idx2 = neighbour[0],",
"self.field[n_idx1][n_idx2] += 1 idx2 += 1 if idx2 > self.size-1: idx2 = 0",
"mine_coefficient) self.shuffle() def shuffle(self): counter = self.mines for idx1 in range(self.size): for idx2",
"= 9 class MineMap: def __init__(self, size=9, mine_coefficient=0.1): self.size = size self.field =",
"'\\n' return text def __int__(self): return self.mines def main(): new_map = MineMap() new_map.checking()",
"idx2+1]) # checking neighbours if self.field[idx1][idx2] == '*': for neighbour in neighbours: n_idx1,",
"1 if idx2 > self.size-1: idx2 = 0 idx1 += 1 return self.field",
"if idx2 - 1 >= 0: neighbours.append([idx1-1, idx2-1]) if idx2 + 1 <",
"random import sample n = 9 class MineMap: def __init__(self, size=9, mine_coefficient=0.1): self.size",
"1 >= 0: neighbours.append([idx1, idx2-1]) if idx2 + 1 < self.size: neighbours.append([idx1, idx2+1])",
"range(self.size)], 4) self.field[idx1][idx2], self.field[idx3][idx4] = \\ self.field[idx3][idx4], self.field[idx1][idx2] epoch -= 1 def checking(self):",
"1 < self.size: neighbours.append([idx1+1, idx2+1]) neighbours.append([idx1+1, idx2]) if idx2 - 1 >= 0:",
"range(self.size)] self.mines = int((self.size**2) * mine_coefficient) self.shuffle() def shuffle(self): counter = self.mines for",
"def __int__(self): return self.mines def main(): new_map = MineMap() new_map.checking() print(new_map, '\\n', int(new_map),"
] |
[] |
[
"import DynamixelMotor from .fan import Fan from .force_sensor import ForceSensor from .joint import",
".joint import Joint from .orbita import OrbitaActuator Device = Union[Fan, Joint, DynamixelMotor, ForceSensor,",
"from .force_sensor import ForceSensor from .joint import Joint from .orbita import OrbitaActuator Device",
"from typing import Union from .dynamixel import DynamixelMotor from .fan import Fan from",
"from .dynamixel import DynamixelMotor from .fan import Fan from .force_sensor import ForceSensor from",
"from .fan import Fan from .force_sensor import ForceSensor from .joint import Joint from",
"import ForceSensor from .joint import Joint from .orbita import OrbitaActuator Device = Union[Fan,",
"ForceSensor from .joint import Joint from .orbita import OrbitaActuator Device = Union[Fan, Joint,",
"import Fan from .force_sensor import ForceSensor from .joint import Joint from .orbita import",
"import Union from .dynamixel import DynamixelMotor from .fan import Fan from .force_sensor import",
"import Joint from .orbita import OrbitaActuator Device = Union[Fan, Joint, DynamixelMotor, ForceSensor, OrbitaActuator]",
".fan import Fan from .force_sensor import ForceSensor from .joint import Joint from .orbita",
"type annotation.\"\"\" from typing import Union from .dynamixel import DynamixelMotor from .fan import",
"annotation.\"\"\" from typing import Union from .dynamixel import DynamixelMotor from .fan import Fan",
".dynamixel import DynamixelMotor from .fan import Fan from .force_sensor import ForceSensor from .joint",
"typing import Union from .dynamixel import DynamixelMotor from .fan import Fan from .force_sensor",
"Fan from .force_sensor import ForceSensor from .joint import Joint from .orbita import OrbitaActuator",
"from .joint import Joint from .orbita import OrbitaActuator Device = Union[Fan, Joint, DynamixelMotor,",
"Union from .dynamixel import DynamixelMotor from .fan import Fan from .force_sensor import ForceSensor",
"DynamixelMotor from .fan import Fan from .force_sensor import ForceSensor from .joint import Joint",
"\"\"\"Device type annotation.\"\"\" from typing import Union from .dynamixel import DynamixelMotor from .fan",
".force_sensor import ForceSensor from .joint import Joint from .orbita import OrbitaActuator Device ="
] |
[
"\"\"\" # O(n) time # O(n) memory from typing import Optional # Definition",
"head visitedNodes = {} while currentNode is not None: if visitedNodes.get(currentNode) is not",
"Cycle https://leetcode.com/problems/linked-list-cycle/ \"\"\" # O(n) time # O(n) memory from typing import Optional",
"= None class Solution: def hasCycle(self, head: Optional[ListNode]) -> bool: currentNode = head",
"141. Linked List Cycle https://leetcode.com/problems/linked-list-cycle/ \"\"\" # O(n) time # O(n) memory from",
"{} while currentNode is not None: if visitedNodes.get(currentNode) is not None: return True",
"currentNode is not None: if visitedNodes.get(currentNode) is not None: return True visitedNodes[currentNode] =",
"LeetCode 141. Linked List Cycle https://leetcode.com/problems/linked-list-cycle/ \"\"\" # O(n) time # O(n) memory",
"def hasCycle(self, head: Optional[ListNode]) -> bool: currentNode = head visitedNodes = {} while",
"Optional # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val =",
"self.next = None class Solution: def hasCycle(self, head: Optional[ListNode]) -> bool: currentNode =",
"None: if visitedNodes.get(currentNode) is not None: return True visitedNodes[currentNode] = True currentNode =",
"from typing import Optional # Definition for singly-linked list. class ListNode: def __init__(self,",
"x): self.val = x self.next = None class Solution: def hasCycle(self, head: Optional[ListNode])",
"head: Optional[ListNode]) -> bool: currentNode = head visitedNodes = {} while currentNode is",
"memory from typing import Optional # Definition for singly-linked list. class ListNode: def",
"-> bool: currentNode = head visitedNodes = {} while currentNode is not None:",
"O(n) memory from typing import Optional # Definition for singly-linked list. class ListNode:",
"ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def",
"currentNode = head visitedNodes = {} while currentNode is not None: if visitedNodes.get(currentNode)",
"visitedNodes = {} while currentNode is not None: if visitedNodes.get(currentNode) is not None:",
"List Cycle https://leetcode.com/problems/linked-list-cycle/ \"\"\" # O(n) time # O(n) memory from typing import",
"for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next =",
"visitedNodes.get(currentNode) is not None: return True visitedNodes[currentNode] = True currentNode = currentNode.next return",
"= x self.next = None class Solution: def hasCycle(self, head: Optional[ListNode]) -> bool:",
"is not None: return True visitedNodes[currentNode] = True currentNode = currentNode.next return False",
"class Solution: def hasCycle(self, head: Optional[ListNode]) -> bool: currentNode = head visitedNodes =",
"x self.next = None class Solution: def hasCycle(self, head: Optional[ListNode]) -> bool: currentNode",
"if visitedNodes.get(currentNode) is not None: return True visitedNodes[currentNode] = True currentNode = currentNode.next",
"= {} while currentNode is not None: if visitedNodes.get(currentNode) is not None: return",
"not None: if visitedNodes.get(currentNode) is not None: return True visitedNodes[currentNode] = True currentNode",
"class ListNode: def __init__(self, x): self.val = x self.next = None class Solution:",
"singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None",
"Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next",
"def __init__(self, x): self.val = x self.next = None class Solution: def hasCycle(self,",
"= head visitedNodes = {} while currentNode is not None: if visitedNodes.get(currentNode) is",
"None class Solution: def hasCycle(self, head: Optional[ListNode]) -> bool: currentNode = head visitedNodes",
"is not None: if visitedNodes.get(currentNode) is not None: return True visitedNodes[currentNode] = True",
"Linked List Cycle https://leetcode.com/problems/linked-list-cycle/ \"\"\" # O(n) time # O(n) memory from typing",
"while currentNode is not None: if visitedNodes.get(currentNode) is not None: return True visitedNodes[currentNode]",
"# O(n) time # O(n) memory from typing import Optional # Definition for",
"list. class ListNode: def __init__(self, x): self.val = x self.next = None class",
"self.val = x self.next = None class Solution: def hasCycle(self, head: Optional[ListNode]) ->",
"__init__(self, x): self.val = x self.next = None class Solution: def hasCycle(self, head:",
"O(n) time # O(n) memory from typing import Optional # Definition for singly-linked",
"\"\"\" LeetCode 141. Linked List Cycle https://leetcode.com/problems/linked-list-cycle/ \"\"\" # O(n) time # O(n)",
"time # O(n) memory from typing import Optional # Definition for singly-linked list.",
"hasCycle(self, head: Optional[ListNode]) -> bool: currentNode = head visitedNodes = {} while currentNode",
"# O(n) memory from typing import Optional # Definition for singly-linked list. class",
"Optional[ListNode]) -> bool: currentNode = head visitedNodes = {} while currentNode is not",
"Solution: def hasCycle(self, head: Optional[ListNode]) -> bool: currentNode = head visitedNodes = {}",
"# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x",
"<reponame>andrenbrandao/algorithm-problems \"\"\" LeetCode 141. Linked List Cycle https://leetcode.com/problems/linked-list-cycle/ \"\"\" # O(n) time #",
"bool: currentNode = head visitedNodes = {} while currentNode is not None: if",
"typing import Optional # Definition for singly-linked list. class ListNode: def __init__(self, x):",
"import Optional # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val",
"https://leetcode.com/problems/linked-list-cycle/ \"\"\" # O(n) time # O(n) memory from typing import Optional #"
] |
[
"as f: long_desc = f.read() setup( name=\"pyumlgen\", version=\"0.1.6\", description=\"Generate UML diagrams with type",
"type information from python modules\", author=\"<NAME>\", packages=find_packages(), entry_points={ \"console_scripts\": [ \"pyumlgen=pyumlgen:main\" ] }",
"path.abspath(path.dirname(__file__)) with open(path.join(here, \"README.md\")) as f: long_desc = f.read() setup( name=\"pyumlgen\", version=\"0.1.6\", description=\"Generate",
"= path.abspath(path.dirname(__file__)) with open(path.join(here, \"README.md\")) as f: long_desc = f.read() setup( name=\"pyumlgen\", version=\"0.1.6\",",
"version=\"0.1.6\", description=\"Generate UML diagrams with type information from python modules\", author=\"<NAME>\", packages=find_packages(), entry_points={",
"from setuptools import setup, find_packages from codecs import open from os import path",
"setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__))",
"description=\"Generate UML diagrams with type information from python modules\", author=\"<NAME>\", packages=find_packages(), entry_points={ \"console_scripts\":",
"f: long_desc = f.read() setup( name=\"pyumlgen\", version=\"0.1.6\", description=\"Generate UML diagrams with type information",
"setuptools import setup, find_packages from codecs import open from os import path here",
"find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with",
"from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here,",
"with type information from python modules\", author=\"<NAME>\", packages=find_packages(), entry_points={ \"console_scripts\": [ \"pyumlgen=pyumlgen:main\" ]",
"<filename>setup.py from setuptools import setup, find_packages from codecs import open from os import",
"path here = path.abspath(path.dirname(__file__)) with open(path.join(here, \"README.md\")) as f: long_desc = f.read() setup(",
"UML diagrams with type information from python modules\", author=\"<NAME>\", packages=find_packages(), entry_points={ \"console_scripts\": [",
"long_desc = f.read() setup( name=\"pyumlgen\", version=\"0.1.6\", description=\"Generate UML diagrams with type information from",
"setup( name=\"pyumlgen\", version=\"0.1.6\", description=\"Generate UML diagrams with type information from python modules\", author=\"<NAME>\",",
"os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, \"README.md\")) as f: long_desc =",
"codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, \"README.md\"))",
"\"README.md\")) as f: long_desc = f.read() setup( name=\"pyumlgen\", version=\"0.1.6\", description=\"Generate UML diagrams with",
"import setup, find_packages from codecs import open from os import path here =",
"diagrams with type information from python modules\", author=\"<NAME>\", packages=find_packages(), entry_points={ \"console_scripts\": [ \"pyumlgen=pyumlgen:main\"",
"= f.read() setup( name=\"pyumlgen\", version=\"0.1.6\", description=\"Generate UML diagrams with type information from python",
"information from python modules\", author=\"<NAME>\", packages=find_packages(), entry_points={ \"console_scripts\": [ \"pyumlgen=pyumlgen:main\" ] } )",
"open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, \"README.md\")) as f:",
"here = path.abspath(path.dirname(__file__)) with open(path.join(here, \"README.md\")) as f: long_desc = f.read() setup( name=\"pyumlgen\",",
"name=\"pyumlgen\", version=\"0.1.6\", description=\"Generate UML diagrams with type information from python modules\", author=\"<NAME>\", packages=find_packages(),",
"import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, \"README.md\")) as",
"from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, \"README.md\")) as f: long_desc",
"import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, \"README.md\")) as f: long_desc = f.read()",
"with open(path.join(here, \"README.md\")) as f: long_desc = f.read() setup( name=\"pyumlgen\", version=\"0.1.6\", description=\"Generate UML",
"f.read() setup( name=\"pyumlgen\", version=\"0.1.6\", description=\"Generate UML diagrams with type information from python modules\",",
"open(path.join(here, \"README.md\")) as f: long_desc = f.read() setup( name=\"pyumlgen\", version=\"0.1.6\", description=\"Generate UML diagrams"
] |
[
"self.assertEqual( self.method.charge_excl_tax_before_discount, D('10.00')) self.assertEqual(self.method.code, self.base_method.code) self.assertEqual(self.method.name, self.base_method.name) self.assertEqual(self.method.description, self.base_method.description) def test_discounts_charge(self): self.assertEqual(self.method.charge_excl_tax, D('5.00'))",
"oscar.apps.shipping.models import OrderAndItemCharges @attr('shipping') class TestStandardMethods(TestCase): def setUp(self): self.non_discount_methods = [ methods.Free(), methods.FixedPrice(D('10.00'),",
"import mock from oscar.apps.shipping import methods from oscar.apps.shipping.models import OrderAndItemCharges @attr('shipping') class TestStandardMethods(TestCase):",
"self.assertFalse(self.method.is_tax_known) self.assertEqual( self.method.charge_excl_tax_before_discount, D('10.00')) self.assertEqual(self.method.code, self.base_method.code) self.assertEqual(self.method.name, self.base_method.name) self.assertEqual(self.method.description, self.base_method.description) def test_discounts_charge(self): self.assertEqual(self.method.charge_excl_tax,",
"import methods from oscar.apps.shipping.models import OrderAndItemCharges @attr('shipping') class TestStandardMethods(TestCase): def setUp(self): self.non_discount_methods =",
"self.method.charge_excl_tax_before_discount, D('10.00')) self.assertEqual(self.method.code, self.base_method.code) self.assertEqual(self.method.name, self.base_method.name) self.assertEqual(self.method.description, self.base_method.description) def test_discounts_charge(self): self.assertEqual(self.method.charge_excl_tax, D('5.00')) def",
"self.assertEqual(self.method.code, self.base_method.code) self.assertEqual(self.method.name, self.base_method.name) self.assertEqual(self.method.description, self.base_method.description) def test_discounts_charge(self): self.assertEqual(self.method.charge_excl_tax, D('5.00')) def test_correctly_sets_tax(self): self.method.tax",
"from decimal import Decimal as D from django.test import TestCase from nose.plugins.attrib import",
"method in self.non_discount_methods: self.assertFalse(method.is_discounted) class TestDiscountingMethodsWithoutTax(TestCase): def setUp(self): self.base_method = methods.FixedPrice(D('10.00')) offer =",
"= mock.Mock( return_value=D('5.00')) self.method = methods.TaxExclusiveOfferDiscount( self.base_method, offer) def test_delegates_properties_onto_wrapped_method(self): self.assertFalse(self.method.is_tax_known) self.assertEqual( self.method.charge_excl_tax_before_discount,",
"Decimal as D from django.test import TestCase from nose.plugins.attrib import attr import mock",
"self.base_method.code) self.assertEqual(self.method.name, self.base_method.name) self.assertEqual(self.method.description, self.base_method.description) def test_discounts_charge(self): self.assertEqual(self.method.charge_excl_tax, D('5.00')) def test_correctly_sets_tax(self): self.method.tax =",
"mock.Mock() offer.shipping_discount = mock.Mock( return_value=D('5.00')) self.method = methods.TaxExclusiveOfferDiscount( self.base_method, offer) def test_delegates_properties_onto_wrapped_method(self): self.assertFalse(self.method.is_tax_known)",
"methods.Free(), methods.FixedPrice(D('10.00'), D('10.00')), OrderAndItemCharges(price_per_order=D('5.00'), price_per_item=D('1.00'))] def test_have_is_discounted_property(self): for method in self.non_discount_methods: self.assertFalse(method.is_discounted) class",
"import TestCase from nose.plugins.attrib import attr import mock from oscar.apps.shipping import methods from",
"def test_delegates_properties_onto_wrapped_method(self): self.assertFalse(self.method.is_tax_known) self.assertEqual( self.method.charge_excl_tax_before_discount, D('10.00')) self.assertEqual(self.method.code, self.base_method.code) self.assertEqual(self.method.name, self.base_method.name) self.assertEqual(self.method.description, self.base_method.description) def",
"from oscar.apps.shipping.models import OrderAndItemCharges @attr('shipping') class TestStandardMethods(TestCase): def setUp(self): self.non_discount_methods = [ methods.Free(),",
"nose.plugins.attrib import attr import mock from oscar.apps.shipping import methods from oscar.apps.shipping.models import OrderAndItemCharges",
"methods.FixedPrice(D('10.00'), D('10.00')), OrderAndItemCharges(price_per_order=D('5.00'), price_per_item=D('1.00'))] def test_have_is_discounted_property(self): for method in self.non_discount_methods: self.assertFalse(method.is_discounted) class TestDiscountingMethodsWithoutTax(TestCase):",
"import attr import mock from oscar.apps.shipping import methods from oscar.apps.shipping.models import OrderAndItemCharges @attr('shipping')",
"= mock.Mock() offer.shipping_discount = mock.Mock( return_value=D('5.00')) self.method = methods.TaxExclusiveOfferDiscount( self.base_method, offer) def test_delegates_properties_onto_wrapped_method(self):",
"return_value=D('5.00')) self.method = methods.TaxExclusiveOfferDiscount( self.base_method, offer) def test_delegates_properties_onto_wrapped_method(self): self.assertFalse(self.method.is_tax_known) self.assertEqual( self.method.charge_excl_tax_before_discount, D('10.00')) self.assertEqual(self.method.code,",
"= methods.TaxExclusiveOfferDiscount( self.base_method, offer) def test_delegates_properties_onto_wrapped_method(self): self.assertFalse(self.method.is_tax_known) self.assertEqual( self.method.charge_excl_tax_before_discount, D('10.00')) self.assertEqual(self.method.code, self.base_method.code) self.assertEqual(self.method.name,",
"price_per_item=D('1.00'))] def test_have_is_discounted_property(self): for method in self.non_discount_methods: self.assertFalse(method.is_discounted) class TestDiscountingMethodsWithoutTax(TestCase): def setUp(self): self.base_method",
"D('10.00')) self.assertEqual(self.method.code, self.base_method.code) self.assertEqual(self.method.name, self.base_method.name) self.assertEqual(self.method.description, self.base_method.description) def test_discounts_charge(self): self.assertEqual(self.method.charge_excl_tax, D('5.00')) def test_correctly_sets_tax(self):",
"attr import mock from oscar.apps.shipping import methods from oscar.apps.shipping.models import OrderAndItemCharges @attr('shipping') class",
"class TestStandardMethods(TestCase): def setUp(self): self.non_discount_methods = [ methods.Free(), methods.FixedPrice(D('10.00'), D('10.00')), OrderAndItemCharges(price_per_order=D('5.00'), price_per_item=D('1.00'))] def",
"TestCase from nose.plugins.attrib import attr import mock from oscar.apps.shipping import methods from oscar.apps.shipping.models",
"[ methods.Free(), methods.FixedPrice(D('10.00'), D('10.00')), OrderAndItemCharges(price_per_order=D('5.00'), price_per_item=D('1.00'))] def test_have_is_discounted_property(self): for method in self.non_discount_methods: self.assertFalse(method.is_discounted)",
"def setUp(self): self.non_discount_methods = [ methods.Free(), methods.FixedPrice(D('10.00'), D('10.00')), OrderAndItemCharges(price_per_order=D('5.00'), price_per_item=D('1.00'))] def test_have_is_discounted_property(self): for",
"from django.test import TestCase from nose.plugins.attrib import attr import mock from oscar.apps.shipping import",
"self.non_discount_methods = [ methods.Free(), methods.FixedPrice(D('10.00'), D('10.00')), OrderAndItemCharges(price_per_order=D('5.00'), price_per_item=D('1.00'))] def test_have_is_discounted_property(self): for method in",
"mock.Mock( return_value=D('5.00')) self.method = methods.TaxExclusiveOfferDiscount( self.base_method, offer) def test_delegates_properties_onto_wrapped_method(self): self.assertFalse(self.method.is_tax_known) self.assertEqual( self.method.charge_excl_tax_before_discount, D('10.00'))",
"test_have_is_discounted_property(self): for method in self.non_discount_methods: self.assertFalse(method.is_discounted) class TestDiscountingMethodsWithoutTax(TestCase): def setUp(self): self.base_method = methods.FixedPrice(D('10.00'))",
"offer.shipping_discount = mock.Mock( return_value=D('5.00')) self.method = methods.TaxExclusiveOfferDiscount( self.base_method, offer) def test_delegates_properties_onto_wrapped_method(self): self.assertFalse(self.method.is_tax_known) self.assertEqual(",
"from nose.plugins.attrib import attr import mock from oscar.apps.shipping import methods from oscar.apps.shipping.models import",
"as D from django.test import TestCase from nose.plugins.attrib import attr import mock from",
"import Decimal as D from django.test import TestCase from nose.plugins.attrib import attr import",
"self.non_discount_methods: self.assertFalse(method.is_discounted) class TestDiscountingMethodsWithoutTax(TestCase): def setUp(self): self.base_method = methods.FixedPrice(D('10.00')) offer = mock.Mock() offer.shipping_discount",
"methods.FixedPrice(D('10.00')) offer = mock.Mock() offer.shipping_discount = mock.Mock( return_value=D('5.00')) self.method = methods.TaxExclusiveOfferDiscount( self.base_method, offer)",
"for method in self.non_discount_methods: self.assertFalse(method.is_discounted) class TestDiscountingMethodsWithoutTax(TestCase): def setUp(self): self.base_method = methods.FixedPrice(D('10.00')) offer",
"self.method = methods.TaxExclusiveOfferDiscount( self.base_method, offer) def test_delegates_properties_onto_wrapped_method(self): self.assertFalse(self.method.is_tax_known) self.assertEqual( self.method.charge_excl_tax_before_discount, D('10.00')) self.assertEqual(self.method.code, self.base_method.code)",
"D('10.00')), OrderAndItemCharges(price_per_order=D('5.00'), price_per_item=D('1.00'))] def test_have_is_discounted_property(self): for method in self.non_discount_methods: self.assertFalse(method.is_discounted) class TestDiscountingMethodsWithoutTax(TestCase): def",
"setUp(self): self.non_discount_methods = [ methods.Free(), methods.FixedPrice(D('10.00'), D('10.00')), OrderAndItemCharges(price_per_order=D('5.00'), price_per_item=D('1.00'))] def test_have_is_discounted_property(self): for method",
"test_delegates_properties_onto_wrapped_method(self): self.assertFalse(self.method.is_tax_known) self.assertEqual( self.method.charge_excl_tax_before_discount, D('10.00')) self.assertEqual(self.method.code, self.base_method.code) self.assertEqual(self.method.name, self.base_method.name) self.assertEqual(self.method.description, self.base_method.description) def test_discounts_charge(self):",
"def test_have_is_discounted_property(self): for method in self.non_discount_methods: self.assertFalse(method.is_discounted) class TestDiscountingMethodsWithoutTax(TestCase): def setUp(self): self.base_method =",
"OrderAndItemCharges @attr('shipping') class TestStandardMethods(TestCase): def setUp(self): self.non_discount_methods = [ methods.Free(), methods.FixedPrice(D('10.00'), D('10.00')), OrderAndItemCharges(price_per_order=D('5.00'),",
"setUp(self): self.base_method = methods.FixedPrice(D('10.00')) offer = mock.Mock() offer.shipping_discount = mock.Mock( return_value=D('5.00')) self.method =",
"self.base_method, offer) def test_delegates_properties_onto_wrapped_method(self): self.assertFalse(self.method.is_tax_known) self.assertEqual( self.method.charge_excl_tax_before_discount, D('10.00')) self.assertEqual(self.method.code, self.base_method.code) self.assertEqual(self.method.name, self.base_method.name) self.assertEqual(self.method.description,",
"self.base_method.name) self.assertEqual(self.method.description, self.base_method.description) def test_discounts_charge(self): self.assertEqual(self.method.charge_excl_tax, D('5.00')) def test_correctly_sets_tax(self): self.method.tax = D('2.00') self.assertTrue(self.method.is_tax_known)",
"D from django.test import TestCase from nose.plugins.attrib import attr import mock from oscar.apps.shipping",
"methods.TaxExclusiveOfferDiscount( self.base_method, offer) def test_delegates_properties_onto_wrapped_method(self): self.assertFalse(self.method.is_tax_known) self.assertEqual( self.method.charge_excl_tax_before_discount, D('10.00')) self.assertEqual(self.method.code, self.base_method.code) self.assertEqual(self.method.name, self.base_method.name)",
"= methods.FixedPrice(D('10.00')) offer = mock.Mock() offer.shipping_discount = mock.Mock( return_value=D('5.00')) self.method = methods.TaxExclusiveOfferDiscount( self.base_method,",
"self.base_method = methods.FixedPrice(D('10.00')) offer = mock.Mock() offer.shipping_discount = mock.Mock( return_value=D('5.00')) self.method = methods.TaxExclusiveOfferDiscount(",
"offer = mock.Mock() offer.shipping_discount = mock.Mock( return_value=D('5.00')) self.method = methods.TaxExclusiveOfferDiscount( self.base_method, offer) def",
"self.assertEqual(self.method.name, self.base_method.name) self.assertEqual(self.method.description, self.base_method.description) def test_discounts_charge(self): self.assertEqual(self.method.charge_excl_tax, D('5.00')) def test_correctly_sets_tax(self): self.method.tax = D('2.00')",
"mock from oscar.apps.shipping import methods from oscar.apps.shipping.models import OrderAndItemCharges @attr('shipping') class TestStandardMethods(TestCase): def",
"decimal import Decimal as D from django.test import TestCase from nose.plugins.attrib import attr",
"oscar.apps.shipping import methods from oscar.apps.shipping.models import OrderAndItemCharges @attr('shipping') class TestStandardMethods(TestCase): def setUp(self): self.non_discount_methods",
"from oscar.apps.shipping import methods from oscar.apps.shipping.models import OrderAndItemCharges @attr('shipping') class TestStandardMethods(TestCase): def setUp(self):",
"import OrderAndItemCharges @attr('shipping') class TestStandardMethods(TestCase): def setUp(self): self.non_discount_methods = [ methods.Free(), methods.FixedPrice(D('10.00'), D('10.00')),",
"def setUp(self): self.base_method = methods.FixedPrice(D('10.00')) offer = mock.Mock() offer.shipping_discount = mock.Mock( return_value=D('5.00')) self.method",
"TestStandardMethods(TestCase): def setUp(self): self.non_discount_methods = [ methods.Free(), methods.FixedPrice(D('10.00'), D('10.00')), OrderAndItemCharges(price_per_order=D('5.00'), price_per_item=D('1.00'))] def test_have_is_discounted_property(self):",
"self.assertFalse(method.is_discounted) class TestDiscountingMethodsWithoutTax(TestCase): def setUp(self): self.base_method = methods.FixedPrice(D('10.00')) offer = mock.Mock() offer.shipping_discount =",
"self.assertEqual(self.method.description, self.base_method.description) def test_discounts_charge(self): self.assertEqual(self.method.charge_excl_tax, D('5.00')) def test_correctly_sets_tax(self): self.method.tax = D('2.00') self.assertTrue(self.method.is_tax_known) self.assertEqual(self.method.charge_incl_tax,",
"in self.non_discount_methods: self.assertFalse(method.is_discounted) class TestDiscountingMethodsWithoutTax(TestCase): def setUp(self): self.base_method = methods.FixedPrice(D('10.00')) offer = mock.Mock()",
"django.test import TestCase from nose.plugins.attrib import attr import mock from oscar.apps.shipping import methods",
"TestDiscountingMethodsWithoutTax(TestCase): def setUp(self): self.base_method = methods.FixedPrice(D('10.00')) offer = mock.Mock() offer.shipping_discount = mock.Mock( return_value=D('5.00'))",
"methods from oscar.apps.shipping.models import OrderAndItemCharges @attr('shipping') class TestStandardMethods(TestCase): def setUp(self): self.non_discount_methods = [",
"OrderAndItemCharges(price_per_order=D('5.00'), price_per_item=D('1.00'))] def test_have_is_discounted_property(self): for method in self.non_discount_methods: self.assertFalse(method.is_discounted) class TestDiscountingMethodsWithoutTax(TestCase): def setUp(self):",
"= [ methods.Free(), methods.FixedPrice(D('10.00'), D('10.00')), OrderAndItemCharges(price_per_order=D('5.00'), price_per_item=D('1.00'))] def test_have_is_discounted_property(self): for method in self.non_discount_methods:",
"class TestDiscountingMethodsWithoutTax(TestCase): def setUp(self): self.base_method = methods.FixedPrice(D('10.00')) offer = mock.Mock() offer.shipping_discount = mock.Mock(",
"offer) def test_delegates_properties_onto_wrapped_method(self): self.assertFalse(self.method.is_tax_known) self.assertEqual( self.method.charge_excl_tax_before_discount, D('10.00')) self.assertEqual(self.method.code, self.base_method.code) self.assertEqual(self.method.name, self.base_method.name) self.assertEqual(self.method.description, self.base_method.description)",
"self.base_method.description) def test_discounts_charge(self): self.assertEqual(self.method.charge_excl_tax, D('5.00')) def test_correctly_sets_tax(self): self.method.tax = D('2.00') self.assertTrue(self.method.is_tax_known) self.assertEqual(self.method.charge_incl_tax, D('7.00'))",
"@attr('shipping') class TestStandardMethods(TestCase): def setUp(self): self.non_discount_methods = [ methods.Free(), methods.FixedPrice(D('10.00'), D('10.00')), OrderAndItemCharges(price_per_order=D('5.00'), price_per_item=D('1.00'))]"
] |
[
"in data: commentCurr = { \"author\": obj.user_id, \"text\": urllib2.unquote(obj.comment.replace('+', ' ')), \"post_id\": obj.post_id,",
"'GET': return render_to_response('index.html') elif request.method == 'POST': queryDict = QueryDict() queryDict = request.POST",
"= Comments.objects.all() comments = [] for obj in data: commentCurr = { \"author\":",
"for obj in data: commentCurr = { \"author\": obj.user_id, \"text\": urllib2.unquote(obj.comment.replace('+', ' ')),",
"render_to_response # from django.template import RequestContext from django.views.decorators.csrf import csrf_exempt from comment_react.models import",
"== 'POST': queryDict = QueryDict() queryDict = request.POST a = dict(queryDict.lists()) comment =",
"Comments(user_id=author, post_id='1', comment=comment) p1.save() return render_to_response('index.html') @csrf_exempt def getComments(request): data = Comments.objects.all() comments",
"= request.POST a = dict(queryDict.lists()) comment = str(a.get('text')).split(\"'\")[1].decode('utf-8') author = str(a.get('author')).split(\"'\")[1].decode('utf-8') print 'comment",
"str(a.get('author')).split(\"'\")[1].decode('utf-8') print 'comment - ' + comment print 'author - ' + author",
"' + comment print 'author - ' + author p1 = Comments(user_id=author, post_id='1',",
"from django.template import RequestContext from django.views.decorators.csrf import csrf_exempt from comment_react.models import Comments from",
"getComments(request): data = Comments.objects.all() comments = [] for obj in data: commentCurr =",
"\"text\": urllib2.unquote(obj.comment.replace('+', ' ')), \"post_id\": obj.post_id, } comments.append(commentCurr) comments.append({'status_code': 'success'}) return HttpResponse(json.dumps(comments), content_type=\"application/json\")",
"RequestContext from django.views.decorators.csrf import csrf_exempt from comment_react.models import Comments from django.http import HttpResponse",
"RequestContext(request) if request.method == 'GET': return render_to_response('index.html') elif request.method == 'POST': queryDict =",
"print 'author - ' + author p1 = Comments(user_id=author, post_id='1', comment=comment) p1.save() return",
"import HttpResponse import json import urllib2 from django.http import QueryDict @csrf_exempt def home(request):",
"import csrf_exempt from comment_react.models import Comments from django.http import HttpResponse import json import",
"\"author\": obj.user_id, \"text\": urllib2.unquote(obj.comment.replace('+', ' ')), \"post_id\": obj.post_id, } comments.append(commentCurr) comments.append({'status_code': 'success'}) return",
"data: commentCurr = { \"author\": obj.user_id, \"text\": urllib2.unquote(obj.comment.replace('+', ' ')), \"post_id\": obj.post_id, }",
"'author - ' + author p1 = Comments(user_id=author, post_id='1', comment=comment) p1.save() return render_to_response('index.html')",
"def home(request): # context_instance = RequestContext(request) if request.method == 'GET': return render_to_response('index.html') elif",
"import Comments from django.http import HttpResponse import json import urllib2 from django.http import",
"QueryDict() queryDict = request.POST a = dict(queryDict.lists()) comment = str(a.get('text')).split(\"'\")[1].decode('utf-8') author = str(a.get('author')).split(\"'\")[1].decode('utf-8')",
"import QueryDict @csrf_exempt def home(request): # context_instance = RequestContext(request) if request.method == 'GET':",
"django.http import HttpResponse import json import urllib2 from django.http import QueryDict @csrf_exempt def",
"# context_instance = RequestContext(request) if request.method == 'GET': return render_to_response('index.html') elif request.method ==",
"Comments.objects.all() comments = [] for obj in data: commentCurr = { \"author\": obj.user_id,",
"comment_react.models import Comments from django.http import HttpResponse import json import urllib2 from django.http",
"import render_to_response # from django.template import RequestContext from django.views.decorators.csrf import csrf_exempt from comment_react.models",
"Comments from django.http import HttpResponse import json import urllib2 from django.http import QueryDict",
"from django.http import QueryDict @csrf_exempt def home(request): # context_instance = RequestContext(request) if request.method",
"+ comment print 'author - ' + author p1 = Comments(user_id=author, post_id='1', comment=comment)",
"render_to_response('index.html') @csrf_exempt def getComments(request): data = Comments.objects.all() comments = [] for obj in",
"home(request): # context_instance = RequestContext(request) if request.method == 'GET': return render_to_response('index.html') elif request.method",
"a = dict(queryDict.lists()) comment = str(a.get('text')).split(\"'\")[1].decode('utf-8') author = str(a.get('author')).split(\"'\")[1].decode('utf-8') print 'comment - '",
"author = str(a.get('author')).split(\"'\")[1].decode('utf-8') print 'comment - ' + comment print 'author - '",
"'comment - ' + comment print 'author - ' + author p1 =",
"str(a.get('text')).split(\"'\")[1].decode('utf-8') author = str(a.get('author')).split(\"'\")[1].decode('utf-8') print 'comment - ' + comment print 'author -",
"request.POST a = dict(queryDict.lists()) comment = str(a.get('text')).split(\"'\")[1].decode('utf-8') author = str(a.get('author')).split(\"'\")[1].decode('utf-8') print 'comment -",
"queryDict = QueryDict() queryDict = request.POST a = dict(queryDict.lists()) comment = str(a.get('text')).split(\"'\")[1].decode('utf-8') author",
"return render_to_response('index.html') @csrf_exempt def getComments(request): data = Comments.objects.all() comments = [] for obj",
"dict(queryDict.lists()) comment = str(a.get('text')).split(\"'\")[1].decode('utf-8') author = str(a.get('author')).split(\"'\")[1].decode('utf-8') print 'comment - ' + comment",
"import json import urllib2 from django.http import QueryDict @csrf_exempt def home(request): # context_instance",
"django.shortcuts import render_to_response # from django.template import RequestContext from django.views.decorators.csrf import csrf_exempt from",
"django.http import QueryDict @csrf_exempt def home(request): # context_instance = RequestContext(request) if request.method ==",
"comment=comment) p1.save() return render_to_response('index.html') @csrf_exempt def getComments(request): data = Comments.objects.all() comments = []",
"@csrf_exempt def getComments(request): data = Comments.objects.all() comments = [] for obj in data:",
"<gh_stars>1-10 from django.shortcuts import render_to_response # from django.template import RequestContext from django.views.decorators.csrf import",
"comments = [] for obj in data: commentCurr = { \"author\": obj.user_id, \"text\":",
"queryDict = request.POST a = dict(queryDict.lists()) comment = str(a.get('text')).split(\"'\")[1].decode('utf-8') author = str(a.get('author')).split(\"'\")[1].decode('utf-8') print",
"author p1 = Comments(user_id=author, post_id='1', comment=comment) p1.save() return render_to_response('index.html') @csrf_exempt def getComments(request): data",
"import RequestContext from django.views.decorators.csrf import csrf_exempt from comment_react.models import Comments from django.http import",
"= str(a.get('text')).split(\"'\")[1].decode('utf-8') author = str(a.get('author')).split(\"'\")[1].decode('utf-8') print 'comment - ' + comment print 'author",
"p1.save() return render_to_response('index.html') @csrf_exempt def getComments(request): data = Comments.objects.all() comments = [] for",
"comment = str(a.get('text')).split(\"'\")[1].decode('utf-8') author = str(a.get('author')).split(\"'\")[1].decode('utf-8') print 'comment - ' + comment print",
"def getComments(request): data = Comments.objects.all() comments = [] for obj in data: commentCurr",
"= RequestContext(request) if request.method == 'GET': return render_to_response('index.html') elif request.method == 'POST': queryDict",
"print 'comment - ' + comment print 'author - ' + author p1",
"+ author p1 = Comments(user_id=author, post_id='1', comment=comment) p1.save() return render_to_response('index.html') @csrf_exempt def getComments(request):",
"if request.method == 'GET': return render_to_response('index.html') elif request.method == 'POST': queryDict = QueryDict()",
"obj.user_id, \"text\": urllib2.unquote(obj.comment.replace('+', ' ')), \"post_id\": obj.post_id, } comments.append(commentCurr) comments.append({'status_code': 'success'}) return HttpResponse(json.dumps(comments),",
"@csrf_exempt def home(request): # context_instance = RequestContext(request) if request.method == 'GET': return render_to_response('index.html')",
"request.method == 'POST': queryDict = QueryDict() queryDict = request.POST a = dict(queryDict.lists()) comment",
"'POST': queryDict = QueryDict() queryDict = request.POST a = dict(queryDict.lists()) comment = str(a.get('text')).split(\"'\")[1].decode('utf-8')",
"- ' + author p1 = Comments(user_id=author, post_id='1', comment=comment) p1.save() return render_to_response('index.html') @csrf_exempt",
"obj in data: commentCurr = { \"author\": obj.user_id, \"text\": urllib2.unquote(obj.comment.replace('+', ' ')), \"post_id\":",
"from django.http import HttpResponse import json import urllib2 from django.http import QueryDict @csrf_exempt",
"[] for obj in data: commentCurr = { \"author\": obj.user_id, \"text\": urllib2.unquote(obj.comment.replace('+', '",
"import urllib2 from django.http import QueryDict @csrf_exempt def home(request): # context_instance = RequestContext(request)",
"django.views.decorators.csrf import csrf_exempt from comment_react.models import Comments from django.http import HttpResponse import json",
"= Comments(user_id=author, post_id='1', comment=comment) p1.save() return render_to_response('index.html') @csrf_exempt def getComments(request): data = Comments.objects.all()",
"return render_to_response('index.html') elif request.method == 'POST': queryDict = QueryDict() queryDict = request.POST a",
"QueryDict @csrf_exempt def home(request): # context_instance = RequestContext(request) if request.method == 'GET': return",
"request.method == 'GET': return render_to_response('index.html') elif request.method == 'POST': queryDict = QueryDict() queryDict",
"data = Comments.objects.all() comments = [] for obj in data: commentCurr = {",
"from comment_react.models import Comments from django.http import HttpResponse import json import urllib2 from",
"== 'GET': return render_to_response('index.html') elif request.method == 'POST': queryDict = QueryDict() queryDict =",
"json import urllib2 from django.http import QueryDict @csrf_exempt def home(request): # context_instance =",
"= dict(queryDict.lists()) comment = str(a.get('text')).split(\"'\")[1].decode('utf-8') author = str(a.get('author')).split(\"'\")[1].decode('utf-8') print 'comment - ' +",
"context_instance = RequestContext(request) if request.method == 'GET': return render_to_response('index.html') elif request.method == 'POST':",
"django.template import RequestContext from django.views.decorators.csrf import csrf_exempt from comment_react.models import Comments from django.http",
"p1 = Comments(user_id=author, post_id='1', comment=comment) p1.save() return render_to_response('index.html') @csrf_exempt def getComments(request): data =",
"= [] for obj in data: commentCurr = { \"author\": obj.user_id, \"text\": urllib2.unquote(obj.comment.replace('+',",
"post_id='1', comment=comment) p1.save() return render_to_response('index.html') @csrf_exempt def getComments(request): data = Comments.objects.all() comments =",
"# from django.template import RequestContext from django.views.decorators.csrf import csrf_exempt from comment_react.models import Comments",
"commentCurr = { \"author\": obj.user_id, \"text\": urllib2.unquote(obj.comment.replace('+', ' ')), \"post_id\": obj.post_id, } comments.append(commentCurr)",
"render_to_response('index.html') elif request.method == 'POST': queryDict = QueryDict() queryDict = request.POST a =",
"from django.shortcuts import render_to_response # from django.template import RequestContext from django.views.decorators.csrf import csrf_exempt",
"' + author p1 = Comments(user_id=author, post_id='1', comment=comment) p1.save() return render_to_response('index.html') @csrf_exempt def",
"from django.views.decorators.csrf import csrf_exempt from comment_react.models import Comments from django.http import HttpResponse import",
"- ' + comment print 'author - ' + author p1 = Comments(user_id=author,",
"elif request.method == 'POST': queryDict = QueryDict() queryDict = request.POST a = dict(queryDict.lists())",
"= QueryDict() queryDict = request.POST a = dict(queryDict.lists()) comment = str(a.get('text')).split(\"'\")[1].decode('utf-8') author =",
"{ \"author\": obj.user_id, \"text\": urllib2.unquote(obj.comment.replace('+', ' ')), \"post_id\": obj.post_id, } comments.append(commentCurr) comments.append({'status_code': 'success'})",
"csrf_exempt from comment_react.models import Comments from django.http import HttpResponse import json import urllib2",
"HttpResponse import json import urllib2 from django.http import QueryDict @csrf_exempt def home(request): #",
"= str(a.get('author')).split(\"'\")[1].decode('utf-8') print 'comment - ' + comment print 'author - ' +",
"= { \"author\": obj.user_id, \"text\": urllib2.unquote(obj.comment.replace('+', ' ')), \"post_id\": obj.post_id, } comments.append(commentCurr) comments.append({'status_code':",
"urllib2 from django.http import QueryDict @csrf_exempt def home(request): # context_instance = RequestContext(request) if",
"comment print 'author - ' + author p1 = Comments(user_id=author, post_id='1', comment=comment) p1.save()"
] |
[
"3 - Recovered = 4 - Dead = 5 \"\"\" # Copia degli",
"contaggiosi = np.concatenate((n_exp,n_inf,n_g_inf), axis=None) for x in contaggiosi: for n in self.g.neighbors(x): Rand",
"t_inc: {}; t_inf: {}\\n alpha: {}; beta: {}; gamma: {}'.format(simulator.p_link, simulator.exp0,simulator.t_exp,simulator.t_inf,simulator.alfa,simulator.beta,simulator.gamma)) plt.xlabel('Time (days)')",
"infected\",\"recovered\",\"dead\",\"susceptible\",\"total\"]) # Tabella stati def update_states(self,i,simulator): # Aggiornamento degli stati \"\"\"Lista degli stati:",
"self.data.plot(x = 'days', y = 'severe infected', kind = 'line', color = 'magenta',",
"plt.savefig('./plots/states.png') def update_nodes(self,i,simulator): # Aggiornamento dei nodi del network (rimozione dei nodi morti",
"i vicini siano contaggiati con tasso alfa # Nodi esposti n_exp = np.array(np.nonzero(self.states['exposed'])[0])",
"infetti e gravemente infetti e trovo i loro vicini suscettibili che vengono contaggiati",
"tasso alfa # Nodi esposti n_exp = np.array(np.nonzero(self.states['exposed'])[0]) # Nodi infetti n_inf =",
"5 \"\"\" # Copia degli stati epidemici dagli array degli stati epidemici al",
"plt.clf() ax = plt.gca() self.data.plot(x = 'days', y = 'susceptible', kind = 'line',",
"dei nodi del network (rimozione dei nodi morti e isolamento dei nodi gravemente",
"{} # Lista degli stati self.data = pd.DataFrame(columns=[\"index\",\"days\",\"exposed\",\"infected\",\"severe infected\",\"recovered\",\"dead\",\"susceptible\",\"total\"]) # Tabella stati def",
"loro vicini suscettibili che vengono contaggiati con tasso alfa contaggiosi = np.concatenate((n_exp,n_inf,n_g_inf), axis=None)",
"gravemente infetti # Calcola la probabilità che i vicini siano contaggiati con tasso",
"temporali e degli stati epidemici self.t_state = np.zeros((simulator.num_nodi,1)) self.e_state = np.zeros((simulator.num_nodi,1),dtype=np.int8) # assegnazione",
"nodi che propagano l'epidemia) # Trova i vicini degli esposti, infetti e gravemente",
"np import pandas as pd import simulator import random from igraph import *",
"kind = 'line', color = 'cyan', ax = ax) self.data.plot(x = 'days', y",
"= np.array(np.nonzero(self.states['infected'])[0]) # Nodi gravemente infetti n_g_inf = np.array(np.nonzero(self.states['severe_infected'])[0]) # Nodi guariti n_rec",
"entrare nei nuovi casi di esposto (Rientra nella prob, non è nella categoria",
"= np.array(np.nonzero(self.states['recovered'])[0]) # Nodi morti n_dead = np.array(np.nonzero(self.states['dead'])[0]) new_cases = [] # Ciclo",
"la probabilità che i vicini siano contaggiati con tasso alfa # Nodi esposti",
"n_inf = np.array(np.nonzero(self.states['infected'])[0]) # Nodi gravemente infetti n_g_inf = np.array(np.nonzero(self.states['severe_infected'])[0]) # Nodi guariti",
"{}\\n alpha: {}; beta: {}; gamma: {}'.format(simulator.p_link, simulator.exp0,simulator.t_exp,simulator.t_inf,simulator.alfa,simulator.beta,simulator.gamma)) plt.xlabel('Time (days)') plt.ylabel('Number of nodes')",
"def get_new_cases(self,i,simulator): # Nuovi casi (aggiornamento dei nodi che propagano l'epidemia) # Trova",
"degli stati epidemici al dizionario self.states = { 'exposed':np.where(np.copy(self.e_state)==1,self.e_state,0), 'infected':np.where(np.copy(self.e_state)==2,self.e_state,0), 'recovered':np.where(np.copy(self.e_state)==4,self.e_state,0), 'severe_infected':np.where(np.copy(self.e_state)==3,self.e_state,0), 'dead':np.where(np.copy(self.e_state)==5,self.e_state,0),",
"= np.concatenate((n_exp,n_inf,n_g_inf), axis=None) for x in contaggiosi: for n in self.g.neighbors(x): Rand =",
"- Recovered = 4 - Dead = 5 \"\"\" # Copia degli stati",
"con tasso alfa # Nodi esposti n_exp = np.array(np.nonzero(self.states['exposed'])[0]) # Nodi infetti n_inf",
"tasso alfa contaggiosi = np.concatenate((n_exp,n_inf,n_g_inf), axis=None) for x in contaggiosi: for n in",
"degli stati: - Susceptible = 0 - Exposed = 1 - Infected =",
"non è nella categoria contaggiati, ne in quella guariti ne in quella morti,",
"nel dataframe self.data.loc[i,:] = [i, i*simulator.dt_state,np.count_nonzero(self.states['exposed']), np.count_nonzero(self.states['infected']), np.count_nonzero(self.states['severe_infected']), np.count_nonzero(self.states['recovered']), np.count_nonzero(self.states['dead']), self.states['susceptible'], self.states['total_cases']] #print(self.data)",
"and (n not in n_rec) and (n not in n_dead) and (n not",
"isolamento dei nodi gravemente infetti) pass def get_new_cases(self,i,simulator): # Nuovi casi (aggiornamento dei",
"= 'line', color = 'yellow', ax = ax) self.data.plot(x = 'days', y =",
"guariti n_rec = np.array(np.nonzero(self.states['recovered'])[0]) # Nodi morti n_dead = np.array(np.nonzero(self.states['dead'])[0]) new_cases = []",
"esposti n_exp = np.array(np.nonzero(self.states['exposed'])[0]) # Nodi infetti n_inf = np.array(np.nonzero(self.states['infected'])[0]) # Nodi gravemente",
"Nodi morti n_dead = np.array(np.nonzero(self.states['dead'])[0]) new_cases = [] # Ciclo i Nodi esposti,",
"infetti n_g_inf = np.array(np.nonzero(self.states['severe_infected'])[0]) # Nodi guariti n_rec = np.array(np.nonzero(self.states['recovered'])[0]) # Nodi morti",
"self.data = pd.DataFrame(columns=[\"index\",\"days\",\"exposed\",\"infected\",\"severe infected\",\"recovered\",\"dead\",\"susceptible\",\"total\"]) # Tabella stati def update_states(self,i,simulator): # Aggiornamento degli stati",
"ax = ax) self.data.plot(x = 'days', y = 'infected', kind = 'line', color",
"nodi gravemente infetti) pass def get_new_cases(self,i,simulator): # Nuovi casi (aggiornamento dei nodi che",
"gravemente infetti) pass def get_new_cases(self,i,simulator): # Nuovi casi (aggiornamento dei nodi che propagano",
"np.zeros((simulator.num_nodi,1)) self.e_state = np.zeros((simulator.num_nodi,1),dtype=np.int8) # assegnazione iniziale random dei nodi esposti np.put(self.e_state,np.random.choice(range(simulator.num_nodi*1), simulator.exp0,",
"kind = 'line', color = 'yellow', ax = ax) self.data.plot(x = 'days', y",
"= 'yellow', ax = ax) self.data.plot(x = 'days', y = 'infected', kind =",
"= ax) plt.title('link_p: {}; exp0: {}; t_inc: {}; t_inf: {}\\n alpha: {}; beta:",
"'exposed', kind = 'line', color = 'yellow', ax = ax) self.data.plot(x = 'days',",
"not in contaggiosi) and (n not in n_rec) and (n not in n_dead)",
"np.zeros((simulator.num_nodi,1),dtype=np.int8) # assegnazione iniziale random dei nodi esposti np.put(self.e_state,np.random.choice(range(simulator.num_nodi*1), simulator.exp0, replace=False),1) self.states =",
"pandas as pd import simulator import random from igraph import * import matplotlib.pyplot",
"# Aggiornamento dei nodi del network (rimozione dei nodi morti e isolamento dei",
"and (n not in n_dead) and (n not in new_cases): new_cases.append(n) #print(new_cases) return",
"stati \"\"\"Lista degli stati: - Susceptible = 0 - Exposed = 1 -",
"as plt class Network(): \"\"\"docstring for Network\"\"\" def __init__(self, simulator): # Genero un",
"morti e isolamento dei nodi gravemente infetti) pass def get_new_cases(self,i,simulator): # Nuovi casi",
"self.data.plot(x = 'days', y = 'dead', kind = 'line', color = 'brown', ax",
"n_rec = np.array(np.nonzero(self.states['recovered'])[0]) # Nodi morti n_dead = np.array(np.nonzero(self.states['dead'])[0]) new_cases = [] #",
"{}; exp0: {}; t_inc: {}; t_inf: {}\\n alpha: {}; beta: {}; gamma: {}'.format(simulator.p_link,",
"in contaggiosi: for n in self.g.neighbors(x): Rand = np.random.random() # Condizione per entrare",
"che vengono contaggiati con tasso alfa contaggiosi = np.concatenate((n_exp,n_inf,n_g_inf), axis=None) for x in",
"# Network import numpy as np import pandas as pd import simulator import",
"'days', y = 'dead', kind = 'line', color = 'brown', ax = ax)",
"not in n_rec) and (n not in n_dead) and (n not in new_cases):",
"dataframe self.data.loc[i,:] = [i, i*simulator.dt_state,np.count_nonzero(self.states['exposed']), np.count_nonzero(self.states['infected']), np.count_nonzero(self.states['severe_infected']), np.count_nonzero(self.states['recovered']), np.count_nonzero(self.states['dead']), self.states['susceptible'], self.states['total_cases']] #print(self.data) def",
"= { 'exposed':np.where(np.copy(self.e_state)==1,self.e_state,0), 'infected':np.where(np.copy(self.e_state)==2,self.e_state,0), 'recovered':np.where(np.copy(self.e_state)==4,self.e_state,0), 'severe_infected':np.where(np.copy(self.e_state)==3,self.e_state,0), 'dead':np.where(np.copy(self.e_state)==5,self.e_state,0), 'susceptible':(simulator.num_nodi - np.count_nonzero(np.copy(self.e_state))), 'total_cases':np.count_nonzero(np.copy(self.e_state)) } #",
"n_rec) and (n not in n_dead) and (n not in new_cases): new_cases.append(n) #print(new_cases)",
"self.e_state = np.zeros((simulator.num_nodi,1),dtype=np.int8) # assegnazione iniziale random dei nodi esposti np.put(self.e_state,np.random.choice(range(simulator.num_nodi*1), simulator.exp0, replace=False),1)",
"Infected = 2 - Severe Infected = 3 - Recovered = 4 -",
"per entrare nei nuovi casi di esposto (Rientra nella prob, non è nella",
"Copia degli stati epidemici dagli array degli stati epidemici al dizionario self.states =",
"dagli array degli stati epidemici al dizionario self.states = { 'exposed':np.where(np.copy(self.e_state)==1,self.e_state,0), 'infected':np.where(np.copy(self.e_state)==2,self.e_state,0), 'recovered':np.where(np.copy(self.e_state)==4,self.e_state,0),",
"np.put(self.e_state,np.random.choice(range(simulator.num_nodi*1), simulator.exp0, replace=False),1) self.states = {} # Lista degli stati self.data = pd.DataFrame(columns=[\"index\",\"days\",\"exposed\",\"infected\",\"severe",
"= 'cyan', ax = ax) self.data.plot(x = 'days', y = 'exposed', kind =",
"epidemico nel dataframe self.data.loc[i,:] = [i, i*simulator.dt_state,np.count_nonzero(self.states['exposed']), np.count_nonzero(self.states['infected']), np.count_nonzero(self.states['severe_infected']), np.count_nonzero(self.states['recovered']), np.count_nonzero(self.states['dead']), self.states['susceptible'], self.states['total_cases']]",
"dizionario self.states = { 'exposed':np.where(np.copy(self.e_state)==1,self.e_state,0), 'infected':np.where(np.copy(self.e_state)==2,self.e_state,0), 'recovered':np.where(np.copy(self.e_state)==4,self.e_state,0), 'severe_infected':np.where(np.copy(self.e_state)==3,self.e_state,0), 'dead':np.where(np.copy(self.e_state)==5,self.e_state,0), 'susceptible':(simulator.num_nodi - np.count_nonzero(np.copy(self.e_state))), 'total_cases':np.count_nonzero(np.copy(self.e_state))",
"np.array(np.nonzero(self.states['infected'])[0]) # Nodi gravemente infetti n_g_inf = np.array(np.nonzero(self.states['severe_infected'])[0]) # Nodi guariti n_rec =",
"nuovi casi di esposto (Rientra nella prob, non è nella categoria contaggiati, ne",
"matplotlib.pyplot as plt class Network(): \"\"\"docstring for Network\"\"\" def __init__(self, simulator): # Genero",
"= 'days', y = 'exposed', kind = 'line', color = 'yellow', ax =",
"new_cases = [] # Ciclo i Nodi esposti, infetti e gravemente infetti e",
"plot(self,i,simulator): # Creazione Grafici plt.clf() ax = plt.gca() self.data.plot(x = 'days', y =",
"= np.array(np.nonzero(self.states['exposed'])[0]) # Nodi infetti n_inf = np.array(np.nonzero(self.states['infected'])[0]) # Nodi gravemente infetti n_g_inf",
"= np.random.random() # Condizione per entrare nei nuovi casi di esposto (Rientra nella",
"Genero un grafo random self.g = Graph.Erdos_Renyi(simulator.num_nodi,simulator.p_link) # Inizializzazione dei vettori degli step",
"'exposed':np.where(np.copy(self.e_state)==1,self.e_state,0), 'infected':np.where(np.copy(self.e_state)==2,self.e_state,0), 'recovered':np.where(np.copy(self.e_state)==4,self.e_state,0), 'severe_infected':np.where(np.copy(self.e_state)==3,self.e_state,0), 'dead':np.where(np.copy(self.e_state)==5,self.e_state,0), 'susceptible':(simulator.num_nodi - np.count_nonzero(np.copy(self.e_state))), 'total_cases':np.count_nonzero(np.copy(self.e_state)) } # Inserimento della",
"infetti e gravemente infetti # Calcola la probabilità che i vicini siano contaggiati",
"epidemici dagli array degli stati epidemici al dizionario self.states = { 'exposed':np.where(np.copy(self.e_state)==1,self.e_state,0), 'infected':np.where(np.copy(self.e_state)==2,self.e_state,0),",
"- Susceptible = 0 - Exposed = 1 - Infected = 2 -",
"if (Rand<simulator.alfa) and (n not in contaggiosi) and (n not in n_rec) and",
"dei nodi esposti np.put(self.e_state,np.random.choice(range(simulator.num_nodi*1), simulator.exp0, replace=False),1) self.states = {} # Lista degli stati",
"as pd import simulator import random from igraph import * import matplotlib.pyplot as",
"'days', y = 'severe infected', kind = 'line', color = 'magenta', ax =",
"stati epidemici al dizionario self.states = { 'exposed':np.where(np.copy(self.e_state)==1,self.e_state,0), 'infected':np.where(np.copy(self.e_state)==2,self.e_state,0), 'recovered':np.where(np.copy(self.e_state)==4,self.e_state,0), 'severe_infected':np.where(np.copy(self.e_state)==3,self.e_state,0), 'dead':np.where(np.copy(self.e_state)==5,self.e_state,0), 'susceptible':(simulator.num_nodi",
"np.array(np.nonzero(self.states['recovered'])[0]) # Nodi morti n_dead = np.array(np.nonzero(self.states['dead'])[0]) new_cases = [] # Ciclo i",
"{}; t_inf: {}\\n alpha: {}; beta: {}; gamma: {}'.format(simulator.p_link, simulator.exp0,simulator.t_exp,simulator.t_inf,simulator.alfa,simulator.beta,simulator.gamma)) plt.xlabel('Time (days)') plt.ylabel('Number",
"della somma di ogni stato epidemico nel dataframe self.data.loc[i,:] = [i, i*simulator.dt_state,np.count_nonzero(self.states['exposed']), np.count_nonzero(self.states['infected']),",
"Dead = 5 \"\"\" # Copia degli stati epidemici dagli array degli stati",
"'line', color = 'brown', ax = ax) plt.title('link_p: {}; exp0: {}; t_inc: {};",
"e gravemente infetti # Calcola la probabilità che i vicini siano contaggiati con",
"infetti # Calcola la probabilità che i vicini siano contaggiati con tasso alfa",
"\"\"\"docstring for Network\"\"\" def __init__(self, simulator): # Genero un grafo random self.g =",
"Nodi guariti n_rec = np.array(np.nonzero(self.states['recovered'])[0]) # Nodi morti n_dead = np.array(np.nonzero(self.states['dead'])[0]) new_cases =",
"dei nodi che propagano l'epidemia) # Trova i vicini degli esposti, infetti e",
"array degli stati epidemici al dizionario self.states = { 'exposed':np.where(np.copy(self.e_state)==1,self.e_state,0), 'infected':np.where(np.copy(self.e_state)==2,self.e_state,0), 'recovered':np.where(np.copy(self.e_state)==4,self.e_state,0), 'severe_infected':np.where(np.copy(self.e_state)==3,self.e_state,0),",
"in quella morti, nemmeno doppione) if (Rand<simulator.alfa) and (n not in contaggiosi) and",
"siano contaggiati con tasso alfa # Nodi esposti n_exp = np.array(np.nonzero(self.states['exposed'])[0]) # Nodi",
"Recovered = 4 - Dead = 5 \"\"\" # Copia degli stati epidemici",
"'days', y = 'exposed', kind = 'line', color = 'yellow', ax = ax)",
"'total_cases':np.count_nonzero(np.copy(self.e_state)) } # Inserimento della somma di ogni stato epidemico nel dataframe self.data.loc[i,:]",
"quella guariti ne in quella morti, nemmeno doppione) if (Rand<simulator.alfa) and (n not",
"self.data.plot(x = 'days', y = 'infected', kind = 'line', color = 'blue', ax",
"# Nodi gravemente infetti n_g_inf = np.array(np.nonzero(self.states['severe_infected'])[0]) # Nodi guariti n_rec = np.array(np.nonzero(self.states['recovered'])[0])",
"= plt.gca() self.data.plot(x = 'days', y = 'susceptible', kind = 'line', color =",
"'days', y = 'susceptible', kind = 'line', color = 'cyan', ax = ax)",
"self.g = Graph.Erdos_Renyi(simulator.num_nodi,simulator.p_link) # Inizializzazione dei vettori degli step temporali e degli stati",
"# Creazione Grafici plt.clf() ax = plt.gca() self.data.plot(x = 'days', y = 'susceptible',",
"from igraph import * import matplotlib.pyplot as plt class Network(): \"\"\"docstring for Network\"\"\"",
"(aggiornamento dei nodi che propagano l'epidemia) # Trova i vicini degli esposti, infetti",
"stati epidemici self.t_state = np.zeros((simulator.num_nodi,1)) self.e_state = np.zeros((simulator.num_nodi,1),dtype=np.int8) # assegnazione iniziale random dei",
"\"\"\"Lista degli stati: - Susceptible = 0 - Exposed = 1 - Infected",
"np.count_nonzero(self.states['dead']), self.states['susceptible'], self.states['total_cases']] #print(self.data) def plot(self,i,simulator): # Creazione Grafici plt.clf() ax = plt.gca()",
"n_dead = np.array(np.nonzero(self.states['dead'])[0]) new_cases = [] # Ciclo i Nodi esposti, infetti e",
"Aggiornamento degli stati \"\"\"Lista degli stati: - Susceptible = 0 - Exposed =",
"Creazione Grafici plt.clf() ax = plt.gca() self.data.plot(x = 'days', y = 'susceptible', kind",
"# Calcola la probabilità che i vicini siano contaggiati con tasso alfa #",
"nodi del network (rimozione dei nodi morti e isolamento dei nodi gravemente infetti)",
"ax = ax) self.data.plot(x = 'days', y = 'severe infected', kind = 'line',",
"update_states(self,i,simulator): # Aggiornamento degli stati \"\"\"Lista degli stati: - Susceptible = 0 -",
"infected', kind = 'line', color = 'magenta', ax = ax) self.data.plot(x = 'days',",
"- Severe Infected = 3 - Recovered = 4 - Dead = 5",
"dei nodi gravemente infetti) pass def get_new_cases(self,i,simulator): # Nuovi casi (aggiornamento dei nodi",
"= np.array(np.nonzero(self.states['severe_infected'])[0]) # Nodi guariti n_rec = np.array(np.nonzero(self.states['recovered'])[0]) # Nodi morti n_dead =",
"# Nodi morti n_dead = np.array(np.nonzero(self.states['dead'])[0]) new_cases = [] # Ciclo i Nodi",
"di ogni stato epidemico nel dataframe self.data.loc[i,:] = [i, i*simulator.dt_state,np.count_nonzero(self.states['exposed']), np.count_nonzero(self.states['infected']), np.count_nonzero(self.states['severe_infected']), np.count_nonzero(self.states['recovered']),",
"= 4 - Dead = 5 \"\"\" # Copia degli stati epidemici dagli",
"trovo i loro vicini suscettibili che vengono contaggiati con tasso alfa contaggiosi =",
"4 - Dead = 5 \"\"\" # Copia degli stati epidemici dagli array",
"ne in quella morti, nemmeno doppione) if (Rand<simulator.alfa) and (n not in contaggiosi)",
"(n not in n_rec) and (n not in n_dead) and (n not in",
"ax) self.data.plot(x = 'days', y = 'infected', kind = 'line', color = 'blue',",
"'line', color = 'blue', ax = ax) self.data.plot(x = 'days', y = 'severe",
"ax = ax) plt.title('link_p: {}; exp0: {}; t_inc: {}; t_inf: {}\\n alpha: {};",
"import pandas as pd import simulator import random from igraph import * import",
"np.concatenate((n_exp,n_inf,n_g_inf), axis=None) for x in contaggiosi: for n in self.g.neighbors(x): Rand = np.random.random()",
"nei nuovi casi di esposto (Rientra nella prob, non è nella categoria contaggiati,",
"nodes') plt.savefig('./plots/states.png') def update_nodes(self,i,simulator): # Aggiornamento dei nodi del network (rimozione dei nodi",
"che i vicini siano contaggiati con tasso alfa # Nodi esposti n_exp =",
"contaggiati, ne in quella guariti ne in quella morti, nemmeno doppione) if (Rand<simulator.alfa)",
"= pd.DataFrame(columns=[\"index\",\"days\",\"exposed\",\"infected\",\"severe infected\",\"recovered\",\"dead\",\"susceptible\",\"total\"]) # Tabella stati def update_states(self,i,simulator): # Aggiornamento degli stati \"\"\"Lista",
"vicini suscettibili che vengono contaggiati con tasso alfa contaggiosi = np.concatenate((n_exp,n_inf,n_g_inf), axis=None) for",
"'line', color = 'green', ax = ax) self.data.plot(x = 'days', y = 'dead',",
"vicini siano contaggiati con tasso alfa # Nodi esposti n_exp = np.array(np.nonzero(self.states['exposed'])[0]) #",
"= 'days', y = 'dead', kind = 'line', color = 'brown', ax =",
"color = 'brown', ax = ax) plt.title('link_p: {}; exp0: {}; t_inc: {}; t_inf:",
"epidemici self.t_state = np.zeros((simulator.num_nodi,1)) self.e_state = np.zeros((simulator.num_nodi,1),dtype=np.int8) # assegnazione iniziale random dei nodi",
"Grafici plt.clf() ax = plt.gca() self.data.plot(x = 'days', y = 'susceptible', kind =",
"dei vettori degli step temporali e degli stati epidemici self.t_state = np.zeros((simulator.num_nodi,1)) self.e_state",
"Tabella stati def update_states(self,i,simulator): # Aggiornamento degli stati \"\"\"Lista degli stati: - Susceptible",
"'susceptible', kind = 'line', color = 'cyan', ax = ax) self.data.plot(x = 'days',",
"Nuovi casi (aggiornamento dei nodi che propagano l'epidemia) # Trova i vicini degli",
"esposti, infetti e gravemente infetti e trovo i loro vicini suscettibili che vengono",
"def update_nodes(self,i,simulator): # Aggiornamento dei nodi del network (rimozione dei nodi morti e",
"pd import simulator import random from igraph import * import matplotlib.pyplot as plt",
"# Inizializzazione dei vettori degli step temporali e degli stati epidemici self.t_state =",
"def update_states(self,i,simulator): # Aggiornamento degli stati \"\"\"Lista degli stati: - Susceptible = 0",
"infetti) pass def get_new_cases(self,i,simulator): # Nuovi casi (aggiornamento dei nodi che propagano l'epidemia)",
"import matplotlib.pyplot as plt class Network(): \"\"\"docstring for Network\"\"\" def __init__(self, simulator): #",
"{ 'exposed':np.where(np.copy(self.e_state)==1,self.e_state,0), 'infected':np.where(np.copy(self.e_state)==2,self.e_state,0), 'recovered':np.where(np.copy(self.e_state)==4,self.e_state,0), 'severe_infected':np.where(np.copy(self.e_state)==3,self.e_state,0), 'dead':np.where(np.copy(self.e_state)==5,self.e_state,0), 'susceptible':(simulator.num_nodi - np.count_nonzero(np.copy(self.e_state))), 'total_cases':np.count_nonzero(np.copy(self.e_state)) } # Inserimento",
"= 'days', y = 'infected', kind = 'line', color = 'blue', ax =",
"un grafo random self.g = Graph.Erdos_Renyi(simulator.num_nodi,simulator.p_link) # Inizializzazione dei vettori degli step temporali",
"color = 'green', ax = ax) self.data.plot(x = 'days', y = 'dead', kind",
"color = 'blue', ax = ax) self.data.plot(x = 'days', y = 'severe infected',",
"vicini degli esposti, infetti e gravemente infetti # Calcola la probabilità che i",
"self.states['total_cases']] #print(self.data) def plot(self,i,simulator): # Creazione Grafici plt.clf() ax = plt.gca() self.data.plot(x =",
"self.data.plot(x = 'days', y = 'exposed', kind = 'line', color = 'yellow', ax",
"'dead', kind = 'line', color = 'brown', ax = ax) plt.title('link_p: {}; exp0:",
"and (n not in contaggiosi) and (n not in n_rec) and (n not",
"1 - Infected = 2 - Severe Infected = 3 - Recovered =",
"= np.array(np.nonzero(self.states['dead'])[0]) new_cases = [] # Ciclo i Nodi esposti, infetti e gravemente",
"gravemente infetti n_g_inf = np.array(np.nonzero(self.states['severe_infected'])[0]) # Nodi guariti n_rec = np.array(np.nonzero(self.states['recovered'])[0]) # Nodi",
"simulator.exp0, replace=False),1) self.states = {} # Lista degli stati self.data = pd.DataFrame(columns=[\"index\",\"days\",\"exposed\",\"infected\",\"severe infected\",\"recovered\",\"dead\",\"susceptible\",\"total\"])",
"ax = ax) self.data.plot(x = 'days', y = 'dead', kind = 'line', color",
"ogni stato epidemico nel dataframe self.data.loc[i,:] = [i, i*simulator.dt_state,np.count_nonzero(self.states['exposed']), np.count_nonzero(self.states['infected']), np.count_nonzero(self.states['severe_infected']), np.count_nonzero(self.states['recovered']), np.count_nonzero(self.states['dead']),",
"= 'days', y = 'susceptible', kind = 'line', color = 'cyan', ax =",
"in self.g.neighbors(x): Rand = np.random.random() # Condizione per entrare nei nuovi casi di",
"= 'green', ax = ax) self.data.plot(x = 'days', y = 'dead', kind =",
"'line', color = 'magenta', ax = ax) self.data.plot(x = 'days', y = 'recovered',",
"update_nodes(self,i,simulator): # Aggiornamento dei nodi del network (rimozione dei nodi morti e isolamento",
"con tasso alfa contaggiosi = np.concatenate((n_exp,n_inf,n_g_inf), axis=None) for x in contaggiosi: for n",
"Inizializzazione dei vettori degli step temporali e degli stati epidemici self.t_state = np.zeros((simulator.num_nodi,1))",
"= 'dead', kind = 'line', color = 'brown', ax = ax) plt.title('link_p: {};",
"np.count_nonzero(np.copy(self.e_state))), 'total_cases':np.count_nonzero(np.copy(self.e_state)) } # Inserimento della somma di ogni stato epidemico nel dataframe",
"Nodi esposti n_exp = np.array(np.nonzero(self.states['exposed'])[0]) # Nodi infetti n_inf = np.array(np.nonzero(self.states['infected'])[0]) # Nodi",
"doppione) if (Rand<simulator.alfa) and (n not in contaggiosi) and (n not in n_rec)",
"Severe Infected = 3 - Recovered = 4 - Dead = 5 \"\"\"",
"= 'line', color = 'brown', ax = ax) plt.title('link_p: {}; exp0: {}; t_inc:",
"'blue', ax = ax) self.data.plot(x = 'days', y = 'severe infected', kind =",
"color = 'magenta', ax = ax) self.data.plot(x = 'days', y = 'recovered', kind",
"nodi morti e isolamento dei nodi gravemente infetti) pass def get_new_cases(self,i,simulator): # Nuovi",
"import numpy as np import pandas as pd import simulator import random from",
"ne in quella guariti ne in quella morti, nemmeno doppione) if (Rand<simulator.alfa) and",
"ax) self.data.plot(x = 'days', y = 'dead', kind = 'line', color = 'brown',",
"che propagano l'epidemia) # Trova i vicini degli esposti, infetti e gravemente infetti",
"{}; beta: {}; gamma: {}'.format(simulator.p_link, simulator.exp0,simulator.t_exp,simulator.t_inf,simulator.alfa,simulator.beta,simulator.gamma)) plt.xlabel('Time (days)') plt.ylabel('Number of nodes') plt.savefig('./plots/states.png') def",
"Susceptible = 0 - Exposed = 1 - Infected = 2 - Severe",
"'severe infected', kind = 'line', color = 'magenta', ax = ax) self.data.plot(x =",
"(n not in n_dead) and (n not in new_cases): new_cases.append(n) #print(new_cases) return new_cases",
"color = 'cyan', ax = ax) self.data.plot(x = 'days', y = 'exposed', kind",
"'green', ax = ax) self.data.plot(x = 'days', y = 'dead', kind = 'line',",
"l'epidemia) # Trova i vicini degli esposti, infetti e gravemente infetti # Calcola",
"ax) plt.title('link_p: {}; exp0: {}; t_inc: {}; t_inf: {}\\n alpha: {}; beta: {};",
"nella categoria contaggiati, ne in quella guariti ne in quella morti, nemmeno doppione)",
"Exposed = 1 - Infected = 2 - Severe Infected = 3 -",
"Network\"\"\" def __init__(self, simulator): # Genero un grafo random self.g = Graph.Erdos_Renyi(simulator.num_nodi,simulator.p_link) #",
"quella morti, nemmeno doppione) if (Rand<simulator.alfa) and (n not in contaggiosi) and (n",
"contaggiati con tasso alfa # Nodi esposti n_exp = np.array(np.nonzero(self.states['exposed'])[0]) # Nodi infetti",
"of nodes') plt.savefig('./plots/states.png') def update_nodes(self,i,simulator): # Aggiornamento dei nodi del network (rimozione dei",
"in quella guariti ne in quella morti, nemmeno doppione) if (Rand<simulator.alfa) and (n",
"alfa contaggiosi = np.concatenate((n_exp,n_inf,n_g_inf), axis=None) for x in contaggiosi: for n in self.g.neighbors(x):",
"self.states = {} # Lista degli stati self.data = pd.DataFrame(columns=[\"index\",\"days\",\"exposed\",\"infected\",\"severe infected\",\"recovered\",\"dead\",\"susceptible\",\"total\"]) # Tabella",
"esposto (Rientra nella prob, non è nella categoria contaggiati, ne in quella guariti",
"Graph.Erdos_Renyi(simulator.num_nodi,simulator.p_link) # Inizializzazione dei vettori degli step temporali e degli stati epidemici self.t_state",
"= {} # Lista degli stati self.data = pd.DataFrame(columns=[\"index\",\"days\",\"exposed\",\"infected\",\"severe infected\",\"recovered\",\"dead\",\"susceptible\",\"total\"]) # Tabella stati",
"esposti, infetti e gravemente infetti # Calcola la probabilità che i vicini siano",
"Rand = np.random.random() # Condizione per entrare nei nuovi casi di esposto (Rientra",
"{}'.format(simulator.p_link, simulator.exp0,simulator.t_exp,simulator.t_inf,simulator.alfa,simulator.beta,simulator.gamma)) plt.xlabel('Time (days)') plt.ylabel('Number of nodes') plt.savefig('./plots/states.png') def update_nodes(self,i,simulator): # Aggiornamento dei",
"in contaggiosi) and (n not in n_rec) and (n not in n_dead) and",
"stati def update_states(self,i,simulator): # Aggiornamento degli stati \"\"\"Lista degli stati: - Susceptible =",
"= 5 \"\"\" # Copia degli stati epidemici dagli array degli stati epidemici",
"np.count_nonzero(self.states['severe_infected']), np.count_nonzero(self.states['recovered']), np.count_nonzero(self.states['dead']), self.states['susceptible'], self.states['total_cases']] #print(self.data) def plot(self,i,simulator): # Creazione Grafici plt.clf() ax",
"# Genero un grafo random self.g = Graph.Erdos_Renyi(simulator.num_nodi,simulator.p_link) # Inizializzazione dei vettori degli",
"del network (rimozione dei nodi morti e isolamento dei nodi gravemente infetti) pass",
"# Ciclo i Nodi esposti, infetti e gravemente infetti e trovo i loro",
"= np.zeros((simulator.num_nodi,1),dtype=np.int8) # assegnazione iniziale random dei nodi esposti np.put(self.e_state,np.random.choice(range(simulator.num_nodi*1), simulator.exp0, replace=False),1) self.states",
"degli stati epidemici self.t_state = np.zeros((simulator.num_nodi,1)) self.e_state = np.zeros((simulator.num_nodi,1),dtype=np.int8) # assegnazione iniziale random",
"= 'line', color = 'magenta', ax = ax) self.data.plot(x = 'days', y =",
"alpha: {}; beta: {}; gamma: {}'.format(simulator.p_link, simulator.exp0,simulator.t_exp,simulator.t_inf,simulator.alfa,simulator.beta,simulator.gamma)) plt.xlabel('Time (days)') plt.ylabel('Number of nodes') plt.savefig('./plots/states.png')",
"= Graph.Erdos_Renyi(simulator.num_nodi,simulator.p_link) # Inizializzazione dei vettori degli step temporali e degli stati epidemici",
"import simulator import random from igraph import * import matplotlib.pyplot as plt class",
"= 'brown', ax = ax) plt.title('link_p: {}; exp0: {}; t_inc: {}; t_inf: {}\\n",
"'line', color = 'cyan', ax = ax) self.data.plot(x = 'days', y = 'exposed',",
"prob, non è nella categoria contaggiati, ne in quella guariti ne in quella",
"n_exp = np.array(np.nonzero(self.states['exposed'])[0]) # Nodi infetti n_inf = np.array(np.nonzero(self.states['infected'])[0]) # Nodi gravemente infetti",
"propagano l'epidemia) # Trova i vicini degli esposti, infetti e gravemente infetti #",
"Nodi gravemente infetti n_g_inf = np.array(np.nonzero(self.states['severe_infected'])[0]) # Nodi guariti n_rec = np.array(np.nonzero(self.states['recovered'])[0]) #",
"color = 'yellow', ax = ax) self.data.plot(x = 'days', y = 'infected', kind",
"= 'recovered', kind = 'line', color = 'green', ax = ax) self.data.plot(x =",
"plt.gca() self.data.plot(x = 'days', y = 'susceptible', kind = 'line', color = 'cyan',",
"= 'line', color = 'green', ax = ax) self.data.plot(x = 'days', y =",
"0 - Exposed = 1 - Infected = 2 - Severe Infected =",
"ax = plt.gca() self.data.plot(x = 'days', y = 'susceptible', kind = 'line', color",
"= 2 - Severe Infected = 3 - Recovered = 4 - Dead",
"axis=None) for x in contaggiosi: for n in self.g.neighbors(x): Rand = np.random.random() #",
"self.t_state = np.zeros((simulator.num_nodi,1)) self.e_state = np.zeros((simulator.num_nodi,1),dtype=np.int8) # assegnazione iniziale random dei nodi esposti",
"# Trova i vicini degli esposti, infetti e gravemente infetti # Calcola la",
"(n not in contaggiosi) and (n not in n_rec) and (n not in",
"= 'blue', ax = ax) self.data.plot(x = 'days', y = 'severe infected', kind",
"categoria contaggiati, ne in quella guariti ne in quella morti, nemmeno doppione) if",
"step temporali e degli stati epidemici self.t_state = np.zeros((simulator.num_nodi,1)) self.e_state = np.zeros((simulator.num_nodi,1),dtype=np.int8) #",
"# Lista degli stati self.data = pd.DataFrame(columns=[\"index\",\"days\",\"exposed\",\"infected\",\"severe infected\",\"recovered\",\"dead\",\"susceptible\",\"total\"]) # Tabella stati def update_states(self,i,simulator):",
"self.data.loc[i,:] = [i, i*simulator.dt_state,np.count_nonzero(self.states['exposed']), np.count_nonzero(self.states['infected']), np.count_nonzero(self.states['severe_infected']), np.count_nonzero(self.states['recovered']), np.count_nonzero(self.states['dead']), self.states['susceptible'], self.states['total_cases']] #print(self.data) def plot(self,i,simulator):",
"è nella categoria contaggiati, ne in quella guariti ne in quella morti, nemmeno",
"contaggiosi) and (n not in n_rec) and (n not in n_dead) and (n",
"guariti ne in quella morti, nemmeno doppione) if (Rand<simulator.alfa) and (n not in",
"= 3 - Recovered = 4 - Dead = 5 \"\"\" # Copia",
"= 'days', y = 'recovered', kind = 'line', color = 'green', ax =",
"'recovered':np.where(np.copy(self.e_state)==4,self.e_state,0), 'severe_infected':np.where(np.copy(self.e_state)==3,self.e_state,0), 'dead':np.where(np.copy(self.e_state)==5,self.e_state,0), 'susceptible':(simulator.num_nodi - np.count_nonzero(np.copy(self.e_state))), 'total_cases':np.count_nonzero(np.copy(self.e_state)) } # Inserimento della somma di",
"Ciclo i Nodi esposti, infetti e gravemente infetti e trovo i loro vicini",
"plt.xlabel('Time (days)') plt.ylabel('Number of nodes') plt.savefig('./plots/states.png') def update_nodes(self,i,simulator): # Aggiornamento dei nodi del",
"import random from igraph import * import matplotlib.pyplot as plt class Network(): \"\"\"docstring",
"'days', y = 'infected', kind = 'line', color = 'blue', ax = ax)",
"'cyan', ax = ax) self.data.plot(x = 'days', y = 'exposed', kind = 'line',",
"gamma: {}'.format(simulator.p_link, simulator.exp0,simulator.t_exp,simulator.t_inf,simulator.alfa,simulator.beta,simulator.gamma)) plt.xlabel('Time (days)') plt.ylabel('Number of nodes') plt.savefig('./plots/states.png') def update_nodes(self,i,simulator): # Aggiornamento",
"y = 'susceptible', kind = 'line', color = 'cyan', ax = ax) self.data.plot(x",
"2 - Severe Infected = 3 - Recovered = 4 - Dead =",
"# Inserimento della somma di ogni stato epidemico nel dataframe self.data.loc[i,:] = [i,",
"# assegnazione iniziale random dei nodi esposti np.put(self.e_state,np.random.choice(range(simulator.num_nodi*1), simulator.exp0, replace=False),1) self.states = {}",
"# Copia degli stati epidemici dagli array degli stati epidemici al dizionario self.states",
"esposti np.put(self.e_state,np.random.choice(range(simulator.num_nodi*1), simulator.exp0, replace=False),1) self.states = {} # Lista degli stati self.data =",
"np.random.random() # Condizione per entrare nei nuovi casi di esposto (Rientra nella prob,",
"degli stati \"\"\"Lista degli stati: - Susceptible = 0 - Exposed = 1",
"np.count_nonzero(self.states['recovered']), np.count_nonzero(self.states['dead']), self.states['susceptible'], self.states['total_cases']] #print(self.data) def plot(self,i,simulator): # Creazione Grafici plt.clf() ax =",
"alfa # Nodi esposti n_exp = np.array(np.nonzero(self.states['exposed'])[0]) # Nodi infetti n_inf = np.array(np.nonzero(self.states['infected'])[0])",
"degli esposti, infetti e gravemente infetti # Calcola la probabilità che i vicini",
"= np.zeros((simulator.num_nodi,1)) self.e_state = np.zeros((simulator.num_nodi,1),dtype=np.int8) # assegnazione iniziale random dei nodi esposti np.put(self.e_state,np.random.choice(range(simulator.num_nodi*1),",
"casi di esposto (Rientra nella prob, non è nella categoria contaggiati, ne in",
"(Rand<simulator.alfa) and (n not in contaggiosi) and (n not in n_rec) and (n",
"pass def get_new_cases(self,i,simulator): # Nuovi casi (aggiornamento dei nodi che propagano l'epidemia) #",
"Inserimento della somma di ogni stato epidemico nel dataframe self.data.loc[i,:] = [i, i*simulator.dt_state,np.count_nonzero(self.states['exposed']),",
"Network(): \"\"\"docstring for Network\"\"\" def __init__(self, simulator): # Genero un grafo random self.g",
"self.data.plot(x = 'days', y = 'susceptible', kind = 'line', color = 'cyan', ax",
"exp0: {}; t_inc: {}; t_inf: {}\\n alpha: {}; beta: {}; gamma: {}'.format(simulator.p_link, simulator.exp0,simulator.t_exp,simulator.t_inf,simulator.alfa,simulator.beta,simulator.gamma))",
"vengono contaggiati con tasso alfa contaggiosi = np.concatenate((n_exp,n_inf,n_g_inf), axis=None) for x in contaggiosi:",
"y = 'dead', kind = 'line', color = 'brown', ax = ax) plt.title('link_p:",
"def plot(self,i,simulator): # Creazione Grafici plt.clf() ax = plt.gca() self.data.plot(x = 'days', y",
"'days', y = 'recovered', kind = 'line', color = 'green', ax = ax)",
"in n_rec) and (n not in n_dead) and (n not in new_cases): new_cases.append(n)",
"degli stati epidemici dagli array degli stati epidemici al dizionario self.states = {",
"= 'severe infected', kind = 'line', color = 'magenta', ax = ax) self.data.plot(x",
"Infected = 3 - Recovered = 4 - Dead = 5 \"\"\" #",
"# Nodi guariti n_rec = np.array(np.nonzero(self.states['recovered'])[0]) # Nodi morti n_dead = np.array(np.nonzero(self.states['dead'])[0]) new_cases",
"- Exposed = 1 - Infected = 2 - Severe Infected = 3",
"stato epidemico nel dataframe self.data.loc[i,:] = [i, i*simulator.dt_state,np.count_nonzero(self.states['exposed']), np.count_nonzero(self.states['infected']), np.count_nonzero(self.states['severe_infected']), np.count_nonzero(self.states['recovered']), np.count_nonzero(self.states['dead']), self.states['susceptible'],",
"import * import matplotlib.pyplot as plt class Network(): \"\"\"docstring for Network\"\"\" def __init__(self,",
"epidemici al dizionario self.states = { 'exposed':np.where(np.copy(self.e_state)==1,self.e_state,0), 'infected':np.where(np.copy(self.e_state)==2,self.e_state,0), 'recovered':np.where(np.copy(self.e_state)==4,self.e_state,0), 'severe_infected':np.where(np.copy(self.e_state)==3,self.e_state,0), 'dead':np.where(np.copy(self.e_state)==5,self.e_state,0), 'susceptible':(simulator.num_nodi -",
"'infected':np.where(np.copy(self.e_state)==2,self.e_state,0), 'recovered':np.where(np.copy(self.e_state)==4,self.e_state,0), 'severe_infected':np.where(np.copy(self.e_state)==3,self.e_state,0), 'dead':np.where(np.copy(self.e_state)==5,self.e_state,0), 'susceptible':(simulator.num_nodi - np.count_nonzero(np.copy(self.e_state))), 'total_cases':np.count_nonzero(np.copy(self.e_state)) } # Inserimento della somma",
"ax) self.data.plot(x = 'days', y = 'recovered', kind = 'line', color = 'green',",
"#print(self.data) def plot(self,i,simulator): # Creazione Grafici plt.clf() ax = plt.gca() self.data.plot(x = 'days',",
"simulator.exp0,simulator.t_exp,simulator.t_inf,simulator.alfa,simulator.beta,simulator.gamma)) plt.xlabel('Time (days)') plt.ylabel('Number of nodes') plt.savefig('./plots/states.png') def update_nodes(self,i,simulator): # Aggiornamento dei nodi",
"casi (aggiornamento dei nodi che propagano l'epidemia) # Trova i vicini degli esposti,",
"# Condizione per entrare nei nuovi casi di esposto (Rientra nella prob, non",
"simulator): # Genero un grafo random self.g = Graph.Erdos_Renyi(simulator.num_nodi,simulator.p_link) # Inizializzazione dei vettori",
"infetti e trovo i loro vicini suscettibili che vengono contaggiati con tasso alfa",
"= 'infected', kind = 'line', color = 'blue', ax = ax) self.data.plot(x =",
"'line', color = 'yellow', ax = ax) self.data.plot(x = 'days', y = 'infected',",
"contaggiati con tasso alfa contaggiosi = np.concatenate((n_exp,n_inf,n_g_inf), axis=None) for x in contaggiosi: for",
"Nodi infetti n_inf = np.array(np.nonzero(self.states['infected'])[0]) # Nodi gravemente infetti n_g_inf = np.array(np.nonzero(self.states['severe_infected'])[0]) #",
"'brown', ax = ax) plt.title('link_p: {}; exp0: {}; t_inc: {}; t_inf: {}\\n alpha:",
"= ax) self.data.plot(x = 'days', y = 'recovered', kind = 'line', color =",
"stati: - Susceptible = 0 - Exposed = 1 - Infected = 2",
"degli stati self.data = pd.DataFrame(columns=[\"index\",\"days\",\"exposed\",\"infected\",\"severe infected\",\"recovered\",\"dead\",\"susceptible\",\"total\"]) # Tabella stati def update_states(self,i,simulator): # Aggiornamento",
"self.data.plot(x = 'days', y = 'recovered', kind = 'line', color = 'green', ax",
"} # Inserimento della somma di ogni stato epidemico nel dataframe self.data.loc[i,:] =",
"e degli stati epidemici self.t_state = np.zeros((simulator.num_nodi,1)) self.e_state = np.zeros((simulator.num_nodi,1),dtype=np.int8) # assegnazione iniziale",
"- np.count_nonzero(np.copy(self.e_state))), 'total_cases':np.count_nonzero(np.copy(self.e_state)) } # Inserimento della somma di ogni stato epidemico nel",
"= 'line', color = 'cyan', ax = ax) self.data.plot(x = 'days', y =",
"self.g.neighbors(x): Rand = np.random.random() # Condizione per entrare nei nuovi casi di esposto",
"'recovered', kind = 'line', color = 'green', ax = ax) self.data.plot(x = 'days',",
"'severe_infected':np.where(np.copy(self.e_state)==3,self.e_state,0), 'dead':np.where(np.copy(self.e_state)==5,self.e_state,0), 'susceptible':(simulator.num_nodi - np.count_nonzero(np.copy(self.e_state))), 'total_cases':np.count_nonzero(np.copy(self.e_state)) } # Inserimento della somma di ogni",
"= 'magenta', ax = ax) self.data.plot(x = 'days', y = 'recovered', kind =",
"= ax) self.data.plot(x = 'days', y = 'infected', kind = 'line', color =",
"grafo random self.g = Graph.Erdos_Renyi(simulator.num_nodi,simulator.p_link) # Inizializzazione dei vettori degli step temporali e",
"np.array(np.nonzero(self.states['dead'])[0]) new_cases = [] # Ciclo i Nodi esposti, infetti e gravemente infetti",
"morti, nemmeno doppione) if (Rand<simulator.alfa) and (n not in contaggiosi) and (n not",
"as np import pandas as pd import simulator import random from igraph import",
"[i, i*simulator.dt_state,np.count_nonzero(self.states['exposed']), np.count_nonzero(self.states['infected']), np.count_nonzero(self.states['severe_infected']), np.count_nonzero(self.states['recovered']), np.count_nonzero(self.states['dead']), self.states['susceptible'], self.states['total_cases']] #print(self.data) def plot(self,i,simulator): # Creazione",
"ax = ax) self.data.plot(x = 'days', y = 'recovered', kind = 'line', color",
"pd.DataFrame(columns=[\"index\",\"days\",\"exposed\",\"infected\",\"severe infected\",\"recovered\",\"dead\",\"susceptible\",\"total\"]) # Tabella stati def update_states(self,i,simulator): # Aggiornamento degli stati \"\"\"Lista degli",
"random dei nodi esposti np.put(self.e_state,np.random.choice(range(simulator.num_nodi*1), simulator.exp0, replace=False),1) self.states = {} # Lista degli",
"assegnazione iniziale random dei nodi esposti np.put(self.e_state,np.random.choice(range(simulator.num_nodi*1), simulator.exp0, replace=False),1) self.states = {} #",
"= [i, i*simulator.dt_state,np.count_nonzero(self.states['exposed']), np.count_nonzero(self.states['infected']), np.count_nonzero(self.states['severe_infected']), np.count_nonzero(self.states['recovered']), np.count_nonzero(self.states['dead']), self.states['susceptible'], self.states['total_cases']] #print(self.data) def plot(self,i,simulator): #",
"n_g_inf = np.array(np.nonzero(self.states['severe_infected'])[0]) # Nodi guariti n_rec = np.array(np.nonzero(self.states['recovered'])[0]) # Nodi morti n_dead",
"i vicini degli esposti, infetti e gravemente infetti # Calcola la probabilità che",
"random self.g = Graph.Erdos_Renyi(simulator.num_nodi,simulator.p_link) # Inizializzazione dei vettori degli step temporali e degli",
"= 0 - Exposed = 1 - Infected = 2 - Severe Infected",
"- Infected = 2 - Severe Infected = 3 - Recovered = 4",
"'yellow', ax = ax) self.data.plot(x = 'days', y = 'infected', kind = 'line',",
"'magenta', ax = ax) self.data.plot(x = 'days', y = 'recovered', kind = 'line',",
"stati self.data = pd.DataFrame(columns=[\"index\",\"days\",\"exposed\",\"infected\",\"severe infected\",\"recovered\",\"dead\",\"susceptible\",\"total\"]) # Tabella stati def update_states(self,i,simulator): # Aggiornamento degli",
"(days)') plt.ylabel('Number of nodes') plt.savefig('./plots/states.png') def update_nodes(self,i,simulator): # Aggiornamento dei nodi del network",
"plt.ylabel('Number of nodes') plt.savefig('./plots/states.png') def update_nodes(self,i,simulator): # Aggiornamento dei nodi del network (rimozione",
"[] # Ciclo i Nodi esposti, infetti e gravemente infetti e trovo i",
"y = 'exposed', kind = 'line', color = 'yellow', ax = ax) self.data.plot(x",
"Condizione per entrare nei nuovi casi di esposto (Rientra nella prob, non è",
"nodi esposti np.put(self.e_state,np.random.choice(range(simulator.num_nodi*1), simulator.exp0, replace=False),1) self.states = {} # Lista degli stati self.data",
"ax) self.data.plot(x = 'days', y = 'exposed', kind = 'line', color = 'yellow',",
"= 'days', y = 'severe infected', kind = 'line', color = 'magenta', ax",
"* import matplotlib.pyplot as plt class Network(): \"\"\"docstring for Network\"\"\" def __init__(self, simulator):",
"network (rimozione dei nodi morti e isolamento dei nodi gravemente infetti) pass def",
"'dead':np.where(np.copy(self.e_state)==5,self.e_state,0), 'susceptible':(simulator.num_nodi - np.count_nonzero(np.copy(self.e_state))), 'total_cases':np.count_nonzero(np.copy(self.e_state)) } # Inserimento della somma di ogni stato",
"t_inf: {}\\n alpha: {}; beta: {}; gamma: {}'.format(simulator.p_link, simulator.exp0,simulator.t_exp,simulator.t_inf,simulator.alfa,simulator.beta,simulator.gamma)) plt.xlabel('Time (days)') plt.ylabel('Number of",
"numpy as np import pandas as pd import simulator import random from igraph",
"'infected', kind = 'line', color = 'blue', ax = ax) self.data.plot(x = 'days',",
"= ax) self.data.plot(x = 'days', y = 'dead', kind = 'line', color =",
"Trova i vicini degli esposti, infetti e gravemente infetti # Calcola la probabilità",
"for Network\"\"\" def __init__(self, simulator): # Genero un grafo random self.g = Graph.Erdos_Renyi(simulator.num_nodi,simulator.p_link)",
"contaggiosi: for n in self.g.neighbors(x): Rand = np.random.random() # Condizione per entrare nei",
"ax) self.data.plot(x = 'days', y = 'severe infected', kind = 'line', color =",
"di esposto (Rientra nella prob, non è nella categoria contaggiati, ne in quella",
"get_new_cases(self,i,simulator): # Nuovi casi (aggiornamento dei nodi che propagano l'epidemia) # Trova i",
"n in self.g.neighbors(x): Rand = np.random.random() # Condizione per entrare nei nuovi casi",
"e trovo i loro vicini suscettibili che vengono contaggiati con tasso alfa contaggiosi",
"plt.title('link_p: {}; exp0: {}; t_inc: {}; t_inf: {}\\n alpha: {}; beta: {}; gamma:",
"al dizionario self.states = { 'exposed':np.where(np.copy(self.e_state)==1,self.e_state,0), 'infected':np.where(np.copy(self.e_state)==2,self.e_state,0), 'recovered':np.where(np.copy(self.e_state)==4,self.e_state,0), 'severe_infected':np.where(np.copy(self.e_state)==3,self.e_state,0), 'dead':np.where(np.copy(self.e_state)==5,self.e_state,0), 'susceptible':(simulator.num_nodi - np.count_nonzero(np.copy(self.e_state))),",
"= ax) self.data.plot(x = 'days', y = 'exposed', kind = 'line', color =",
"{}; gamma: {}'.format(simulator.p_link, simulator.exp0,simulator.t_exp,simulator.t_inf,simulator.alfa,simulator.beta,simulator.gamma)) plt.xlabel('Time (days)') plt.ylabel('Number of nodes') plt.savefig('./plots/states.png') def update_nodes(self,i,simulator): #",
"i Nodi esposti, infetti e gravemente infetti e trovo i loro vicini suscettibili",
"class Network(): \"\"\"docstring for Network\"\"\" def __init__(self, simulator): # Genero un grafo random",
"i*simulator.dt_state,np.count_nonzero(self.states['exposed']), np.count_nonzero(self.states['infected']), np.count_nonzero(self.states['severe_infected']), np.count_nonzero(self.states['recovered']), np.count_nonzero(self.states['dead']), self.states['susceptible'], self.states['total_cases']] #print(self.data) def plot(self,i,simulator): # Creazione Grafici",
"(Rientra nella prob, non è nella categoria contaggiati, ne in quella guariti ne",
"- Dead = 5 \"\"\" # Copia degli stati epidemici dagli array degli",
"def __init__(self, simulator): # Genero un grafo random self.g = Graph.Erdos_Renyi(simulator.num_nodi,simulator.p_link) # Inizializzazione",
"kind = 'line', color = 'blue', ax = ax) self.data.plot(x = 'days', y",
"Lista degli stati self.data = pd.DataFrame(columns=[\"index\",\"days\",\"exposed\",\"infected\",\"severe infected\",\"recovered\",\"dead\",\"susceptible\",\"total\"]) # Tabella stati def update_states(self,i,simulator): #",
"# Aggiornamento degli stati \"\"\"Lista degli stati: - Susceptible = 0 - Exposed",
"morti n_dead = np.array(np.nonzero(self.states['dead'])[0]) new_cases = [] # Ciclo i Nodi esposti, infetti",
"suscettibili che vengono contaggiati con tasso alfa contaggiosi = np.concatenate((n_exp,n_inf,n_g_inf), axis=None) for x",
"degli step temporali e degli stati epidemici self.t_state = np.zeros((simulator.num_nodi,1)) self.e_state = np.zeros((simulator.num_nodi,1),dtype=np.int8)",
"stati epidemici dagli array degli stati epidemici al dizionario self.states = { 'exposed':np.where(np.copy(self.e_state)==1,self.e_state,0),",
"Aggiornamento dei nodi del network (rimozione dei nodi morti e isolamento dei nodi",
"Network import numpy as np import pandas as pd import simulator import random",
"= 'susceptible', kind = 'line', color = 'cyan', ax = ax) self.data.plot(x =",
"random from igraph import * import matplotlib.pyplot as plt class Network(): \"\"\"docstring for",
"self.states['susceptible'], self.states['total_cases']] #print(self.data) def plot(self,i,simulator): # Creazione Grafici plt.clf() ax = plt.gca() self.data.plot(x",
"# Tabella stati def update_states(self,i,simulator): # Aggiornamento degli stati \"\"\"Lista degli stati: -",
"Nodi esposti, infetti e gravemente infetti e trovo i loro vicini suscettibili che",
"e isolamento dei nodi gravemente infetti) pass def get_new_cases(self,i,simulator): # Nuovi casi (aggiornamento",
"np.array(np.nonzero(self.states['exposed'])[0]) # Nodi infetti n_inf = np.array(np.nonzero(self.states['infected'])[0]) # Nodi gravemente infetti n_g_inf =",
"somma di ogni stato epidemico nel dataframe self.data.loc[i,:] = [i, i*simulator.dt_state,np.count_nonzero(self.states['exposed']), np.count_nonzero(self.states['infected']), np.count_nonzero(self.states['severe_infected']),",
"nella prob, non è nella categoria contaggiati, ne in quella guariti ne in",
"beta: {}; gamma: {}'.format(simulator.p_link, simulator.exp0,simulator.t_exp,simulator.t_inf,simulator.alfa,simulator.beta,simulator.gamma)) plt.xlabel('Time (days)') plt.ylabel('Number of nodes') plt.savefig('./plots/states.png') def update_nodes(self,i,simulator):",
"(rimozione dei nodi morti e isolamento dei nodi gravemente infetti) pass def get_new_cases(self,i,simulator):",
"np.array(np.nonzero(self.states['severe_infected'])[0]) # Nodi guariti n_rec = np.array(np.nonzero(self.states['recovered'])[0]) # Nodi morti n_dead = np.array(np.nonzero(self.states['dead'])[0])",
"e gravemente infetti e trovo i loro vicini suscettibili che vengono contaggiati con",
"'susceptible':(simulator.num_nodi - np.count_nonzero(np.copy(self.e_state))), 'total_cases':np.count_nonzero(np.copy(self.e_state)) } # Inserimento della somma di ogni stato epidemico",
"x in contaggiosi: for n in self.g.neighbors(x): Rand = np.random.random() # Condizione per",
"# Nodi esposti n_exp = np.array(np.nonzero(self.states['exposed'])[0]) # Nodi infetti n_inf = np.array(np.nonzero(self.states['infected'])[0]) #",
"y = 'severe infected', kind = 'line', color = 'magenta', ax = ax)",
"infetti n_inf = np.array(np.nonzero(self.states['infected'])[0]) # Nodi gravemente infetti n_g_inf = np.array(np.nonzero(self.states['severe_infected'])[0]) # Nodi",
"kind = 'line', color = 'green', ax = ax) self.data.plot(x = 'days', y",
"# Nodi infetti n_inf = np.array(np.nonzero(self.states['infected'])[0]) # Nodi gravemente infetti n_g_inf = np.array(np.nonzero(self.states['severe_infected'])[0])",
"igraph import * import matplotlib.pyplot as plt class Network(): \"\"\"docstring for Network\"\"\" def",
"= [] # Ciclo i Nodi esposti, infetti e gravemente infetti e trovo",
"# Nuovi casi (aggiornamento dei nodi che propagano l'epidemia) # Trova i vicini",
"= 'exposed', kind = 'line', color = 'yellow', ax = ax) self.data.plot(x =",
"simulator import random from igraph import * import matplotlib.pyplot as plt class Network():",
"= 'line', color = 'blue', ax = ax) self.data.plot(x = 'days', y =",
"self.states = { 'exposed':np.where(np.copy(self.e_state)==1,self.e_state,0), 'infected':np.where(np.copy(self.e_state)==2,self.e_state,0), 'recovered':np.where(np.copy(self.e_state)==4,self.e_state,0), 'severe_infected':np.where(np.copy(self.e_state)==3,self.e_state,0), 'dead':np.where(np.copy(self.e_state)==5,self.e_state,0), 'susceptible':(simulator.num_nodi - np.count_nonzero(np.copy(self.e_state))), 'total_cases':np.count_nonzero(np.copy(self.e_state)) }",
"probabilità che i vicini siano contaggiati con tasso alfa # Nodi esposti n_exp",
"for x in contaggiosi: for n in self.g.neighbors(x): Rand = np.random.random() # Condizione",
"i loro vicini suscettibili che vengono contaggiati con tasso alfa contaggiosi = np.concatenate((n_exp,n_inf,n_g_inf),",
"gravemente infetti e trovo i loro vicini suscettibili che vengono contaggiati con tasso",
"ax = ax) self.data.plot(x = 'days', y = 'exposed', kind = 'line', color",
"= 1 - Infected = 2 - Severe Infected = 3 - Recovered",
"nemmeno doppione) if (Rand<simulator.alfa) and (n not in contaggiosi) and (n not in",
"vettori degli step temporali e degli stati epidemici self.t_state = np.zeros((simulator.num_nodi,1)) self.e_state =",
"for n in self.g.neighbors(x): Rand = np.random.random() # Condizione per entrare nei nuovi",
"replace=False),1) self.states = {} # Lista degli stati self.data = pd.DataFrame(columns=[\"index\",\"days\",\"exposed\",\"infected\",\"severe infected\",\"recovered\",\"dead\",\"susceptible\",\"total\"]) #",
"= ax) self.data.plot(x = 'days', y = 'severe infected', kind = 'line', color",
"dei nodi morti e isolamento dei nodi gravemente infetti) pass def get_new_cases(self,i,simulator): #",
"kind = 'line', color = 'magenta', ax = ax) self.data.plot(x = 'days', y",
"plt class Network(): \"\"\"docstring for Network\"\"\" def __init__(self, simulator): # Genero un grafo",
"iniziale random dei nodi esposti np.put(self.e_state,np.random.choice(range(simulator.num_nodi*1), simulator.exp0, replace=False),1) self.states = {} # Lista",
"Calcola la probabilità che i vicini siano contaggiati con tasso alfa # Nodi",
"{}; t_inc: {}; t_inf: {}\\n alpha: {}; beta: {}; gamma: {}'.format(simulator.p_link, simulator.exp0,simulator.t_exp,simulator.t_inf,simulator.alfa,simulator.beta,simulator.gamma)) plt.xlabel('Time",
"np.count_nonzero(self.states['infected']), np.count_nonzero(self.states['severe_infected']), np.count_nonzero(self.states['recovered']), np.count_nonzero(self.states['dead']), self.states['susceptible'], self.states['total_cases']] #print(self.data) def plot(self,i,simulator): # Creazione Grafici plt.clf()",
"kind = 'line', color = 'brown', ax = ax) plt.title('link_p: {}; exp0: {};",
"\"\"\" # Copia degli stati epidemici dagli array degli stati epidemici al dizionario",
"y = 'recovered', kind = 'line', color = 'green', ax = ax) self.data.plot(x",
"y = 'infected', kind = 'line', color = 'blue', ax = ax) self.data.plot(x",
"__init__(self, simulator): # Genero un grafo random self.g = Graph.Erdos_Renyi(simulator.num_nodi,simulator.p_link) # Inizializzazione dei"
] |
[
"django.contrib import admin # Register your models here. from .models import shortenedUrl admin.site.register(shortenedUrl)",
"from django.contrib import admin # Register your models here. from .models import shortenedUrl"
] |
[
"actually accounted for. The rest are absolutely trashed. ''' res = subprocess.run( [DIALOG_NAME,",
"= (0,0,) # Try to get the primary screen resolution from xrandr. try:",
"join def _fix_output(output): ''' Removes miscelanous stdout output that can happen with Mesa",
"to jump into the except block. raise ValueError def _parse_file_filters(the_filters): ''' Parses the",
"hide it from our terminal. if subprocess.run(\"kdialog\", capture_output=True).returncode != 0: # Hacky way",
"than the default filedialog # from tkinter on Linux. # This joins all",
"255: DIALOG_NAME = \"zenity\" except Exception: pass # These are the functions to",
"# kdialog sadly isn't the nicest thing ever. But we have something at",
"of the command of the native filedialog if we have one. DIALOG_NAME =",
"wrapper for kdialog --getexistingdirectory. Arguments listed at the top are the only ones",
"# This joins all the filters like so: \"*.mp3|*.ogg|*.wav\" # If we weren't",
"= SCREEN_RES_REGEX.search( subprocess.run( \"xrandr\", capture_output=True, universal_newlines=True).stdout ).group(1,2) screen_resolution = ( int(screen_resolution[0]), int(screen_resolution[1]), )",
"universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\" USE_TK_DIALOG = False if DIALOG_NAME",
"''' res = subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, \"--filename=%s/\" % (initialdir), *_parse_file_filters(filetypes)],",
"tkinter filedialog for Linux does not work\\n\" \"properly with symlinks.\\n\\n\" \"Please install either",
"askopenfilename( title=\"Open file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw): ''' Tkinter style wrapper for kdialog",
"== \"yad\": ZENITY_COMMON_ARGS.extend([ \"--on-top\", \"--mouse\", ]) # Yad likes to open with a",
"kdialog sadly isn't the nicest thing ever. But we have something at #",
"(initialdir)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\" def asksaveasfilename( title=\"Open",
"everywhere I would have # done a \"thing1 thing2 thing3 ( *.ext1 *.ext2",
"of filters for zenity. ''' # Filters look like \"name (extension)\" to users.",
"subprocess.run(\"kdialog\", capture_output=True).returncode == 0: DIALOG_NAME = \"kdialog\" except Exception: try: # This one",
"Tkinter style wrapper for kdialog --getsavefilename. Arguments listed at the top are the",
"USE_TK_DIALOG: if \"linux\" in sys.platform: from tkinter import messagebox error = (\"No supported",
"if subprocess.run(\"kdialog\", capture_output=True).returncode == 0: DIALOG_NAME = \"kdialog\" except Exception: try: # This",
"filters for kdialog. ''' # This sucks right now. # We can't get",
"defaultextension=\"\", **kw): ''' Tkinter style wrapper for kdialog --getsavefilename. Arguments listed at the",
"native filedialog if we have one. DIALOG_NAME = \"\" # Used for getting",
"_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\" USE_TK_DIALOG = False",
"except IndexError: return \"\" USE_TK_DIALOG = False # These are the functions used",
"res = subprocess.run( [DIALOG_NAME, \"--title\", str(title), \"--getexistingdirectory\", str(initialdir)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0]",
"Exception: pass # These are the functions to wrap zenity and yad. if",
"(0,0,) # Try to get the primary screen resolution from xrandr. try: screen_resolution",
"\"--filename=%s/%s\" % (initialdir, defaultextension), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return",
"# Try to get the primary screen resolution from xrandr. try: screen_resolution =",
"us that. if subprocess.run(\"kdialog\", capture_output=True).returncode == 0: DIALOG_NAME = \"kdialog\" except Exception: try:",
"= False if DIALOG_NAME and not USE_TK_DIALOG: print(\"Using native %s for filedialogs.\" %",
"this is the alternative solution. ''' import sys from pathlib import Path USE_TK_DIALOG",
"# Yad likes to open with a really small window size. Work around",
"set of filters for zenity. ''' # Filters look like \"name (extension)\" to",
"\"--getexistingdirectory\", str(initialdir)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\" def asksaveasfilename(",
"\"--title=%s\" % (title), *ZENITY_COMMON_ARGS, \"--filename=%s/\" % (initialdir), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0]",
"**kw): ''' Tkinter style wrapper for kdialog --getsavefilename. Arguments listed at the top",
"for filedialogs.\" % DIALOG_NAME) # Fallback for Linux, default for mac and Windows.",
"wrap zenity and yad. if DIALOG_NAME in (\"yad\", \"zenity\"): # Construct the common",
"= ( int(screen_resolution[0]), int(screen_resolution[1]), ) except Exception: print(\"Couldn't retrieve screen resolution.\") # Figure",
"def askdirectory( title=\"Choose folder\", initialdir=str(Path.cwd()), **kw): ''' Tkinter style wrapper for kdialog --getexistingdirectory.",
"# Get multiple items, put them on different lines for parsing. \"--multiple\", \"--separate-output\",",
"\"kdialog\" except Exception: try: # This one is nice. But it has a",
"zenity --file-selection. Arguments listed at the top are the only ones actually accounted",
"folder\", initialdir=str(Path.cwd()), **kw): ''' Tkinter style wrapper for kdialog --getexistingdirectory. Arguments listed at",
"supported native filedialog package installed.\", \"The default tkinter filedialog for Linux does not",
"the primary screen resolution from xrandr. try: screen_resolution = SCREEN_RES_REGEX.search( subprocess.run( \"xrandr\", capture_output=True,",
"to wrap zenity and yad. if DIALOG_NAME in (\"yad\", \"zenity\"): # Construct the",
"\"--filename=%s/\" % (initialdir)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\" def",
"sucks right now. # We can't get file type descriptions into kdialog. #",
"messagebox.showerror(error[0], error[1]) from tkinter.filedialog import ( askopenfilename, askopenfilenames, askdirectory, asksaveasfilename ) del sys",
"are the functions used for kdialog. if DIALOG_NAME == \"kdialog\": # capture_output to",
"[DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, # Get a directory. \"--directory\", \"--filename=%s/\" % (initialdir)],",
"And I don't like that >:P if subprocess.run(\"zenity\", capture_output=True).returncode == 255: DIALOG_NAME =",
"''' res = subprocess.run( [DIALOG_NAME, \"--title\", str(title), \"--getsavefilename\", # Joining these causes the",
"ouch. So, this is the alternative solution. ''' import sys from pathlib import",
"default filedialog # from tkinter on Linux. # This joins all the filters",
"''' Parses the tkinter file filters into a set of filters for zenity.",
"if \"linux\" in sys.platform: import subprocess import re from os.path import join def",
"nice. But it has a tendency to keep opening the # recent files",
"look like \"name (extension)\" to users. # Filters get a * prepended so",
"what native file dialog we can use. try: # Yad is the best,",
"get file type descriptions into kdialog. # Still, anything better than the default",
"_fix_output(res.stdout)[0] except IndexError: return \"\" def askopenfilenames( title=\"Open files\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw):",
"Work around that. if screen_resolution[0] and screen_resolution[1]: ZENITY_COMMON_ARGS.extend([ \"--width=%d\" % (int(screen_resolution[0]/1.5)), \"--height=%d\" %",
"''' Only exists if there is no native file dialog. Displays an error",
"\"The default tkinter filedialog for Linux does not work\\n\" \"properly with symlinks.\\n\\n\" \"Please",
"on Linux. # This joins all the filters like so: \"*.mp3|*.ogg|*.wav\" # If",
"rest are discarded. ''' res = subprocess.run( [DIALOG_NAME, \"--title\", str(title), # Get multiple",
"the best, please have yad. if subprocess.run([\"yad\", \"--help\"], capture_output=True).returncode == 0: DIALOG_NAME =",
"(a[0], a[1], a[1].lstrip('*')), the_filters)) def askopenfilename( title=\"Open file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw): '''",
"native file dialog. Displays an error warning the user when called. ''' messagebox.showerror(error[0],",
"files folder. And I don't like that >:P if subprocess.run(\"zenity\", capture_output=True).returncode == 255:",
"joins all the filters like so: \"*.mp3|*.ogg|*.wav\" # If we weren't supplying *",
"used for kdialog. if DIALOG_NAME == \"kdialog\": # capture_output to hide it from",
"error = (\"No supported native filedialog package installed.\", \"The default tkinter filedialog for",
"they actually work. return list(map(lambda a : '--file-filter=%s (%s) | *%s' % (a[0],",
"screen_resolution[1]: ZENITY_COMMON_ARGS.extend([ \"--width=%d\" % (int(screen_resolution[0]/1.5)), \"--height=%d\" % (int(screen_resolution[1]/1.5)), ]) def _parse_file_filters(the_filters): ''' Parses",
"\"--on-top\", \"--mouse\", ]) # Yad likes to open with a really small window",
"discarded. ''' res = subprocess.run( [DIALOG_NAME, \"--title\", str(title), \"--getopenfilename\", str(initialdir), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True)",
"and not USE_TK_DIALOG: print(\"Using native %s for filedialogs.\" % DIALOG_NAME) # Fallback for",
"top are the only ones actually accounted for. The rest are discarded. '''",
"_fix_output(res.stdout) def askdirectory( title=\"Choose folder\", initialdir=str(Path.cwd()), **kw): ''' Tkinter style wrapper for kdialog",
"better than the default filedialog # from tkinter on Linux. # This joins",
"no_native_file_dialog_error(): ''' Only exists if there is no native file dialog. Displays an",
"keep opening the # recent files folder. And I don't like that >:P",
"has a tendency to keep opening the # recent files folder. And I",
"def askdirectory( title=\"Choose folder\", initialdir=str(Path.cwd()), **kw): ''' Tkinter style wrapper for zenity --file-selection.",
"initialdir=str(Path.cwd()), filetypes=(('All', '*'),), defaultextension=\"\", **kw): ''' Tkinter style wrapper for kdialog --getsavefilename. Arguments",
"True if \"linux\" in sys.platform: import subprocess import re from os.path import join",
"filters like so: \"*.mp3|*.ogg|*.wav\" # If we weren't supplying * as a filter",
"separator. ''' return list(filter(lambda a : a.startswith(\"/\"), output.split(\"\\n\"))) # Name of the command",
"* prepended so they actually work. return list(map(lambda a : '--file-filter=%s (%s) |",
"% (initialdir), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\" def",
"at the top are the only ones actually accounted for. The rest are",
"our terminal. if subprocess.run(\"kdialog\", capture_output=True).returncode != 0: # Hacky way to jump into",
"at # least. return \"|\".join(map(lambda a : \"*%s\" % a[1].lstrip('*'), the_filters)) def askopenfilename(",
"import Path USE_TK_DIALOG = True if \"linux\" in sys.platform: import subprocess import re",
"use. try: # Yad is the best, please have yad. if subprocess.run([\"yad\", \"--help\"],",
"== 255: DIALOG_NAME = \"zenity\" except Exception: pass # These are the functions",
"the # xrandr command output. Tests here: https://regex101.com/r/clpmtZ/1 SCREEN_RES_REGEX = re.compile(r'primary (\\d+)x(\\d+)') screen_resolution",
"title=\"Open files\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw): ''' Tkinter style wrapper for kdialog --getopenfilename.",
"start with the root separator. ''' return list(filter(lambda a : a.startswith(\"/\"), output.split(\"\\n\"))) #",
"are the functions to wrap zenity and yad. if DIALOG_NAME in (\"yad\", \"zenity\"):",
"Linux is just... ouch. So, this is the alternative solution. ''' import sys",
"have something at # least. return \"|\".join(map(lambda a : \"*%s\" % a[1].lstrip('*'), the_filters))",
"# Joining these causes the extension to appear in the name box join(str(initialdir),",
"if DIALOG_NAME and not USE_TK_DIALOG: print(\"Using native %s for filedialogs.\" % DIALOG_NAME) #",
"symlinks.\\n\\n\" \"Please install either yad, kdialog, or zenity.\\n\" \"(These suggestions are ordered based",
"second best, give us that. if subprocess.run(\"kdialog\", capture_output=True).returncode == 0: DIALOG_NAME = \"kdialog\"",
"primary monitor from the # xrandr command output. Tests here: https://regex101.com/r/clpmtZ/1 SCREEN_RES_REGEX =",
"''' res = subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, # Start in save",
"= re.compile(r'primary (\\d+)x(\\d+)') screen_resolution = (0,0,) # Try to get the primary screen",
"return \"|\".join(map(lambda a : \"*%s\" % a[1].lstrip('*'), the_filters)) def askopenfilename( title=\"Open file\", initialdir=str(Path.cwd()),",
"work. return list(map(lambda a : '--file-filter=%s (%s) | *%s' % (a[0], a[1], a[1].lstrip('*')),",
"Fallback for Linux, default for mac and Windows. if USE_TK_DIALOG: if \"linux\" in",
"kdialog, or zenity.\\n\" \"(These suggestions are ordered based on how well they work.)\")",
"*_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) return _fix_output(res.stdout) def askdirectory( title=\"Choose folder\", initialdir=str(Path.cwd()), **kw): ''' Tkinter",
"[DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, \"--filename=%s/\" % (initialdir), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return",
"Get multiple items, put them on different lines for parsing. \"--multiple\", \"--separate-output\", \"--getopenfilename\",",
"''' res = subprocess.run( [DIALOG_NAME, \"--title\", str(title), \"--getexistingdirectory\", str(initialdir)], capture_output=True, universal_newlines=True) try: return",
"Name of the command of the native filedialog if we have one. DIALOG_NAME",
"filter. # kdialog sadly isn't the nicest thing ever. But we have something",
"''' return list(filter(lambda a : a.startswith(\"/\"), output.split(\"\\n\"))) # Name of the command of",
"actually work. return list(map(lambda a : '--file-filter=%s (%s) | *%s' % (a[0], a[1],",
"a[1], a[1].lstrip('*')), the_filters)) def askopenfilename( title=\"Open file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw): ''' Tkinter",
"rest are discarded. ''' res = subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, \"--filename=%s/\"",
"The filepicker for Tkinter on Linux is just... ouch. So, this is the",
"def _fix_output(output): ''' Removes miscelanous stdout output that can happen with Mesa drivers.",
"that. if subprocess.run(\"kdialog\", capture_output=True).returncode == 0: DIALOG_NAME = \"kdialog\" except Exception: try: #",
"\"--getopenfilename\", str(initialdir), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\" def",
"output that can happen with Mesa drivers. Only accept absolute paths that start",
"askopenfilenames( title=\"Open files\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw): ''' Tkinter style wrapper for zenity",
"\"\" USE_TK_DIALOG = False # These are the functions used for kdialog. if",
"accounted for. The rest are absolutely trashed. ''' res = subprocess.run( [DIALOG_NAME, \"--title\",",
"are absolutely trashed. ''' res = subprocess.run( [DIALOG_NAME, \"--title\", str(title), \"--getexistingdirectory\", str(initialdir)], capture_output=True,",
"are discarded. ''' res = subprocess.run( [DIALOG_NAME, \"--title\", str(title), \"--getsavefilename\", # Joining these",
"\"\" def askopenfilenames( title=\"Open files\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw): ''' Tkinter style wrapper",
"for filedialog so we can use a better one if it is available.",
"_parse_file_filters(the_filters): ''' Parses the tkinter file filters into a set of filters for",
"'*'),), defaultextension=\"\", **kw): ''' Tkinter style wrapper for kdialog --getsavefilename. Arguments listed at",
"USE_TK_DIALOG = False # These are the functions used for kdialog. if DIALOG_NAME",
"str(title), \"--getopenfilename\", str(initialdir), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\"",
"root separator. ''' return list(filter(lambda a : a.startswith(\"/\"), output.split(\"\\n\"))) # Name of the",
"kdialog. # Still, anything better than the default filedialog # from tkinter on",
"these causes the extension to appear in the name box join(str(initialdir), defaultextension), _parse_file_filters(filetypes)],",
"for. The rest are discarded. ''' res = subprocess.run( [DIALOG_NAME, \"--title\", str(title), #",
"capture_output=True, universal_newlines=True).stdout ).group(1,2) screen_resolution = ( int(screen_resolution[0]), int(screen_resolution[1]), ) except Exception: print(\"Couldn't retrieve",
"we have something at # least. return \"|\".join(map(lambda a : \"*%s\" % a[1].lstrip('*'),",
"files\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw): ''' Tkinter style wrapper for zenity --file-selection. Arguments",
"_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) return _fix_output(res.stdout) def askdirectory( title=\"Choose folder\", initialdir=str(Path.cwd()), **kw): ''' Tkinter",
"ones actually accounted for. The rest are discarded. ''' res = subprocess.run( [DIALOG_NAME,",
"in save mode. \"--save\", \"--confirm-overwrite\", \"--filename=%s/%s\" % (initialdir, defaultextension), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try:",
"**kw): ''' Tkinter style wrapper for kdialog --getexistingdirectory. Arguments listed at the top",
"Parses the tkinter file filters into a set of filters for kdialog. '''",
"pass # These are the functions to wrap zenity and yad. if DIALOG_NAME",
"please have yad. if subprocess.run([\"yad\", \"--help\"], capture_output=True).returncode == 0: DIALOG_NAME = \"yad\" except",
"sys.platform: from tkinter import messagebox error = (\"No supported native filedialog package installed.\",",
"ZENITY_COMMON_ARGS.extend([ \"--width=%d\" % (int(screen_resolution[0]/1.5)), \"--height=%d\" % (int(screen_resolution[1]/1.5)), ]) def _parse_file_filters(the_filters): ''' Parses the",
"\"*.mp3|*.ogg|*.wav\" # If we weren't supplying * as a filter everywhere I would",
"primary screen resolution from xrandr. try: screen_resolution = SCREEN_RES_REGEX.search( subprocess.run( \"xrandr\", capture_output=True, universal_newlines=True).stdout",
"SCREEN_RES_REGEX.search( subprocess.run( \"xrandr\", capture_output=True, universal_newlines=True).stdout ).group(1,2) screen_resolution = ( int(screen_resolution[0]), int(screen_resolution[1]), ) except",
"filetypes=(('All', '*'),), defaultextension=\"\", **kw): ''' Tkinter style wrapper for kdialog --getsavefilename. Arguments listed",
"out what native file dialog we can use. try: # Yad is the",
"actually accounted for. The rest are discarded. ''' res = subprocess.run( [DIALOG_NAME, \"--title\",",
"( int(screen_resolution[0]), int(screen_resolution[1]), ) except Exception: print(\"Couldn't retrieve screen resolution.\") # Figure out",
"that >:P if subprocess.run(\"zenity\", capture_output=True).returncode == 255: DIALOG_NAME = \"zenity\" except Exception: pass",
"''' This module is our wrapper for filedialog so we can use a",
"# kdialog is second best, give us that. if subprocess.run(\"kdialog\", capture_output=True).returncode == 0:",
"file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw): ''' Tkinter style wrapper for zenity --file-selection. Arguments",
"return list(filter(lambda a : a.startswith(\"/\"), output.split(\"\\n\"))) # Name of the command of the",
"= subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, # Start in save mode. \"--save\",",
": a.startswith(\"/\"), output.split(\"\\n\"))) # Name of the command of the native filedialog if",
"''' # Filters look like \"name (extension)\" to users. # Filters get a",
"accounted for. The rest are discarded. ''' res = subprocess.run( [DIALOG_NAME, \"--title\", str(title),",
"called. ''' messagebox.showerror(error[0], error[1]) from tkinter.filedialog import ( askopenfilename, askopenfilenames, askdirectory, asksaveasfilename )",
"here: https://regex101.com/r/clpmtZ/1 SCREEN_RES_REGEX = re.compile(r'primary (\\d+)x(\\d+)') screen_resolution = (0,0,) # Try to get",
"filters into a set of filters for zenity. ''' # Filters look like",
"is the best, please have yad. if subprocess.run([\"yad\", \"--help\"], capture_output=True).returncode == 0: DIALOG_NAME",
"Construct the common arguments for the calling of zenity or yad. ZENITY_COMMON_ARGS =",
"os.path import join def _fix_output(output): ''' Removes miscelanous stdout output that can happen",
"**kw): ''' Tkinter style wrapper for zenity --file-selection. Arguments listed at the top",
"zenity or yad. ZENITY_COMMON_ARGS = [ \"--file-selection\", \"--separator=\\n\", ] # If any of",
"accounted for. The rest are discarded. ''' res = subprocess.run( [DIALOG_NAME, \"--title=%s\" %",
"\"--save\", \"--confirm-overwrite\", \"--filename=%s/%s\" % (initialdir, defaultextension), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except",
"for. The rest are absolutely trashed. ''' res = subprocess.run( [DIALOG_NAME, \"--title\", str(title),",
"# Fallback for Linux, default for mac and Windows. if USE_TK_DIALOG: if \"linux\"",
"int(screen_resolution[1]), ) except Exception: print(\"Couldn't retrieve screen resolution.\") # Figure out what native",
"universal_newlines=True) return _fix_output(res.stdout) def askdirectory( title=\"Choose folder\", initialdir=str(Path.cwd()), **kw): ''' Tkinter style wrapper",
"zenity and yad. if DIALOG_NAME in (\"yad\", \"zenity\"): # Construct the common arguments",
"except IndexError: return \"\" USE_TK_DIALOG = False if DIALOG_NAME and not USE_TK_DIALOG: print(\"Using",
"actually accounted for. The rest are discarded. ''' res = subprocess.run( [DIALOG_NAME, \"--title=%s\"",
"the functions to wrap zenity and yad. if DIALOG_NAME in (\"yad\", \"zenity\"): #",
"for zenity. ''' # Filters look like \"name (extension)\" to users. # Filters",
"a better one if it is available. The filepicker for Tkinter on Linux",
"wrapper for zenity --file-selection. Arguments listed at the top are the only ones",
"import sys from pathlib import Path USE_TK_DIALOG = True if \"linux\" in sys.platform:",
"\"--confirm-overwrite\", \"--filename=%s/%s\" % (initialdir, defaultextension), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError:",
"\"--file-selection\", \"--separator=\\n\", ] # If any of these arguments are present zenity won't",
"absolute paths that start with the root separator. ''' return list(filter(lambda a :",
"top are the only ones actually accounted for. The rest are absolutely trashed.",
"\"--title\", str(title), \"--getopenfilename\", str(initialdir), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return",
"native %s for filedialogs.\" % DIALOG_NAME) # Fallback for Linux, default for mac",
"get the primary screen resolution from xrandr. try: screen_resolution = SCREEN_RES_REGEX.search( subprocess.run( \"xrandr\",",
"alternative solution. ''' import sys from pathlib import Path USE_TK_DIALOG = True if",
"\"--title\", str(title), \"--getexistingdirectory\", str(initialdir)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\"",
"kdialog --getsavefilename. Arguments listed at the top are the only ones actually accounted",
"capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\" USE_TK_DIALOG = False if",
"as a filter everywhere I would have # done a \"thing1 thing2 thing3",
"least. return \"|\".join(map(lambda a : \"*%s\" % a[1].lstrip('*'), the_filters)) def askopenfilename( title=\"Open file\",",
"\"--mouse\", ]) # Yad likes to open with a really small window size.",
"res = subprocess.run( [DIALOG_NAME, \"--title\", str(title), \"--getopenfilename\", str(initialdir), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return",
"multiple items, put them on different lines for parsing. \"--multiple\", \"--filename=%s/%s\" % (initialdir,",
"*_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\" def askopenfilenames( title=\"Open",
"*ZENITY_COMMON_ARGS, # Start in save mode. \"--save\", \"--confirm-overwrite\", \"--filename=%s/%s\" % (initialdir, defaultextension), *_parse_file_filters(filetypes)],",
"one is nice. But it has a tendency to keep opening the #",
"resolution.\") # Figure out what native file dialog we can use. try: #",
"(initialdir), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\" def askopenfilenames(",
"\"--width=%d\" % (int(screen_resolution[0]/1.5)), \"--height=%d\" % (int(screen_resolution[1]/1.5)), ]) def _parse_file_filters(the_filters): ''' Parses the tkinter",
"[DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, # Get multiple items, put them on different",
"_fix_output(res.stdout)[0] except IndexError: return \"\" def asksaveasfilename( title=\"Open file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), defaultextension=\"\",",
"won't open. if DIALOG_NAME == \"yad\": ZENITY_COMMON_ARGS.extend([ \"--on-top\", \"--mouse\", ]) # Yad likes",
"''' # This sucks right now. # We can't get file type descriptions",
"stdout output that can happen with Mesa drivers. Only accept absolute paths that",
"best, please have yad. if subprocess.run([\"yad\", \"--help\"], capture_output=True).returncode == 0: DIALOG_NAME = \"yad\"",
"\"--multiple\", \"--separate-output\", \"--getopenfilename\", str(initialdir), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) return _fix_output(res.stdout) def askdirectory( title=\"Choose folder\",",
"items, put them on different lines for parsing. \"--multiple\", \"--separate-output\", \"--getopenfilename\", str(initialdir), _parse_file_filters(filetypes)],",
"Windows. if USE_TK_DIALOG: if \"linux\" in sys.platform: from tkinter import messagebox error =",
"Exception: print(\"Couldn't retrieve screen resolution.\") # Figure out what native file dialog we",
"initialdir=str(Path.cwd()), **kw): ''' Tkinter style wrapper for kdialog --getexistingdirectory. Arguments listed at the",
"= subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, # Get a directory. \"--directory\", \"--filename=%s/\"",
"mac and Windows. if USE_TK_DIALOG: if \"linux\" in sys.platform: from tkinter import messagebox",
"the # recent files folder. And I don't like that >:P if subprocess.run(\"zenity\",",
"get a * prepended so they actually work. return list(map(lambda a : '--file-filter=%s",
"capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\" def askopenfilenames( title=\"Open files\",",
"likes to open with a really small window size. Work around that. if",
"initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw): ''' Tkinter style wrapper for kdialog --getopenfilename. Arguments listed",
"return \"\" def askopenfilenames( title=\"Open files\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw): ''' Tkinter style",
"on how well they work.)\") print(\"\\n\".join(error)) def no_native_file_dialog_error(): ''' Only exists if there",
"lines for parsing. \"--multiple\", \"--filename=%s/%s\" % (initialdir, filetypes[0][1]), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) return _fix_output(res.stdout)",
"Get a directory. \"--directory\", \"--filename=%s/\" % (initialdir)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except",
"in the name box join(str(initialdir), defaultextension), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except",
"better one if it is available. The filepicker for Tkinter on Linux is",
"a set of filters for kdialog. ''' # This sucks right now. #",
"''' Parses the tkinter file filters into a set of filters for kdialog.",
"into kdialog. # Still, anything better than the default filedialog # from tkinter",
"mode. \"--save\", \"--confirm-overwrite\", \"--filename=%s/%s\" % (initialdir, defaultextension), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0]",
"descriptions into kdialog. # Still, anything better than the default filedialog # from",
"a[1].lstrip('*'), the_filters)) def askopenfilename( title=\"Open file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw): ''' Tkinter style",
"re.compile(r'primary (\\d+)x(\\d+)') screen_resolution = (0,0,) # Try to get the primary screen resolution",
"rest are absolutely trashed. ''' res = subprocess.run( [DIALOG_NAME, \"--title\", str(title), \"--getexistingdirectory\", str(initialdir)],",
"These are the functions to wrap zenity and yad. if DIALOG_NAME in (\"yad\",",
"''' Tkinter style wrapper for kdialog --getsavefilename. Arguments listed at the top are",
"(title), *ZENITY_COMMON_ARGS, # Get multiple items, put them on different lines for parsing.",
"kdialog is second best, give us that. if subprocess.run(\"kdialog\", capture_output=True).returncode == 0: DIALOG_NAME",
"# Filters get a * prepended so they actually work. return list(map(lambda a",
"This module is our wrapper for filedialog so we can use a better",
"\"\" # Used for getting the width and height of the primary monitor",
"folder\", initialdir=str(Path.cwd()), **kw): ''' Tkinter style wrapper for zenity --file-selection. Arguments listed at",
"== \"kdialog\": # capture_output to hide it from our terminal. if subprocess.run(\"kdialog\", capture_output=True).returncode",
"the filters like so: \"*.mp3|*.ogg|*.wav\" # If we weren't supplying * as a",
"_fix_output(res.stdout) def askdirectory( title=\"Choose folder\", initialdir=str(Path.cwd()), **kw): ''' Tkinter style wrapper for zenity",
"( *.ext1 *.ext2 *.ext3 )\" filter. # kdialog sadly isn't the nicest thing",
"\"|\".join(map(lambda a : \"*%s\" % a[1].lstrip('*'), the_filters)) def askopenfilename( title=\"Open file\", initialdir=str(Path.cwd()), filetypes=(('All',",
"% (int(screen_resolution[1]/1.5)), ]) def _parse_file_filters(the_filters): ''' Parses the tkinter file filters into a",
"screen resolution.\") # Figure out what native file dialog we can use. try:",
"for parsing. \"--multiple\", \"--filename=%s/%s\" % (initialdir, filetypes[0][1]), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) return _fix_output(res.stdout) def",
"# capture_output to hide it from our terminal. if subprocess.run(\"kdialog\", capture_output=True).returncode != 0:",
"= subprocess.run( [DIALOG_NAME, \"--title\", str(title), \"--getopenfilename\", str(initialdir), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0]",
"except block. raise ValueError def _parse_file_filters(the_filters): ''' Parses the tkinter file filters into",
"can use. try: # Yad is the best, please have yad. if subprocess.run([\"yad\",",
"functions used for kdialog. if DIALOG_NAME == \"kdialog\": # capture_output to hide it",
"DIALOG_NAME in (\"yad\", \"zenity\"): # Construct the common arguments for the calling of",
"str(initialdir), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\" def askopenfilenames(",
"<reponame>delan/binilla<gh_stars>1-10 ''' This module is our wrapper for filedialog so we can use",
"resolution from xrandr. try: screen_resolution = SCREEN_RES_REGEX.search( subprocess.run( \"xrandr\", capture_output=True, universal_newlines=True).stdout ).group(1,2) screen_resolution",
"would have # done a \"thing1 thing2 thing3 ( *.ext1 *.ext2 *.ext3 )\"",
"print(\"Using native %s for filedialogs.\" % DIALOG_NAME) # Fallback for Linux, default for",
"default for mac and Windows. if USE_TK_DIALOG: if \"linux\" in sys.platform: from tkinter",
"= (\"No supported native filedialog package installed.\", \"The default tkinter filedialog for Linux",
"Tkinter style wrapper for kdialog --getexistingdirectory. Arguments listed at the top are the",
"But it has a tendency to keep opening the # recent files folder.",
"for parsing. \"--multiple\", \"--separate-output\", \"--getopenfilename\", str(initialdir), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) return _fix_output(res.stdout) def askdirectory(",
"So, this is the alternative solution. ''' import sys from pathlib import Path",
"really small window size. Work around that. if screen_resolution[0] and screen_resolution[1]: ZENITY_COMMON_ARGS.extend([ \"--width=%d\"",
"the nicest thing ever. But we have something at # least. return \"|\".join(map(lambda",
"Tkinter on Linux is just... ouch. So, this is the alternative solution. '''",
"Yad is the best, please have yad. if subprocess.run([\"yad\", \"--help\"], capture_output=True).returncode == 0:",
"(\"yad\", \"zenity\"): # Construct the common arguments for the calling of zenity or",
"default tkinter filedialog for Linux does not work\\n\" \"properly with symlinks.\\n\\n\" \"Please install",
"--file-selection. Arguments listed at the top are the only ones actually accounted for.",
"anything better than the default filedialog # from tkinter on Linux. # This",
"try: return _fix_output(res.stdout)[0] except IndexError: return \"\" def askopenfilenames( title=\"Open files\", initialdir=str(Path.cwd()), filetypes=(('All',",
"a * prepended so they actually work. return list(map(lambda a : '--file-filter=%s (%s)",
"if there is no native file dialog. Displays an error warning the user",
"use a better one if it is available. The filepicker for Tkinter on",
"are present zenity won't open. if DIALOG_NAME == \"yad\": ZENITY_COMMON_ARGS.extend([ \"--on-top\", \"--mouse\", ])",
"a : a.startswith(\"/\"), output.split(\"\\n\"))) # Name of the command of the native filedialog",
"except Exception: try: # kdialog is second best, give us that. if subprocess.run(\"kdialog\",",
": \"*%s\" % a[1].lstrip('*'), the_filters)) def askopenfilename( title=\"Open file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw):",
"# recent files folder. And I don't like that >:P if subprocess.run(\"zenity\", capture_output=True).returncode",
"are absolutely trashed. ''' res = subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, #",
"Filters get a * prepended so they actually work. return list(map(lambda a :",
"of filters for kdialog. ''' # This sucks right now. # We can't",
"filedialog package installed.\", \"The default tkinter filedialog for Linux does not work\\n\" \"properly",
"for mac and Windows. if USE_TK_DIALOG: if \"linux\" in sys.platform: from tkinter import",
"% (title), *ZENITY_COMMON_ARGS, # Start in save mode. \"--save\", \"--confirm-overwrite\", \"--filename=%s/%s\" % (initialdir,",
"package installed.\", \"The default tkinter filedialog for Linux does not work\\n\" \"properly with",
"installed.\", \"The default tkinter filedialog for Linux does not work\\n\" \"properly with symlinks.\\n\\n\"",
"screen_resolution = (0,0,) # Try to get the primary screen resolution from xrandr.",
"are discarded. ''' res = subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, # Get",
"**kw): ''' Tkinter style wrapper for kdialog --getopenfilename. Arguments listed at the top",
"[DIALOG_NAME, \"--title\", str(title), \"--getsavefilename\", # Joining these causes the extension to appear in",
"set of filters for kdialog. ''' # This sucks right now. # We",
"(initialdir, defaultextension), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\" USE_TK_DIALOG",
"xrandr command output. Tests here: https://regex101.com/r/clpmtZ/1 SCREEN_RES_REGEX = re.compile(r'primary (\\d+)x(\\d+)') screen_resolution = (0,0,)",
"from our terminal. if subprocess.run(\"kdialog\", capture_output=True).returncode != 0: # Hacky way to jump",
"defaultextension), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\" USE_TK_DIALOG =",
"if subprocess.run(\"kdialog\", capture_output=True).returncode != 0: # Hacky way to jump into the except",
"a : '--file-filter=%s (%s) | *%s' % (a[0], a[1], a[1].lstrip('*')), the_filters)) def askopenfilename(",
"one if it is available. The filepicker for Tkinter on Linux is just...",
"= [ \"--file-selection\", \"--separator=\\n\", ] # If any of these arguments are present",
"\"--title\", str(title), # Get multiple items, put them on different lines for parsing.",
"so: \"*.mp3|*.ogg|*.wav\" # If we weren't supplying * as a filter everywhere I",
"put them on different lines for parsing. \"--multiple\", \"--separate-output\", \"--getopenfilename\", str(initialdir), _parse_file_filters(filetypes)], capture_output=True,",
"jump into the except block. raise ValueError def _parse_file_filters(the_filters): ''' Parses the tkinter",
"0: DIALOG_NAME = \"yad\" except Exception: try: # kdialog is second best, give",
"\"--separator=\\n\", ] # If any of these arguments are present zenity won't open.",
"not work\\n\" \"properly with symlinks.\\n\\n\" \"Please install either yad, kdialog, or zenity.\\n\" \"(These",
"exists if there is no native file dialog. Displays an error warning the",
"This one is nice. But it has a tendency to keep opening the",
"user when called. ''' messagebox.showerror(error[0], error[1]) from tkinter.filedialog import ( askopenfilename, askopenfilenames, askdirectory,",
"''' res = subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, # Get multiple items,",
"== 0: DIALOG_NAME = \"kdialog\" except Exception: try: # This one is nice.",
"is our wrapper for filedialog so we can use a better one if",
"size. Work around that. if screen_resolution[0] and screen_resolution[1]: ZENITY_COMMON_ARGS.extend([ \"--width=%d\" % (int(screen_resolution[0]/1.5)), \"--height=%d\"",
"a set of filters for zenity. ''' # Filters look like \"name (extension)\"",
"the only ones actually accounted for. The rest are absolutely trashed. ''' res",
"how well they work.)\") print(\"\\n\".join(error)) def no_native_file_dialog_error(): ''' Only exists if there is",
"or yad. ZENITY_COMMON_ARGS = [ \"--file-selection\", \"--separator=\\n\", ] # If any of these",
"Only exists if there is no native file dialog. Displays an error warning",
"except Exception: try: # This one is nice. But it has a tendency",
"capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\" USE_TK_DIALOG = False #",
"have # done a \"thing1 thing2 thing3 ( *.ext1 *.ext2 *.ext3 )\" filter.",
"False # These are the functions used for kdialog. if DIALOG_NAME == \"kdialog\":",
"the default filedialog # from tkinter on Linux. # This joins all the",
"The rest are absolutely trashed. ''' res = subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title),",
"\"--height=%d\" % (int(screen_resolution[1]/1.5)), ]) def _parse_file_filters(the_filters): ''' Parses the tkinter file filters into",
"_fix_output(output): ''' Removes miscelanous stdout output that can happen with Mesa drivers. Only",
"ZENITY_COMMON_ARGS = [ \"--file-selection\", \"--separator=\\n\", ] # If any of these arguments are",
"tkinter import messagebox error = (\"No supported native filedialog package installed.\", \"The default",
"error warning the user when called. ''' messagebox.showerror(error[0], error[1]) from tkinter.filedialog import (",
"'*'),), **kw): ''' Tkinter style wrapper for kdialog --getopenfilename. Arguments listed at the",
"except Exception: pass # These are the functions to wrap zenity and yad.",
"best, give us that. if subprocess.run(\"kdialog\", capture_output=True).returncode == 0: DIALOG_NAME = \"kdialog\" except",
"kdialog. ''' # This sucks right now. # We can't get file type",
"that start with the root separator. ''' return list(filter(lambda a : a.startswith(\"/\"), output.split(\"\\n\")))",
"return \"\" USE_TK_DIALOG = False if DIALOG_NAME and not USE_TK_DIALOG: print(\"Using native %s",
"filedialog if we have one. DIALOG_NAME = \"\" # Used for getting the",
"% (int(screen_resolution[0]/1.5)), \"--height=%d\" % (int(screen_resolution[1]/1.5)), ]) def _parse_file_filters(the_filters): ''' Parses the tkinter file",
"for. The rest are discarded. ''' res = subprocess.run( [DIALOG_NAME, \"--title\", str(title), \"--getsavefilename\",",
"for kdialog. if DIALOG_NAME == \"kdialog\": # capture_output to hide it from our",
"height of the primary monitor from the # xrandr command output. Tests here:",
"(%s) | *%s' % (a[0], a[1], a[1].lstrip('*')), the_filters)) def askopenfilename( title=\"Open file\", initialdir=str(Path.cwd()),",
"res = subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, # Get a directory. \"--directory\",",
"# Construct the common arguments for the calling of zenity or yad. ZENITY_COMMON_ARGS",
"discarded. ''' res = subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, # Start in",
"\"thing1 thing2 thing3 ( *.ext1 *.ext2 *.ext3 )\" filter. # kdialog sadly isn't",
"# We can't get file type descriptions into kdialog. # Still, anything better",
"*.ext1 *.ext2 *.ext3 )\" filter. # kdialog sadly isn't the nicest thing ever.",
"like so: \"*.mp3|*.ogg|*.wav\" # If we weren't supplying * as a filter everywhere",
"Tkinter style wrapper for kdialog --getopenfilename. Arguments listed at the top are the",
"return _fix_output(res.stdout)[0] except IndexError: return \"\" USE_TK_DIALOG = False # These are the",
"filter everywhere I would have # done a \"thing1 thing2 thing3 ( *.ext1",
"and screen_resolution[1]: ZENITY_COMMON_ARGS.extend([ \"--width=%d\" % (int(screen_resolution[0]/1.5)), \"--height=%d\" % (int(screen_resolution[1]/1.5)), ]) def _parse_file_filters(the_filters): '''",
"warning the user when called. ''' messagebox.showerror(error[0], error[1]) from tkinter.filedialog import ( askopenfilename,",
"# Filters look like \"name (extension)\" to users. # Filters get a *",
"capture_output=True).returncode == 255: DIALOG_NAME = \"zenity\" except Exception: pass # These are the",
"Linux. # This joins all the filters like so: \"*.mp3|*.ogg|*.wav\" # If we",
"askopenfilenames( title=\"Open files\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw): ''' Tkinter style wrapper for kdialog",
"based on how well they work.)\") print(\"\\n\".join(error)) def no_native_file_dialog_error(): ''' Only exists if",
"Tests here: https://regex101.com/r/clpmtZ/1 SCREEN_RES_REGEX = re.compile(r'primary (\\d+)x(\\d+)') screen_resolution = (0,0,) # Try to",
"# Start in save mode. \"--save\", \"--confirm-overwrite\", \"--filename=%s/%s\" % (initialdir, defaultextension), *_parse_file_filters(filetypes)], capture_output=True,",
"kdialog --getopenfilename. Arguments listed at the top are the only ones actually accounted",
"functions to wrap zenity and yad. if DIALOG_NAME in (\"yad\", \"zenity\"): # Construct",
"solution. ''' import sys from pathlib import Path USE_TK_DIALOG = True if \"linux\"",
"so they actually work. return list(map(lambda a : '--file-filter=%s (%s) | *%s' %",
"subprocess.run(\"kdialog\", capture_output=True).returncode != 0: # Hacky way to jump into the except block.",
"with Mesa drivers. Only accept absolute paths that start with the root separator.",
"drivers. Only accept absolute paths that start with the root separator. ''' return",
"(\\d+)x(\\d+)') screen_resolution = (0,0,) # Try to get the primary screen resolution from",
"I don't like that >:P if subprocess.run(\"zenity\", capture_output=True).returncode == 255: DIALOG_NAME = \"zenity\"",
"res = subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, # Get multiple items, put",
"title=\"Choose folder\", initialdir=str(Path.cwd()), **kw): ''' Tkinter style wrapper for zenity --file-selection. Arguments listed",
"style wrapper for kdialog --getsavefilename. Arguments listed at the top are the only",
"for Linux does not work\\n\" \"properly with symlinks.\\n\\n\" \"Please install either yad, kdialog,",
"there is no native file dialog. Displays an error warning the user when",
"yad, kdialog, or zenity.\\n\" \"(These suggestions are ordered based on how well they",
"capture_output=True).returncode == 0: DIALOG_NAME = \"yad\" except Exception: try: # kdialog is second",
"the top are the only ones actually accounted for. The rest are absolutely",
"command of the native filedialog if we have one. DIALOG_NAME = \"\" #",
"dialog we can use. try: # Yad is the best, please have yad.",
"https://regex101.com/r/clpmtZ/1 SCREEN_RES_REGEX = re.compile(r'primary (\\d+)x(\\d+)') screen_resolution = (0,0,) # Try to get the",
"style wrapper for zenity --file-selection. Arguments listed at the top are the only",
"'*'),), defaultextension=\"\", **kw): ''' Tkinter style wrapper for zenity --file-selection. Arguments listed at",
"If we weren't supplying * as a filter everywhere I would have #",
"isn't the nicest thing ever. But we have something at # least. return",
"(\"No supported native filedialog package installed.\", \"The default tkinter filedialog for Linux does",
"no native file dialog. Displays an error warning the user when called. '''",
"# Used for getting the width and height of the primary monitor from",
"Yad likes to open with a really small window size. Work around that.",
"tkinter file filters into a set of filters for kdialog. ''' # This",
"either yad, kdialog, or zenity.\\n\" \"(These suggestions are ordered based on how well",
"(title), *ZENITY_COMMON_ARGS, # Get a directory. \"--directory\", \"--filename=%s/\" % (initialdir)], capture_output=True, universal_newlines=True) try:",
"= \"yad\" except Exception: try: # kdialog is second best, give us that.",
"DIALOG_NAME = \"yad\" except Exception: try: # kdialog is second best, give us",
"different lines for parsing. \"--multiple\", \"--filename=%s/%s\" % (initialdir, filetypes[0][1]), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) return",
"window size. Work around that. if screen_resolution[0] and screen_resolution[1]: ZENITY_COMMON_ARGS.extend([ \"--width=%d\" % (int(screen_resolution[0]/1.5)),",
"\"*%s\" % a[1].lstrip('*'), the_filters)) def askopenfilename( title=\"Open file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw): '''",
"Exception: try: # kdialog is second best, give us that. if subprocess.run(\"kdialog\", capture_output=True).returncode",
"\"--getopenfilename\", str(initialdir), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) return _fix_output(res.stdout) def askdirectory( title=\"Choose folder\", initialdir=str(Path.cwd()), **kw):",
"open. if DIALOG_NAME == \"yad\": ZENITY_COMMON_ARGS.extend([ \"--on-top\", \"--mouse\", ]) # Yad likes to",
"initialdir=str(Path.cwd()), **kw): ''' Tkinter style wrapper for zenity --file-selection. Arguments listed at the",
"parsing. \"--multiple\", \"--separate-output\", \"--getopenfilename\", str(initialdir), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) return _fix_output(res.stdout) def askdirectory( title=\"Choose",
"discarded. ''' res = subprocess.run( [DIALOG_NAME, \"--title\", str(title), \"--getsavefilename\", # Joining these causes",
"IndexError: return \"\" USE_TK_DIALOG = False if DIALOG_NAME and not USE_TK_DIALOG: print(\"Using native",
"\"--title=%s\" % (title), *ZENITY_COMMON_ARGS, # Get a directory. \"--directory\", \"--filename=%s/\" % (initialdir)], capture_output=True,",
"The rest are discarded. ''' res = subprocess.run( [DIALOG_NAME, \"--title\", str(title), \"--getopenfilename\", str(initialdir),",
"title=\"Open file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw): ''' Tkinter style wrapper for kdialog --getopenfilename.",
"the width and height of the primary monitor from the # xrandr command",
"(title), *ZENITY_COMMON_ARGS, \"--filename=%s/\" % (initialdir), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError:",
"print(\"Couldn't retrieve screen resolution.\") # Figure out what native file dialog we can",
"int(screen_resolution[0]), int(screen_resolution[1]), ) except Exception: print(\"Couldn't retrieve screen resolution.\") # Figure out what",
"does not work\\n\" \"properly with symlinks.\\n\\n\" \"Please install either yad, kdialog, or zenity.\\n\"",
"try: # This one is nice. But it has a tendency to keep",
"Tkinter style wrapper for zenity --file-selection. Arguments listed at the top are the",
"present zenity won't open. if DIALOG_NAME == \"yad\": ZENITY_COMMON_ARGS.extend([ \"--on-top\", \"--mouse\", ]) #",
"can happen with Mesa drivers. Only accept absolute paths that start with the",
"filedialogs.\" % DIALOG_NAME) # Fallback for Linux, default for mac and Windows. if",
"of the primary monitor from the # xrandr command output. Tests here: https://regex101.com/r/clpmtZ/1",
"is nice. But it has a tendency to keep opening the # recent",
"Figure out what native file dialog we can use. try: # Yad is",
"subprocess.run( [DIALOG_NAME, \"--title\", str(title), # Get multiple items, put them on different lines",
"in sys.platform: from tkinter import messagebox error = (\"No supported native filedialog package",
"''' messagebox.showerror(error[0], error[1]) from tkinter.filedialog import ( askopenfilename, askopenfilenames, askdirectory, asksaveasfilename ) del",
"SCREEN_RES_REGEX = re.compile(r'primary (\\d+)x(\\d+)') screen_resolution = (0,0,) # Try to get the primary",
"0: DIALOG_NAME = \"kdialog\" except Exception: try: # This one is nice. But",
"I would have # done a \"thing1 thing2 thing3 ( *.ext1 *.ext2 *.ext3",
"are discarded. ''' res = subprocess.run( [DIALOG_NAME, \"--title\", str(title), # Get multiple items,",
"askdirectory( title=\"Choose folder\", initialdir=str(Path.cwd()), **kw): ''' Tkinter style wrapper for kdialog --getexistingdirectory. Arguments",
"False if DIALOG_NAME and not USE_TK_DIALOG: print(\"Using native %s for filedialogs.\" % DIALOG_NAME)",
"like that >:P if subprocess.run(\"zenity\", capture_output=True).returncode == 255: DIALOG_NAME = \"zenity\" except Exception:",
"discarded. ''' res = subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, # Get multiple",
"output.split(\"\\n\"))) # Name of the command of the native filedialog if we have",
"ever. But we have something at # least. return \"|\".join(map(lambda a : \"*%s\"",
"output. Tests here: https://regex101.com/r/clpmtZ/1 SCREEN_RES_REGEX = re.compile(r'primary (\\d+)x(\\d+)') screen_resolution = (0,0,) # Try",
"% (initialdir, defaultextension), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\"",
"DIALOG_NAME) # Fallback for Linux, default for mac and Windows. if USE_TK_DIALOG: if",
"''' Tkinter style wrapper for kdialog --getopenfilename. Arguments listed at the top are",
"module is our wrapper for filedialog so we can use a better one",
"= True if \"linux\" in sys.platform: import subprocess import re from os.path import",
"the tkinter file filters into a set of filters for kdialog. ''' #",
"def askopenfilename( title=\"Open file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw): ''' Tkinter style wrapper for",
"title=\"Open files\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw): ''' Tkinter style wrapper for zenity --file-selection.",
"tkinter on Linux. # This joins all the filters like so: \"*.mp3|*.ogg|*.wav\" #",
"now. # We can't get file type descriptions into kdialog. # Still, anything",
"Mesa drivers. Only accept absolute paths that start with the root separator. '''",
"the native filedialog if we have one. DIALOG_NAME = \"\" # Used for",
"*%s' % (a[0], a[1], a[1].lstrip('*')), the_filters)) def askopenfilename( title=\"Open file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),),",
"str(initialdir), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) return _fix_output(res.stdout) def askdirectory( title=\"Choose folder\", initialdir=str(Path.cwd()), **kw): '''",
"str(title), \"--getexistingdirectory\", str(initialdir)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\" def",
"initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw): ''' Tkinter style wrapper for zenity --file-selection. Arguments listed",
"is just... ouch. So, this is the alternative solution. ''' import sys from",
"if \"linux\" in sys.platform: from tkinter import messagebox error = (\"No supported native",
"these arguments are present zenity won't open. if DIALOG_NAME == \"yad\": ZENITY_COMMON_ARGS.extend([ \"--on-top\",",
"we weren't supplying * as a filter everywhere I would have # done",
"]) def _parse_file_filters(the_filters): ''' Parses the tkinter file filters into a set of",
"multiple items, put them on different lines for parsing. \"--multiple\", \"--separate-output\", \"--getopenfilename\", str(initialdir),",
"for kdialog --getexistingdirectory. Arguments listed at the top are the only ones actually",
"miscelanous stdout output that can happen with Mesa drivers. Only accept absolute paths",
"a filter everywhere I would have # done a \"thing1 thing2 thing3 (",
"into the except block. raise ValueError def _parse_file_filters(the_filters): ''' Parses the tkinter file",
"Linux, default for mac and Windows. if USE_TK_DIALOG: if \"linux\" in sys.platform: from",
"0: # Hacky way to jump into the except block. raise ValueError def",
"USE_TK_DIALOG: print(\"Using native %s for filedialogs.\" % DIALOG_NAME) # Fallback for Linux, default",
"the primary monitor from the # xrandr command output. Tests here: https://regex101.com/r/clpmtZ/1 SCREEN_RES_REGEX",
"for getting the width and height of the primary monitor from the #",
"dialog. Displays an error warning the user when called. ''' messagebox.showerror(error[0], error[1]) from",
"just... ouch. So, this is the alternative solution. ''' import sys from pathlib",
"list(filter(lambda a : a.startswith(\"/\"), output.split(\"\\n\"))) # Name of the command of the native",
"# If any of these arguments are present zenity won't open. if DIALOG_NAME",
"we can use a better one if it is available. The filepicker for",
"the extension to appear in the name box join(str(initialdir), defaultextension), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True)",
"\"linux\" in sys.platform: from tkinter import messagebox error = (\"No supported native filedialog",
"we have one. DIALOG_NAME = \"\" # Used for getting the width and",
"\"--multiple\", \"--filename=%s/%s\" % (initialdir, filetypes[0][1]), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) return _fix_output(res.stdout) def askdirectory( title=\"Choose",
"*ZENITY_COMMON_ARGS, \"--filename=%s/\" % (initialdir), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return",
"\"(These suggestions are ordered based on how well they work.)\") print(\"\\n\".join(error)) def no_native_file_dialog_error():",
"screen_resolution = SCREEN_RES_REGEX.search( subprocess.run( \"xrandr\", capture_output=True, universal_newlines=True).stdout ).group(1,2) screen_resolution = ( int(screen_resolution[0]), int(screen_resolution[1]),",
"absolutely trashed. ''' res = subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, # Get",
"''' Removes miscelanous stdout output that can happen with Mesa drivers. Only accept",
"if DIALOG_NAME == \"kdialog\": # capture_output to hide it from our terminal. if",
"don't like that >:P if subprocess.run(\"zenity\", capture_output=True).returncode == 255: DIALOG_NAME = \"zenity\" except",
"*.ext3 )\" filter. # kdialog sadly isn't the nicest thing ever. But we",
"causes the extension to appear in the name box join(str(initialdir), defaultextension), _parse_file_filters(filetypes)], capture_output=True,",
"= subprocess.run( [DIALOG_NAME, \"--title\", str(title), \"--getexistingdirectory\", str(initialdir)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except",
"''' Tkinter style wrapper for zenity --file-selection. Arguments listed at the top are",
"capture_output=True).returncode != 0: # Hacky way to jump into the except block. raise",
"% (initialdir, filetypes[0][1]), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) return _fix_output(res.stdout) def askdirectory( title=\"Choose folder\", initialdir=str(Path.cwd()),",
"extension to appear in the name box join(str(initialdir), defaultextension), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try:",
"The rest are discarded. ''' res = subprocess.run( [DIALOG_NAME, \"--title\", str(title), \"--getsavefilename\", #",
"filetypes[0][1]), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) return _fix_output(res.stdout) def askdirectory( title=\"Choose folder\", initialdir=str(Path.cwd()), **kw): '''",
"kdialog. if DIALOG_NAME == \"kdialog\": # capture_output to hide it from our terminal.",
"title=\"Open file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), defaultextension=\"\", **kw): ''' Tkinter style wrapper for zenity",
"for Tkinter on Linux is just... ouch. So, this is the alternative solution.",
"filetypes=(('All', '*'),), defaultextension=\"\", **kw): ''' Tkinter style wrapper for zenity --file-selection. Arguments listed",
"save mode. \"--save\", \"--confirm-overwrite\", \"--filename=%s/%s\" % (initialdir, defaultextension), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return",
"\"\" def asksaveasfilename( title=\"Open file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), defaultextension=\"\", **kw): ''' Tkinter style",
"DIALOG_NAME == \"yad\": ZENITY_COMMON_ARGS.extend([ \"--on-top\", \"--mouse\", ]) # Yad likes to open with",
"the functions used for kdialog. if DIALOG_NAME == \"kdialog\": # capture_output to hide",
"tendency to keep opening the # recent files folder. And I don't like",
"from the # xrandr command output. Tests here: https://regex101.com/r/clpmtZ/1 SCREEN_RES_REGEX = re.compile(r'primary (\\d+)x(\\d+)')",
"asksaveasfilename( title=\"Open file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), defaultextension=\"\", **kw): ''' Tkinter style wrapper for",
"If any of these arguments are present zenity won't open. if DIALOG_NAME ==",
"file dialog we can use. try: # Yad is the best, please have",
"if screen_resolution[0] and screen_resolution[1]: ZENITY_COMMON_ARGS.extend([ \"--width=%d\" % (int(screen_resolution[0]/1.5)), \"--height=%d\" % (int(screen_resolution[1]/1.5)), ]) def",
"# This sucks right now. # We can't get file type descriptions into",
"the_filters)) def askopenfilename( title=\"Open file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw): ''' Tkinter style wrapper",
"for. The rest are discarded. ''' res = subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title),",
"zenity.\\n\" \"(These suggestions are ordered based on how well they work.)\") print(\"\\n\".join(error)) def",
"\"yad\" except Exception: try: # kdialog is second best, give us that. if",
"import join def _fix_output(output): ''' Removes miscelanous stdout output that can happen with",
"--getexistingdirectory. Arguments listed at the top are the only ones actually accounted for.",
"# Hacky way to jump into the except block. raise ValueError def _parse_file_filters(the_filters):",
"\"zenity\" except Exception: pass # These are the functions to wrap zenity and",
"file filters into a set of filters for kdialog. ''' # This sucks",
"filters into a set of filters for kdialog. ''' # This sucks right",
"try: return _fix_output(res.stdout)[0] except IndexError: return \"\" USE_TK_DIALOG = False if DIALOG_NAME and",
"''' res = subprocess.run( [DIALOG_NAME, \"--title\", str(title), \"--getopenfilename\", str(initialdir), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try:",
"if subprocess.run([\"yad\", \"--help\"], capture_output=True).returncode == 0: DIALOG_NAME = \"yad\" except Exception: try: #",
"work\\n\" \"properly with symlinks.\\n\\n\" \"Please install either yad, kdialog, or zenity.\\n\" \"(These suggestions",
"\"--filename=%s/%s\" % (initialdir, filetypes[0][1]), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) return _fix_output(res.stdout) def askdirectory( title=\"Choose folder\",",
"Removes miscelanous stdout output that can happen with Mesa drivers. Only accept absolute",
"from xrandr. try: screen_resolution = SCREEN_RES_REGEX.search( subprocess.run( \"xrandr\", capture_output=True, universal_newlines=True).stdout ).group(1,2) screen_resolution =",
"\"xrandr\", capture_output=True, universal_newlines=True).stdout ).group(1,2) screen_resolution = ( int(screen_resolution[0]), int(screen_resolution[1]), ) except Exception: print(\"Couldn't",
"to keep opening the # recent files folder. And I don't like that",
"rest are discarded. ''' res = subprocess.run( [DIALOG_NAME, \"--title\", str(title), \"--getopenfilename\", str(initialdir), _parse_file_filters(filetypes)],",
"a directory. \"--directory\", \"--filename=%s/\" % (initialdir)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError:",
"weren't supplying * as a filter everywhere I would have # done a",
"Displays an error warning the user when called. ''' messagebox.showerror(error[0], error[1]) from tkinter.filedialog",
"discarded. ''' res = subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, \"--filename=%s/\" % (initialdir),",
"in sys.platform: import subprocess import re from os.path import join def _fix_output(output): '''",
"them on different lines for parsing. \"--multiple\", \"--filename=%s/%s\" % (initialdir, filetypes[0][1]), *_parse_file_filters(filetypes)], capture_output=True,",
"\"--title\", str(title), \"--getsavefilename\", # Joining these causes the extension to appear in the",
"This joins all the filters like so: \"*.mp3|*.ogg|*.wav\" # If we weren't supplying",
"available. The filepicker for Tkinter on Linux is just... ouch. So, this is",
"\"--title=%s\" % (title), *ZENITY_COMMON_ARGS, # Get multiple items, put them on different lines",
"except IndexError: return \"\" def askopenfilenames( title=\"Open files\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw): '''",
"in (\"yad\", \"zenity\"): # Construct the common arguments for the calling of zenity",
"str(title), # Get multiple items, put them on different lines for parsing. \"--multiple\",",
"\"yad\": ZENITY_COMMON_ARGS.extend([ \"--on-top\", \"--mouse\", ]) # Yad likes to open with a really",
"for the calling of zenity or yad. ZENITY_COMMON_ARGS = [ \"--file-selection\", \"--separator=\\n\", ]",
"to open with a really small window size. Work around that. if screen_resolution[0]",
"!= 0: # Hacky way to jump into the except block. raise ValueError",
"to hide it from our terminal. if subprocess.run(\"kdialog\", capture_output=True).returncode != 0: # Hacky",
"ZENITY_COMMON_ARGS.extend([ \"--on-top\", \"--mouse\", ]) # Yad likes to open with a really small",
"pathlib import Path USE_TK_DIALOG = True if \"linux\" in sys.platform: import subprocess import",
"except IndexError: return \"\" def asksaveasfilename( title=\"Open file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), defaultextension=\"\", **kw):",
")\" filter. # kdialog sadly isn't the nicest thing ever. But we have",
"\"--help\"], capture_output=True).returncode == 0: DIALOG_NAME = \"yad\" except Exception: try: # kdialog is",
"a really small window size. Work around that. if screen_resolution[0] and screen_resolution[1]: ZENITY_COMMON_ARGS.extend([",
"small window size. Work around that. if screen_resolution[0] and screen_resolution[1]: ZENITY_COMMON_ARGS.extend([ \"--width=%d\" %",
"= subprocess.run( [DIALOG_NAME, \"--title\", str(title), \"--getsavefilename\", # Joining these causes the extension to",
"*ZENITY_COMMON_ARGS, # Get a directory. \"--directory\", \"--filename=%s/\" % (initialdir)], capture_output=True, universal_newlines=True) try: return",
"files\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw): ''' Tkinter style wrapper for kdialog --getopenfilename. Arguments",
"is no native file dialog. Displays an error warning the user when called.",
"only ones actually accounted for. The rest are absolutely trashed. ''' res =",
"file type descriptions into kdialog. # Still, anything better than the default filedialog",
"\"\" USE_TK_DIALOG = False if DIALOG_NAME and not USE_TK_DIALOG: print(\"Using native %s for",
"try: # Yad is the best, please have yad. if subprocess.run([\"yad\", \"--help\"], capture_output=True).returncode",
"re from os.path import join def _fix_output(output): ''' Removes miscelanous stdout output that",
"--getopenfilename. Arguments listed at the top are the only ones actually accounted for.",
"res = subprocess.run( [DIALOG_NAME, \"--title\", str(title), # Get multiple items, put them on",
"opening the # recent files folder. And I don't like that >:P if",
"and height of the primary monitor from the # xrandr command output. Tests",
"accounted for. The rest are absolutely trashed. ''' res = subprocess.run( [DIALOG_NAME, \"--title=%s\"",
"try: screen_resolution = SCREEN_RES_REGEX.search( subprocess.run( \"xrandr\", capture_output=True, universal_newlines=True).stdout ).group(1,2) screen_resolution = ( int(screen_resolution[0]),",
"is the alternative solution. ''' import sys from pathlib import Path USE_TK_DIALOG =",
"# Get a directory. \"--directory\", \"--filename=%s/\" % (initialdir)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0]",
"\"zenity\"): # Construct the common arguments for the calling of zenity or yad.",
") except Exception: print(\"Couldn't retrieve screen resolution.\") # Figure out what native file",
"the tkinter file filters into a set of filters for zenity. ''' #",
"into a set of filters for zenity. ''' # Filters look like \"name",
"return \"\" USE_TK_DIALOG = False # These are the functions used for kdialog.",
"rest are absolutely trashed. ''' res = subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS,",
"Hacky way to jump into the except block. raise ValueError def _parse_file_filters(the_filters): '''",
"[DIALOG_NAME, \"--title\", str(title), \"--getexistingdirectory\", str(initialdir)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return",
"Try to get the primary screen resolution from xrandr. try: screen_resolution = SCREEN_RES_REGEX.search(",
"all the filters like so: \"*.mp3|*.ogg|*.wav\" # If we weren't supplying * as",
"*.ext2 *.ext3 )\" filter. # kdialog sadly isn't the nicest thing ever. But",
"install either yad, kdialog, or zenity.\\n\" \"(These suggestions are ordered based on how",
"list(map(lambda a : '--file-filter=%s (%s) | *%s' % (a[0], a[1], a[1].lstrip('*')), the_filters)) def",
"are the only ones actually accounted for. The rest are absolutely trashed. '''",
"# from tkinter on Linux. # This joins all the filters like so:",
"filedialog # from tkinter on Linux. # This joins all the filters like",
"% (initialdir)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\" def asksaveasfilename(",
"# These are the functions used for kdialog. if DIALOG_NAME == \"kdialog\": #",
"if it is available. The filepicker for Tkinter on Linux is just... ouch.",
"res = subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, # Start in save mode.",
"and yad. if DIALOG_NAME in (\"yad\", \"zenity\"): # Construct the common arguments for",
"initialdir=str(Path.cwd()), filetypes=(('All', '*'),), defaultextension=\"\", **kw): ''' Tkinter style wrapper for zenity --file-selection. Arguments",
"screen_resolution[0] and screen_resolution[1]: ZENITY_COMMON_ARGS.extend([ \"--width=%d\" % (int(screen_resolution[0]/1.5)), \"--height=%d\" % (int(screen_resolution[1]/1.5)), ]) def _parse_file_filters(the_filters):",
"\"kdialog\": # capture_output to hide it from our terminal. if subprocess.run(\"kdialog\", capture_output=True).returncode !=",
"# Still, anything better than the default filedialog # from tkinter on Linux.",
"one. DIALOG_NAME = \"\" # Used for getting the width and height of",
"for zenity --file-selection. Arguments listed at the top are the only ones actually",
"for. The rest are absolutely trashed. ''' res = subprocess.run( [DIALOG_NAME, \"--title=%s\" %",
"Start in save mode. \"--save\", \"--confirm-overwrite\", \"--filename=%s/%s\" % (initialdir, defaultextension), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True)",
"[DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, # Start in save mode. \"--save\", \"--confirm-overwrite\", \"--filename=%s/%s\"",
"title=\"Choose folder\", initialdir=str(Path.cwd()), **kw): ''' Tkinter style wrapper for kdialog --getexistingdirectory. Arguments listed",
"prepended so they actually work. return list(map(lambda a : '--file-filter=%s (%s) | *%s'",
"except Exception: print(\"Couldn't retrieve screen resolution.\") # Figure out what native file dialog",
"for kdialog --getopenfilename. Arguments listed at the top are the only ones actually",
"DIALOG_NAME and not USE_TK_DIALOG: print(\"Using native %s for filedialogs.\" % DIALOG_NAME) # Fallback",
"return _fix_output(res.stdout)[0] except IndexError: return \"\" USE_TK_DIALOG = False if DIALOG_NAME and not",
"can use a better one if it is available. The filepicker for Tkinter",
"| *%s' % (a[0], a[1], a[1].lstrip('*')), the_filters)) def askopenfilename( title=\"Open file\", initialdir=str(Path.cwd()), filetypes=(('All',",
"done a \"thing1 thing2 thing3 ( *.ext1 *.ext2 *.ext3 )\" filter. # kdialog",
"[DIALOG_NAME, \"--title\", str(title), # Get multiple items, put them on different lines for",
"put them on different lines for parsing. \"--multiple\", \"--filename=%s/%s\" % (initialdir, filetypes[0][1]), *_parse_file_filters(filetypes)],",
"way to jump into the except block. raise ValueError def _parse_file_filters(the_filters): ''' Parses",
"'*'),), **kw): ''' Tkinter style wrapper for zenity --file-selection. Arguments listed at the",
"on Linux is just... ouch. So, this is the alternative solution. ''' import",
"to get the primary screen resolution from xrandr. try: screen_resolution = SCREEN_RES_REGEX.search( subprocess.run(",
"trashed. ''' res = subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, # Get a",
"sys from pathlib import Path USE_TK_DIALOG = True if \"linux\" in sys.platform: import",
"them on different lines for parsing. \"--multiple\", \"--separate-output\", \"--getopenfilename\", str(initialdir), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True)",
"are discarded. ''' res = subprocess.run( [DIALOG_NAME, \"--title\", str(title), \"--getopenfilename\", str(initialdir), _parse_file_filters(filetypes)], capture_output=True,",
"sys.platform: import subprocess import re from os.path import join def _fix_output(output): ''' Removes",
"return list(map(lambda a : '--file-filter=%s (%s) | *%s' % (a[0], a[1], a[1].lstrip('*')), the_filters))",
"if we have one. DIALOG_NAME = \"\" # Used for getting the width",
"wrapper for kdialog --getopenfilename. Arguments listed at the top are the only ones",
"subprocess.run( [DIALOG_NAME, \"--title\", str(title), \"--getopenfilename\", str(initialdir), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except",
"file dialog. Displays an error warning the user when called. ''' messagebox.showerror(error[0], error[1])",
"directory. \"--directory\", \"--filename=%s/\" % (initialdir)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return",
"The rest are discarded. ''' res = subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS,",
"from tkinter on Linux. # This joins all the filters like so: \"*.mp3|*.ogg|*.wav\"",
"items, put them on different lines for parsing. \"--multiple\", \"--filename=%s/%s\" % (initialdir, filetypes[0][1]),",
"the name box join(str(initialdir), defaultextension), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError:",
"nicest thing ever. But we have something at # least. return \"|\".join(map(lambda a",
"[DIALOG_NAME, \"--title\", str(title), \"--getopenfilename\", str(initialdir), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError:",
"DIALOG_NAME = \"kdialog\" except Exception: try: # This one is nice. But it",
"return \"\" def asksaveasfilename( title=\"Open file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), defaultextension=\"\", **kw): ''' Tkinter",
"supplying * as a filter everywhere I would have # done a \"thing1",
"\"--filename=%s/\" % (initialdir), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\"",
"return _fix_output(res.stdout) def askdirectory( title=\"Choose folder\", initialdir=str(Path.cwd()), **kw): ''' Tkinter style wrapper for",
"accept absolute paths that start with the root separator. ''' return list(filter(lambda a",
"thing2 thing3 ( *.ext1 *.ext2 *.ext3 )\" filter. # kdialog sadly isn't the",
"arguments for the calling of zenity or yad. ZENITY_COMMON_ARGS = [ \"--file-selection\", \"--separator=\\n\",",
"the calling of zenity or yad. ZENITY_COMMON_ARGS = [ \"--file-selection\", \"--separator=\\n\", ] #",
"# This one is nice. But it has a tendency to keep opening",
"# These are the functions to wrap zenity and yad. if DIALOG_NAME in",
"ordered based on how well they work.)\") print(\"\\n\".join(error)) def no_native_file_dialog_error(): ''' Only exists",
"have yad. if subprocess.run([\"yad\", \"--help\"], capture_output=True).returncode == 0: DIALOG_NAME = \"yad\" except Exception:",
"print(\"\\n\".join(error)) def no_native_file_dialog_error(): ''' Only exists if there is no native file dialog.",
"= \"\" # Used for getting the width and height of the primary",
"capture_output=True, universal_newlines=True) return _fix_output(res.stdout) def askdirectory( title=\"Choose folder\", initialdir=str(Path.cwd()), **kw): ''' Tkinter style",
"% DIALOG_NAME) # Fallback for Linux, default for mac and Windows. if USE_TK_DIALOG:",
"a : \"*%s\" % a[1].lstrip('*'), the_filters)) def askopenfilename( title=\"Open file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),),",
"it is available. The filepicker for Tkinter on Linux is just... ouch. So,",
"the only ones actually accounted for. The rest are discarded. ''' res =",
"file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw): ''' Tkinter style wrapper for kdialog --getopenfilename. Arguments",
"calling of zenity or yad. ZENITY_COMMON_ARGS = [ \"--file-selection\", \"--separator=\\n\", ] # If",
"recent files folder. And I don't like that >:P if subprocess.run(\"zenity\", capture_output=True).returncode ==",
"so we can use a better one if it is available. The filepicker",
"a tendency to keep opening the # recent files folder. And I don't",
"file filters into a set of filters for zenity. ''' # Filters look",
"universal_newlines=True).stdout ).group(1,2) screen_resolution = ( int(screen_resolution[0]), int(screen_resolution[1]), ) except Exception: print(\"Couldn't retrieve screen",
"xrandr. try: screen_resolution = SCREEN_RES_REGEX.search( subprocess.run( \"xrandr\", capture_output=True, universal_newlines=True).stdout ).group(1,2) screen_resolution = (",
"if subprocess.run(\"zenity\", capture_output=True).returncode == 255: DIALOG_NAME = \"zenity\" except Exception: pass # These",
"any of these arguments are present zenity won't open. if DIALOG_NAME == \"yad\":",
"% (title), *ZENITY_COMMON_ARGS, \"--filename=%s/\" % (initialdir), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except",
"they work.)\") print(\"\\n\".join(error)) def no_native_file_dialog_error(): ''' Only exists if there is no native",
"(int(screen_resolution[0]/1.5)), \"--height=%d\" % (int(screen_resolution[1]/1.5)), ]) def _parse_file_filters(the_filters): ''' Parses the tkinter file filters",
"''' res = subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, # Get a directory.",
"= subprocess.run( [DIALOG_NAME, \"--title\", str(title), # Get multiple items, put them on different",
"filedialog for Linux does not work\\n\" \"properly with symlinks.\\n\\n\" \"Please install either yad,",
"== 0: DIALOG_NAME = \"yad\" except Exception: try: # kdialog is second best,",
"]) # Yad likes to open with a really small window size. Work",
"are discarded. ''' res = subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, # Start",
"is available. The filepicker for Tkinter on Linux is just... ouch. So, this",
"try: return _fix_output(res.stdout)[0] except IndexError: return \"\" USE_TK_DIALOG = False # These are",
"with the root separator. ''' return list(filter(lambda a : a.startswith(\"/\"), output.split(\"\\n\"))) # Name",
"discarded. ''' res = subprocess.run( [DIALOG_NAME, \"--title\", str(title), # Get multiple items, put",
"are ordered based on how well they work.)\") print(\"\\n\".join(error)) def no_native_file_dialog_error(): ''' Only",
"to users. # Filters get a * prepended so they actually work. return",
"terminal. if subprocess.run(\"kdialog\", capture_output=True).returncode != 0: # Hacky way to jump into the",
"on different lines for parsing. \"--multiple\", \"--filename=%s/%s\" % (initialdir, filetypes[0][1]), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True)",
"are the only ones actually accounted for. The rest are discarded. ''' res",
"for Linux, default for mac and Windows. if USE_TK_DIALOG: if \"linux\" in sys.platform:",
"yad. if DIALOG_NAME in (\"yad\", \"zenity\"): # Construct the common arguments for the",
"with a really small window size. Work around that. if screen_resolution[0] and screen_resolution[1]:",
"= subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, \"--filename=%s/\" % (initialdir), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True)",
"ones actually accounted for. The rest are absolutely trashed. ''' res = subprocess.run(",
"something at # least. return \"|\".join(map(lambda a : \"*%s\" % a[1].lstrip('*'), the_filters)) def",
"screen resolution from xrandr. try: screen_resolution = SCREEN_RES_REGEX.search( subprocess.run( \"xrandr\", capture_output=True, universal_newlines=True).stdout ).group(1,2)",
"and Windows. if USE_TK_DIALOG: if \"linux\" in sys.platform: from tkinter import messagebox error",
"subprocess import re from os.path import join def _fix_output(output): ''' Removes miscelanous stdout",
"The rest are discarded. ''' res = subprocess.run( [DIALOG_NAME, \"--title\", str(title), # Get",
"filepicker for Tkinter on Linux is just... ouch. So, this is the alternative",
"\"properly with symlinks.\\n\\n\" \"Please install either yad, kdialog, or zenity.\\n\" \"(These suggestions are",
").group(1,2) screen_resolution = ( int(screen_resolution[0]), int(screen_resolution[1]), ) except Exception: print(\"Couldn't retrieve screen resolution.\")",
"str(initialdir)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\" def asksaveasfilename( title=\"Open",
"res = subprocess.run( [DIALOG_NAME, \"--title\", str(title), \"--getsavefilename\", # Joining these causes the extension",
"file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), defaultextension=\"\", **kw): ''' Tkinter style wrapper for zenity --file-selection.",
"capture_output=True).returncode == 0: DIALOG_NAME = \"kdialog\" except Exception: try: # This one is",
"messagebox error = (\"No supported native filedialog package installed.\", \"The default tkinter filedialog",
"native filedialog package installed.\", \"The default tkinter filedialog for Linux does not work\\n\"",
"*_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\" USE_TK_DIALOG = False",
"''' import sys from pathlib import Path USE_TK_DIALOG = True if \"linux\" in",
"[ \"--file-selection\", \"--separator=\\n\", ] # If any of these arguments are present zenity",
"return _fix_output(res.stdout)[0] except IndexError: return \"\" def asksaveasfilename( title=\"Open file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),),",
"an error warning the user when called. ''' messagebox.showerror(error[0], error[1]) from tkinter.filedialog import",
"style wrapper for kdialog --getexistingdirectory. Arguments listed at the top are the only",
"it has a tendency to keep opening the # recent files folder. And",
"import messagebox error = (\"No supported native filedialog package installed.\", \"The default tkinter",
"monitor from the # xrandr command output. Tests here: https://regex101.com/r/clpmtZ/1 SCREEN_RES_REGEX = re.compile(r'primary",
"can't get file type descriptions into kdialog. # Still, anything better than the",
"the except block. raise ValueError def _parse_file_filters(the_filters): ''' Parses the tkinter file filters",
"IndexError: return \"\" def askopenfilenames( title=\"Open files\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw): ''' Tkinter",
"\"--getsavefilename\", # Joining these causes the extension to appear in the name box",
"name box join(str(initialdir), defaultextension), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return",
"to appear in the name box join(str(initialdir), defaultextension), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return",
"zenity won't open. if DIALOG_NAME == \"yad\": ZENITY_COMMON_ARGS.extend([ \"--on-top\", \"--mouse\", ]) # Yad",
"right now. # We can't get file type descriptions into kdialog. # Still,",
"the common arguments for the calling of zenity or yad. ZENITY_COMMON_ARGS = [",
"box join(str(initialdir), defaultextension), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\"",
"Path USE_TK_DIALOG = True if \"linux\" in sys.platform: import subprocess import re from",
"have one. DIALOG_NAME = \"\" # Used for getting the width and height",
"Linux does not work\\n\" \"properly with symlinks.\\n\\n\" \"Please install either yad, kdialog, or",
"folder. And I don't like that >:P if subprocess.run(\"zenity\", capture_output=True).returncode == 255: DIALOG_NAME",
"appear in the name box join(str(initialdir), defaultextension), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0]",
"or zenity.\\n\" \"(These suggestions are ordered based on how well they work.)\") print(\"\\n\".join(error))",
"res = subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, \"--filename=%s/\" % (initialdir), *_parse_file_filters(filetypes)], capture_output=True,",
"] # If any of these arguments are present zenity won't open. if",
"--getsavefilename. Arguments listed at the top are the only ones actually accounted for.",
"are discarded. ''' res = subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, \"--filename=%s/\" %",
"it from our terminal. if subprocess.run(\"kdialog\", capture_output=True).returncode != 0: # Hacky way to",
"we can use. try: # Yad is the best, please have yad. if",
"if DIALOG_NAME == \"yad\": ZENITY_COMMON_ARGS.extend([ \"--on-top\", \"--mouse\", ]) # Yad likes to open",
"Filters look like \"name (extension)\" to users. # Filters get a * prepended",
"from os.path import join def _fix_output(output): ''' Removes miscelanous stdout output that can",
"on different lines for parsing. \"--multiple\", \"--separate-output\", \"--getopenfilename\", str(initialdir), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) return",
"= \"zenity\" except Exception: pass # These are the functions to wrap zenity",
"from tkinter import messagebox error = (\"No supported native filedialog package installed.\", \"The",
"defaultextension), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\" USE_TK_DIALOG =",
"= False # These are the functions used for kdialog. if DIALOG_NAME ==",
"import subprocess import re from os.path import join def _fix_output(output): ''' Removes miscelanous",
"(int(screen_resolution[1]/1.5)), ]) def _parse_file_filters(the_filters): ''' Parses the tkinter file filters into a set",
"block. raise ValueError def _parse_file_filters(the_filters): ''' Parses the tkinter file filters into a",
"native file dialog we can use. try: # Yad is the best, please",
"is second best, give us that. if subprocess.run(\"kdialog\", capture_output=True).returncode == 0: DIALOG_NAME =",
"% (a[0], a[1], a[1].lstrip('*')), the_filters)) def askopenfilename( title=\"Open file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw):",
"\"linux\" in sys.platform: import subprocess import re from os.path import join def _fix_output(output):",
"suggestions are ordered based on how well they work.)\") print(\"\\n\".join(error)) def no_native_file_dialog_error(): '''",
"# xrandr command output. Tests here: https://regex101.com/r/clpmtZ/1 SCREEN_RES_REGEX = re.compile(r'primary (\\d+)x(\\d+)') screen_resolution =",
"filedialog so we can use a better one if it is available. The",
"Exception: try: # This one is nice. But it has a tendency to",
"when called. ''' messagebox.showerror(error[0], error[1]) from tkinter.filedialog import ( askopenfilename, askopenfilenames, askdirectory, asksaveasfilename",
"_fix_output(res.stdout)[0] except IndexError: return \"\" USE_TK_DIALOG = False if DIALOG_NAME and not USE_TK_DIALOG:",
"*ZENITY_COMMON_ARGS, # Get multiple items, put them on different lines for parsing. \"--multiple\",",
"work.)\") print(\"\\n\".join(error)) def no_native_file_dialog_error(): ''' Only exists if there is no native file",
"for kdialog. ''' # This sucks right now. # We can't get file",
"zenity. ''' # Filters look like \"name (extension)\" to users. # Filters get",
"of the native filedialog if we have one. DIALOG_NAME = \"\" # Used",
"The rest are absolutely trashed. ''' res = subprocess.run( [DIALOG_NAME, \"--title\", str(title), \"--getexistingdirectory\",",
"\"--directory\", \"--filename=%s/\" % (initialdir)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\"",
"the alternative solution. ''' import sys from pathlib import Path USE_TK_DIALOG = True",
"tkinter file filters into a set of filters for zenity. ''' # Filters",
">:P if subprocess.run(\"zenity\", capture_output=True).returncode == 255: DIALOG_NAME = \"zenity\" except Exception: pass #",
"Arguments listed at the top are the only ones actually accounted for. The",
"% (title), *ZENITY_COMMON_ARGS, # Get multiple items, put them on different lines for",
"type descriptions into kdialog. # Still, anything better than the default filedialog #",
"filetypes=(('All', '*'),), **kw): ''' Tkinter style wrapper for zenity --file-selection. Arguments listed at",
"subprocess.run( [DIALOG_NAME, \"--title\", str(title), \"--getexistingdirectory\", str(initialdir)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError:",
"DIALOG_NAME = \"zenity\" except Exception: pass # These are the functions to wrap",
"Joining these causes the extension to appear in the name box join(str(initialdir), defaultextension),",
"into a set of filters for kdialog. ''' # This sucks right now.",
"sadly isn't the nicest thing ever. But we have something at # least.",
"Used for getting the width and height of the primary monitor from the",
"a[1].lstrip('*')), the_filters)) def askopenfilename( title=\"Open file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw): ''' Tkinter style",
"askdirectory( title=\"Choose folder\", initialdir=str(Path.cwd()), **kw): ''' Tkinter style wrapper for zenity --file-selection. Arguments",
"Only accept absolute paths that start with the root separator. ''' return list(filter(lambda",
"retrieve screen resolution.\") # Figure out what native file dialog we can use.",
"_fix_output(res.stdout)[0] except IndexError: return \"\" USE_TK_DIALOG = False # These are the functions",
"command output. Tests here: https://regex101.com/r/clpmtZ/1 SCREEN_RES_REGEX = re.compile(r'primary (\\d+)x(\\d+)') screen_resolution = (0,0,) #",
"* as a filter everywhere I would have # done a \"thing1 thing2",
"the user when called. ''' messagebox.showerror(error[0], error[1]) from tkinter.filedialog import ( askopenfilename, askopenfilenames,",
"different lines for parsing. \"--multiple\", \"--separate-output\", \"--getopenfilename\", str(initialdir), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) return _fix_output(res.stdout)",
"file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), defaultextension=\"\", **kw): ''' Tkinter style wrapper for kdialog --getsavefilename.",
"wrapper for filedialog so we can use a better one if it is",
"like \"name (extension)\" to users. # Filters get a * prepended so they",
"rest are discarded. ''' res = subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, #",
"ValueError def _parse_file_filters(the_filters): ''' Parses the tkinter file filters into a set of",
"Parses the tkinter file filters into a set of filters for zenity. '''",
"lines for parsing. \"--multiple\", \"--separate-output\", \"--getopenfilename\", str(initialdir), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) return _fix_output(res.stdout) def",
"a \"thing1 thing2 thing3 ( *.ext1 *.ext2 *.ext3 )\" filter. # kdialog sadly",
"# If we weren't supplying * as a filter everywhere I would have",
"try: # kdialog is second best, give us that. if subprocess.run(\"kdialog\", capture_output=True).returncode ==",
"style wrapper for kdialog --getopenfilename. Arguments listed at the top are the only",
"capture_output to hide it from our terminal. if subprocess.run(\"kdialog\", capture_output=True).returncode != 0: #",
"around that. if screen_resolution[0] and screen_resolution[1]: ZENITY_COMMON_ARGS.extend([ \"--width=%d\" % (int(screen_resolution[0]/1.5)), \"--height=%d\" % (int(screen_resolution[1]/1.5)),",
"subprocess.run( [DIALOG_NAME, \"--title\", str(title), \"--getsavefilename\", # Joining these causes the extension to appear",
"thing ever. But we have something at # least. return \"|\".join(map(lambda a :",
"trashed. ''' res = subprocess.run( [DIALOG_NAME, \"--title\", str(title), \"--getexistingdirectory\", str(initialdir)], capture_output=True, universal_newlines=True) try:",
"width and height of the primary monitor from the # xrandr command output.",
"subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, \"--filename=%s/\" % (initialdir), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try:",
"return _fix_output(res.stdout)[0] except IndexError: return \"\" def askopenfilenames( title=\"Open files\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),),",
"for kdialog --getsavefilename. Arguments listed at the top are the only ones actually",
"# Get multiple items, put them on different lines for parsing. \"--multiple\", \"--filename=%s/%s\"",
"universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\" def askopenfilenames( title=\"Open files\", initialdir=str(Path.cwd()),",
"our wrapper for filedialog so we can use a better one if it",
"% a[1].lstrip('*'), the_filters)) def askopenfilename( title=\"Open file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw): ''' Tkinter",
"# least. return \"|\".join(map(lambda a : \"*%s\" % a[1].lstrip('*'), the_filters)) def askopenfilename( title=\"Open",
"But we have something at # least. return \"|\".join(map(lambda a : \"*%s\" %",
"parsing. \"--multiple\", \"--filename=%s/%s\" % (initialdir, filetypes[0][1]), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) return _fix_output(res.stdout) def askdirectory(",
"IndexError: return \"\" def asksaveasfilename( title=\"Open file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), defaultextension=\"\", **kw): '''",
"USE_TK_DIALOG = False if DIALOG_NAME and not USE_TK_DIALOG: print(\"Using native %s for filedialogs.\"",
"= \"kdialog\" except Exception: try: # This one is nice. But it has",
"absolutely trashed. ''' res = subprocess.run( [DIALOG_NAME, \"--title\", str(title), \"--getexistingdirectory\", str(initialdir)], capture_output=True, universal_newlines=True)",
"users. # Filters get a * prepended so they actually work. return list(map(lambda",
"well they work.)\") print(\"\\n\".join(error)) def no_native_file_dialog_error(): ''' Only exists if there is no",
"Still, anything better than the default filedialog # from tkinter on Linux. #",
"subprocess.run( \"xrandr\", capture_output=True, universal_newlines=True).stdout ).group(1,2) screen_resolution = ( int(screen_resolution[0]), int(screen_resolution[1]), ) except Exception:",
"the root separator. ''' return list(filter(lambda a : a.startswith(\"/\"), output.split(\"\\n\"))) # Name of",
"'--file-filter=%s (%s) | *%s' % (a[0], a[1], a[1].lstrip('*')), the_filters)) def askopenfilename( title=\"Open file\",",
"# Yad is the best, please have yad. if subprocess.run([\"yad\", \"--help\"], capture_output=True).returncode ==",
"\"--title=%s\" % (title), *ZENITY_COMMON_ARGS, # Start in save mode. \"--save\", \"--confirm-overwrite\", \"--filename=%s/%s\" %",
"getting the width and height of the primary monitor from the # xrandr",
"subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, # Start in save mode. \"--save\", \"--confirm-overwrite\",",
"DIALOG_NAME == \"kdialog\": # capture_output to hide it from our terminal. if subprocess.run(\"kdialog\",",
"filters for zenity. ''' # Filters look like \"name (extension)\" to users. #",
"open with a really small window size. Work around that. if screen_resolution[0] and",
"wrapper for kdialog --getsavefilename. Arguments listed at the top are the only ones",
"if USE_TK_DIALOG: if \"linux\" in sys.platform: from tkinter import messagebox error = (\"No",
"import re from os.path import join def _fix_output(output): ''' Removes miscelanous stdout output",
"% (title), *ZENITY_COMMON_ARGS, # Get a directory. \"--directory\", \"--filename=%s/\" % (initialdir)], capture_output=True, universal_newlines=True)",
"happen with Mesa drivers. Only accept absolute paths that start with the root",
"''' res = subprocess.run( [DIALOG_NAME, \"--title\", str(title), # Get multiple items, put them",
"rest are discarded. ''' res = subprocess.run( [DIALOG_NAME, \"--title\", str(title), \"--getsavefilename\", # Joining",
"of zenity or yad. ZENITY_COMMON_ARGS = [ \"--file-selection\", \"--separator=\\n\", ] # If any",
"defaultextension=\"\", **kw): ''' Tkinter style wrapper for zenity --file-selection. Arguments listed at the",
"arguments are present zenity won't open. if DIALOG_NAME == \"yad\": ZENITY_COMMON_ARGS.extend([ \"--on-top\", \"--mouse\",",
"_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\" def askopenfilenames( title=\"Open",
"of these arguments are present zenity won't open. if DIALOG_NAME == \"yad\": ZENITY_COMMON_ARGS.extend([",
"listed at the top are the only ones actually accounted for. The rest",
"# done a \"thing1 thing2 thing3 ( *.ext1 *.ext2 *.ext3 )\" filter. #",
"filetypes=(('All', '*'),), **kw): ''' Tkinter style wrapper for kdialog --getopenfilename. Arguments listed at",
"yad. ZENITY_COMMON_ARGS = [ \"--file-selection\", \"--separator=\\n\", ] # If any of these arguments",
"askopenfilename( title=\"Open file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw): ''' Tkinter style wrapper for zenity",
"with symlinks.\\n\\n\" \"Please install either yad, kdialog, or zenity.\\n\" \"(These suggestions are ordered",
"DIALOG_NAME = \"\" # Used for getting the width and height of the",
"\"Please install either yad, kdialog, or zenity.\\n\" \"(These suggestions are ordered based on",
"IndexError: return \"\" USE_TK_DIALOG = False # These are the functions used for",
"a.startswith(\"/\"), output.split(\"\\n\"))) # Name of the command of the native filedialog if we",
"def _parse_file_filters(the_filters): ''' Parses the tkinter file filters into a set of filters",
"(initialdir, filetypes[0][1]), *_parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) return _fix_output(res.stdout) def askdirectory( title=\"Choose folder\", initialdir=str(Path.cwd()), **kw):",
"for. The rest are discarded. ''' res = subprocess.run( [DIALOG_NAME, \"--title\", str(title), \"--getopenfilename\",",
"the command of the native filedialog if we have one. DIALOG_NAME = \"\"",
"common arguments for the calling of zenity or yad. ZENITY_COMMON_ARGS = [ \"--file-selection\",",
"(title), *ZENITY_COMMON_ARGS, # Start in save mode. \"--save\", \"--confirm-overwrite\", \"--filename=%s/%s\" % (initialdir, defaultextension),",
"This sucks right now. # We can't get file type descriptions into kdialog.",
"subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, # Get multiple items, put them on",
"give us that. if subprocess.run(\"kdialog\", capture_output=True).returncode == 0: DIALOG_NAME = \"kdialog\" except Exception:",
"thing3 ( *.ext1 *.ext2 *.ext3 )\" filter. # kdialog sadly isn't the nicest",
": '--file-filter=%s (%s) | *%s' % (a[0], a[1], a[1].lstrip('*')), the_filters)) def askopenfilename( title=\"Open",
"universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\" def asksaveasfilename( title=\"Open file\", initialdir=str(Path.cwd()),",
"def asksaveasfilename( title=\"Open file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), defaultextension=\"\", **kw): ''' Tkinter style wrapper",
"These are the functions used for kdialog. if DIALOG_NAME == \"kdialog\": # capture_output",
"\"--separate-output\", \"--getopenfilename\", str(initialdir), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) return _fix_output(res.stdout) def askdirectory( title=\"Choose folder\", initialdir=str(Path.cwd()),",
"%s for filedialogs.\" % DIALOG_NAME) # Fallback for Linux, default for mac and",
"from pathlib import Path USE_TK_DIALOG = True if \"linux\" in sys.platform: import subprocess",
"yad. if subprocess.run([\"yad\", \"--help\"], capture_output=True).returncode == 0: DIALOG_NAME = \"yad\" except Exception: try:",
"only ones actually accounted for. The rest are discarded. ''' res = subprocess.run(",
"# Name of the command of the native filedialog if we have one.",
"def no_native_file_dialog_error(): ''' Only exists if there is no native file dialog. Displays",
"# Figure out what native file dialog we can use. try: # Yad",
"universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\" USE_TK_DIALOG = False # These",
"the top are the only ones actually accounted for. The rest are discarded.",
"subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, # Get a directory. \"--directory\", \"--filename=%s/\" %",
"raise ValueError def _parse_file_filters(the_filters): ''' Parses the tkinter file filters into a set",
"that. if screen_resolution[0] and screen_resolution[1]: ZENITY_COMMON_ARGS.extend([ \"--width=%d\" % (int(screen_resolution[0]/1.5)), \"--height=%d\" % (int(screen_resolution[1]/1.5)), ])",
"Get multiple items, put them on different lines for parsing. \"--multiple\", \"--filename=%s/%s\" %",
"str(title), \"--getsavefilename\", # Joining these causes the extension to appear in the name",
"''' Tkinter style wrapper for kdialog --getexistingdirectory. Arguments listed at the top are",
"subprocess.run(\"zenity\", capture_output=True).returncode == 255: DIALOG_NAME = \"zenity\" except Exception: pass # These are",
"that can happen with Mesa drivers. Only accept absolute paths that start with",
"\"name (extension)\" to users. # Filters get a * prepended so they actually",
"(extension)\" to users. # Filters get a * prepended so they actually work.",
"screen_resolution = ( int(screen_resolution[0]), int(screen_resolution[1]), ) except Exception: print(\"Couldn't retrieve screen resolution.\") #",
"if DIALOG_NAME in (\"yad\", \"zenity\"): # Construct the common arguments for the calling",
"try: return _fix_output(res.stdout)[0] except IndexError: return \"\" def asksaveasfilename( title=\"Open file\", initialdir=str(Path.cwd()), filetypes=(('All',",
"not USE_TK_DIALOG: print(\"Using native %s for filedialogs.\" % DIALOG_NAME) # Fallback for Linux,",
"= subprocess.run( [DIALOG_NAME, \"--title=%s\" % (title), *ZENITY_COMMON_ARGS, # Get multiple items, put them",
"capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\" def asksaveasfilename( title=\"Open file\",",
"title=\"Open file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), defaultextension=\"\", **kw): ''' Tkinter style wrapper for kdialog",
"kdialog --getexistingdirectory. Arguments listed at the top are the only ones actually accounted",
"USE_TK_DIALOG = True if \"linux\" in sys.platform: import subprocess import re from os.path",
"We can't get file type descriptions into kdialog. # Still, anything better than",
"title=\"Open file\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw): ''' Tkinter style wrapper for zenity --file-selection.",
"subprocess.run([\"yad\", \"--help\"], capture_output=True).returncode == 0: DIALOG_NAME = \"yad\" except Exception: try: # kdialog",
"def askopenfilenames( title=\"Open files\", initialdir=str(Path.cwd()), filetypes=(('All', '*'),), **kw): ''' Tkinter style wrapper for",
"paths that start with the root separator. ''' return list(filter(lambda a : a.startswith(\"/\"),",
"join(str(initialdir), defaultextension), _parse_file_filters(filetypes)], capture_output=True, universal_newlines=True) try: return _fix_output(res.stdout)[0] except IndexError: return \"\" USE_TK_DIALOG"
] |
[
"import division from __future__ import absolute_import from future import standard_library import twitter_scraper as",
"division from __future__ import absolute_import from future import standard_library import twitter_scraper as twitter_scraper",
"tweets = twitter_scraper.scraper.Scraper.get_tweets(search_params) t_list = [] for tweet in tweets: t_list = build_list(tweet,",
"import absolute_import from future import standard_library import twitter_scraper as twitter_scraper import json import",
"'utf-8') as f: f.write(data) return True except BaseException as e: print(e) search_term =",
"twitter_scraper.scraper.Scraper.get_tweets(search_params) t_list = [] for tweet in tweets: t_list = build_list(tweet, t_list) json_data",
"except BaseException as e: print(e) search_term = '@meshivammathur' search_params = twitter_scraper.scraper.SearchParams().set_username(search_term).set_max_tweets(400) tweets =",
"try: with codecs.open(filename + '.json', 'a', 'utf-8') as f: f.write(data) return True except",
"__future__ import absolute_import from future import standard_library import twitter_scraper as twitter_scraper import json",
"True except BaseException as e: print(e) search_term = '@meshivammathur' search_params = twitter_scraper.scraper.SearchParams().set_username(search_term).set_max_tweets(400) tweets",
"= twitter_scraper.scraper.SearchParams().set_username(search_term).set_max_tweets(400) tweets = twitter_scraper.scraper.Scraper.get_tweets(search_params) t_list = [] for tweet in tweets: t_list",
"from __future__ import print_function from __future__ import unicode_literals from __future__ import division from",
"from __future__ import absolute_import from future import standard_library import twitter_scraper as twitter_scraper import",
"in tweets: t_list = build_list(tweet, t_list) json_data = json.dumps(t_list, indent=4) print_to_file(json_data, search_term) if",
"e: print(e) search_term = '@meshivammathur' search_params = twitter_scraper.scraper.SearchParams().set_username(search_term).set_max_tweets(400) tweets = twitter_scraper.scraper.Scraper.get_tweets(search_params) t_list =",
"print(e) search_term = '@meshivammathur' search_params = twitter_scraper.scraper.SearchParams().set_username(search_term).set_max_tweets(400) tweets = twitter_scraper.scraper.Scraper.get_tweets(search_params) t_list = []",
"for tweet in tweets: t_list = build_list(tweet, t_list) json_data = json.dumps(t_list, indent=4) print_to_file(json_data,",
"\"retweet\": t.retweets, \"tweet\": t.text, \"mentions\": t.mentions, \"hashtags\": t.hashtags, \"date\": t.date.__str__() } ) return",
"\"hashtags\": t.hashtags, \"date\": t.date.__str__() } ) return tweet_list def print_to_file(data, filename): try: with",
"t.username, \"retweet\": t.retweets, \"tweet\": t.text, \"mentions\": t.mentions, \"hashtags\": t.hashtags, \"date\": t.date.__str__() } )",
"tweet_list.append( { \"username\": t.username, \"retweet\": t.retweets, \"tweet\": t.text, \"mentions\": t.mentions, \"hashtags\": t.hashtags, \"date\":",
"import codecs standard_library.install_aliases() def main(): def build_list(t, tweet_list): tweet_list.append( { \"username\": t.username, \"retweet\":",
"twitter_scraper.scraper.SearchParams().set_username(search_term).set_max_tweets(400) tweets = twitter_scraper.scraper.Scraper.get_tweets(search_params) t_list = [] for tweet in tweets: t_list =",
"[] for tweet in tweets: t_list = build_list(tweet, t_list) json_data = json.dumps(t_list, indent=4)",
"tweets: t_list = build_list(tweet, t_list) json_data = json.dumps(t_list, indent=4) print_to_file(json_data, search_term) if __name__",
"twitter_scraper as twitter_scraper import json import codecs standard_library.install_aliases() def main(): def build_list(t, tweet_list):",
"with codecs.open(filename + '.json', 'a', 'utf-8') as f: f.write(data) return True except BaseException",
"future import standard_library import twitter_scraper as twitter_scraper import json import codecs standard_library.install_aliases() def",
"return tweet_list def print_to_file(data, filename): try: with codecs.open(filename + '.json', 'a', 'utf-8') as",
"twitter_scraper import json import codecs standard_library.install_aliases() def main(): def build_list(t, tweet_list): tweet_list.append( {",
"return True except BaseException as e: print(e) search_term = '@meshivammathur' search_params = twitter_scraper.scraper.SearchParams().set_username(search_term).set_max_tweets(400)",
"+ '.json', 'a', 'utf-8') as f: f.write(data) return True except BaseException as e:",
"import print_function from __future__ import unicode_literals from __future__ import division from __future__ import",
"filename): try: with codecs.open(filename + '.json', 'a', 'utf-8') as f: f.write(data) return True",
"print_to_file(data, filename): try: with codecs.open(filename + '.json', 'a', 'utf-8') as f: f.write(data) return",
"import json import codecs standard_library.install_aliases() def main(): def build_list(t, tweet_list): tweet_list.append( { \"username\":",
"BaseException as e: print(e) search_term = '@meshivammathur' search_params = twitter_scraper.scraper.SearchParams().set_username(search_term).set_max_tweets(400) tweets = twitter_scraper.scraper.Scraper.get_tweets(search_params)",
"import unicode_literals from __future__ import division from __future__ import absolute_import from future import",
"as twitter_scraper import json import codecs standard_library.install_aliases() def main(): def build_list(t, tweet_list): tweet_list.append(",
"\"mentions\": t.mentions, \"hashtags\": t.hashtags, \"date\": t.date.__str__() } ) return tweet_list def print_to_file(data, filename):",
"print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import",
"unicode_literals from __future__ import division from __future__ import absolute_import from future import standard_library",
"__future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__",
"{ \"username\": t.username, \"retweet\": t.retweets, \"tweet\": t.text, \"mentions\": t.mentions, \"hashtags\": t.hashtags, \"date\": t.date.__str__()",
"'.json', 'a', 'utf-8') as f: f.write(data) return True except BaseException as e: print(e)",
"import standard_library import twitter_scraper as twitter_scraper import json import codecs standard_library.install_aliases() def main():",
"'a', 'utf-8') as f: f.write(data) return True except BaseException as e: print(e) search_term",
"__future__ import unicode_literals from __future__ import division from __future__ import absolute_import from future",
"tweet in tweets: t_list = build_list(tweet, t_list) json_data = json.dumps(t_list, indent=4) print_to_file(json_data, search_term)",
"tweet_list): tweet_list.append( { \"username\": t.username, \"retweet\": t.retweets, \"tweet\": t.text, \"mentions\": t.mentions, \"hashtags\": t.hashtags,",
"f.write(data) return True except BaseException as e: print(e) search_term = '@meshivammathur' search_params =",
"t.retweets, \"tweet\": t.text, \"mentions\": t.mentions, \"hashtags\": t.hashtags, \"date\": t.date.__str__() } ) return tweet_list",
"standard_library.install_aliases() def main(): def build_list(t, tweet_list): tweet_list.append( { \"username\": t.username, \"retweet\": t.retweets, \"tweet\":",
"from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from",
"json import codecs standard_library.install_aliases() def main(): def build_list(t, tweet_list): tweet_list.append( { \"username\": t.username,",
"= build_list(tweet, t_list) json_data = json.dumps(t_list, indent=4) print_to_file(json_data, search_term) if __name__ == '__main__':",
"codecs standard_library.install_aliases() def main(): def build_list(t, tweet_list): tweet_list.append( { \"username\": t.username, \"retweet\": t.retweets,",
"= '@meshivammathur' search_params = twitter_scraper.scraper.SearchParams().set_username(search_term).set_max_tweets(400) tweets = twitter_scraper.scraper.Scraper.get_tweets(search_params) t_list = [] for tweet",
"tweet_list def print_to_file(data, filename): try: with codecs.open(filename + '.json', 'a', 'utf-8') as f:",
"f: f.write(data) return True except BaseException as e: print(e) search_term = '@meshivammathur' search_params",
"= twitter_scraper.scraper.Scraper.get_tweets(search_params) t_list = [] for tweet in tweets: t_list = build_list(tweet, t_list)",
"\"username\": t.username, \"retweet\": t.retweets, \"tweet\": t.text, \"mentions\": t.mentions, \"hashtags\": t.hashtags, \"date\": t.date.__str__() }",
"\"date\": t.date.__str__() } ) return tweet_list def print_to_file(data, filename): try: with codecs.open(filename +",
"t.date.__str__() } ) return tweet_list def print_to_file(data, filename): try: with codecs.open(filename + '.json',",
"= [] for tweet in tweets: t_list = build_list(tweet, t_list) json_data = json.dumps(t_list,",
"build_list(t, tweet_list): tweet_list.append( { \"username\": t.username, \"retweet\": t.retweets, \"tweet\": t.text, \"mentions\": t.mentions, \"hashtags\":",
"t.hashtags, \"date\": t.date.__str__() } ) return tweet_list def print_to_file(data, filename): try: with codecs.open(filename",
"def print_to_file(data, filename): try: with codecs.open(filename + '.json', 'a', 'utf-8') as f: f.write(data)",
"import twitter_scraper as twitter_scraper import json import codecs standard_library.install_aliases() def main(): def build_list(t,",
"t_list = build_list(tweet, t_list) json_data = json.dumps(t_list, indent=4) print_to_file(json_data, search_term) if __name__ ==",
"standard_library import twitter_scraper as twitter_scraper import json import codecs standard_library.install_aliases() def main(): def",
"__future__ import division from __future__ import absolute_import from future import standard_library import twitter_scraper",
"\"tweet\": t.text, \"mentions\": t.mentions, \"hashtags\": t.hashtags, \"date\": t.date.__str__() } ) return tweet_list def",
"codecs.open(filename + '.json', 'a', 'utf-8') as f: f.write(data) return True except BaseException as",
"search_term = '@meshivammathur' search_params = twitter_scraper.scraper.SearchParams().set_username(search_term).set_max_tweets(400) tweets = twitter_scraper.scraper.Scraper.get_tweets(search_params) t_list = [] for",
"} ) return tweet_list def print_to_file(data, filename): try: with codecs.open(filename + '.json', 'a',",
"build_list(tweet, t_list) json_data = json.dumps(t_list, indent=4) print_to_file(json_data, search_term) if __name__ == '__main__': main()",
"from __future__ import division from __future__ import absolute_import from future import standard_library import",
"t.text, \"mentions\": t.mentions, \"hashtags\": t.hashtags, \"date\": t.date.__str__() } ) return tweet_list def print_to_file(data,",
"as e: print(e) search_term = '@meshivammathur' search_params = twitter_scraper.scraper.SearchParams().set_username(search_term).set_max_tweets(400) tweets = twitter_scraper.scraper.Scraper.get_tweets(search_params) t_list",
"def build_list(t, tweet_list): tweet_list.append( { \"username\": t.username, \"retweet\": t.retweets, \"tweet\": t.text, \"mentions\": t.mentions,",
"absolute_import from future import standard_library import twitter_scraper as twitter_scraper import json import codecs",
"search_params = twitter_scraper.scraper.SearchParams().set_username(search_term).set_max_tweets(400) tweets = twitter_scraper.scraper.Scraper.get_tweets(search_params) t_list = [] for tweet in tweets:",
"from future import standard_library import twitter_scraper as twitter_scraper import json import codecs standard_library.install_aliases()",
") return tweet_list def print_to_file(data, filename): try: with codecs.open(filename + '.json', 'a', 'utf-8')",
"as f: f.write(data) return True except BaseException as e: print(e) search_term = '@meshivammathur'",
"'@meshivammathur' search_params = twitter_scraper.scraper.SearchParams().set_username(search_term).set_max_tweets(400) tweets = twitter_scraper.scraper.Scraper.get_tweets(search_params) t_list = [] for tweet in",
"def main(): def build_list(t, tweet_list): tweet_list.append( { \"username\": t.username, \"retweet\": t.retweets, \"tweet\": t.text,",
"t.mentions, \"hashtags\": t.hashtags, \"date\": t.date.__str__() } ) return tweet_list def print_to_file(data, filename): try:",
"t_list = [] for tweet in tweets: t_list = build_list(tweet, t_list) json_data =",
"main(): def build_list(t, tweet_list): tweet_list.append( { \"username\": t.username, \"retweet\": t.retweets, \"tweet\": t.text, \"mentions\":"
] |
[
"get_banned_users( active_only, ban_type, limit, offset, namespace, doc, login_as, ): login_as_internal(login_as) if doc: click.echo(admin_get_banned_users_v3.__doc__)",
"type=int) @click.option(\"--namespace\") @click.option(\"--doc\", type=bool) @click.option(\"--login_as\", type=click.Choice([\"client\", \"user\"], case_sensitive=False)) def get_banned_users( active_only, ban_type, limit,",
"import login_as as login_as_internal @click.command() @click.argument(\"active_only\", type=bool) @click.argument(\"ban_type\") @click.argument(\"offset\", type=int) @click.argument(\"limit\", type=int) @click.option(\"--namespace\")",
"._utils import login_as as login_as_internal @click.command() @click.argument(\"active_only\", type=bool) @click.argument(\"ban_type\") @click.argument(\"offset\", type=int) @click.argument(\"limit\", type=int)",
"limit, offset, namespace, doc, login_as, ): login_as_internal(login_as) if doc: click.echo(admin_get_banned_users_v3.__doc__) result, error =",
"from ._utils import login_as as login_as_internal @click.command() @click.argument(\"active_only\", type=bool) @click.argument(\"ban_type\") @click.argument(\"offset\", type=int) @click.argument(\"limit\",",
"import click from accelbyte_py_sdk.api.iam import admin_get_banned_users_v3 from ._utils import login_as as login_as_internal @click.command()",
"\"user\"], case_sensitive=False)) def get_banned_users( active_only, ban_type, limit, offset, namespace, doc, login_as, ): login_as_internal(login_as)",
"import yaml import click from accelbyte_py_sdk.api.iam import admin_get_banned_users_v3 from ._utils import login_as as",
"result, error = admin_get_banned_users_v3( active_only=active_only, ban_type=ban_type, offset=offset, limit=limit, namespace=namespace, ) if error: raise",
"error = admin_get_banned_users_v3( active_only=active_only, ban_type=ban_type, offset=offset, limit=limit, namespace=namespace, ) if error: raise Exception(str(error))",
"type=int) @click.argument(\"limit\", type=int) @click.option(\"--namespace\") @click.option(\"--doc\", type=bool) @click.option(\"--login_as\", type=click.Choice([\"client\", \"user\"], case_sensitive=False)) def get_banned_users( active_only,",
"if doc: click.echo(admin_get_banned_users_v3.__doc__) result, error = admin_get_banned_users_v3( active_only=active_only, ban_type=ban_type, offset=offset, limit=limit, namespace=namespace, )",
"doc, login_as, ): login_as_internal(login_as) if doc: click.echo(admin_get_banned_users_v3.__doc__) result, error = admin_get_banned_users_v3( active_only=active_only, ban_type=ban_type,",
"type=bool) @click.argument(\"ban_type\") @click.argument(\"offset\", type=int) @click.argument(\"limit\", type=int) @click.option(\"--namespace\") @click.option(\"--doc\", type=bool) @click.option(\"--login_as\", type=click.Choice([\"client\", \"user\"], case_sensitive=False))",
"case_sensitive=False)) def get_banned_users( active_only, ban_type, limit, offset, namespace, doc, login_as, ): login_as_internal(login_as) if",
"as login_as_internal @click.command() @click.argument(\"active_only\", type=bool) @click.argument(\"ban_type\") @click.argument(\"offset\", type=int) @click.argument(\"limit\", type=int) @click.option(\"--namespace\") @click.option(\"--doc\", type=bool)",
"@click.command() @click.argument(\"active_only\", type=bool) @click.argument(\"ban_type\") @click.argument(\"offset\", type=int) @click.argument(\"limit\", type=int) @click.option(\"--namespace\") @click.option(\"--doc\", type=bool) @click.option(\"--login_as\", type=click.Choice([\"client\",",
"admin_get_banned_users_v3( active_only=active_only, ban_type=ban_type, offset=offset, limit=limit, namespace=namespace, ) if error: raise Exception(str(error)) click.echo(\"Get banned",
"type=bool) @click.option(\"--login_as\", type=click.Choice([\"client\", \"user\"], case_sensitive=False)) def get_banned_users( active_only, ban_type, limit, offset, namespace, doc,",
"from accelbyte_py_sdk.api.iam import admin_get_banned_users_v3 from ._utils import login_as as login_as_internal @click.command() @click.argument(\"active_only\", type=bool)",
"offset, namespace, doc, login_as, ): login_as_internal(login_as) if doc: click.echo(admin_get_banned_users_v3.__doc__) result, error = admin_get_banned_users_v3(",
"@click.option(\"--login_as\", type=click.Choice([\"client\", \"user\"], case_sensitive=False)) def get_banned_users( active_only, ban_type, limit, offset, namespace, doc, login_as,",
"import admin_get_banned_users_v3 from ._utils import login_as as login_as_internal @click.command() @click.argument(\"active_only\", type=bool) @click.argument(\"ban_type\") @click.argument(\"offset\",",
"@click.argument(\"limit\", type=int) @click.option(\"--namespace\") @click.option(\"--doc\", type=bool) @click.option(\"--login_as\", type=click.Choice([\"client\", \"user\"], case_sensitive=False)) def get_banned_users( active_only, ban_type,",
"@click.option(\"--doc\", type=bool) @click.option(\"--login_as\", type=click.Choice([\"client\", \"user\"], case_sensitive=False)) def get_banned_users( active_only, ban_type, limit, offset, namespace,",
"admin_get_banned_users_v3 from ._utils import login_as as login_as_internal @click.command() @click.argument(\"active_only\", type=bool) @click.argument(\"ban_type\") @click.argument(\"offset\", type=int)",
"click.echo(admin_get_banned_users_v3.__doc__) result, error = admin_get_banned_users_v3( active_only=active_only, ban_type=ban_type, offset=offset, limit=limit, namespace=namespace, ) if error:",
"@click.option(\"--namespace\") @click.option(\"--doc\", type=bool) @click.option(\"--login_as\", type=click.Choice([\"client\", \"user\"], case_sensitive=False)) def get_banned_users( active_only, ban_type, limit, offset,",
"@click.argument(\"offset\", type=int) @click.argument(\"limit\", type=int) @click.option(\"--namespace\") @click.option(\"--doc\", type=bool) @click.option(\"--login_as\", type=click.Choice([\"client\", \"user\"], case_sensitive=False)) def get_banned_users(",
"= admin_get_banned_users_v3( active_only=active_only, ban_type=ban_type, offset=offset, limit=limit, namespace=namespace, ) if error: raise Exception(str(error)) click.echo(\"Get",
"active_only=active_only, ban_type=ban_type, offset=offset, limit=limit, namespace=namespace, ) if error: raise Exception(str(error)) click.echo(\"Get banned users",
"offset=offset, limit=limit, namespace=namespace, ) if error: raise Exception(str(error)) click.echo(\"Get banned users success.\") click.echo(yaml.safe_dump(result.to_dict()))",
"namespace, doc, login_as, ): login_as_internal(login_as) if doc: click.echo(admin_get_banned_users_v3.__doc__) result, error = admin_get_banned_users_v3( active_only=active_only,",
"@click.argument(\"active_only\", type=bool) @click.argument(\"ban_type\") @click.argument(\"offset\", type=int) @click.argument(\"limit\", type=int) @click.option(\"--namespace\") @click.option(\"--doc\", type=bool) @click.option(\"--login_as\", type=click.Choice([\"client\", \"user\"],",
"accelbyte_py_sdk.api.iam import admin_get_banned_users_v3 from ._utils import login_as as login_as_internal @click.command() @click.argument(\"active_only\", type=bool) @click.argument(\"ban_type\")",
"login_as_internal(login_as) if doc: click.echo(admin_get_banned_users_v3.__doc__) result, error = admin_get_banned_users_v3( active_only=active_only, ban_type=ban_type, offset=offset, limit=limit, namespace=namespace,",
"def get_banned_users( active_only, ban_type, limit, offset, namespace, doc, login_as, ): login_as_internal(login_as) if doc:",
"active_only, ban_type, limit, offset, namespace, doc, login_as, ): login_as_internal(login_as) if doc: click.echo(admin_get_banned_users_v3.__doc__) result,",
"login_as_internal @click.command() @click.argument(\"active_only\", type=bool) @click.argument(\"ban_type\") @click.argument(\"offset\", type=int) @click.argument(\"limit\", type=int) @click.option(\"--namespace\") @click.option(\"--doc\", type=bool) @click.option(\"--login_as\",",
"yaml import click from accelbyte_py_sdk.api.iam import admin_get_banned_users_v3 from ._utils import login_as as login_as_internal",
"@click.argument(\"ban_type\") @click.argument(\"offset\", type=int) @click.argument(\"limit\", type=int) @click.option(\"--namespace\") @click.option(\"--doc\", type=bool) @click.option(\"--login_as\", type=click.Choice([\"client\", \"user\"], case_sensitive=False)) def",
"ban_type=ban_type, offset=offset, limit=limit, namespace=namespace, ) if error: raise Exception(str(error)) click.echo(\"Get banned users success.\")",
"ban_type, limit, offset, namespace, doc, login_as, ): login_as_internal(login_as) if doc: click.echo(admin_get_banned_users_v3.__doc__) result, error",
"login_as as login_as_internal @click.command() @click.argument(\"active_only\", type=bool) @click.argument(\"ban_type\") @click.argument(\"offset\", type=int) @click.argument(\"limit\", type=int) @click.option(\"--namespace\") @click.option(\"--doc\",",
"doc: click.echo(admin_get_banned_users_v3.__doc__) result, error = admin_get_banned_users_v3( active_only=active_only, ban_type=ban_type, offset=offset, limit=limit, namespace=namespace, ) if",
"type=click.Choice([\"client\", \"user\"], case_sensitive=False)) def get_banned_users( active_only, ban_type, limit, offset, namespace, doc, login_as, ):",
"click from accelbyte_py_sdk.api.iam import admin_get_banned_users_v3 from ._utils import login_as as login_as_internal @click.command() @click.argument(\"active_only\",",
"): login_as_internal(login_as) if doc: click.echo(admin_get_banned_users_v3.__doc__) result, error = admin_get_banned_users_v3( active_only=active_only, ban_type=ban_type, offset=offset, limit=limit,",
"login_as, ): login_as_internal(login_as) if doc: click.echo(admin_get_banned_users_v3.__doc__) result, error = admin_get_banned_users_v3( active_only=active_only, ban_type=ban_type, offset=offset,"
] |
[
"return sum(len(l.encode('unicode_escape').decode('utf-8').replace('\"', '\\\\\"')) - len(l) + 2 for l in a) if __name__",
"2 for l in a) def part2(a): return sum(len(l.encode('unicode_escape').decode('utf-8').replace('\"', '\\\\\"')) - len(l) +",
"a) if __name__ == '__main__': data = get_data(day=8, year=2015) inp = data.splitlines() print(part1(inp))",
"in a) def part2(a): return sum(len(l.encode('unicode_escape').decode('utf-8').replace('\"', '\\\\\"')) - len(l) + 2 for l",
"def part1(a): return sum(len(l) - len(l.encode('utf-8').decode('unicode_escape')) + 2 for l in a) def",
"l in a) if __name__ == '__main__': data = get_data(day=8, year=2015) inp =",
"for l in a) def part2(a): return sum(len(l.encode('unicode_escape').decode('utf-8').replace('\"', '\\\\\"')) - len(l) + 2",
"from aocd import get_data def part1(a): return sum(len(l) - len(l.encode('utf-8').decode('unicode_escape')) + 2 for",
"+ 2 for l in a) if __name__ == '__main__': data = get_data(day=8,",
"+ 2 for l in a) def part2(a): return sum(len(l.encode('unicode_escape').decode('utf-8').replace('\"', '\\\\\"')) - len(l)",
"aocd import get_data def part1(a): return sum(len(l) - len(l.encode('utf-8').decode('unicode_escape')) + 2 for l",
"get_data def part1(a): return sum(len(l) - len(l.encode('utf-8').decode('unicode_escape')) + 2 for l in a)",
"return sum(len(l) - len(l.encode('utf-8').decode('unicode_escape')) + 2 for l in a) def part2(a): return",
"in a) if __name__ == '__main__': data = get_data(day=8, year=2015) inp = data.splitlines()",
"for l in a) if __name__ == '__main__': data = get_data(day=8, year=2015) inp",
"len(l.encode('utf-8').decode('unicode_escape')) + 2 for l in a) def part2(a): return sum(len(l.encode('unicode_escape').decode('utf-8').replace('\"', '\\\\\"')) -",
"sum(len(l.encode('unicode_escape').decode('utf-8').replace('\"', '\\\\\"')) - len(l) + 2 for l in a) if __name__ ==",
"part2(a): return sum(len(l.encode('unicode_escape').decode('utf-8').replace('\"', '\\\\\"')) - len(l) + 2 for l in a) if",
"sum(len(l) - len(l.encode('utf-8').decode('unicode_escape')) + 2 for l in a) def part2(a): return sum(len(l.encode('unicode_escape').decode('utf-8').replace('\"',",
"- len(l) + 2 for l in a) if __name__ == '__main__': data",
"'\\\\\"')) - len(l) + 2 for l in a) if __name__ == '__main__':",
"l in a) def part2(a): return sum(len(l.encode('unicode_escape').decode('utf-8').replace('\"', '\\\\\"')) - len(l) + 2 for",
"- len(l.encode('utf-8').decode('unicode_escape')) + 2 for l in a) def part2(a): return sum(len(l.encode('unicode_escape').decode('utf-8').replace('\"', '\\\\\"'))",
"import get_data def part1(a): return sum(len(l) - len(l.encode('utf-8').decode('unicode_escape')) + 2 for l in",
"a) def part2(a): return sum(len(l.encode('unicode_escape').decode('utf-8').replace('\"', '\\\\\"')) - len(l) + 2 for l in",
"len(l) + 2 for l in a) if __name__ == '__main__': data =",
"part1(a): return sum(len(l) - len(l.encode('utf-8').decode('unicode_escape')) + 2 for l in a) def part2(a):",
"2 for l in a) if __name__ == '__main__': data = get_data(day=8, year=2015)",
"if __name__ == '__main__': data = get_data(day=8, year=2015) inp = data.splitlines() print(part1(inp)) print(part2(inp))",
"def part2(a): return sum(len(l.encode('unicode_escape').decode('utf-8').replace('\"', '\\\\\"')) - len(l) + 2 for l in a)"
] |
[
"grid_object.height) self._fb = adafruit_framebuf.FrameBuffer(self._buffer, grid_object.width, grid_object.height, buf_format=adafruit_framebuf.MVLSB) super().__init__(grid_object, speed, color, name=name) on_cycle_complete_supported =",
"on the display self.cycle_complete = True self._frame = 0 def reset(self): self._frame =",
"completes after text scrolls completely out of view on the display self.cycle_complete =",
"(char_width + 1) + self.pixel_object.width: # Cycle completes after text scrolls completely out",
"1 if self._frame >= len(self._text) * (char_width + 1) + self.pixel_object.width: # Cycle",
"self._frame >= len(self._text) * (char_width + 1) + self.pixel_object.width: # Cycle completes after",
"+ self.pixel_object.width: # Cycle completes after text scrolls completely out of view on",
"self._text = text self._font_name = font_name self._frame = 0 # We're only using",
"self._get_color(x, y) if self._fb.pixel(x, y) else (0, 0, 0) self._frame += 1 if",
"= True def _get_color(self, x, y): return self.color def draw(self): self._fb.fill(0x000000) self._fb.text(self._text, self.pixel_object.width",
"self.pixel_object[x, y] = self._get_color(x, y) if self._fb.pixel(x, y) else (0, 0, 0) self._frame",
"if self._fb.pixel(x, y) else (0, 0, 0) self._frame += 1 if self._frame >=",
"self._fb.pixel(x, y) else (0, 0, 0) self._frame += 1 if self._frame >= len(self._text)",
"frame buffer for on/off information, not color self._buffer = bytearray(grid_object.width * grid_object.height) self._fb",
"font_name self._frame = 0 # We're only using the frame buffer for on/off",
"+ 1) + self.pixel_object.width: # Cycle completes after text scrolls completely out of",
"for x in range(self.pixel_object.width): self.pixel_object[x, y] = self._get_color(x, y) if self._fb.pixel(x, y) else",
"the character width char_width = self._fb._font.font_width for y in range(self.pixel_object.height): for x in",
"# We're only using the frame buffer for on/off information, not color self._buffer",
"text scrolls completely out of view on the display self.cycle_complete = True self._frame",
"draw(self): self._fb.fill(0x000000) self._fb.text(self._text, self.pixel_object.width - self._frame, 0, 0xFFFFFF, font_name=self._font_name) # Cheating to get",
"class TextScroll(Animation): def __init__(self, grid_object, speed, text, color, font_name='font5x8.bin', name=None): self._text = text",
"completely out of view on the display self.cycle_complete = True self._frame = 0",
"* grid_object.height) self._fb = adafruit_framebuf.FrameBuffer(self._buffer, grid_object.width, grid_object.height, buf_format=adafruit_framebuf.MVLSB) super().__init__(grid_object, speed, color, name=name) on_cycle_complete_supported",
"out of view on the display self.cycle_complete = True self._frame = 0 def",
"name=name) on_cycle_complete_supported = True def _get_color(self, x, y): return self.color def draw(self): self._fb.fill(0x000000)",
"speed, color, name=name) on_cycle_complete_supported = True def _get_color(self, x, y): return self.color def",
"= adafruit_framebuf.FrameBuffer(self._buffer, grid_object.width, grid_object.height, buf_format=adafruit_framebuf.MVLSB) super().__init__(grid_object, speed, color, name=name) on_cycle_complete_supported = True def",
"super().__init__(grid_object, speed, color, name=name) on_cycle_complete_supported = True def _get_color(self, x, y): return self.color",
"0xFFFFFF, font_name=self._font_name) # Cheating to get the character width char_width = self._fb._font.font_width for",
"(0, 0, 0) self._frame += 1 if self._frame >= len(self._text) * (char_width +",
"self.pixel_object.width: # Cycle completes after text scrolls completely out of view on the",
"char_width = self._fb._font.font_width for y in range(self.pixel_object.height): for x in range(self.pixel_object.width): self.pixel_object[x, y]",
"= self._fb._font.font_width for y in range(self.pixel_object.height): for x in range(self.pixel_object.width): self.pixel_object[x, y] =",
"the frame buffer for on/off information, not color self._buffer = bytearray(grid_object.width * grid_object.height)",
"Cycle completes after text scrolls completely out of view on the display self.cycle_complete",
"adafruit_framebuf.FrameBuffer(self._buffer, grid_object.width, grid_object.height, buf_format=adafruit_framebuf.MVLSB) super().__init__(grid_object, speed, color, name=name) on_cycle_complete_supported = True def _get_color(self,",
"self.pixel_object.width - self._frame, 0, 0xFFFFFF, font_name=self._font_name) # Cheating to get the character width",
"grid_object.width, grid_object.height, buf_format=adafruit_framebuf.MVLSB) super().__init__(grid_object, speed, color, name=name) on_cycle_complete_supported = True def _get_color(self, x,",
"0) self._frame += 1 if self._frame >= len(self._text) * (char_width + 1) +",
"range(self.pixel_object.height): for x in range(self.pixel_object.width): self.pixel_object[x, y] = self._get_color(x, y) if self._fb.pixel(x, y)",
"get the character width char_width = self._fb._font.font_width for y in range(self.pixel_object.height): for x",
"of view on the display self.cycle_complete = True self._frame = 0 def reset(self):",
"_get_color(self, x, y): return self.color def draw(self): self._fb.fill(0x000000) self._fb.text(self._text, self.pixel_object.width - self._frame, 0,",
"- self._frame, 0, 0xFFFFFF, font_name=self._font_name) # Cheating to get the character width char_width",
"+= 1 if self._frame >= len(self._text) * (char_width + 1) + self.pixel_object.width: #",
"buf_format=adafruit_framebuf.MVLSB) super().__init__(grid_object, speed, color, name=name) on_cycle_complete_supported = True def _get_color(self, x, y): return",
"adafruit_led_animation.animation import Animation import adafruit_framebuf class TextScroll(Animation): def __init__(self, grid_object, speed, text, color,",
"x in range(self.pixel_object.width): self.pixel_object[x, y] = self._get_color(x, y) if self._fb.pixel(x, y) else (0,",
"= text self._font_name = font_name self._frame = 0 # We're only using the",
"self._font_name = font_name self._frame = 0 # We're only using the frame buffer",
"scrolls completely out of view on the display self.cycle_complete = True self._frame =",
"self._fb._font.font_width for y in range(self.pixel_object.height): for x in range(self.pixel_object.width): self.pixel_object[x, y] = self._get_color(x,",
"only using the frame buffer for on/off information, not color self._buffer = bytearray(grid_object.width",
"font_name='font5x8.bin', name=None): self._text = text self._font_name = font_name self._frame = 0 # We're",
"grid_object, speed, text, color, font_name='font5x8.bin', name=None): self._text = text self._font_name = font_name self._frame",
"on/off information, not color self._buffer = bytearray(grid_object.width * grid_object.height) self._fb = adafruit_framebuf.FrameBuffer(self._buffer, grid_object.width,",
"font_name=self._font_name) # Cheating to get the character width char_width = self._fb._font.font_width for y",
"__init__(self, grid_object, speed, text, color, font_name='font5x8.bin', name=None): self._text = text self._font_name = font_name",
"def _get_color(self, x, y): return self.color def draw(self): self._fb.fill(0x000000) self._fb.text(self._text, self.pixel_object.width - self._frame,",
"not color self._buffer = bytearray(grid_object.width * grid_object.height) self._fb = adafruit_framebuf.FrameBuffer(self._buffer, grid_object.width, grid_object.height, buf_format=adafruit_framebuf.MVLSB)",
"y) else (0, 0, 0) self._frame += 1 if self._frame >= len(self._text) *",
"y in range(self.pixel_object.height): for x in range(self.pixel_object.width): self.pixel_object[x, y] = self._get_color(x, y) if",
"y): return self.color def draw(self): self._fb.fill(0x000000) self._fb.text(self._text, self.pixel_object.width - self._frame, 0, 0xFFFFFF, font_name=self._font_name)",
"* (char_width + 1) + self.pixel_object.width: # Cycle completes after text scrolls completely",
"range(self.pixel_object.width): self.pixel_object[x, y] = self._get_color(x, y) if self._fb.pixel(x, y) else (0, 0, 0)",
"0 # We're only using the frame buffer for on/off information, not color",
"character width char_width = self._fb._font.font_width for y in range(self.pixel_object.height): for x in range(self.pixel_object.width):",
"Animation import adafruit_framebuf class TextScroll(Animation): def __init__(self, grid_object, speed, text, color, font_name='font5x8.bin', name=None):",
">= len(self._text) * (char_width + 1) + self.pixel_object.width: # Cycle completes after text",
"for y in range(self.pixel_object.height): for x in range(self.pixel_object.width): self.pixel_object[x, y] = self._get_color(x, y)",
"text self._font_name = font_name self._frame = 0 # We're only using the frame",
"name=None): self._text = text self._font_name = font_name self._frame = 0 # We're only",
"to get the character width char_width = self._fb._font.font_width for y in range(self.pixel_object.height): for",
"after text scrolls completely out of view on the display self.cycle_complete = True",
"import adafruit_framebuf class TextScroll(Animation): def __init__(self, grid_object, speed, text, color, font_name='font5x8.bin', name=None): self._text",
"adafruit_framebuf class TextScroll(Animation): def __init__(self, grid_object, speed, text, color, font_name='font5x8.bin', name=None): self._text =",
"from adafruit_led_animation.animation import Animation import adafruit_framebuf class TextScroll(Animation): def __init__(self, grid_object, speed, text,",
"self._frame, 0, 0xFFFFFF, font_name=self._font_name) # Cheating to get the character width char_width =",
"speed, text, color, font_name='font5x8.bin', name=None): self._text = text self._font_name = font_name self._frame =",
"1) + self.pixel_object.width: # Cycle completes after text scrolls completely out of view",
"self._frame += 1 if self._frame >= len(self._text) * (char_width + 1) + self.pixel_object.width:",
"in range(self.pixel_object.height): for x in range(self.pixel_object.width): self.pixel_object[x, y] = self._get_color(x, y) if self._fb.pixel(x,",
"# Cycle completes after text scrolls completely out of view on the display",
"if self._frame >= len(self._text) * (char_width + 1) + self.pixel_object.width: # Cycle completes",
"grid_object.height, buf_format=adafruit_framebuf.MVLSB) super().__init__(grid_object, speed, color, name=name) on_cycle_complete_supported = True def _get_color(self, x, y):",
"TextScroll(Animation): def __init__(self, grid_object, speed, text, color, font_name='font5x8.bin', name=None): self._text = text self._font_name",
"buffer for on/off information, not color self._buffer = bytearray(grid_object.width * grid_object.height) self._fb =",
"color, font_name='font5x8.bin', name=None): self._text = text self._font_name = font_name self._frame = 0 #",
"True def _get_color(self, x, y): return self.color def draw(self): self._fb.fill(0x000000) self._fb.text(self._text, self.pixel_object.width -",
"on_cycle_complete_supported = True def _get_color(self, x, y): return self.color def draw(self): self._fb.fill(0x000000) self._fb.text(self._text,",
"= bytearray(grid_object.width * grid_object.height) self._fb = adafruit_framebuf.FrameBuffer(self._buffer, grid_object.width, grid_object.height, buf_format=adafruit_framebuf.MVLSB) super().__init__(grid_object, speed, color,",
"view on the display self.cycle_complete = True self._frame = 0 def reset(self): self._frame",
"self.color def draw(self): self._fb.fill(0x000000) self._fb.text(self._text, self.pixel_object.width - self._frame, 0, 0xFFFFFF, font_name=self._font_name) # Cheating",
"x, y): return self.color def draw(self): self._fb.fill(0x000000) self._fb.text(self._text, self.pixel_object.width - self._frame, 0, 0xFFFFFF,",
"# Cheating to get the character width char_width = self._fb._font.font_width for y in",
"color, name=name) on_cycle_complete_supported = True def _get_color(self, x, y): return self.color def draw(self):",
"width char_width = self._fb._font.font_width for y in range(self.pixel_object.height): for x in range(self.pixel_object.width): self.pixel_object[x,",
"self._fb.fill(0x000000) self._fb.text(self._text, self.pixel_object.width - self._frame, 0, 0xFFFFFF, font_name=self._font_name) # Cheating to get the",
"0, 0) self._frame += 1 if self._frame >= len(self._text) * (char_width + 1)",
"len(self._text) * (char_width + 1) + self.pixel_object.width: # Cycle completes after text scrolls",
"= self._get_color(x, y) if self._fb.pixel(x, y) else (0, 0, 0) self._frame += 1",
"import Animation import adafruit_framebuf class TextScroll(Animation): def __init__(self, grid_object, speed, text, color, font_name='font5x8.bin',",
"y] = self._get_color(x, y) if self._fb.pixel(x, y) else (0, 0, 0) self._frame +=",
"def draw(self): self._fb.fill(0x000000) self._fb.text(self._text, self.pixel_object.width - self._frame, 0, 0xFFFFFF, font_name=self._font_name) # Cheating to",
"= font_name self._frame = 0 # We're only using the frame buffer for",
"in range(self.pixel_object.width): self.pixel_object[x, y] = self._get_color(x, y) if self._fb.pixel(x, y) else (0, 0,",
"text, color, font_name='font5x8.bin', name=None): self._text = text self._font_name = font_name self._frame = 0",
"for on/off information, not color self._buffer = bytearray(grid_object.width * grid_object.height) self._fb = adafruit_framebuf.FrameBuffer(self._buffer,",
"the display self.cycle_complete = True self._frame = 0 def reset(self): self._frame = 0",
"self._fb.text(self._text, self.pixel_object.width - self._frame, 0, 0xFFFFFF, font_name=self._font_name) # Cheating to get the character",
"def __init__(self, grid_object, speed, text, color, font_name='font5x8.bin', name=None): self._text = text self._font_name =",
"We're only using the frame buffer for on/off information, not color self._buffer =",
"information, not color self._buffer = bytearray(grid_object.width * grid_object.height) self._fb = adafruit_framebuf.FrameBuffer(self._buffer, grid_object.width, grid_object.height,",
"y) if self._fb.pixel(x, y) else (0, 0, 0) self._frame += 1 if self._frame",
"self._fb = adafruit_framebuf.FrameBuffer(self._buffer, grid_object.width, grid_object.height, buf_format=adafruit_framebuf.MVLSB) super().__init__(grid_object, speed, color, name=name) on_cycle_complete_supported = True",
"0, 0xFFFFFF, font_name=self._font_name) # Cheating to get the character width char_width = self._fb._font.font_width",
"return self.color def draw(self): self._fb.fill(0x000000) self._fb.text(self._text, self.pixel_object.width - self._frame, 0, 0xFFFFFF, font_name=self._font_name) #",
"using the frame buffer for on/off information, not color self._buffer = bytearray(grid_object.width *",
"self._frame = 0 # We're only using the frame buffer for on/off information,",
"Cheating to get the character width char_width = self._fb._font.font_width for y in range(self.pixel_object.height):",
"bytearray(grid_object.width * grid_object.height) self._fb = adafruit_framebuf.FrameBuffer(self._buffer, grid_object.width, grid_object.height, buf_format=adafruit_framebuf.MVLSB) super().__init__(grid_object, speed, color, name=name)",
"= 0 # We're only using the frame buffer for on/off information, not",
"self._buffer = bytearray(grid_object.width * grid_object.height) self._fb = adafruit_framebuf.FrameBuffer(self._buffer, grid_object.width, grid_object.height, buf_format=adafruit_framebuf.MVLSB) super().__init__(grid_object, speed,",
"color self._buffer = bytearray(grid_object.width * grid_object.height) self._fb = adafruit_framebuf.FrameBuffer(self._buffer, grid_object.width, grid_object.height, buf_format=adafruit_framebuf.MVLSB) super().__init__(grid_object,",
"else (0, 0, 0) self._frame += 1 if self._frame >= len(self._text) * (char_width"
] |
[
"self.fc1 = layers.Dense(128) self.fc2 = layers.Dense(4) def call(self, x, training=False): x,_ = self.encoder(x)",
"CNN() ip_dims = self.cnn.compute_output_shape((None,None,None,5))[-1] self.encoder = Encoder(self.cnn,ip_dims) self.flatten = layers.Flatten() self.drop = layers.Dropout(0.3)",
"layers.Dense(4) def call(self, x, training=False): x,_ = self.encoder(x) x = self.flatten(x) x =",
"from tensorflow import keras from tensorflow.keras import layers, models, activations from models.cnn_gru.cnn import",
"CNN, Encoder class CnnGru(tf.keras.Model): def __init__(self, seq_len): super().__init__() self.seq_len = seq_len self.cnn =",
"= seq_len self.cnn = CNN() ip_dims = self.cnn.compute_output_shape((None,None,None,5))[-1] self.encoder = Encoder(self.cnn,ip_dims) self.flatten =",
"= self.encoder(x) x = self.flatten(x) x = self.drop(x,training=training) x = self.fc1(x) x =",
"= layers.Flatten() self.drop = layers.Dropout(0.3) self.fc1 = layers.Dense(128) self.fc2 = layers.Dense(4) def call(self,",
"self.fc2 = layers.Dense(4) def call(self, x, training=False): x,_ = self.encoder(x) x = self.flatten(x)",
"ip_dims = self.cnn.compute_output_shape((None,None,None,5))[-1] self.encoder = Encoder(self.cnn,ip_dims) self.flatten = layers.Flatten() self.drop = layers.Dropout(0.3) self.fc1",
"training=False): x,_ = self.encoder(x) x = self.flatten(x) x = self.drop(x,training=training) x = self.fc1(x)",
"activations from models.cnn_gru.cnn import CNN, Encoder class CnnGru(tf.keras.Model): def __init__(self, seq_len): super().__init__() self.seq_len",
"class CnnGru(tf.keras.Model): def __init__(self, seq_len): super().__init__() self.seq_len = seq_len self.cnn = CNN() ip_dims",
"CnnGru(tf.keras.Model): def __init__(self, seq_len): super().__init__() self.seq_len = seq_len self.cnn = CNN() ip_dims =",
"Encoder class CnnGru(tf.keras.Model): def __init__(self, seq_len): super().__init__() self.seq_len = seq_len self.cnn = CNN()",
"layers, models, activations from models.cnn_gru.cnn import CNN, Encoder class CnnGru(tf.keras.Model): def __init__(self, seq_len):",
"models.cnn_gru.cnn import CNN, Encoder class CnnGru(tf.keras.Model): def __init__(self, seq_len): super().__init__() self.seq_len = seq_len",
"self.encoder = Encoder(self.cnn,ip_dims) self.flatten = layers.Flatten() self.drop = layers.Dropout(0.3) self.fc1 = layers.Dense(128) self.fc2",
"= layers.Dropout(0.3) self.fc1 = layers.Dense(128) self.fc2 = layers.Dense(4) def call(self, x, training=False): x,_",
"layers.Dropout(0.3) self.fc1 = layers.Dense(128) self.fc2 = layers.Dense(4) def call(self, x, training=False): x,_ =",
"x, training=False): x,_ = self.encoder(x) x = self.flatten(x) x = self.drop(x,training=training) x =",
"tensorflow.keras import layers, models, activations from models.cnn_gru.cnn import CNN, Encoder class CnnGru(tf.keras.Model): def",
"= self.flatten(x) x = self.drop(x,training=training) x = self.fc1(x) x = tf.nn.relu(x) x =",
"def __init__(self, seq_len): super().__init__() self.seq_len = seq_len self.cnn = CNN() ip_dims = self.cnn.compute_output_shape((None,None,None,5))[-1]",
"x = self.flatten(x) x = self.drop(x,training=training) x = self.fc1(x) x = tf.nn.relu(x) x",
"= layers.Dense(128) self.fc2 = layers.Dense(4) def call(self, x, training=False): x,_ = self.encoder(x) x",
"self.cnn.compute_output_shape((None,None,None,5))[-1] self.encoder = Encoder(self.cnn,ip_dims) self.flatten = layers.Flatten() self.drop = layers.Dropout(0.3) self.fc1 = layers.Dense(128)",
"tensorflow as tf from tensorflow import keras from tensorflow.keras import layers, models, activations",
"import layers, models, activations from models.cnn_gru.cnn import CNN, Encoder class CnnGru(tf.keras.Model): def __init__(self,",
"import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers, models,",
"as tf from tensorflow import keras from tensorflow.keras import layers, models, activations from",
"from models.cnn_gru.cnn import CNN, Encoder class CnnGru(tf.keras.Model): def __init__(self, seq_len): super().__init__() self.seq_len =",
"super().__init__() self.seq_len = seq_len self.cnn = CNN() ip_dims = self.cnn.compute_output_shape((None,None,None,5))[-1] self.encoder = Encoder(self.cnn,ip_dims)",
"layers.Dense(128) self.fc2 = layers.Dense(4) def call(self, x, training=False): x,_ = self.encoder(x) x =",
"import CNN, Encoder class CnnGru(tf.keras.Model): def __init__(self, seq_len): super().__init__() self.seq_len = seq_len self.cnn",
"seq_len): super().__init__() self.seq_len = seq_len self.cnn = CNN() ip_dims = self.cnn.compute_output_shape((None,None,None,5))[-1] self.encoder =",
"seq_len self.cnn = CNN() ip_dims = self.cnn.compute_output_shape((None,None,None,5))[-1] self.encoder = Encoder(self.cnn,ip_dims) self.flatten = layers.Flatten()",
"Encoder(self.cnn,ip_dims) self.flatten = layers.Flatten() self.drop = layers.Dropout(0.3) self.fc1 = layers.Dense(128) self.fc2 = layers.Dense(4)",
"x,_ = self.encoder(x) x = self.flatten(x) x = self.drop(x,training=training) x = self.fc1(x) x",
"models, activations from models.cnn_gru.cnn import CNN, Encoder class CnnGru(tf.keras.Model): def __init__(self, seq_len): super().__init__()",
"import numpy as np import tensorflow as tf from tensorflow import keras from",
"import keras from tensorflow.keras import layers, models, activations from models.cnn_gru.cnn import CNN, Encoder",
"= Encoder(self.cnn,ip_dims) self.flatten = layers.Flatten() self.drop = layers.Dropout(0.3) self.fc1 = layers.Dense(128) self.fc2 =",
"__init__(self, seq_len): super().__init__() self.seq_len = seq_len self.cnn = CNN() ip_dims = self.cnn.compute_output_shape((None,None,None,5))[-1] self.encoder",
"self.flatten = layers.Flatten() self.drop = layers.Dropout(0.3) self.fc1 = layers.Dense(128) self.fc2 = layers.Dense(4) def",
"= self.cnn.compute_output_shape((None,None,None,5))[-1] self.encoder = Encoder(self.cnn,ip_dims) self.flatten = layers.Flatten() self.drop = layers.Dropout(0.3) self.fc1 =",
"x = self.drop(x,training=training) x = self.fc1(x) x = tf.nn.relu(x) x = self.fc2(x) return",
"numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras",
"call(self, x, training=False): x,_ = self.encoder(x) x = self.flatten(x) x = self.drop(x,training=training) x",
"= self.drop(x,training=training) x = self.fc1(x) x = tf.nn.relu(x) x = self.fc2(x) return x",
"as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import",
"np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers,",
"= CNN() ip_dims = self.cnn.compute_output_shape((None,None,None,5))[-1] self.encoder = Encoder(self.cnn,ip_dims) self.flatten = layers.Flatten() self.drop =",
"self.seq_len = seq_len self.cnn = CNN() ip_dims = self.cnn.compute_output_shape((None,None,None,5))[-1] self.encoder = Encoder(self.cnn,ip_dims) self.flatten",
"self.drop = layers.Dropout(0.3) self.fc1 = layers.Dense(128) self.fc2 = layers.Dense(4) def call(self, x, training=False):",
"self.encoder(x) x = self.flatten(x) x = self.drop(x,training=training) x = self.fc1(x) x = tf.nn.relu(x)",
"tf from tensorflow import keras from tensorflow.keras import layers, models, activations from models.cnn_gru.cnn",
"self.flatten(x) x = self.drop(x,training=training) x = self.fc1(x) x = tf.nn.relu(x) x = self.fc2(x)",
"tensorflow import keras from tensorflow.keras import layers, models, activations from models.cnn_gru.cnn import CNN,",
"= layers.Dense(4) def call(self, x, training=False): x,_ = self.encoder(x) x = self.flatten(x) x",
"keras from tensorflow.keras import layers, models, activations from models.cnn_gru.cnn import CNN, Encoder class",
"from tensorflow.keras import layers, models, activations from models.cnn_gru.cnn import CNN, Encoder class CnnGru(tf.keras.Model):",
"layers.Flatten() self.drop = layers.Dropout(0.3) self.fc1 = layers.Dense(128) self.fc2 = layers.Dense(4) def call(self, x,",
"self.cnn = CNN() ip_dims = self.cnn.compute_output_shape((None,None,None,5))[-1] self.encoder = Encoder(self.cnn,ip_dims) self.flatten = layers.Flatten() self.drop",
"def call(self, x, training=False): x,_ = self.encoder(x) x = self.flatten(x) x = self.drop(x,training=training)"
] |
[
"import re from os import environ # URL to the Groupme API endpoint",
"endpoint API_URL = 'https://api.groupme.com/v3/bots/post' # URL to the Google Sheets JSON API endpoint",
"API_URL = 'https://api.groupme.com/v3/bots/post' # URL to the Google Sheets JSON API endpoint SHEET_BASE_URL",
"re from os import environ # URL to the Groupme API endpoint API_URL",
"'https://api.groupme.com/v3/bots/post' # URL to the Google Sheets JSON API endpoint SHEET_BASE_URL = ('https://spreadsheets.google.com/feeds/cells/%s/%s'",
"by Heroku variables COMMAND_PREFIX = environ['BOT_NAME'] + ' ' BOT_ID = environ['GROUPME_BOT_ID'] WORKSHEET_KEYS_TO_SCRAPE",
"# URL to the Google Sheets JSON API endpoint SHEET_BASE_URL = ('https://spreadsheets.google.com/feeds/cells/%s/%s' '/public/values?alt=json')",
"environ['BOT_NAME'] + ' ' BOT_ID = environ['GROUPME_BOT_ID'] WORKSHEET_KEYS_TO_SCRAPE = environ['WORKSHEET_KEYS'].split(',') INDEX_REDIRECT_URL = 'https://github.com/mplewis/trianglebot'",
"# Set by Heroku variables COMMAND_PREFIX = environ['BOT_NAME'] + ' ' BOT_ID =",
"Set by Heroku variables COMMAND_PREFIX = environ['BOT_NAME'] + ' ' BOT_ID = environ['GROUPME_BOT_ID']",
"from os import environ # URL to the Groupme API endpoint API_URL =",
"the Groupme API endpoint API_URL = 'https://api.groupme.com/v3/bots/post' # URL to the Google Sheets",
"SHEET_BASE_URL = ('https://spreadsheets.google.com/feeds/cells/%s/%s' '/public/values?alt=json') SHEET_ID_MATCHER = r'spreadsheets\\/d\\/(.+)\\/' # Set by Heroku variables COMMAND_PREFIX",
"to the Groupme API endpoint API_URL = 'https://api.groupme.com/v3/bots/post' # URL to the Google",
"' ' BOT_ID = environ['GROUPME_BOT_ID'] WORKSHEET_KEYS_TO_SCRAPE = environ['WORKSHEET_KEYS'].split(',') INDEX_REDIRECT_URL = 'https://github.com/mplewis/trianglebot' SHEET_KEY =",
"= ('https://spreadsheets.google.com/feeds/cells/%s/%s' '/public/values?alt=json') SHEET_ID_MATCHER = r'spreadsheets\\/d\\/(.+)\\/' # Set by Heroku variables COMMAND_PREFIX =",
"= environ['BOT_NAME'] + ' ' BOT_ID = environ['GROUPME_BOT_ID'] WORKSHEET_KEYS_TO_SCRAPE = environ['WORKSHEET_KEYS'].split(',') INDEX_REDIRECT_URL =",
"the Google Sheets JSON API endpoint SHEET_BASE_URL = ('https://spreadsheets.google.com/feeds/cells/%s/%s' '/public/values?alt=json') SHEET_ID_MATCHER = r'spreadsheets\\/d\\/(.+)\\/'",
"r'spreadsheets\\/d\\/(.+)\\/' # Set by Heroku variables COMMAND_PREFIX = environ['BOT_NAME'] + ' ' BOT_ID",
"import environ # URL to the Groupme API endpoint API_URL = 'https://api.groupme.com/v3/bots/post' #",
"Google Sheets JSON API endpoint SHEET_BASE_URL = ('https://spreadsheets.google.com/feeds/cells/%s/%s' '/public/values?alt=json') SHEET_ID_MATCHER = r'spreadsheets\\/d\\/(.+)\\/' #",
"COMMAND_PREFIX = environ['BOT_NAME'] + ' ' BOT_ID = environ['GROUPME_BOT_ID'] WORKSHEET_KEYS_TO_SCRAPE = environ['WORKSHEET_KEYS'].split(',') INDEX_REDIRECT_URL",
"URL to the Groupme API endpoint API_URL = 'https://api.groupme.com/v3/bots/post' # URL to the",
"API endpoint SHEET_BASE_URL = ('https://spreadsheets.google.com/feeds/cells/%s/%s' '/public/values?alt=json') SHEET_ID_MATCHER = r'spreadsheets\\/d\\/(.+)\\/' # Set by Heroku",
"endpoint SHEET_BASE_URL = ('https://spreadsheets.google.com/feeds/cells/%s/%s' '/public/values?alt=json') SHEET_ID_MATCHER = r'spreadsheets\\/d\\/(.+)\\/' # Set by Heroku variables",
"JSON API endpoint SHEET_BASE_URL = ('https://spreadsheets.google.com/feeds/cells/%s/%s' '/public/values?alt=json') SHEET_ID_MATCHER = r'spreadsheets\\/d\\/(.+)\\/' # Set by",
"<reponame>mplewis/trianglebot import re from os import environ # URL to the Groupme API",
"environ # URL to the Groupme API endpoint API_URL = 'https://api.groupme.com/v3/bots/post' # URL",
"variables COMMAND_PREFIX = environ['BOT_NAME'] + ' ' BOT_ID = environ['GROUPME_BOT_ID'] WORKSHEET_KEYS_TO_SCRAPE = environ['WORKSHEET_KEYS'].split(',')",
"('https://spreadsheets.google.com/feeds/cells/%s/%s' '/public/values?alt=json') SHEET_ID_MATCHER = r'spreadsheets\\/d\\/(.+)\\/' # Set by Heroku variables COMMAND_PREFIX = environ['BOT_NAME']",
"# URL to the Groupme API endpoint API_URL = 'https://api.groupme.com/v3/bots/post' # URL to",
"Sheets JSON API endpoint SHEET_BASE_URL = ('https://spreadsheets.google.com/feeds/cells/%s/%s' '/public/values?alt=json') SHEET_ID_MATCHER = r'spreadsheets\\/d\\/(.+)\\/' # Set",
"' BOT_ID = environ['GROUPME_BOT_ID'] WORKSHEET_KEYS_TO_SCRAPE = environ['WORKSHEET_KEYS'].split(',') INDEX_REDIRECT_URL = 'https://github.com/mplewis/trianglebot' SHEET_KEY = re.search(SHEET_ID_MATCHER,",
"to the Google Sheets JSON API endpoint SHEET_BASE_URL = ('https://spreadsheets.google.com/feeds/cells/%s/%s' '/public/values?alt=json') SHEET_ID_MATCHER =",
"+ ' ' BOT_ID = environ['GROUPME_BOT_ID'] WORKSHEET_KEYS_TO_SCRAPE = environ['WORKSHEET_KEYS'].split(',') INDEX_REDIRECT_URL = 'https://github.com/mplewis/trianglebot' SHEET_KEY",
"Groupme API endpoint API_URL = 'https://api.groupme.com/v3/bots/post' # URL to the Google Sheets JSON",
"API endpoint API_URL = 'https://api.groupme.com/v3/bots/post' # URL to the Google Sheets JSON API",
"'/public/values?alt=json') SHEET_ID_MATCHER = r'spreadsheets\\/d\\/(.+)\\/' # Set by Heroku variables COMMAND_PREFIX = environ['BOT_NAME'] +",
"BOT_ID = environ['GROUPME_BOT_ID'] WORKSHEET_KEYS_TO_SCRAPE = environ['WORKSHEET_KEYS'].split(',') INDEX_REDIRECT_URL = 'https://github.com/mplewis/trianglebot' SHEET_KEY = re.search(SHEET_ID_MATCHER, environ['DOCUMENT_URL']).group(1)",
"= 'https://api.groupme.com/v3/bots/post' # URL to the Google Sheets JSON API endpoint SHEET_BASE_URL =",
"Heroku variables COMMAND_PREFIX = environ['BOT_NAME'] + ' ' BOT_ID = environ['GROUPME_BOT_ID'] WORKSHEET_KEYS_TO_SCRAPE =",
"URL to the Google Sheets JSON API endpoint SHEET_BASE_URL = ('https://spreadsheets.google.com/feeds/cells/%s/%s' '/public/values?alt=json') SHEET_ID_MATCHER",
"= r'spreadsheets\\/d\\/(.+)\\/' # Set by Heroku variables COMMAND_PREFIX = environ['BOT_NAME'] + ' '",
"SHEET_ID_MATCHER = r'spreadsheets\\/d\\/(.+)\\/' # Set by Heroku variables COMMAND_PREFIX = environ['BOT_NAME'] + '",
"os import environ # URL to the Groupme API endpoint API_URL = 'https://api.groupme.com/v3/bots/post'"
] |
[] |
[
"ConfigManager config_data = ConfigManager() f2g_session = Face2Gene(config=config_data) s_list = f2g_session.browse_all_syndromes() with open(\"f2g_library_dump.json\", \"w\")",
"pprint import json from lib.api.face2gene import Face2Gene from lib.model.config import ConfigManager config_data =",
"from lib.model.config import ConfigManager config_data = ConfigManager() f2g_session = Face2Gene(config=config_data) s_list = f2g_session.browse_all_syndromes()",
"= ConfigManager() f2g_session = Face2Gene(config=config_data) s_list = f2g_session.browse_all_syndromes() with open(\"f2g_library_dump.json\", \"w\") as f2g_dump:",
"import json from lib.api.face2gene import Face2Gene from lib.model.config import ConfigManager config_data = ConfigManager()",
"import ConfigManager config_data = ConfigManager() f2g_session = Face2Gene(config=config_data) s_list = f2g_session.browse_all_syndromes() with open(\"f2g_library_dump.json\",",
"based on information from Face2Gene using the Face2Gene library.''' from pprint import pprint",
"f2g_session = Face2Gene(config=config_data) s_list = f2g_session.browse_all_syndromes() with open(\"f2g_library_dump.json\", \"w\") as f2g_dump: json.dump(s_list, f2g_dump,",
"lib.api.face2gene import Face2Gene from lib.model.config import ConfigManager config_data = ConfigManager() f2g_session = Face2Gene(config=config_data)",
"import pprint import json from lib.api.face2gene import Face2Gene from lib.model.config import ConfigManager config_data",
"information from Face2Gene using the Face2Gene library.''' from pprint import pprint import json",
"ConfigManager() f2g_session = Face2Gene(config=config_data) s_list = f2g_session.browse_all_syndromes() with open(\"f2g_library_dump.json\", \"w\") as f2g_dump: json.dump(s_list,",
"the Face2Gene library.''' from pprint import pprint import json from lib.api.face2gene import Face2Gene",
"from lib.api.face2gene import Face2Gene from lib.model.config import ConfigManager config_data = ConfigManager() f2g_session =",
"= Face2Gene(config=config_data) s_list = f2g_session.browse_all_syndromes() with open(\"f2g_library_dump.json\", \"w\") as f2g_dump: json.dump(s_list, f2g_dump, indent=4)",
"json from lib.api.face2gene import Face2Gene from lib.model.config import ConfigManager config_data = ConfigManager() f2g_session",
"import Face2Gene from lib.model.config import ConfigManager config_data = ConfigManager() f2g_session = Face2Gene(config=config_data) s_list",
"from Face2Gene using the Face2Gene library.''' from pprint import pprint import json from",
"omim mapping based on information from Face2Gene using the Face2Gene library.''' from pprint",
"'''Create an omim mapping based on information from Face2Gene using the Face2Gene library.'''",
"lib.model.config import ConfigManager config_data = ConfigManager() f2g_session = Face2Gene(config=config_data) s_list = f2g_session.browse_all_syndromes() with",
"pprint import pprint import json from lib.api.face2gene import Face2Gene from lib.model.config import ConfigManager",
"on information from Face2Gene using the Face2Gene library.''' from pprint import pprint import",
"mapping based on information from Face2Gene using the Face2Gene library.''' from pprint import",
"Face2Gene from lib.model.config import ConfigManager config_data = ConfigManager() f2g_session = Face2Gene(config=config_data) s_list =",
"Face2Gene using the Face2Gene library.''' from pprint import pprint import json from lib.api.face2gene",
"an omim mapping based on information from Face2Gene using the Face2Gene library.''' from",
"Face2Gene library.''' from pprint import pprint import json from lib.api.face2gene import Face2Gene from",
"config_data = ConfigManager() f2g_session = Face2Gene(config=config_data) s_list = f2g_session.browse_all_syndromes() with open(\"f2g_library_dump.json\", \"w\") as",
"from pprint import pprint import json from lib.api.face2gene import Face2Gene from lib.model.config import",
"library.''' from pprint import pprint import json from lib.api.face2gene import Face2Gene from lib.model.config",
"using the Face2Gene library.''' from pprint import pprint import json from lib.api.face2gene import"
] |
[
"as system class TestShadowMayaSystem(MayaBaseTestCase): def test_system(self): \"\"\"Test system in some fashion\"\"\" return True",
"from maya import cmds from base import MayaBaseTestCase import shadow_maya.shadow_maya_system as system class",
"base import MayaBaseTestCase import shadow_maya.shadow_maya_system as system class TestShadowMayaSystem(MayaBaseTestCase): def test_system(self): \"\"\"Test system",
"MayaBaseTestCase import shadow_maya.shadow_maya_system as system class TestShadowMayaSystem(MayaBaseTestCase): def test_system(self): \"\"\"Test system in some",
"import shadow_maya.shadow_maya_system as system class TestShadowMayaSystem(MayaBaseTestCase): def test_system(self): \"\"\"Test system in some fashion\"\"\"",
"shadow_maya.shadow_maya_system as system class TestShadowMayaSystem(MayaBaseTestCase): def test_system(self): \"\"\"Test system in some fashion\"\"\" return",
"maya import cmds from base import MayaBaseTestCase import shadow_maya.shadow_maya_system as system class TestShadowMayaSystem(MayaBaseTestCase):",
"import MayaBaseTestCase import shadow_maya.shadow_maya_system as system class TestShadowMayaSystem(MayaBaseTestCase): def test_system(self): \"\"\"Test system in",
"from base import MayaBaseTestCase import shadow_maya.shadow_maya_system as system class TestShadowMayaSystem(MayaBaseTestCase): def test_system(self): \"\"\"Test",
"import cmds from base import MayaBaseTestCase import shadow_maya.shadow_maya_system as system class TestShadowMayaSystem(MayaBaseTestCase): def",
"cmds from base import MayaBaseTestCase import shadow_maya.shadow_maya_system as system class TestShadowMayaSystem(MayaBaseTestCase): def test_system(self):"
] |
[
"async def linguas(message, _): msg = \"```\\n\" for k in LANGUAGES.keys(): msg +=",
"cod2 in list(LANGUAGES.values())): for k in LANGUAGES.keys(): if LANGUAGES[k] == cod2: cod2 =",
"= k elif (len(cod1) == 2 and cod1 not in list(LANGUAGES.keys())): return Exception",
"for k in LANGUAGES.keys(): msg += str(k)+' - '+str(LANGUAGES[k])+'\\n' msg += \"```\" await",
"msg = ' '.join(msg[1:-2]) out = translator.translate(text=msg, dest=cod1, src=cod2).text await message.channel.send(out) async def",
"_): msg = message.content.strip().lower().split() if len(msg)<4: return Exception cod1 = msg[-1] cod2 =",
"for c in comandos.keys(): msg += comandos[c][1]+'\\n' msg += \"```\" await message.channel.send(msg) async",
"return Exception cod1 = msg[-1] cod2 = msg[-2] if (len(cod1) > 2 and",
"Translator() async def ajuda(message, comandos :dict): msg = \"```\\n\" for c in comandos.keys():",
"LANGUAGES[k] == cod1: cod1 = k elif (len(cod1) == 2 and cod1 not",
"dest=cod1, src=cod2).text await message.channel.send(out) async def linguas(message, _): msg = \"```\\n\" for k",
"= Translator() async def ajuda(message, comandos :dict): msg = \"```\\n\" for c in",
"def ajuda(message, comandos :dict): msg = \"```\\n\" for c in comandos.keys(): msg +=",
"(len(cod2) > 2 and cod2 in list(LANGUAGES.values())): for k in LANGUAGES.keys(): if LANGUAGES[k]",
"import Translator translator = Translator() async def ajuda(message, comandos :dict): msg = \"```\\n\"",
":dict): msg = \"```\\n\" for c in comandos.keys(): msg += comandos[c][1]+'\\n' msg +=",
"cod2 = msg[-2] if (len(cod1) > 2 and cod1 in list(LANGUAGES.values())): for k",
"cod2: cod2 = k elif (len(cod2) == 2 and cod2 not in list(LANGUAGES.keys())):",
"in list(LANGUAGES.values())): for k in LANGUAGES.keys(): if LANGUAGES[k] == cod2: cod2 = k",
"message.channel.send(out) async def linguas(message, _): msg = \"```\\n\" for k in LANGUAGES.keys(): msg",
"traduz(message, _): msg = message.content.strip().lower().split() if len(msg)<4: return Exception cod1 = msg[-1] cod2",
"not in list(LANGUAGES.keys())): return Exception msg = ' '.join(msg[1:-2]) out = translator.translate(text=msg, dest=cod1,",
"in LANGUAGES.keys(): if LANGUAGES[k] == cod2: cod2 = k elif (len(cod2) == 2",
"googletrans import LANGUAGES from googletrans import Translator translator = Translator() async def ajuda(message,",
"k in LANGUAGES.keys(): if LANGUAGES[k] == cod2: cod2 = k elif (len(cod2) ==",
"msg = message.content.strip().lower().split() if len(msg)<4: return Exception cod1 = msg[-1] cod2 = msg[-2]",
"elif (len(cod2) == 2 and cod2 not in list(LANGUAGES.keys())): return Exception msg =",
"LANGUAGES.keys(): if LANGUAGES[k] == cod2: cod2 = k elif (len(cod2) == 2 and",
"cod1: cod1 = k elif (len(cod1) == 2 and cod1 not in list(LANGUAGES.keys())):",
"== 2 and cod2 not in list(LANGUAGES.keys())): return Exception msg = ' '.join(msg[1:-2])",
"translator = Translator() async def ajuda(message, comandos :dict): msg = \"```\\n\" for c",
"from googletrans import LANGUAGES from googletrans import Translator translator = Translator() async def",
"LANGUAGES.keys(): if LANGUAGES[k] == cod1: cod1 = k elif (len(cod1) == 2 and",
"k elif (len(cod1) == 2 and cod1 not in list(LANGUAGES.keys())): return Exception if",
"and cod2 not in list(LANGUAGES.keys())): return Exception msg = ' '.join(msg[1:-2]) out =",
"comandos.keys(): msg += comandos[c][1]+'\\n' msg += \"```\" await message.channel.send(msg) async def traduz(message, _):",
"(len(cod2) == 2 and cod2 not in list(LANGUAGES.keys())): return Exception msg = '",
"= \"```\\n\" for k in LANGUAGES.keys(): msg += str(k)+' - '+str(LANGUAGES[k])+'\\n' msg +=",
"if (len(cod1) > 2 and cod1 in list(LANGUAGES.values())): for k in LANGUAGES.keys(): if",
"2 and cod2 not in list(LANGUAGES.keys())): return Exception msg = ' '.join(msg[1:-2]) out",
"in LANGUAGES.keys(): if LANGUAGES[k] == cod1: cod1 = k elif (len(cod1) == 2",
"cod2 = k elif (len(cod2) == 2 and cod2 not in list(LANGUAGES.keys())): return",
"googletrans import Translator translator = Translator() async def ajuda(message, comandos :dict): msg =",
"from googletrans import Translator translator = Translator() async def ajuda(message, comandos :dict): msg",
"(len(cod1) == 2 and cod1 not in list(LANGUAGES.keys())): return Exception if (len(cod2) >",
"msg = \"```\\n\" for k in LANGUAGES.keys(): msg += str(k)+' - '+str(LANGUAGES[k])+'\\n' msg",
"> 2 and cod2 in list(LANGUAGES.values())): for k in LANGUAGES.keys(): if LANGUAGES[k] ==",
"cod1 = msg[-1] cod2 = msg[-2] if (len(cod1) > 2 and cod1 in",
"in list(LANGUAGES.keys())): return Exception msg = ' '.join(msg[1:-2]) out = translator.translate(text=msg, dest=cod1, src=cod2).text",
"len(msg)<4: return Exception cod1 = msg[-1] cod2 = msg[-2] if (len(cod1) > 2",
"msg[-2] if (len(cod1) > 2 and cod1 in list(LANGUAGES.values())): for k in LANGUAGES.keys():",
"if LANGUAGES[k] == cod2: cod2 = k elif (len(cod2) == 2 and cod2",
"msg = \"```\\n\" for c in comandos.keys(): msg += comandos[c][1]+'\\n' msg += \"```\"",
"def linguas(message, _): msg = \"```\\n\" for k in LANGUAGES.keys(): msg += str(k)+'",
"cod1 in list(LANGUAGES.values())): for k in LANGUAGES.keys(): if LANGUAGES[k] == cod1: cod1 =",
"list(LANGUAGES.keys())): return Exception if (len(cod2) > 2 and cod2 in list(LANGUAGES.values())): for k",
"k elif (len(cod2) == 2 and cod2 not in list(LANGUAGES.keys())): return Exception msg",
"msg += comandos[c][1]+'\\n' msg += \"```\" await message.channel.send(msg) async def traduz(message, _): msg",
"and cod1 not in list(LANGUAGES.keys())): return Exception if (len(cod2) > 2 and cod2",
"LANGUAGES from googletrans import Translator translator = Translator() async def ajuda(message, comandos :dict):",
"src=cod2).text await message.channel.send(out) async def linguas(message, _): msg = \"```\\n\" for k in",
"cod2 not in list(LANGUAGES.keys())): return Exception msg = ' '.join(msg[1:-2]) out = translator.translate(text=msg,",
"= ' '.join(msg[1:-2]) out = translator.translate(text=msg, dest=cod1, src=cod2).text await message.channel.send(out) async def linguas(message,",
"cod1 = k elif (len(cod1) == 2 and cod1 not in list(LANGUAGES.keys())): return",
"in comandos.keys(): msg += comandos[c][1]+'\\n' msg += \"```\" await message.channel.send(msg) async def traduz(message,",
"'.join(msg[1:-2]) out = translator.translate(text=msg, dest=cod1, src=cod2).text await message.channel.send(out) async def linguas(message, _): msg",
"+= comandos[c][1]+'\\n' msg += \"```\" await message.channel.send(msg) async def traduz(message, _): msg =",
"Exception cod1 = msg[-1] cod2 = msg[-2] if (len(cod1) > 2 and cod1",
"translator.translate(text=msg, dest=cod1, src=cod2).text await message.channel.send(out) async def linguas(message, _): msg = \"```\\n\" for",
"for k in LANGUAGES.keys(): if LANGUAGES[k] == cod2: cod2 = k elif (len(cod2)",
"2 and cod1 not in list(LANGUAGES.keys())): return Exception if (len(cod2) > 2 and",
"LANGUAGES[k] == cod2: cod2 = k elif (len(cod2) == 2 and cod2 not",
"2 and cod1 in list(LANGUAGES.values())): for k in LANGUAGES.keys(): if LANGUAGES[k] == cod1:",
"= message.content.strip().lower().split() if len(msg)<4: return Exception cod1 = msg[-1] cod2 = msg[-2] if",
"await message.channel.send(out) async def linguas(message, _): msg = \"```\\n\" for k in LANGUAGES.keys():",
"async def ajuda(message, comandos :dict): msg = \"```\\n\" for c in comandos.keys(): msg",
"not in list(LANGUAGES.keys())): return Exception if (len(cod2) > 2 and cod2 in list(LANGUAGES.values())):",
"' '.join(msg[1:-2]) out = translator.translate(text=msg, dest=cod1, src=cod2).text await message.channel.send(out) async def linguas(message, _):",
"return Exception msg = ' '.join(msg[1:-2]) out = translator.translate(text=msg, dest=cod1, src=cod2).text await message.channel.send(out)",
"import LANGUAGES from googletrans import Translator translator = Translator() async def ajuda(message, comandos",
"(len(cod1) > 2 and cod1 in list(LANGUAGES.values())): for k in LANGUAGES.keys(): if LANGUAGES[k]",
"+= \"```\" await message.channel.send(msg) async def traduz(message, _): msg = message.content.strip().lower().split() if len(msg)<4:",
"Translator translator = Translator() async def ajuda(message, comandos :dict): msg = \"```\\n\" for",
"msg[-1] cod2 = msg[-2] if (len(cod1) > 2 and cod1 in list(LANGUAGES.values())): for",
"message.channel.send(msg) async def traduz(message, _): msg = message.content.strip().lower().split() if len(msg)<4: return Exception cod1",
"> 2 and cod1 in list(LANGUAGES.values())): for k in LANGUAGES.keys(): if LANGUAGES[k] ==",
"if LANGUAGES[k] == cod1: cod1 = k elif (len(cod1) == 2 and cod1",
"== 2 and cod1 not in list(LANGUAGES.keys())): return Exception if (len(cod2) > 2",
"k in LANGUAGES.keys(): msg += str(k)+' - '+str(LANGUAGES[k])+'\\n' msg += \"```\" await message.channel.send(msg)",
"= \"```\\n\" for c in comandos.keys(): msg += comandos[c][1]+'\\n' msg += \"```\" await",
"list(LANGUAGES.values())): for k in LANGUAGES.keys(): if LANGUAGES[k] == cod2: cod2 = k elif",
"list(LANGUAGES.keys())): return Exception msg = ' '.join(msg[1:-2]) out = translator.translate(text=msg, dest=cod1, src=cod2).text await",
"_): msg = \"```\\n\" for k in LANGUAGES.keys(): msg += str(k)+' - '+str(LANGUAGES[k])+'\\n'",
"= msg[-2] if (len(cod1) > 2 and cod1 in list(LANGUAGES.values())): for k in",
"== cod2: cod2 = k elif (len(cod2) == 2 and cod2 not in",
"= msg[-1] cod2 = msg[-2] if (len(cod1) > 2 and cod1 in list(LANGUAGES.values())):",
"comandos :dict): msg = \"```\\n\" for c in comandos.keys(): msg += comandos[c][1]+'\\n' msg",
"list(LANGUAGES.values())): for k in LANGUAGES.keys(): if LANGUAGES[k] == cod1: cod1 = k elif",
"Exception msg = ' '.join(msg[1:-2]) out = translator.translate(text=msg, dest=cod1, src=cod2).text await message.channel.send(out) async",
"2 and cod2 in list(LANGUAGES.values())): for k in LANGUAGES.keys(): if LANGUAGES[k] == cod2:",
"in list(LANGUAGES.keys())): return Exception if (len(cod2) > 2 and cod2 in list(LANGUAGES.values())): for",
"msg += \"```\" await message.channel.send(msg) async def traduz(message, _): msg = message.content.strip().lower().split() if",
"c in comandos.keys(): msg += comandos[c][1]+'\\n' msg += \"```\" await message.channel.send(msg) async def",
"ajuda(message, comandos :dict): msg = \"```\\n\" for c in comandos.keys(): msg += comandos[c][1]+'\\n'",
"if (len(cod2) > 2 and cod2 in list(LANGUAGES.values())): for k in LANGUAGES.keys(): if",
"elif (len(cod1) == 2 and cod1 not in list(LANGUAGES.keys())): return Exception if (len(cod2)",
"\"```\\n\" for c in comandos.keys(): msg += comandos[c][1]+'\\n' msg += \"```\" await message.channel.send(msg)",
"linguas(message, _): msg = \"```\\n\" for k in LANGUAGES.keys(): msg += str(k)+' -",
"\"```\" await message.channel.send(msg) async def traduz(message, _): msg = message.content.strip().lower().split() if len(msg)<4: return",
"for k in LANGUAGES.keys(): if LANGUAGES[k] == cod1: cod1 = k elif (len(cod1)",
"and cod2 in list(LANGUAGES.values())): for k in LANGUAGES.keys(): if LANGUAGES[k] == cod2: cod2",
"and cod1 in list(LANGUAGES.values())): for k in LANGUAGES.keys(): if LANGUAGES[k] == cod1: cod1",
"\"```\\n\" for k in LANGUAGES.keys(): msg += str(k)+' - '+str(LANGUAGES[k])+'\\n' msg += \"```\"",
"message.content.strip().lower().split() if len(msg)<4: return Exception cod1 = msg[-1] cod2 = msg[-2] if (len(cod1)",
"if len(msg)<4: return Exception cod1 = msg[-1] cod2 = msg[-2] if (len(cod1) >",
"cod1 not in list(LANGUAGES.keys())): return Exception if (len(cod2) > 2 and cod2 in",
"return Exception if (len(cod2) > 2 and cod2 in list(LANGUAGES.values())): for k in",
"def traduz(message, _): msg = message.content.strip().lower().split() if len(msg)<4: return Exception cod1 = msg[-1]",
"= k elif (len(cod2) == 2 and cod2 not in list(LANGUAGES.keys())): return Exception",
"k in LANGUAGES.keys(): if LANGUAGES[k] == cod1: cod1 = k elif (len(cod1) ==",
"= translator.translate(text=msg, dest=cod1, src=cod2).text await message.channel.send(out) async def linguas(message, _): msg = \"```\\n\"",
"await message.channel.send(msg) async def traduz(message, _): msg = message.content.strip().lower().split() if len(msg)<4: return Exception",
"== cod1: cod1 = k elif (len(cod1) == 2 and cod1 not in",
"async def traduz(message, _): msg = message.content.strip().lower().split() if len(msg)<4: return Exception cod1 =",
"in list(LANGUAGES.values())): for k in LANGUAGES.keys(): if LANGUAGES[k] == cod1: cod1 = k",
"comandos[c][1]+'\\n' msg += \"```\" await message.channel.send(msg) async def traduz(message, _): msg = message.content.strip().lower().split()",
"out = translator.translate(text=msg, dest=cod1, src=cod2).text await message.channel.send(out) async def linguas(message, _): msg =",
"Exception if (len(cod2) > 2 and cod2 in list(LANGUAGES.values())): for k in LANGUAGES.keys():"
] |
[
"self._inject_provider(account) return account raise IndexError(f\"No account with alias '{alias}'.\") @singledispatchmethod def __getitem__(self, account_id)",
"import ConfigManager from .converters import ConversionManager from .networks import NetworkManager @dataclass class AccountManager:",
"section of the `ape-config.yaml` file. Usage example:: def test_my_contract(accounts): # The \"accounts\" fixture",
"Iterator[str]: \"\"\" All account aliases from every account-related plugin. The \"alias\" is part",
"ape.types import AddressType from ape.utils import cached_property, singledispatchmethod from .config import ConfigManager from",
"for plugin_name, (container_type, account_type) in self.plugin_manager.account_types: if not issubclass(account_type, TestAccountAPI): continue container =",
"self.containers.values(): yield from container.aliases def get_accounts_by_type(self, type_: Type[AccountAPI]) -> List[AccountAPI]: \"\"\" Get a",
"\"\"\" accounts_with_type = [] for account in self: if isinstance(account, type_): self._inject_provider(account) accounts_with_type.append(account)",
"-> int: \"\"\" The number of accounts managed by all account plugins. Returns:",
"treated as singletons. Import the accounts manager singleton from the root ``ape`` namespace.",
"The address to check. Returns: bool: ``True`` when the given address is found.",
"all account plugins. Returns: int \"\"\" return sum(len(container) for container in self.containers.values()) def",
"Type[AccountAPI]) -> List[AccountAPI]: \"\"\" Get a list of accounts by their type. Args:",
"in container: account = container[account_id] self._inject_provider(account) return account raise IndexError(f\"No account with address",
"also the subject of a fixture available in the ``test`` plugin called ``accounts``.",
"account aliases from every account-related plugin. The \"alias\" is part of the :class:`~ape.api.accounts.AccountAPI`.",
"The list of all :class:`~ape.api.accounts.AccountContainerAPI` instances across all installed plugins. Returns: dict[str, :class:`~ape.api.accounts.AccountContainerAPI`]",
"yield account def __repr__(self) -> str: return \"[\" + \", \".join(repr(a) for a",
"container in self.containers.values()) def _inject_provider(self, account: AccountAPI): if self.network_manager.active_provider is not None: account.provider",
"def containers(self) -> Dict[str, AccountContainerAPI]: \"\"\" The list of all :class:`~ape.api.accounts.AccountContainerAPI` instances across",
"the mnemonic and / or number-of-accounts using the ``test`` section of the `ape-config.yaml`",
"converters: ConversionManager plugin_manager: PluginManager network_manager: NetworkManager @cached_property def containers(self) -> Dict[str, AccountContainerAPI]: \"\"\"",
"managed by all account plugins. Returns: int \"\"\" return sum(len(container) for container in",
"continue container = container_type(None, account_type, self.config) for account in container: self._inject_provider(account) accounts.append(account) return",
"generally preferred to use :meth:`~ape.managers.accounts.AccountManager.load` or :meth:`~ape.managers.accounts.AccountManager.__getitem_str`. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" for idx, account",
"-> AccountAPI: \"\"\" Get an account by address. Raises: IndexError: When there is",
"Get an account by its alias. Raises: IndexError: When there is no local",
"NotImplementedError(f\"Cannot use {type(account_id)} as account ID.\") @__getitem__.register def __getitem_int(self, account_id: int) -> AccountAPI:",
"@singledispatchmethod def __getitem__(self, account_id) -> AccountAPI: raise NotImplementedError(f\"Cannot use {type(account_id)} as account ID.\")",
"to check. Returns: bool: ``True`` when the given address is found. \"\"\" return",
"from ape.utils import cached_property, singledispatchmethod from .config import ConfigManager from .converters import ConversionManager",
"number of accounts managed by all account plugins. Returns: int \"\"\" return sum(len(container)",
"for container in self.containers.values(): for account in container: self._inject_provider(account) yield account def __repr__(self)",
"When there is no local account with the given alias. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\"",
"in self.containers.values(): if account_id in container: account = container[account_id] self._inject_provider(account) return account raise",
"singleton my_accounts = accounts.load(\"dev\") \"\"\" config: ConfigManager converters: ConversionManager plugin_manager: PluginManager network_manager: NetworkManager",
"TestAccountAPI): continue container = container_type(None, account_type, self.config) for account in container: self._inject_provider(account) accounts.append(account)",
"account with the given address. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" account_id = self.converters.convert(account_str, AddressType) for",
"in ``ape``. Args: address (:class:`~ape.types.AddressType`): The address to check. Returns: bool: ``True`` when",
"(container_type, account_type) in self.plugin_manager.account_types: # Ignore containers that contain test accounts. if issubclass(account_type,",
"-> bool: \"\"\" Determine if the given address matches an account in ``ape``.",
"bool: ``True`` when the given address is found. \"\"\" return any(address in container",
"raise ValueError(\"Cannot use empty string as alias!\") for account in self: if account.alias",
"accounts managed by all account plugins. Returns: int \"\"\" return sum(len(container) for container",
"the account alias to load an account using method :meth:`~ape.managers.accounts.AccountManager.load`. Returns: Iterator[str] \"\"\"",
"account-related plugin. The \"alias\" is part of the :class:`~ape.api.accounts.AccountAPI`. Use the account alias",
"account_type, self.config) for account in container: self._inject_provider(account) accounts.append(account) return accounts def load(self, alias:",
"a in self) + \"]\" @cached_property def test_accounts(self) -> List[TestAccountAPI]: \"\"\" Accounts generated",
"when you do the CLI command ``ape accounts list --all``, you will see",
"Iterator, List, Type from dataclassy import dataclass from pluggy import PluginManager # type:",
"in self.containers.values(): yield from container.aliases def get_accounts_by_type(self, type_: Type[AccountAPI]) -> List[AccountAPI]: \"\"\" Get",
"sum(len(container) for container in self.containers.values()) def __iter__(self) -> Iterator[AccountAPI]: for container in self.containers.values():",
"not issubclass(account_type, TestAccountAPI): continue container = container_type(None, account_type, self.config) for account in container:",
"if issubclass(account_type, TestAccountAPI): continue accounts_folder = data_folder / plugin_name accounts_folder.mkdir(exist_ok=True) containers[plugin_name] = container_type(accounts_folder,",
"--all``, you will see a list of enumerated accounts by their indices. Use",
"of a fixture available in the ``test`` plugin called ``accounts``. Configure these accounts,",
"(:class:`~ape.types.AddressType`): The address to check. Returns: bool: ``True`` when the given address is",
"import PluginManager # type: ignore from ape.api.accounts import AccountAPI, AccountContainerAPI, TestAccountAPI from ape.types",
"``ape`` namespace. Usage example:: from ape import accounts # \"accounts\" is the AccountManager",
"\"\"\" Determine if the given address matches an account in ``ape``. Args: address",
"get an account from that index. **NOTE**: It is generally preferred to use",
"if alias == \"\": raise ValueError(\"Cannot use empty string as alias!\") for account",
"account to get. Returns: List[:class:`~ape.api.accounts.AccountAPI`] \"\"\" accounts_with_type = [] for account in self:",
"raise NotImplementedError(f\"Cannot use {type(account_id)} as account ID.\") @__getitem__.register def __getitem_int(self, account_id: int) ->",
"ConversionManager from .networks import NetworkManager @dataclass class AccountManager: \"\"\" The ``AccountManager`` is a",
"+ \", \".join(repr(a) for a in self) + \"]\" @cached_property def test_accounts(self) ->",
"List[:class:`~ape.api.accounts.TestAccountAPI`] \"\"\" accounts = [] for plugin_name, (container_type, account_type) in self.plugin_manager.account_types: if not",
"Args: type_ (Type[:class:`~ape.api.accounts.AccountAPI`]): The type of account to get. Returns: List[:class:`~ape.api.accounts.AccountAPI`] \"\"\" accounts_with_type",
"-> Dict[str, AccountContainerAPI]: \"\"\" The list of all :class:`~ape.api.accounts.AccountContainerAPI` instances across all installed",
"container: self._inject_provider(account) accounts.append(account) return accounts def load(self, alias: str) -> AccountAPI: \"\"\" Get",
"Usage example:: from ape import accounts # \"accounts\" is the AccountManager singleton my_accounts",
"self._inject_provider(account) return account raise IndexError(f\"No account at index '{account_id}'.\") @__getitem__.register def __getitem_str(self, account_str:",
"singledispatchmethod from .config import ConfigManager from .converters import ConversionManager from .networks import NetworkManager",
"type_): self._inject_provider(account) accounts_with_type.append(account) return accounts_with_type def __len__(self) -> int: \"\"\" The number of",
"no local account with the given address. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" account_id = self.converters.convert(account_str,",
"index '{account_id}'.\") @__getitem__.register def __getitem_str(self, account_str: str) -> AccountAPI: \"\"\" Get an account",
"Returns: List[:class:`~ape.api.accounts.AccountAPI`] \"\"\" accounts_with_type = [] for account in self: if isinstance(account, type_):",
"uses the AccountsManager.test_accounts() sender = accounts[0] receiver = accounts[1] ... Returns: List[:class:`~ape.api.accounts.TestAccountAPI`] \"\"\"",
"\"\": raise ValueError(\"Cannot use empty string as alias!\") for account in self: if",
"index. For example, when you do the CLI command ``ape accounts list --all``,",
"Ignore containers that contain test accounts. if issubclass(account_type, TestAccountAPI): continue accounts_folder = data_folder",
"= [] for plugin_name, (container_type, account_type) in self.plugin_manager.account_types: if not issubclass(account_type, TestAccountAPI): continue",
"AccountManager: \"\"\" The ``AccountManager`` is a container of containers for :class:`~ape.api.accounts.AccountAPI` objects. All",
"(container_type, account_type) in self.plugin_manager.account_types: if not issubclass(account_type, TestAccountAPI): continue container = container_type(None, account_type,",
":meth:`~ape.managers.accounts.AccountManager.load` or :meth:`~ape.managers.accounts.AccountManager.__getitem_str`. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" for idx, account in enumerate(self.__iter__()): if account_id",
"raise IndexError(f\"No account with address '{account_id}'.\") def __contains__(self, address: AddressType) -> bool: \"\"\"",
"of account to get. Returns: List[:class:`~ape.api.accounts.AccountAPI`] \"\"\" accounts_with_type = [] for account in",
"AccountAPI: \"\"\" Get an account by its alias. Raises: IndexError: When there is",
"in enumerate(self.__iter__()): if account_id == idx: self._inject_provider(account) return account raise IndexError(f\"No account at",
"self.containers.values(): for account in container: self._inject_provider(account) yield account def __repr__(self) -> str: return",
"their type. Args: type_ (Type[:class:`~ape.api.accounts.AccountAPI`]): The type of account to get. Returns: List[:class:`~ape.api.accounts.AccountAPI`]",
"plugins. Returns: int \"\"\" return sum(len(container) for container in self.containers.values()) def __iter__(self) ->",
"import NetworkManager @dataclass class AccountManager: \"\"\" The ``AccountManager`` is a container of containers",
"is no local account with the given address. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" account_id =",
"accounts manager singleton from the root ``ape`` namespace. Usage example:: from ape import",
"return any(address in container for container in self.containers.values()) def _inject_provider(self, account: AccountAPI): if",
"ConfigManager converters: ConversionManager plugin_manager: PluginManager network_manager: NetworkManager @cached_property def containers(self) -> Dict[str, AccountContainerAPI]:",
"str) -> AccountAPI: \"\"\" Get an account by its alias. Raises: IndexError: When",
"singletons. Import the accounts manager singleton from the root ``ape`` namespace. Usage example::",
"way to get an account from that index. **NOTE**: It is generally preferred",
"def __contains__(self, address: AddressType) -> bool: \"\"\" Determine if the given address matches",
"accounts_with_type def __len__(self) -> int: \"\"\" The number of accounts managed by all",
"for container in self.containers.values(): if account_id in container: account = container[account_id] self._inject_provider(account) return",
"bool: \"\"\" Determine if the given address matches an account in ``ape``. Args:",
"[] for account in self: if isinstance(account, type_): self._inject_provider(account) accounts_with_type.append(account) return accounts_with_type def",
"= accounts[0] receiver = accounts[1] ... Returns: List[:class:`~ape.api.accounts.TestAccountAPI`] \"\"\" accounts = [] for",
"and are treated as singletons. Import the accounts manager singleton from the root",
"type: ignore from ape.api.accounts import AccountAPI, AccountContainerAPI, TestAccountAPI from ape.types import AddressType from",
"{} data_folder = self.config.DATA_FOLDER data_folder.mkdir(exist_ok=True) for plugin_name, (container_type, account_type) in self.plugin_manager.account_types: # Ignore",
"\"\"\" The number of accounts managed by all account plugins. Returns: int \"\"\"",
"ID.\") @__getitem__.register def __getitem_int(self, account_id: int) -> AccountAPI: \"\"\" Get an account by",
"plugin called ``accounts``. Configure these accounts, such as the mnemonic and / or",
"get. Returns: List[:class:`~ape.api.accounts.AccountAPI`] \"\"\" accounts_with_type = [] for account in self: if isinstance(account,",
"from pluggy import PluginManager # type: ignore from ape.api.accounts import AccountAPI, AccountContainerAPI, TestAccountAPI",
"dataclass from pluggy import PluginManager # type: ignore from ape.api.accounts import AccountAPI, AccountContainerAPI,",
"receiver = accounts[1] ... Returns: List[:class:`~ape.api.accounts.TestAccountAPI`] \"\"\" accounts = [] for plugin_name, (container_type,",
"address (:class:`~ape.types.AddressType`): The address to check. Returns: bool: ``True`` when the given address",
"from the configured test mnemonic. These accounts are also the subject of a",
"as the mnemonic and / or number-of-accounts using the ``test`` section of the",
"are also the subject of a fixture available in the ``test`` plugin called",
"All containers must subclass :class:`~ape.api.accounts.AccountContainerAPI` and are treated as singletons. Import the accounts",
"return containers @property def aliases(self) -> Iterator[str]: \"\"\" All account aliases from every",
"Returns: bool: ``True`` when the given address is found. \"\"\" return any(address in",
"network_manager: NetworkManager @cached_property def containers(self) -> Dict[str, AccountContainerAPI]: \"\"\" The list of all",
"for idx, account in enumerate(self.__iter__()): if account_id == idx: self._inject_provider(account) return account raise",
"test_my_contract(accounts): # The \"accounts\" fixture uses the AccountsManager.test_accounts() sender = accounts[0] receiver =",
"List[AccountAPI]: \"\"\" Get a list of accounts by their type. Args: type_ (Type[:class:`~ape.api.accounts.AccountAPI`]):",
"plugin_name, (container_type, account_type) in self.plugin_manager.account_types: if not issubclass(account_type, TestAccountAPI): continue container = container_type(None,",
"with alias '{alias}'.\") @singledispatchmethod def __getitem__(self, account_id) -> AccountAPI: raise NotImplementedError(f\"Cannot use {type(account_id)}",
"account_type) in self.plugin_manager.account_types: if not issubclass(account_type, TestAccountAPI): continue container = container_type(None, account_type, self.config)",
"if account_id == idx: self._inject_provider(account) return account raise IndexError(f\"No account at index '{account_id}'.\")",
"are treated as singletons. Import the accounts manager singleton from the root ``ape``",
"from dataclassy import dataclass from pluggy import PluginManager # type: ignore from ape.api.accounts",
"@dataclass class AccountManager: \"\"\" The ``AccountManager`` is a container of containers for :class:`~ape.api.accounts.AccountAPI`",
"self.config) for account in container: self._inject_provider(account) accounts.append(account) return accounts def load(self, alias: str)",
"account with the given alias. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" if alias == \"\": raise",
"that index. **NOTE**: It is generally preferred to use :meth:`~ape.managers.accounts.AccountManager.load` or :meth:`~ape.managers.accounts.AccountManager.__getitem_str`. Returns:",
"for account in container: self._inject_provider(account) yield account def __repr__(self) -> str: return \"[\"",
"accounts_with_type.append(account) return accounts_with_type def __len__(self) -> int: \"\"\" The number of accounts managed",
"contain test accounts. if issubclass(account_type, TestAccountAPI): continue accounts_folder = data_folder / plugin_name accounts_folder.mkdir(exist_ok=True)",
"in self.containers.values(): for account in container: self._inject_provider(account) yield account def __repr__(self) -> str:",
"that contain test accounts. if issubclass(account_type, TestAccountAPI): continue accounts_folder = data_folder / plugin_name",
"data_folder.mkdir(exist_ok=True) for plugin_name, (container_type, account_type) in self.plugin_manager.account_types: # Ignore containers that contain test",
"see a list of enumerated accounts by their indices. Use this method as",
"ape import accounts # \"accounts\" is the AccountManager singleton my_accounts = accounts.load(\"dev\") \"\"\"",
"ValueError(\"Cannot use empty string as alias!\") for account in self: if account.alias and",
"account with address '{account_id}'.\") def __contains__(self, address: AddressType) -> bool: \"\"\" Determine if",
"def load(self, alias: str) -> AccountAPI: \"\"\" Get an account by its alias.",
"Import the accounts manager singleton from the root ``ape`` namespace. Usage example:: from",
"container = container_type(None, account_type, self.config) for account in container: self._inject_provider(account) accounts.append(account) return accounts",
"the accounts manager singleton from the root ``ape`` namespace. Usage example:: from ape",
"For example, when you do the CLI command ``ape accounts list --all``, you",
"account def __repr__(self) -> str: return \"[\" + \", \".join(repr(a) for a in",
"@property def aliases(self) -> Iterator[str]: \"\"\" All account aliases from every account-related plugin.",
"account by address. Raises: IndexError: When there is no local account with the",
"container in self.containers.values(): yield from container.aliases def get_accounts_by_type(self, type_: Type[AccountAPI]) -> List[AccountAPI]: \"\"\"",
"in self.plugin_manager.account_types: # Ignore containers that contain test accounts. if issubclass(account_type, TestAccountAPI): continue",
"(Type[:class:`~ape.api.accounts.AccountAPI`]): The type of account to get. Returns: List[:class:`~ape.api.accounts.AccountAPI`] \"\"\" accounts_with_type = []",
"/ or number-of-accounts using the ``test`` section of the `ape-config.yaml` file. Usage example::",
"The \"accounts\" fixture uses the AccountsManager.test_accounts() sender = accounts[0] receiver = accounts[1] ...",
"... Returns: List[:class:`~ape.api.accounts.TestAccountAPI`] \"\"\" accounts = [] for plugin_name, (container_type, account_type) in self.plugin_manager.account_types:",
"found. \"\"\" return any(address in container for container in self.containers.values()) def _inject_provider(self, account:",
"-> Iterator[str]: \"\"\" All account aliases from every account-related plugin. The \"alias\" is",
"import cached_property, singledispatchmethod from .config import ConfigManager from .converters import ConversionManager from .networks",
"fixture available in the ``test`` plugin called ``accounts``. Configure these accounts, such as",
"a list of enumerated accounts by their indices. Use this method as a",
"The ``AccountManager`` is a container of containers for :class:`~ape.api.accounts.AccountAPI` objects. All containers must",
"by their indices. Use this method as a quicker, ad-hoc way to get",
"TestAccountAPI from ape.types import AddressType from ape.utils import cached_property, singledispatchmethod from .config import",
"Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" account_id = self.converters.convert(account_str, AddressType) for container in self.containers.values(): if account_id",
"to get an account from that index. **NOTE**: It is generally preferred to",
"plugins. Returns: dict[str, :class:`~ape.api.accounts.AccountContainerAPI`] \"\"\" containers = {} data_folder = self.config.DATA_FOLDER data_folder.mkdir(exist_ok=True) for",
"IndexError(f\"No account at index '{account_id}'.\") @__getitem__.register def __getitem_str(self, account_str: str) -> AccountAPI: \"\"\"",
"example, when you do the CLI command ``ape accounts list --all``, you will",
"\"\"\" account_id = self.converters.convert(account_str, AddressType) for container in self.containers.values(): if account_id in container:",
"of accounts by their type. Args: type_ (Type[:class:`~ape.api.accounts.AccountAPI`]): The type of account to",
"mnemonic and / or number-of-accounts using the ``test`` section of the `ape-config.yaml` file.",
"\"\"\" Accounts generated from the configured test mnemonic. These accounts are also the",
"return account raise IndexError(f\"No account with address '{account_id}'.\") def __contains__(self, address: AddressType) ->",
"__getitem_str(self, account_str: str) -> AccountAPI: \"\"\" Get an account by address. Raises: IndexError:",
"all installed plugins. Returns: dict[str, :class:`~ape.api.accounts.AccountContainerAPI`] \"\"\" containers = {} data_folder = self.config.DATA_FOLDER",
"self.converters.convert(account_str, AddressType) for container in self.containers.values(): if account_id in container: account = container[account_id]",
"Accounts generated from the configured test mnemonic. These accounts are also the subject",
"alias. Raises: IndexError: When there is no local account with the given alias.",
"from .converters import ConversionManager from .networks import NetworkManager @dataclass class AccountManager: \"\"\" The",
"from .networks import NetworkManager @dataclass class AccountManager: \"\"\" The ``AccountManager`` is a container",
"container: self._inject_provider(account) yield account def __repr__(self) -> str: return \"[\" + \", \".join(repr(a)",
"self: if isinstance(account, type_): self._inject_provider(account) accounts_with_type.append(account) return accounts_with_type def __len__(self) -> int: \"\"\"",
"from that index. **NOTE**: It is generally preferred to use :meth:`~ape.managers.accounts.AccountManager.load` or :meth:`~ape.managers.accounts.AccountManager.__getitem_str`.",
"of all :class:`~ape.api.accounts.AccountContainerAPI` instances across all installed plugins. Returns: dict[str, :class:`~ape.api.accounts.AccountContainerAPI`] \"\"\" containers",
"with the given address. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" account_id = self.converters.convert(account_str, AddressType) for container",
"account_str: str) -> AccountAPI: \"\"\" Get an account by address. Raises: IndexError: When",
"account in enumerate(self.__iter__()): if account_id == idx: self._inject_provider(account) return account raise IndexError(f\"No account",
"data_folder / plugin_name accounts_folder.mkdir(exist_ok=True) containers[plugin_name] = container_type(accounts_folder, account_type, self.config) return containers @property def",
"a fixture available in the ``test`` plugin called ``accounts``. Configure these accounts, such",
"in container for container in self.containers.values()) def _inject_provider(self, account: AccountAPI): if self.network_manager.active_provider is",
"configured test mnemonic. These accounts are also the subject of a fixture available",
"/ plugin_name accounts_folder.mkdir(exist_ok=True) containers[plugin_name] = container_type(accounts_folder, account_type, self.config) return containers @property def aliases(self)",
"the given alias. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" if alias == \"\": raise ValueError(\"Cannot use",
".converters import ConversionManager from .networks import NetworkManager @dataclass class AccountManager: \"\"\" The ``AccountManager``",
"to load an account using method :meth:`~ape.managers.accounts.AccountManager.load`. Returns: Iterator[str] \"\"\" for container in",
"account with alias '{alias}'.\") @singledispatchmethod def __getitem__(self, account_id) -> AccountAPI: raise NotImplementedError(f\"Cannot use",
"cached_property, singledispatchmethod from .config import ConfigManager from .converters import ConversionManager from .networks import",
"given alias. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" if alias == \"\": raise ValueError(\"Cannot use empty",
"no local account with the given alias. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" if alias ==",
"issubclass(account_type, TestAccountAPI): continue accounts_folder = data_folder / plugin_name accounts_folder.mkdir(exist_ok=True) containers[plugin_name] = container_type(accounts_folder, account_type,",
"indices. Use this method as a quicker, ad-hoc way to get an account",
"self.config) return containers @property def aliases(self) -> Iterator[str]: \"\"\" All account aliases from",
"subject of a fixture available in the ``test`` plugin called ``accounts``. Configure these",
"ape.utils import cached_property, singledispatchmethod from .config import ConfigManager from .converters import ConversionManager from",
"of the :class:`~ape.api.accounts.AccountAPI`. Use the account alias to load an account using method",
"my_accounts = accounts.load(\"dev\") \"\"\" config: ConfigManager converters: ConversionManager plugin_manager: PluginManager network_manager: NetworkManager @cached_property",
"These accounts are also the subject of a fixture available in the ``test``",
"'{alias}'.\") @singledispatchmethod def __getitem__(self, account_id) -> AccountAPI: raise NotImplementedError(f\"Cannot use {type(account_id)} as account",
"manager singleton from the root ``ape`` namespace. Usage example:: from ape import accounts",
"@__getitem__.register def __getitem_str(self, account_str: str) -> AccountAPI: \"\"\" Get an account by address.",
"Returns: Iterator[str] \"\"\" for container in self.containers.values(): yield from container.aliases def get_accounts_by_type(self, type_:",
"self.containers.values()) def __iter__(self) -> Iterator[AccountAPI]: for container in self.containers.values(): for account in container:",
"AccountAPI, AccountContainerAPI, TestAccountAPI from ape.types import AddressType from ape.utils import cached_property, singledispatchmethod from",
"for container in self.containers.values()) def _inject_provider(self, account: AccountAPI): if self.network_manager.active_provider is not None:",
":class:`~ape.api.accounts.AccountAPI` \"\"\" account_id = self.converters.convert(account_str, AddressType) for container in self.containers.values(): if account_id in",
"plugin_name, (container_type, account_type) in self.plugin_manager.account_types: # Ignore containers that contain test accounts. if",
"account_type, self.config) return containers @property def aliases(self) -> Iterator[str]: \"\"\" All account aliases",
"account ID.\") @__getitem__.register def __getitem_int(self, account_id: int) -> AccountAPI: \"\"\" Get an account",
"def test_my_contract(accounts): # The \"accounts\" fixture uses the AccountsManager.test_accounts() sender = accounts[0] receiver",
":class:`~ape.api.accounts.AccountContainerAPI` and are treated as singletons. Import the accounts manager singleton from the",
"the ``test`` plugin called ``accounts``. Configure these accounts, such as the mnemonic and",
"account by index. For example, when you do the CLI command ``ape accounts",
"by their type. Args: type_ (Type[:class:`~ape.api.accounts.AccountAPI`]): The type of account to get. Returns:",
"alias to load an account using method :meth:`~ape.managers.accounts.AccountManager.load`. Returns: Iterator[str] \"\"\" for container",
"with the given alias. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" if alias == \"\": raise ValueError(\"Cannot",
".networks import NetworkManager @dataclass class AccountManager: \"\"\" The ``AccountManager`` is a container of",
"an account using method :meth:`~ape.managers.accounts.AccountManager.load`. Returns: Iterator[str] \"\"\" for container in self.containers.values(): yield",
"load(self, alias: str) -> AccountAPI: \"\"\" Get an account by its alias. Raises:",
"return account raise IndexError(f\"No account with alias '{alias}'.\") @singledispatchmethod def __getitem__(self, account_id) ->",
"ignore from ape.api.accounts import AccountAPI, AccountContainerAPI, TestAccountAPI from ape.types import AddressType from ape.utils",
"``True`` when the given address is found. \"\"\" return any(address in container for",
"self.containers.values(): if account_id in container: account = container[account_id] self._inject_provider(account) return account raise IndexError(f\"No",
"account = container[account_id] self._inject_provider(account) return account raise IndexError(f\"No account with address '{account_id}'.\") def",
"if the given address matches an account in ``ape``. Args: address (:class:`~ape.types.AddressType`): The",
"or number-of-accounts using the ``test`` section of the `ape-config.yaml` file. Usage example:: def",
"root ``ape`` namespace. Usage example:: from ape import accounts # \"accounts\" is the",
"accounts_with_type = [] for account in self: if isinstance(account, type_): self._inject_provider(account) accounts_with_type.append(account) return",
"NetworkManager @dataclass class AccountManager: \"\"\" The ``AccountManager`` is a container of containers for",
"# The \"accounts\" fixture uses the AccountsManager.test_accounts() sender = accounts[0] receiver = accounts[1]",
"such as the mnemonic and / or number-of-accounts using the ``test`` section of",
"CLI command ``ape accounts list --all``, you will see a list of enumerated",
"str) -> AccountAPI: \"\"\" Get an account by address. Raises: IndexError: When there",
"the ``test`` section of the `ape-config.yaml` file. Usage example:: def test_my_contract(accounts): # The",
"Dict, Iterator, List, Type from dataclassy import dataclass from pluggy import PluginManager #",
"\"\"\" config: ConfigManager converters: ConversionManager plugin_manager: PluginManager network_manager: NetworkManager @cached_property def containers(self) ->",
"Returns: int \"\"\" return sum(len(container) for container in self.containers.values()) def __iter__(self) -> Iterator[AccountAPI]:",
"account raise IndexError(f\"No account with address '{account_id}'.\") def __contains__(self, address: AddressType) -> bool:",
"from ape import accounts # \"accounts\" is the AccountManager singleton my_accounts = accounts.load(\"dev\")",
"AccountContainerAPI]: \"\"\" The list of all :class:`~ape.api.accounts.AccountContainerAPI` instances across all installed plugins. Returns:",
"When there is no local account with the given address. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\"",
"\"alias\" is part of the :class:`~ape.api.accounts.AccountAPI`. Use the account alias to load an",
"the `ape-config.yaml` file. Usage example:: def test_my_contract(accounts): # The \"accounts\" fixture uses the",
"issubclass(account_type, TestAccountAPI): continue container = container_type(None, account_type, self.config) for account in container: self._inject_provider(account)",
"ConfigManager from .converters import ConversionManager from .networks import NetworkManager @dataclass class AccountManager: \"\"\"",
"command ``ape accounts list --all``, you will see a list of enumerated accounts",
"__contains__(self, address: AddressType) -> bool: \"\"\" Determine if the given address matches an",
"All account aliases from every account-related plugin. The \"alias\" is part of the",
"def __getitem__(self, account_id) -> AccountAPI: raise NotImplementedError(f\"Cannot use {type(account_id)} as account ID.\") @__getitem__.register",
"containers must subclass :class:`~ape.api.accounts.AccountContainerAPI` and are treated as singletons. Import the accounts manager",
"Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" if alias == \"\": raise ValueError(\"Cannot use empty string as",
"account raise IndexError(f\"No account at index '{account_id}'.\") @__getitem__.register def __getitem_str(self, account_str: str) ->",
".config import ConfigManager from .converters import ConversionManager from .networks import NetworkManager @dataclass class",
"as singletons. Import the accounts manager singleton from the root ``ape`` namespace. Usage",
"accounts_folder = data_folder / plugin_name accounts_folder.mkdir(exist_ok=True) containers[plugin_name] = container_type(accounts_folder, account_type, self.config) return containers",
"The number of accounts managed by all account plugins. Returns: int \"\"\" return",
"you do the CLI command ``ape accounts list --all``, you will see a",
"this method as a quicker, ad-hoc way to get an account from that",
":class:`~ape.api.accounts.AccountContainerAPI`] \"\"\" containers = {} data_folder = self.config.DATA_FOLDER data_folder.mkdir(exist_ok=True) for plugin_name, (container_type, account_type)",
"def aliases(self) -> Iterator[str]: \"\"\" All account aliases from every account-related plugin. The",
"accounts[1] ... Returns: List[:class:`~ape.api.accounts.TestAccountAPI`] \"\"\" accounts = [] for plugin_name, (container_type, account_type) in",
"use :meth:`~ape.managers.accounts.AccountManager.load` or :meth:`~ape.managers.accounts.AccountManager.__getitem_str`. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" for idx, account in enumerate(self.__iter__()): if",
"AddressType from ape.utils import cached_property, singledispatchmethod from .config import ConfigManager from .converters import",
"``accounts``. Configure these accounts, such as the mnemonic and / or number-of-accounts using",
"address '{account_id}'.\") def __contains__(self, address: AddressType) -> bool: \"\"\" Determine if the given",
"account_id = self.converters.convert(account_str, AddressType) for container in self.containers.values(): if account_id in container: account",
"int \"\"\" return sum(len(container) for container in self.containers.values()) def __iter__(self) -> Iterator[AccountAPI]: for",
"accounts are also the subject of a fixture available in the ``test`` plugin",
"all :class:`~ape.api.accounts.AccountContainerAPI` instances across all installed plugins. Returns: dict[str, :class:`~ape.api.accounts.AccountContainerAPI`] \"\"\" containers =",
"dataclassy import dataclass from pluggy import PluginManager # type: ignore from ape.api.accounts import",
"alias: str) -> AccountAPI: \"\"\" Get an account by its alias. Raises: IndexError:",
"ConversionManager plugin_manager: PluginManager network_manager: NetworkManager @cached_property def containers(self) -> Dict[str, AccountContainerAPI]: \"\"\" The",
"of enumerated accounts by their indices. Use this method as a quicker, ad-hoc",
"in container: self._inject_provider(account) yield account def __repr__(self) -> str: return \"[\" + \",",
"Determine if the given address matches an account in ``ape``. Args: address (:class:`~ape.types.AddressType`):",
"-> Iterator[AccountAPI]: for container in self.containers.values(): for account in container: self._inject_provider(account) yield account",
"def __getitem_str(self, account_str: str) -> AccountAPI: \"\"\" Get an account by address. Raises:",
"the AccountManager singleton my_accounts = accounts.load(\"dev\") \"\"\" config: ConfigManager converters: ConversionManager plugin_manager: PluginManager",
"in self) + \"]\" @cached_property def test_accounts(self) -> List[TestAccountAPI]: \"\"\" Accounts generated from",
"the root ``ape`` namespace. Usage example:: from ape import accounts # \"accounts\" is",
"container.aliases def get_accounts_by_type(self, type_: Type[AccountAPI]) -> List[AccountAPI]: \"\"\" Get a list of accounts",
"containers that contain test accounts. if issubclass(account_type, TestAccountAPI): continue accounts_folder = data_folder /",
"namespace. Usage example:: from ape import accounts # \"accounts\" is the AccountManager singleton",
"Raises: IndexError: When there is no local account with the given alias. Returns:",
"Use this method as a quicker, ad-hoc way to get an account from",
"return sum(len(container) for container in self.containers.values()) def __iter__(self) -> Iterator[AccountAPI]: for container in",
":meth:`~ape.managers.accounts.AccountManager.load`. Returns: Iterator[str] \"\"\" for container in self.containers.values(): yield from container.aliases def get_accounts_by_type(self,",
"Iterator[AccountAPI]: for container in self.containers.values(): for account in container: self._inject_provider(account) yield account def",
"[] for plugin_name, (container_type, account_type) in self.plugin_manager.account_types: if not issubclass(account_type, TestAccountAPI): continue container",
"accounts by their indices. Use this method as a quicker, ad-hoc way to",
"type_ (Type[:class:`~ape.api.accounts.AccountAPI`]): The type of account to get. Returns: List[:class:`~ape.api.accounts.AccountAPI`] \"\"\" accounts_with_type =",
"pluggy import PluginManager # type: ignore from ape.api.accounts import AccountAPI, AccountContainerAPI, TestAccountAPI from",
"by its alias. Raises: IndexError: When there is no local account with the",
"account_id) -> AccountAPI: raise NotImplementedError(f\"Cannot use {type(account_id)} as account ID.\") @__getitem__.register def __getitem_int(self,",
"or :meth:`~ape.managers.accounts.AccountManager.__getitem_str`. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" for idx, account in enumerate(self.__iter__()): if account_id ==",
"for :class:`~ape.api.accounts.AccountAPI` objects. All containers must subclass :class:`~ape.api.accounts.AccountContainerAPI` and are treated as singletons.",
"__repr__(self) -> str: return \"[\" + \", \".join(repr(a) for a in self) +",
"the given address matches an account in ``ape``. Args: address (:class:`~ape.types.AddressType`): The address",
"self: if account.alias and account.alias == alias: self._inject_provider(account) return account raise IndexError(f\"No account",
"address matches an account in ``ape``. Args: address (:class:`~ape.types.AddressType`): The address to check.",
"list of accounts by their type. Args: type_ (Type[:class:`~ape.api.accounts.AccountAPI`]): The type of account",
"containers for :class:`~ape.api.accounts.AccountAPI` objects. All containers must subclass :class:`~ape.api.accounts.AccountContainerAPI` and are treated as",
"class AccountManager: \"\"\" The ``AccountManager`` is a container of containers for :class:`~ape.api.accounts.AccountAPI` objects.",
"return \"[\" + \", \".join(repr(a) for a in self) + \"]\" @cached_property def",
"accounts. if issubclass(account_type, TestAccountAPI): continue accounts_folder = data_folder / plugin_name accounts_folder.mkdir(exist_ok=True) containers[plugin_name] =",
"and / or number-of-accounts using the ``test`` section of the `ape-config.yaml` file. Usage",
"alias == \"\": raise ValueError(\"Cannot use empty string as alias!\") for account in",
"IndexError(f\"No account with alias '{alias}'.\") @singledispatchmethod def __getitem__(self, account_id) -> AccountAPI: raise NotImplementedError(f\"Cannot",
"in self.containers.values()) def _inject_provider(self, account: AccountAPI): if self.network_manager.active_provider is not None: account.provider =",
"in self: if isinstance(account, type_): self._inject_provider(account) accounts_with_type.append(account) return accounts_with_type def __len__(self) -> int:",
"= accounts[1] ... Returns: List[:class:`~ape.api.accounts.TestAccountAPI`] \"\"\" accounts = [] for plugin_name, (container_type, account_type)",
"alias: self._inject_provider(account) return account raise IndexError(f\"No account with alias '{alias}'.\") @singledispatchmethod def __getitem__(self,",
"for plugin_name, (container_type, account_type) in self.plugin_manager.account_types: # Ignore containers that contain test accounts.",
"-> List[TestAccountAPI]: \"\"\" Accounts generated from the configured test mnemonic. These accounts are",
"containers = {} data_folder = self.config.DATA_FOLDER data_folder.mkdir(exist_ok=True) for plugin_name, (container_type, account_type) in self.plugin_manager.account_types:",
"as alias!\") for account in self: if account.alias and account.alias == alias: self._inject_provider(account)",
"**NOTE**: It is generally preferred to use :meth:`~ape.managers.accounts.AccountManager.load` or :meth:`~ape.managers.accounts.AccountManager.__getitem_str`. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\"",
"PluginManager # type: ignore from ape.api.accounts import AccountAPI, AccountContainerAPI, TestAccountAPI from ape.types import",
"import AddressType from ape.utils import cached_property, singledispatchmethod from .config import ConfigManager from .converters",
"in self.containers.values()) def __iter__(self) -> Iterator[AccountAPI]: for container in self.containers.values(): for account in",
"``ape``. Args: address (:class:`~ape.types.AddressType`): The address to check. Returns: bool: ``True`` when the",
"int) -> AccountAPI: \"\"\" Get an account by index. For example, when you",
"by address. Raises: IndexError: When there is no local account with the given",
"``test`` plugin called ``accounts``. Configure these accounts, such as the mnemonic and /",
"for a in self) + \"]\" @cached_property def test_accounts(self) -> List[TestAccountAPI]: \"\"\" Accounts",
"continue accounts_folder = data_folder / plugin_name accounts_folder.mkdir(exist_ok=True) containers[plugin_name] = container_type(accounts_folder, account_type, self.config) return",
"\"\"\" for idx, account in enumerate(self.__iter__()): if account_id == idx: self._inject_provider(account) return account",
"= container[account_id] self._inject_provider(account) return account raise IndexError(f\"No account with address '{account_id}'.\") def __contains__(self,",
"account_id == idx: self._inject_provider(account) return account raise IndexError(f\"No account at index '{account_id}'.\") @__getitem__.register",
"type_: Type[AccountAPI]) -> List[AccountAPI]: \"\"\" Get a list of accounts by their type.",
"self._inject_provider(account) accounts_with_type.append(account) return accounts_with_type def __len__(self) -> int: \"\"\" The number of accounts",
"container: account = container[account_id] self._inject_provider(account) return account raise IndexError(f\"No account with address '{account_id}'.\")",
"subclass :class:`~ape.api.accounts.AccountContainerAPI` and are treated as singletons. Import the accounts manager singleton from",
"return accounts def load(self, alias: str) -> AccountAPI: \"\"\" Get an account by",
"number-of-accounts using the ``test`` section of the `ape-config.yaml` file. Usage example:: def test_my_contract(accounts):",
"config: ConfigManager converters: ConversionManager plugin_manager: PluginManager network_manager: NetworkManager @cached_property def containers(self) -> Dict[str,",
"Get a list of accounts by their type. Args: type_ (Type[:class:`~ape.api.accounts.AccountAPI`]): The type",
"the given address is found. \"\"\" return any(address in container for container in",
"in self: if account.alias and account.alias == alias: self._inject_provider(account) return account raise IndexError(f\"No",
"NetworkManager @cached_property def containers(self) -> Dict[str, AccountContainerAPI]: \"\"\" The list of all :class:`~ape.api.accounts.AccountContainerAPI`",
"plugin. The \"alias\" is part of the :class:`~ape.api.accounts.AccountAPI`. Use the account alias to",
"def __repr__(self) -> str: return \"[\" + \", \".join(repr(a) for a in self)",
"= accounts.load(\"dev\") \"\"\" config: ConfigManager converters: ConversionManager plugin_manager: PluginManager network_manager: NetworkManager @cached_property def",
"these accounts, such as the mnemonic and / or number-of-accounts using the ``test``",
"account by its alias. Raises: IndexError: When there is no local account with",
"container_type(accounts_folder, account_type, self.config) return containers @property def aliases(self) -> Iterator[str]: \"\"\" All account",
"The \"alias\" is part of the :class:`~ape.api.accounts.AccountAPI`. Use the account alias to load",
"IndexError(f\"No account with address '{account_id}'.\") def __contains__(self, address: AddressType) -> bool: \"\"\" Determine",
"local account with the given alias. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" if alias == \"\":",
"and account.alias == alias: self._inject_provider(account) return account raise IndexError(f\"No account with alias '{alias}'.\")",
"account.alias == alias: self._inject_provider(account) return account raise IndexError(f\"No account with alias '{alias}'.\") @singledispatchmethod",
"Returns: dict[str, :class:`~ape.api.accounts.AccountContainerAPI`] \"\"\" containers = {} data_folder = self.config.DATA_FOLDER data_folder.mkdir(exist_ok=True) for plugin_name,",
"accounts, such as the mnemonic and / or number-of-accounts using the ``test`` section",
"test mnemonic. These accounts are also the subject of a fixture available in",
"__getitem__(self, account_id) -> AccountAPI: raise NotImplementedError(f\"Cannot use {type(account_id)} as account ID.\") @__getitem__.register def",
"method as a quicker, ad-hoc way to get an account from that index.",
"\"\"\" The ``AccountManager`` is a container of containers for :class:`~ape.api.accounts.AccountAPI` objects. All containers",
"def __iter__(self) -> Iterator[AccountAPI]: for container in self.containers.values(): for account in container: self._inject_provider(account)",
"for account in container: self._inject_provider(account) accounts.append(account) return accounts def load(self, alias: str) ->",
"empty string as alias!\") for account in self: if account.alias and account.alias ==",
"def __getitem_int(self, account_id: int) -> AccountAPI: \"\"\" Get an account by index. For",
"Get an account by index. For example, when you do the CLI command",
"\"\"\" return any(address in container for container in self.containers.values()) def _inject_provider(self, account: AccountAPI):",
"container of containers for :class:`~ape.api.accounts.AccountAPI` objects. All containers must subclass :class:`~ape.api.accounts.AccountContainerAPI` and are",
"alias!\") for account in self: if account.alias and account.alias == alias: self._inject_provider(account) return",
"AddressType) -> bool: \"\"\" Determine if the given address matches an account in",
"@cached_property def containers(self) -> Dict[str, AccountContainerAPI]: \"\"\" The list of all :class:`~ape.api.accounts.AccountContainerAPI` instances",
"ape.api.accounts import AccountAPI, AccountContainerAPI, TestAccountAPI from ape.types import AddressType from ape.utils import cached_property,",
"-> AccountAPI: \"\"\" Get an account by its alias. Raises: IndexError: When there",
"an account by index. For example, when you do the CLI command ``ape",
"containers @property def aliases(self) -> Iterator[str]: \"\"\" All account aliases from every account-related",
"AccountContainerAPI, TestAccountAPI from ape.types import AddressType from ape.utils import cached_property, singledispatchmethod from .config",
"from .config import ConfigManager from .converters import ConversionManager from .networks import NetworkManager @dataclass",
"raise IndexError(f\"No account with alias '{alias}'.\") @singledispatchmethod def __getitem__(self, account_id) -> AccountAPI: raise",
"container for container in self.containers.values()) def _inject_provider(self, account: AccountAPI): if self.network_manager.active_provider is not",
"for container in self.containers.values(): yield from container.aliases def get_accounts_by_type(self, type_: Type[AccountAPI]) -> List[AccountAPI]:",
"accounts = [] for plugin_name, (container_type, account_type) in self.plugin_manager.account_types: if not issubclass(account_type, TestAccountAPI):",
"accounts.load(\"dev\") \"\"\" config: ConfigManager converters: ConversionManager plugin_manager: PluginManager network_manager: NetworkManager @cached_property def containers(self)",
"@cached_property def test_accounts(self) -> List[TestAccountAPI]: \"\"\" Accounts generated from the configured test mnemonic.",
"in container: self._inject_provider(account) accounts.append(account) return accounts def load(self, alias: str) -> AccountAPI: \"\"\"",
"``AccountManager`` is a container of containers for :class:`~ape.api.accounts.AccountAPI` objects. All containers must subclass",
"'{account_id}'.\") @__getitem__.register def __getitem_str(self, account_str: str) -> AccountAPI: \"\"\" Get an account by",
"load an account using method :meth:`~ape.managers.accounts.AccountManager.load`. Returns: Iterator[str] \"\"\" for container in self.containers.values():",
"plugin_manager: PluginManager network_manager: NetworkManager @cached_property def containers(self) -> Dict[str, AccountContainerAPI]: \"\"\" The list",
"# \"accounts\" is the AccountManager singleton my_accounts = accounts.load(\"dev\") \"\"\" config: ConfigManager converters:",
"method :meth:`~ape.managers.accounts.AccountManager.load`. Returns: Iterator[str] \"\"\" for container in self.containers.values(): yield from container.aliases def",
"its alias. Raises: IndexError: When there is no local account with the given",
"dict[str, :class:`~ape.api.accounts.AccountContainerAPI`] \"\"\" containers = {} data_folder = self.config.DATA_FOLDER data_folder.mkdir(exist_ok=True) for plugin_name, (container_type,",
"if not issubclass(account_type, TestAccountAPI): continue container = container_type(None, account_type, self.config) for account in",
"The type of account to get. Returns: List[:class:`~ape.api.accounts.AccountAPI`] \"\"\" accounts_with_type = [] for",
"Get an account by address. Raises: IndexError: When there is no local account",
"= container_type(accounts_folder, account_type, self.config) return containers @property def aliases(self) -> Iterator[str]: \"\"\" All",
"address: AddressType) -> bool: \"\"\" Determine if the given address matches an account",
"\"\"\" accounts = [] for plugin_name, (container_type, account_type) in self.plugin_manager.account_types: if not issubclass(account_type,",
"singleton from the root ``ape`` namespace. Usage example:: from ape import accounts #",
"# Ignore containers that contain test accounts. if issubclass(account_type, TestAccountAPI): continue accounts_folder =",
"\"\"\" containers = {} data_folder = self.config.DATA_FOLDER data_folder.mkdir(exist_ok=True) for plugin_name, (container_type, account_type) in",
"{type(account_id)} as account ID.\") @__getitem__.register def __getitem_int(self, account_id: int) -> AccountAPI: \"\"\" Get",
"from container.aliases def get_accounts_by_type(self, type_: Type[AccountAPI]) -> List[AccountAPI]: \"\"\" Get a list of",
"= [] for account in self: if isinstance(account, type_): self._inject_provider(account) accounts_with_type.append(account) return accounts_with_type",
"of accounts managed by all account plugins. Returns: int \"\"\" return sum(len(container) for",
"sender = accounts[0] receiver = accounts[1] ... Returns: List[:class:`~ape.api.accounts.TestAccountAPI`] \"\"\" accounts = []",
"import AccountAPI, AccountContainerAPI, TestAccountAPI from ape.types import AddressType from ape.utils import cached_property, singledispatchmethod",
"matches an account in ``ape``. Args: address (:class:`~ape.types.AddressType`): The address to check. Returns:",
"an account by its alias. Raises: IndexError: When there is no local account",
"in self.plugin_manager.account_types: if not issubclass(account_type, TestAccountAPI): continue container = container_type(None, account_type, self.config) for",
"return account raise IndexError(f\"No account at index '{account_id}'.\") @__getitem__.register def __getitem_str(self, account_str: str)",
"if account_id in container: account = container[account_id] self._inject_provider(account) return account raise IndexError(f\"No account",
"aliases(self) -> Iterator[str]: \"\"\" All account aliases from every account-related plugin. The \"alias\"",
"container_type(None, account_type, self.config) for account in container: self._inject_provider(account) accounts.append(account) return accounts def load(self,",
"alias '{alias}'.\") @singledispatchmethod def __getitem__(self, account_id) -> AccountAPI: raise NotImplementedError(f\"Cannot use {type(account_id)} as",
"account raise IndexError(f\"No account with alias '{alias}'.\") @singledispatchmethod def __getitem__(self, account_id) -> AccountAPI:",
":class:`~ape.api.accounts.AccountAPI`. Use the account alias to load an account using method :meth:`~ape.managers.accounts.AccountManager.load`. Returns:",
"of the `ape-config.yaml` file. Usage example:: def test_my_contract(accounts): # The \"accounts\" fixture uses",
"Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" for idx, account in enumerate(self.__iter__()): if account_id == idx: self._inject_provider(account)",
"AccountManager singleton my_accounts = accounts.load(\"dev\") \"\"\" config: ConfigManager converters: ConversionManager plugin_manager: PluginManager network_manager:",
"int: \"\"\" The number of accounts managed by all account plugins. Returns: int",
"self._inject_provider(account) accounts.append(account) return accounts def load(self, alias: str) -> AccountAPI: \"\"\" Get an",
"from the root ``ape`` namespace. Usage example:: from ape import accounts # \"accounts\"",
"is generally preferred to use :meth:`~ape.managers.accounts.AccountManager.load` or :meth:`~ape.managers.accounts.AccountManager.__getitem_str`. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" for idx,",
"-> AccountAPI: raise NotImplementedError(f\"Cannot use {type(account_id)} as account ID.\") @__getitem__.register def __getitem_int(self, account_id:",
"objects. All containers must subclass :class:`~ape.api.accounts.AccountContainerAPI` and are treated as singletons. Import the",
"aliases from every account-related plugin. The \"alias\" is part of the :class:`~ape.api.accounts.AccountAPI`. Use",
"fixture uses the AccountsManager.test_accounts() sender = accounts[0] receiver = accounts[1] ... Returns: List[:class:`~ape.api.accounts.TestAccountAPI`]",
"when the given address is found. \"\"\" return any(address in container for container",
"Args: address (:class:`~ape.types.AddressType`): The address to check. Returns: bool: ``True`` when the given",
"List[:class:`~ape.api.accounts.AccountAPI`] \"\"\" accounts_with_type = [] for account in self: if isinstance(account, type_): self._inject_provider(account)",
"every account-related plugin. The \"alias\" is part of the :class:`~ape.api.accounts.AccountAPI`. Use the account",
"account at index '{account_id}'.\") @__getitem__.register def __getitem_str(self, account_str: str) -> AccountAPI: \"\"\" Get",
"AccountAPI: \"\"\" Get an account by address. Raises: IndexError: When there is no",
"accounts def load(self, alias: str) -> AccountAPI: \"\"\" Get an account by its",
"if account.alias and account.alias == alias: self._inject_provider(account) return account raise IndexError(f\"No account with",
"in the ``test`` plugin called ``accounts``. Configure these accounts, such as the mnemonic",
"file. Usage example:: def test_my_contract(accounts): # The \"accounts\" fixture uses the AccountsManager.test_accounts() sender",
"instances across all installed plugins. Returns: dict[str, :class:`~ape.api.accounts.AccountContainerAPI`] \"\"\" containers = {} data_folder",
"self.plugin_manager.account_types: # Ignore containers that contain test accounts. if issubclass(account_type, TestAccountAPI): continue accounts_folder",
"available in the ``test`` plugin called ``accounts``. Configure these accounts, such as the",
"an account from that index. **NOTE**: It is generally preferred to use :meth:`~ape.managers.accounts.AccountManager.load`",
"idx, account in enumerate(self.__iter__()): if account_id == idx: self._inject_provider(account) return account raise IndexError(f\"No",
"@__getitem__.register def __getitem_int(self, account_id: int) -> AccountAPI: \"\"\" Get an account by index.",
"use empty string as alias!\") for account in self: if account.alias and account.alias",
"address is found. \"\"\" return any(address in container for container in self.containers.values()) def",
"a list of accounts by their type. Args: type_ (Type[:class:`~ape.api.accounts.AccountAPI`]): The type of",
"their indices. Use this method as a quicker, ad-hoc way to get an",
"account in container: self._inject_provider(account) yield account def __repr__(self) -> str: return \"[\" +",
"import dataclass from pluggy import PluginManager # type: ignore from ape.api.accounts import AccountAPI,",
"index. **NOTE**: It is generally preferred to use :meth:`~ape.managers.accounts.AccountManager.load` or :meth:`~ape.managers.accounts.AccountManager.__getitem_str`. Returns: :class:`~ape.api.accounts.AccountAPI`",
"account_id: int) -> AccountAPI: \"\"\" Get an account by index. For example, when",
"Type from dataclassy import dataclass from pluggy import PluginManager # type: ignore from",
"list --all``, you will see a list of enumerated accounts by their indices.",
"list of all :class:`~ape.api.accounts.AccountContainerAPI` instances across all installed plugins. Returns: dict[str, :class:`~ape.api.accounts.AccountContainerAPI`] \"\"\"",
"is part of the :class:`~ape.api.accounts.AccountAPI`. Use the account alias to load an account",
"using the ``test`` section of the `ape-config.yaml` file. Usage example:: def test_my_contract(accounts): #",
"``test`` section of the `ape-config.yaml` file. Usage example:: def test_my_contract(accounts): # The \"accounts\"",
"return accounts_with_type def __len__(self) -> int: \"\"\" The number of accounts managed by",
"List[TestAccountAPI]: \"\"\" Accounts generated from the configured test mnemonic. These accounts are also",
"self.config.DATA_FOLDER data_folder.mkdir(exist_ok=True) for plugin_name, (container_type, account_type) in self.plugin_manager.account_types: # Ignore containers that contain",
"self.containers.values()) def _inject_provider(self, account: AccountAPI): if self.network_manager.active_provider is not None: account.provider = self.network_manager.active_provider",
"with address '{account_id}'.\") def __contains__(self, address: AddressType) -> bool: \"\"\" Determine if the",
"test accounts. if issubclass(account_type, TestAccountAPI): continue accounts_folder = data_folder / plugin_name accounts_folder.mkdir(exist_ok=True) containers[plugin_name]",
"raise IndexError(f\"No account at index '{account_id}'.\") @__getitem__.register def __getitem_str(self, account_str: str) -> AccountAPI:",
"must subclass :class:`~ape.api.accounts.AccountContainerAPI` and are treated as singletons. Import the accounts manager singleton",
"type of account to get. Returns: List[:class:`~ape.api.accounts.AccountAPI`] \"\"\" accounts_with_type = [] for account",
"preferred to use :meth:`~ape.managers.accounts.AccountManager.load` or :meth:`~ape.managers.accounts.AccountManager.__getitem_str`. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" for idx, account in",
"do the CLI command ``ape accounts list --all``, you will see a list",
"accounts # \"accounts\" is the AccountManager singleton my_accounts = accounts.load(\"dev\") \"\"\" config: ConfigManager",
"accounts_folder.mkdir(exist_ok=True) containers[plugin_name] = container_type(accounts_folder, account_type, self.config) return containers @property def aliases(self) -> Iterator[str]:",
"yield from container.aliases def get_accounts_by_type(self, type_: Type[AccountAPI]) -> List[AccountAPI]: \"\"\" Get a list",
"alias. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" if alias == \"\": raise ValueError(\"Cannot use empty string",
"-> str: return \"[\" + \", \".join(repr(a) for a in self) + \"]\"",
"str: return \"[\" + \", \".join(repr(a) for a in self) + \"]\" @cached_property",
"Configure these accounts, such as the mnemonic and / or number-of-accounts using the",
"``ape accounts list --all``, you will see a list of enumerated accounts by",
"address. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" account_id = self.converters.convert(account_str, AddressType) for container in self.containers.values(): if",
"`ape-config.yaml` file. Usage example:: def test_my_contract(accounts): # The \"accounts\" fixture uses the AccountsManager.test_accounts()",
"plugin_name accounts_folder.mkdir(exist_ok=True) containers[plugin_name] = container_type(accounts_folder, account_type, self.config) return containers @property def aliases(self) ->",
"account in self: if isinstance(account, type_): self._inject_provider(account) accounts_with_type.append(account) return accounts_with_type def __len__(self) ->",
"an account in ``ape``. Args: address (:class:`~ape.types.AddressType`): The address to check. Returns: bool:",
"to get. Returns: List[:class:`~ape.api.accounts.AccountAPI`] \"\"\" accounts_with_type = [] for account in self: if",
"if isinstance(account, type_): self._inject_provider(account) accounts_with_type.append(account) return accounts_with_type def __len__(self) -> int: \"\"\" The",
":class:`~ape.api.accounts.AccountAPI` \"\"\" for idx, account in enumerate(self.__iter__()): if account_id == idx: self._inject_provider(account) return",
"== idx: self._inject_provider(account) return account raise IndexError(f\"No account at index '{account_id}'.\") @__getitem__.register def",
"__iter__(self) -> Iterator[AccountAPI]: for container in self.containers.values(): for account in container: self._inject_provider(account) yield",
"\"\"\" Get an account by address. Raises: IndexError: When there is no local",
"installed plugins. Returns: dict[str, :class:`~ape.api.accounts.AccountContainerAPI`] \"\"\" containers = {} data_folder = self.config.DATA_FOLDER data_folder.mkdir(exist_ok=True)",
":class:`~ape.api.accounts.AccountAPI` objects. All containers must subclass :class:`~ape.api.accounts.AccountContainerAPI` and are treated as singletons. Import",
"= container_type(None, account_type, self.config) for account in container: self._inject_provider(account) accounts.append(account) return accounts def",
"quicker, ad-hoc way to get an account from that index. **NOTE**: It is",
"\", \".join(repr(a) for a in self) + \"]\" @cached_property def test_accounts(self) -> List[TestAccountAPI]:",
"self.plugin_manager.account_types: if not issubclass(account_type, TestAccountAPI): continue container = container_type(None, account_type, self.config) for account",
"= self.converters.convert(account_str, AddressType) for container in self.containers.values(): if account_id in container: account =",
"the CLI command ``ape accounts list --all``, you will see a list of",
"check. Returns: bool: ``True`` when the given address is found. \"\"\" return any(address",
"AccountsManager.test_accounts() sender = accounts[0] receiver = accounts[1] ... Returns: List[:class:`~ape.api.accounts.TestAccountAPI`] \"\"\" accounts =",
"local account with the given address. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" account_id = self.converters.convert(account_str, AddressType)",
"will see a list of enumerated accounts by their indices. Use this method",
"containers[plugin_name] = container_type(accounts_folder, account_type, self.config) return containers @property def aliases(self) -> Iterator[str]: \"\"\"",
":class:`~ape.api.accounts.AccountAPI` \"\"\" if alias == \"\": raise ValueError(\"Cannot use empty string as alias!\")",
"IndexError: When there is no local account with the given alias. Returns: :class:`~ape.api.accounts.AccountAPI`",
"called ``accounts``. Configure these accounts, such as the mnemonic and / or number-of-accounts",
"\"accounts\" is the AccountManager singleton my_accounts = accounts.load(\"dev\") \"\"\" config: ConfigManager converters: ConversionManager",
"account plugins. Returns: int \"\"\" return sum(len(container) for container in self.containers.values()) def __iter__(self)",
"from every account-related plugin. The \"alias\" is part of the :class:`~ape.api.accounts.AccountAPI`. Use the",
"there is no local account with the given address. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" account_id",
"account_id in container: account = container[account_id] self._inject_provider(account) return account raise IndexError(f\"No account with",
"by all account plugins. Returns: int \"\"\" return sum(len(container) for container in self.containers.values())",
"AccountAPI: \"\"\" Get an account by index. For example, when you do the",
"a container of containers for :class:`~ape.api.accounts.AccountAPI` objects. All containers must subclass :class:`~ape.api.accounts.AccountContainerAPI` and",
":meth:`~ape.managers.accounts.AccountManager.__getitem_str`. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" for idx, account in enumerate(self.__iter__()): if account_id == idx:",
"given address. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" account_id = self.converters.convert(account_str, AddressType) for container in self.containers.values():",
"def test_accounts(self) -> List[TestAccountAPI]: \"\"\" Accounts generated from the configured test mnemonic. These",
"Raises: IndexError: When there is no local account with the given address. Returns:",
"you will see a list of enumerated accounts by their indices. Use this",
"a quicker, ad-hoc way to get an account from that index. **NOTE**: It",
"the :class:`~ape.api.accounts.AccountAPI`. Use the account alias to load an account using method :meth:`~ape.managers.accounts.AccountManager.load`.",
"import Dict, Iterator, List, Type from dataclassy import dataclass from pluggy import PluginManager",
"idx: self._inject_provider(account) return account raise IndexError(f\"No account at index '{account_id}'.\") @__getitem__.register def __getitem_str(self,",
"part of the :class:`~ape.api.accounts.AccountAPI`. Use the account alias to load an account using",
"account_type) in self.plugin_manager.account_types: # Ignore containers that contain test accounts. if issubclass(account_type, TestAccountAPI):",
"__getitem_int(self, account_id: int) -> AccountAPI: \"\"\" Get an account by index. For example,",
"the AccountsManager.test_accounts() sender = accounts[0] receiver = accounts[1] ... Returns: List[:class:`~ape.api.accounts.TestAccountAPI`] \"\"\" accounts",
"from ape.types import AddressType from ape.utils import cached_property, singledispatchmethod from .config import ConfigManager",
"container in self.containers.values()) def __iter__(self) -> Iterator[AccountAPI]: for container in self.containers.values(): for account",
"AccountAPI: raise NotImplementedError(f\"Cannot use {type(account_id)} as account ID.\") @__getitem__.register def __getitem_int(self, account_id: int)",
"account alias to load an account using method :meth:`~ape.managers.accounts.AccountManager.load`. Returns: Iterator[str] \"\"\" for",
"the subject of a fixture available in the ``test`` plugin called ``accounts``. Configure",
"Returns: List[:class:`~ape.api.accounts.TestAccountAPI`] \"\"\" accounts = [] for plugin_name, (container_type, account_type) in self.plugin_manager.account_types: if",
"self._inject_provider(account) yield account def __repr__(self) -> str: return \"[\" + \", \".join(repr(a) for",
"\"\"\" for container in self.containers.values(): yield from container.aliases def get_accounts_by_type(self, type_: Type[AccountAPI]) ->",
"enumerated accounts by their indices. Use this method as a quicker, ad-hoc way",
"import ConversionManager from .networks import NetworkManager @dataclass class AccountManager: \"\"\" The ``AccountManager`` is",
"is the AccountManager singleton my_accounts = accounts.load(\"dev\") \"\"\" config: ConfigManager converters: ConversionManager plugin_manager:",
"of containers for :class:`~ape.api.accounts.AccountAPI` objects. All containers must subclass :class:`~ape.api.accounts.AccountContainerAPI` and are treated",
"the configured test mnemonic. These accounts are also the subject of a fixture",
"the given address. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" account_id = self.converters.convert(account_str, AddressType) for container in",
"account.alias and account.alias == alias: self._inject_provider(account) return account raise IndexError(f\"No account with alias",
"\"\"\" Get an account by its alias. Raises: IndexError: When there is no",
"account in container: self._inject_provider(account) accounts.append(account) return accounts def load(self, alias: str) -> AccountAPI:",
"data_folder = self.config.DATA_FOLDER data_folder.mkdir(exist_ok=True) for plugin_name, (container_type, account_type) in self.plugin_manager.account_types: # Ignore containers",
"is a container of containers for :class:`~ape.api.accounts.AccountAPI` objects. All containers must subclass :class:`~ape.api.accounts.AccountContainerAPI`",
"container in self.containers.values(): for account in container: self._inject_provider(account) yield account def __repr__(self) ->",
"-> AccountAPI: \"\"\" Get an account by index. For example, when you do",
"container in self.containers.values(): if account_id in container: account = container[account_id] self._inject_provider(account) return account",
"for account in self: if account.alias and account.alias == alias: self._inject_provider(account) return account",
"TestAccountAPI): continue accounts_folder = data_folder / plugin_name accounts_folder.mkdir(exist_ok=True) containers[plugin_name] = container_type(accounts_folder, account_type, self.config)",
"AddressType) for container in self.containers.values(): if account_id in container: account = container[account_id] self._inject_provider(account)",
"from typing import Dict, Iterator, List, Type from dataclassy import dataclass from pluggy",
"List, Type from dataclassy import dataclass from pluggy import PluginManager # type: ignore",
"for account in self: if isinstance(account, type_): self._inject_provider(account) accounts_with_type.append(account) return accounts_with_type def __len__(self)",
"\"\"\" Get an account by index. For example, when you do the CLI",
"self._inject_provider(account) return account raise IndexError(f\"No account with address '{account_id}'.\") def __contains__(self, address: AddressType)",
"\"\"\" Get a list of accounts by their type. Args: type_ (Type[:class:`~ape.api.accounts.AccountAPI`]): The",
"= {} data_folder = self.config.DATA_FOLDER data_folder.mkdir(exist_ok=True) for plugin_name, (container_type, account_type) in self.plugin_manager.account_types: #",
"def __len__(self) -> int: \"\"\" The number of accounts managed by all account",
"any(address in container for container in self.containers.values()) def _inject_provider(self, account: AccountAPI): if self.network_manager.active_provider",
"accounts list --all``, you will see a list of enumerated accounts by their",
"for container in self.containers.values()) def __iter__(self) -> Iterator[AccountAPI]: for container in self.containers.values(): for",
":class:`~ape.api.accounts.AccountContainerAPI` instances across all installed plugins. Returns: dict[str, :class:`~ape.api.accounts.AccountContainerAPI`] \"\"\" containers = {}",
"= self.config.DATA_FOLDER data_folder.mkdir(exist_ok=True) for plugin_name, (container_type, account_type) in self.plugin_manager.account_types: # Ignore containers that",
"is no local account with the given alias. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" if alias",
"\".join(repr(a) for a in self) + \"]\" @cached_property def test_accounts(self) -> List[TestAccountAPI]: \"\"\"",
"\"accounts\" fixture uses the AccountsManager.test_accounts() sender = accounts[0] receiver = accounts[1] ... Returns:",
"== \"\": raise ValueError(\"Cannot use empty string as alias!\") for account in self:",
"at index '{account_id}'.\") @__getitem__.register def __getitem_str(self, account_str: str) -> AccountAPI: \"\"\" Get an",
"containers(self) -> Dict[str, AccountContainerAPI]: \"\"\" The list of all :class:`~ape.api.accounts.AccountContainerAPI` instances across all",
"isinstance(account, type_): self._inject_provider(account) accounts_with_type.append(account) return accounts_with_type def __len__(self) -> int: \"\"\" The number",
"get_accounts_by_type(self, type_: Type[AccountAPI]) -> List[AccountAPI]: \"\"\" Get a list of accounts by their",
"Usage example:: def test_my_contract(accounts): # The \"accounts\" fixture uses the AccountsManager.test_accounts() sender =",
"PluginManager network_manager: NetworkManager @cached_property def containers(self) -> Dict[str, AccountContainerAPI]: \"\"\" The list of",
"test_accounts(self) -> List[TestAccountAPI]: \"\"\" Accounts generated from the configured test mnemonic. These accounts",
"to use :meth:`~ape.managers.accounts.AccountManager.load` or :meth:`~ape.managers.accounts.AccountManager.__getitem_str`. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" for idx, account in enumerate(self.__iter__()):",
"# type: ignore from ape.api.accounts import AccountAPI, AccountContainerAPI, TestAccountAPI from ape.types import AddressType",
"account using method :meth:`~ape.managers.accounts.AccountManager.load`. Returns: Iterator[str] \"\"\" for container in self.containers.values(): yield from",
"given address is found. \"\"\" return any(address in container for container in self.containers.values())",
"IndexError: When there is no local account with the given address. Returns: :class:`~ape.api.accounts.AccountAPI`",
"from ape.api.accounts import AccountAPI, AccountContainerAPI, TestAccountAPI from ape.types import AddressType from ape.utils import",
"example:: from ape import accounts # \"accounts\" is the AccountManager singleton my_accounts =",
"string as alias!\") for account in self: if account.alias and account.alias == alias:",
"accounts[0] receiver = accounts[1] ... Returns: List[:class:`~ape.api.accounts.TestAccountAPI`] \"\"\" accounts = [] for plugin_name,",
"type. Args: type_ (Type[:class:`~ape.api.accounts.AccountAPI`]): The type of account to get. Returns: List[:class:`~ape.api.accounts.AccountAPI`] \"\"\"",
"list of enumerated accounts by their indices. Use this method as a quicker,",
"across all installed plugins. Returns: dict[str, :class:`~ape.api.accounts.AccountContainerAPI`] \"\"\" containers = {} data_folder =",
"by index. For example, when you do the CLI command ``ape accounts list",
"container[account_id] self._inject_provider(account) return account raise IndexError(f\"No account with address '{account_id}'.\") def __contains__(self, address:",
"use {type(account_id)} as account ID.\") @__getitem__.register def __getitem_int(self, account_id: int) -> AccountAPI: \"\"\"",
"an account by address. Raises: IndexError: When there is no local account with",
"\"\"\" return sum(len(container) for container in self.containers.values()) def __iter__(self) -> Iterator[AccountAPI]: for container",
"__len__(self) -> int: \"\"\" The number of accounts managed by all account plugins.",
"accounts.append(account) return accounts def load(self, alias: str) -> AccountAPI: \"\"\" Get an account",
"given address matches an account in ``ape``. Args: address (:class:`~ape.types.AddressType`): The address to",
"= data_folder / plugin_name accounts_folder.mkdir(exist_ok=True) containers[plugin_name] = container_type(accounts_folder, account_type, self.config) return containers @property",
"typing import Dict, Iterator, List, Type from dataclassy import dataclass from pluggy import",
"Dict[str, AccountContainerAPI]: \"\"\" The list of all :class:`~ape.api.accounts.AccountContainerAPI` instances across all installed plugins.",
"accounts by their type. Args: type_ (Type[:class:`~ape.api.accounts.AccountAPI`]): The type of account to get.",
"enumerate(self.__iter__()): if account_id == idx: self._inject_provider(account) return account raise IndexError(f\"No account at index",
"example:: def test_my_contract(accounts): # The \"accounts\" fixture uses the AccountsManager.test_accounts() sender = accounts[0]",
"def get_accounts_by_type(self, type_: Type[AccountAPI]) -> List[AccountAPI]: \"\"\" Get a list of accounts by",
"generated from the configured test mnemonic. These accounts are also the subject of",
"as a quicker, ad-hoc way to get an account from that index. **NOTE**:",
"\"\"\" The list of all :class:`~ape.api.accounts.AccountContainerAPI` instances across all installed plugins. Returns: dict[str,",
"import accounts # \"accounts\" is the AccountManager singleton my_accounts = accounts.load(\"dev\") \"\"\" config:",
"\"[\" + \", \".join(repr(a) for a in self) + \"]\" @cached_property def test_accounts(self)",
"Iterator[str] \"\"\" for container in self.containers.values(): yield from container.aliases def get_accounts_by_type(self, type_: Type[AccountAPI])",
"Use the account alias to load an account using method :meth:`~ape.managers.accounts.AccountManager.load`. Returns: Iterator[str]",
"mnemonic. These accounts are also the subject of a fixture available in the",
"account in self: if account.alias and account.alias == alias: self._inject_provider(account) return account raise",
"ad-hoc way to get an account from that index. **NOTE**: It is generally",
"'{account_id}'.\") def __contains__(self, address: AddressType) -> bool: \"\"\" Determine if the given address",
"self) + \"]\" @cached_property def test_accounts(self) -> List[TestAccountAPI]: \"\"\" Accounts generated from the",
"using method :meth:`~ape.managers.accounts.AccountManager.load`. Returns: Iterator[str] \"\"\" for container in self.containers.values(): yield from container.aliases",
"account from that index. **NOTE**: It is generally preferred to use :meth:`~ape.managers.accounts.AccountManager.load` or",
"It is generally preferred to use :meth:`~ape.managers.accounts.AccountManager.load` or :meth:`~ape.managers.accounts.AccountManager.__getitem_str`. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" for",
"\"\"\" All account aliases from every account-related plugin. The \"alias\" is part of",
"account in ``ape``. Args: address (:class:`~ape.types.AddressType`): The address to check. Returns: bool: ``True``",
"is found. \"\"\" return any(address in container for container in self.containers.values()) def _inject_provider(self,",
"== alias: self._inject_provider(account) return account raise IndexError(f\"No account with alias '{alias}'.\") @singledispatchmethod def",
"there is no local account with the given alias. Returns: :class:`~ape.api.accounts.AccountAPI` \"\"\" if",
"\"\"\" if alias == \"\": raise ValueError(\"Cannot use empty string as alias!\") for",
"\"]\" @cached_property def test_accounts(self) -> List[TestAccountAPI]: \"\"\" Accounts generated from the configured test",
"address to check. Returns: bool: ``True`` when the given address is found. \"\"\"",
"+ \"]\" @cached_property def test_accounts(self) -> List[TestAccountAPI]: \"\"\" Accounts generated from the configured",
"as account ID.\") @__getitem__.register def __getitem_int(self, account_id: int) -> AccountAPI: \"\"\" Get an",
"-> List[AccountAPI]: \"\"\" Get a list of accounts by their type. Args: type_",
"address. Raises: IndexError: When there is no local account with the given address."
] |
[
"number # ------------------------------------------------- # # Return triangle number, return number of factors. #",
"if sqrt*sqrt==n: t -=1 return t result,d,num,_tau=0,0,0,0 while _tau < 500: _t=t(d) _tau=tau(_t)",
"-=1 return t result,d,num,_tau=0,0,0,0 while _tau < 500: _t=t(d) _tau=tau(_t) if result <",
"# While factors less than 500, get the triangle number, # then the",
"500, get the triangle number, # then the factors of that number. #",
"of factors. # While factors less than 500, get the triangle number, #",
"_tau=tau(_t) if result < _tau: result = _tau num=d d+=1 print \"Project Euler",
"(n*(n+1))/2 def tau(n): sqrt,t=int(n**0.5),0 for factor in range(1, sqrt+1): if n % factor",
"------------------------------------------------- # def t(n): return (n*(n+1))/2 def tau(n): sqrt,t=int(n**0.5),0 for factor in range(1,",
"------------------------------------------------- # # Return triangle number, return number of factors. # While factors",
"tau(n): sqrt,t=int(n**0.5),0 for factor in range(1, sqrt+1): if n % factor == 0:",
"while _tau < 500: _t=t(d) _tau=tau(_t) if result < _tau: result = _tau",
"the factors of that number. # ------------------------------------------------- # def t(n): return (n*(n+1))/2 def",
"< _tau: result = _tau num=d d+=1 print \"Project Euler #12:\" print \"The",
"return (n*(n+1))/2 def tau(n): sqrt,t=int(n**0.5),0 for factor in range(1, sqrt+1): if n %",
"sqrt*sqrt==n: t -=1 return t result,d,num,_tau=0,0,0,0 while _tau < 500: _t=t(d) _tau=tau(_t) if",
"sqrt+1): if n % factor == 0: t+=2 if sqrt*sqrt==n: t -=1 return",
"for factor in range(1, sqrt+1): if n % factor == 0: t+=2 if",
"d+=1 print \"Project Euler #12:\" print \"The value of the first triangle number",
"number of factors. # While factors less than 500, get the triangle number,",
"triangle number, # then the factors of that number. # ------------------------------------------------- # def",
"result < _tau: result = _tau num=d d+=1 print \"Project Euler #12:\" print",
"number. # ------------------------------------------------- # def t(n): return (n*(n+1))/2 def tau(n): sqrt,t=int(n**0.5),0 for factor",
"# Return triangle number, return number of factors. # While factors less than",
"While factors less than 500, get the triangle number, # then the factors",
"in range(1, sqrt+1): if n % factor == 0: t+=2 if sqrt*sqrt==n: t",
"t(n): return (n*(n+1))/2 def tau(n): sqrt,t=int(n**0.5),0 for factor in range(1, sqrt+1): if n",
"t+=2 if sqrt*sqrt==n: t -=1 return t result,d,num,_tau=0,0,0,0 while _tau < 500: _t=t(d)",
"less than 500, get the triangle number, # then the factors of that",
"factors less than 500, get the triangle number, # then the factors of",
"if n % factor == 0: t+=2 if sqrt*sqrt==n: t -=1 return t",
"# ------------------------------------------------- # # Return triangle number, return number of factors. # While",
"# then the factors of that number. # ------------------------------------------------- # def t(n): return",
"factor == 0: t+=2 if sqrt*sqrt==n: t -=1 return t result,d,num,_tau=0,0,0,0 while _tau",
"# # Return triangle number, return number of factors. # While factors less",
"that number. # ------------------------------------------------- # def t(n): return (n*(n+1))/2 def tau(n): sqrt,t=int(n**0.5),0 for",
"def tau(n): sqrt,t=int(n**0.5),0 for factor in range(1, sqrt+1): if n % factor ==",
"# ------------------------------------------------- # def t(n): return (n*(n+1))/2 def tau(n): sqrt,t=int(n**0.5),0 for factor in",
"_tau num=d d+=1 print \"Project Euler #12:\" print \"The value of the first",
"t -=1 return t result,d,num,_tau=0,0,0,0 while _tau < 500: _t=t(d) _tau=tau(_t) if result",
"t result,d,num,_tau=0,0,0,0 while _tau < 500: _t=t(d) _tau=tau(_t) if result < _tau: result",
"_tau < 500: _t=t(d) _tau=tau(_t) if result < _tau: result = _tau num=d",
"than 500, get the triangle number, # then the factors of that number.",
"<reponame>Drudoo/Euler<gh_stars>0 # Highly divisible triangular number # ------------------------------------------------- # # Return triangle number,",
"result = _tau num=d d+=1 print \"Project Euler #12:\" print \"The value of",
"_t=t(d) _tau=tau(_t) if result < _tau: result = _tau num=d d+=1 print \"Project",
"< 500: _t=t(d) _tau=tau(_t) if result < _tau: result = _tau num=d d+=1",
"return number of factors. # While factors less than 500, get the triangle",
"if result < _tau: result = _tau num=d d+=1 print \"Project Euler #12:\"",
"get the triangle number, # then the factors of that number. # -------------------------------------------------",
"return t result,d,num,_tau=0,0,0,0 while _tau < 500: _t=t(d) _tau=tau(_t) if result < _tau:",
"factors. # While factors less than 500, get the triangle number, # then",
"factors of that number. # ------------------------------------------------- # def t(n): return (n*(n+1))/2 def tau(n):",
"Highly divisible triangular number # ------------------------------------------------- # # Return triangle number, return number",
"500: _t=t(d) _tau=tau(_t) if result < _tau: result = _tau num=d d+=1 print",
"def t(n): return (n*(n+1))/2 def tau(n): sqrt,t=int(n**0.5),0 for factor in range(1, sqrt+1): if",
"the triangle number, # then the factors of that number. # ------------------------------------------------- #",
"triangular number # ------------------------------------------------- # # Return triangle number, return number of factors.",
"0: t+=2 if sqrt*sqrt==n: t -=1 return t result,d,num,_tau=0,0,0,0 while _tau < 500:",
"% factor == 0: t+=2 if sqrt*sqrt==n: t -=1 return t result,d,num,_tau=0,0,0,0 while",
"\"Project Euler #12:\" print \"The value of the first triangle number is\", t(num)",
"number, return number of factors. # While factors less than 500, get the",
"sqrt,t=int(n**0.5),0 for factor in range(1, sqrt+1): if n % factor == 0: t+=2",
"= _tau num=d d+=1 print \"Project Euler #12:\" print \"The value of the",
"triangle number, return number of factors. # While factors less than 500, get",
"range(1, sqrt+1): if n % factor == 0: t+=2 if sqrt*sqrt==n: t -=1",
"number, # then the factors of that number. # ------------------------------------------------- # def t(n):",
"result,d,num,_tau=0,0,0,0 while _tau < 500: _t=t(d) _tau=tau(_t) if result < _tau: result =",
"then the factors of that number. # ------------------------------------------------- # def t(n): return (n*(n+1))/2",
"Return triangle number, return number of factors. # While factors less than 500,",
"print \"Project Euler #12:\" print \"The value of the first triangle number is\",",
"# def t(n): return (n*(n+1))/2 def tau(n): sqrt,t=int(n**0.5),0 for factor in range(1, sqrt+1):",
"# Highly divisible triangular number # ------------------------------------------------- # # Return triangle number, return",
"_tau: result = _tau num=d d+=1 print \"Project Euler #12:\" print \"The value",
"divisible triangular number # ------------------------------------------------- # # Return triangle number, return number of",
"== 0: t+=2 if sqrt*sqrt==n: t -=1 return t result,d,num,_tau=0,0,0,0 while _tau <",
"of that number. # ------------------------------------------------- # def t(n): return (n*(n+1))/2 def tau(n): sqrt,t=int(n**0.5),0",
"factor in range(1, sqrt+1): if n % factor == 0: t+=2 if sqrt*sqrt==n:",
"num=d d+=1 print \"Project Euler #12:\" print \"The value of the first triangle",
"n % factor == 0: t+=2 if sqrt*sqrt==n: t -=1 return t result,d,num,_tau=0,0,0,0"
] |
[
"repository}, # howpublished = {\\url{https://github.com/AntixK/PyTorch-VAE}} # } from torch import nn from abc",
"= {PyTorch-VAE}, # year = {2020}, # publisher = {GitHub}, # journal =",
"= {GitHub}, # journal = {GitHub repository}, # howpublished = {\\url{https://github.com/AntixK/PyTorch-VAE}} # }",
"# } from torch import nn from abc import abstractmethod from typing import",
"-> None: super(BaseVAE, self).__init__() def encode(self, input: Tensor) -> List[Tensor]: raise NotImplementedError def",
"@misc{Subramanian2020, # author = {<NAME>}, # title = {PyTorch-VAE}, # year = {2020},",
"Tensor) -> List[Tensor]: raise NotImplementedError def decode(self, input: Tensor) -> Any: raise NotImplementedError",
"RuntimeWarning() def generate(self, x: Tensor, **kwargs) -> Tensor: raise NotImplementedError def embed(self, x:",
"*inputs: Tensor) -> Tensor: pass @abstractmethod def loss_function(self, *inputs: Any, **kwargs) -> Tensor:",
"title = {PyTorch-VAE}, # year = {2020}, # publisher = {GitHub}, # journal",
"decode(self, input: Tensor) -> Any: raise NotImplementedError def sample(self, batch_size: int, current_device: int,",
"# year = {2020}, # publisher = {GitHub}, # journal = {GitHub repository},",
"sample(self, batch_size: int, current_device: int, **kwargs) -> Tensor: raise RuntimeWarning() def generate(self, x:",
"def forward(self, *inputs: Tensor) -> Tensor: pass @abstractmethod def loss_function(self, *inputs: Any, **kwargs)",
"super(BaseVAE, self).__init__() def encode(self, input: Tensor) -> List[Tensor]: raise NotImplementedError def decode(self, input:",
"TypeVar(\"torch.tensor\") class BaseVAE(nn.Module): def __init__(self) -> None: super(BaseVAE, self).__init__() def encode(self, input: Tensor)",
"} from torch import nn from abc import abstractmethod from typing import List,",
"Tensor: raise RuntimeWarning() def generate(self, x: Tensor, **kwargs) -> Tensor: raise NotImplementedError def",
"abstractmethod from typing import List, Any, TypeVar Tensor = TypeVar(\"torch.tensor\") class BaseVAE(nn.Module): def",
"{GitHub}, # journal = {GitHub repository}, # howpublished = {\\url{https://github.com/AntixK/PyTorch-VAE}} # } from",
"-> List[Tensor]: raise NotImplementedError def decode(self, input: Tensor) -> Any: raise NotImplementedError def",
"from typing import List, Any, TypeVar Tensor = TypeVar(\"torch.tensor\") class BaseVAE(nn.Module): def __init__(self)",
"Tensor: raise NotImplementedError def embed(self, x: Tensor, **kwargs) -> Tensor: raise NotImplementedError @abstractmethod",
"def decode(self, input: Tensor) -> Any: raise NotImplementedError def sample(self, batch_size: int, current_device:",
"batch_size: int, current_device: int, **kwargs) -> Tensor: raise RuntimeWarning() def generate(self, x: Tensor,",
"def embed(self, x: Tensor, **kwargs) -> Tensor: raise NotImplementedError @abstractmethod def forward(self, *inputs:",
"= TypeVar(\"torch.tensor\") class BaseVAE(nn.Module): def __init__(self) -> None: super(BaseVAE, self).__init__() def encode(self, input:",
"import abstractmethod from typing import List, Any, TypeVar Tensor = TypeVar(\"torch.tensor\") class BaseVAE(nn.Module):",
"x: Tensor, **kwargs) -> Tensor: raise NotImplementedError @abstractmethod def forward(self, *inputs: Tensor) ->",
"{<NAME>}, # title = {PyTorch-VAE}, # year = {2020}, # publisher = {GitHub},",
"by: # @misc{Subramanian2020, # author = {<NAME>}, # title = {PyTorch-VAE}, # year",
"TypeVar Tensor = TypeVar(\"torch.tensor\") class BaseVAE(nn.Module): def __init__(self) -> None: super(BaseVAE, self).__init__() def",
"List, Any, TypeVar Tensor = TypeVar(\"torch.tensor\") class BaseVAE(nn.Module): def __init__(self) -> None: super(BaseVAE,",
"Tensor, **kwargs) -> Tensor: raise NotImplementedError def embed(self, x: Tensor, **kwargs) -> Tensor:",
"raise NotImplementedError @abstractmethod def forward(self, *inputs: Tensor) -> Tensor: pass @abstractmethod def loss_function(self,",
"author = {<NAME>}, # title = {PyTorch-VAE}, # year = {2020}, # publisher",
"= {<NAME>}, # title = {PyTorch-VAE}, # year = {2020}, # publisher =",
"# howpublished = {\\url{https://github.com/AntixK/PyTorch-VAE}} # } from torch import nn from abc import",
"def encode(self, input: Tensor) -> List[Tensor]: raise NotImplementedError def decode(self, input: Tensor) ->",
"howpublished = {\\url{https://github.com/AntixK/PyTorch-VAE}} # } from torch import nn from abc import abstractmethod",
"nn from abc import abstractmethod from typing import List, Any, TypeVar Tensor =",
"from abc import abstractmethod from typing import List, Any, TypeVar Tensor = TypeVar(\"torch.tensor\")",
"-> Tensor: raise NotImplementedError def embed(self, x: Tensor, **kwargs) -> Tensor: raise NotImplementedError",
"None: super(BaseVAE, self).__init__() def encode(self, input: Tensor) -> List[Tensor]: raise NotImplementedError def decode(self,",
"Tensor) -> Any: raise NotImplementedError def sample(self, batch_size: int, current_device: int, **kwargs) ->",
"int, current_device: int, **kwargs) -> Tensor: raise RuntimeWarning() def generate(self, x: Tensor, **kwargs)",
"raise NotImplementedError def embed(self, x: Tensor, **kwargs) -> Tensor: raise NotImplementedError @abstractmethod def",
"Any: raise NotImplementedError def sample(self, batch_size: int, current_device: int, **kwargs) -> Tensor: raise",
"Tensor = TypeVar(\"torch.tensor\") class BaseVAE(nn.Module): def __init__(self) -> None: super(BaseVAE, self).__init__() def encode(self,",
"year = {2020}, # publisher = {GitHub}, # journal = {GitHub repository}, #",
"-> Tensor: raise NotImplementedError @abstractmethod def forward(self, *inputs: Tensor) -> Tensor: pass @abstractmethod",
"int, **kwargs) -> Tensor: raise RuntimeWarning() def generate(self, x: Tensor, **kwargs) -> Tensor:",
"encode(self, input: Tensor) -> List[Tensor]: raise NotImplementedError def decode(self, input: Tensor) -> Any:",
"Any, TypeVar Tensor = TypeVar(\"torch.tensor\") class BaseVAE(nn.Module): def __init__(self) -> None: super(BaseVAE, self).__init__()",
"current_device: int, **kwargs) -> Tensor: raise RuntimeWarning() def generate(self, x: Tensor, **kwargs) ->",
"embed(self, x: Tensor, **kwargs) -> Tensor: raise NotImplementedError @abstractmethod def forward(self, *inputs: Tensor)",
"torch import nn from abc import abstractmethod from typing import List, Any, TypeVar",
"from torch import nn from abc import abstractmethod from typing import List, Any,",
"= {2020}, # publisher = {GitHub}, # journal = {GitHub repository}, # howpublished",
"Tensor: raise NotImplementedError @abstractmethod def forward(self, *inputs: Tensor) -> Tensor: pass @abstractmethod def",
"input: Tensor) -> List[Tensor]: raise NotImplementedError def decode(self, input: Tensor) -> Any: raise",
"NotImplementedError def embed(self, x: Tensor, **kwargs) -> Tensor: raise NotImplementedError @abstractmethod def forward(self,",
"# title = {PyTorch-VAE}, # year = {2020}, # publisher = {GitHub}, #",
"# @misc{Subramanian2020, # author = {<NAME>}, # title = {PyTorch-VAE}, # year =",
"Tensor, **kwargs) -> Tensor: raise NotImplementedError @abstractmethod def forward(self, *inputs: Tensor) -> Tensor:",
"**kwargs) -> Tensor: raise NotImplementedError def embed(self, x: Tensor, **kwargs) -> Tensor: raise",
"publisher = {GitHub}, # journal = {GitHub repository}, # howpublished = {\\url{https://github.com/AntixK/PyTorch-VAE}} #",
"# journal = {GitHub repository}, # howpublished = {\\url{https://github.com/AntixK/PyTorch-VAE}} # } from torch",
"List[Tensor]: raise NotImplementedError def decode(self, input: Tensor) -> Any: raise NotImplementedError def sample(self,",
"provided by: # @misc{Subramanian2020, # author = {<NAME>}, # title = {PyTorch-VAE}, #",
"def sample(self, batch_size: int, current_device: int, **kwargs) -> Tensor: raise RuntimeWarning() def generate(self,",
"# publisher = {GitHub}, # journal = {GitHub repository}, # howpublished = {\\url{https://github.com/AntixK/PyTorch-VAE}}",
"def generate(self, x: Tensor, **kwargs) -> Tensor: raise NotImplementedError def embed(self, x: Tensor,",
"{PyTorch-VAE}, # year = {2020}, # publisher = {GitHub}, # journal = {GitHub",
"Code provided by: # @misc{Subramanian2020, # author = {<NAME>}, # title = {PyTorch-VAE},",
"import nn from abc import abstractmethod from typing import List, Any, TypeVar Tensor",
"= {\\url{https://github.com/AntixK/PyTorch-VAE}} # } from torch import nn from abc import abstractmethod from",
"NotImplementedError def sample(self, batch_size: int, current_device: int, **kwargs) -> Tensor: raise RuntimeWarning() def",
"-> Tensor: raise RuntimeWarning() def generate(self, x: Tensor, **kwargs) -> Tensor: raise NotImplementedError",
"BaseVAE(nn.Module): def __init__(self) -> None: super(BaseVAE, self).__init__() def encode(self, input: Tensor) -> List[Tensor]:",
"raise RuntimeWarning() def generate(self, x: Tensor, **kwargs) -> Tensor: raise NotImplementedError def embed(self,",
"forward(self, *inputs: Tensor) -> Tensor: pass @abstractmethod def loss_function(self, *inputs: Any, **kwargs) ->",
"NotImplementedError def decode(self, input: Tensor) -> Any: raise NotImplementedError def sample(self, batch_size: int,",
"{\\url{https://github.com/AntixK/PyTorch-VAE}} # } from torch import nn from abc import abstractmethod from typing",
"typing import List, Any, TypeVar Tensor = TypeVar(\"torch.tensor\") class BaseVAE(nn.Module): def __init__(self) ->",
"abc import abstractmethod from typing import List, Any, TypeVar Tensor = TypeVar(\"torch.tensor\") class",
"journal = {GitHub repository}, # howpublished = {\\url{https://github.com/AntixK/PyTorch-VAE}} # } from torch import",
"{2020}, # publisher = {GitHub}, # journal = {GitHub repository}, # howpublished =",
"# Code provided by: # @misc{Subramanian2020, # author = {<NAME>}, # title =",
"# author = {<NAME>}, # title = {PyTorch-VAE}, # year = {2020}, #",
"NotImplementedError @abstractmethod def forward(self, *inputs: Tensor) -> Tensor: pass @abstractmethod def loss_function(self, *inputs:",
"raise NotImplementedError def decode(self, input: Tensor) -> Any: raise NotImplementedError def sample(self, batch_size:",
"generate(self, x: Tensor, **kwargs) -> Tensor: raise NotImplementedError def embed(self, x: Tensor, **kwargs)",
"@abstractmethod def forward(self, *inputs: Tensor) -> Tensor: pass @abstractmethod def loss_function(self, *inputs: Any,",
"**kwargs) -> Tensor: raise RuntimeWarning() def generate(self, x: Tensor, **kwargs) -> Tensor: raise",
"class BaseVAE(nn.Module): def __init__(self) -> None: super(BaseVAE, self).__init__() def encode(self, input: Tensor) ->",
"import List, Any, TypeVar Tensor = TypeVar(\"torch.tensor\") class BaseVAE(nn.Module): def __init__(self) -> None:",
"= {GitHub repository}, # howpublished = {\\url{https://github.com/AntixK/PyTorch-VAE}} # } from torch import nn",
"x: Tensor, **kwargs) -> Tensor: raise NotImplementedError def embed(self, x: Tensor, **kwargs) ->",
"raise NotImplementedError def sample(self, batch_size: int, current_device: int, **kwargs) -> Tensor: raise RuntimeWarning()",
"**kwargs) -> Tensor: raise NotImplementedError @abstractmethod def forward(self, *inputs: Tensor) -> Tensor: pass",
"def __init__(self) -> None: super(BaseVAE, self).__init__() def encode(self, input: Tensor) -> List[Tensor]: raise",
"-> Any: raise NotImplementedError def sample(self, batch_size: int, current_device: int, **kwargs) -> Tensor:",
"Tensor) -> Tensor: pass @abstractmethod def loss_function(self, *inputs: Any, **kwargs) -> Tensor: pass",
"self).__init__() def encode(self, input: Tensor) -> List[Tensor]: raise NotImplementedError def decode(self, input: Tensor)",
"{GitHub repository}, # howpublished = {\\url{https://github.com/AntixK/PyTorch-VAE}} # } from torch import nn from",
"__init__(self) -> None: super(BaseVAE, self).__init__() def encode(self, input: Tensor) -> List[Tensor]: raise NotImplementedError",
"input: Tensor) -> Any: raise NotImplementedError def sample(self, batch_size: int, current_device: int, **kwargs)"
] |
[
"deviation (FSTDEV)** The sample variance of the forecasts is defined as .. math::",
"@property def BAGSS(self): \"\"\"Bias Adjusted Gilbert Skill Score (BAGSS)\"\"\" return self.bias_adjusted_gilbert_skill_score(self._f, self._o) @staticmethod",
"A perfect forecast would have MSE = RMSE = 0. MSE can be",
"is a measure of overall bias for continuous variables; in particular ME =",
".. math:: \\tau = \\frac{N_c - N_p}{n(n-1)/2} where NC is the number of",
"sample mean observation, OBAR** the sample mean observation (OBAR) is defined as, ..",
"@staticmethod def root_mean_squared_error(error): \"\"\"**Root-mean-squared error (RMSE)** RMSE is simply the square root of",
"fcsterr is not None: logger.warning(\"You give forecast, obs and fcsterr, but the fcsterr",
"------- numpy.ndarray, The Mean Error (ME) \"\"\" return np.average(error) @property def ME2(self): \"\"\"**The",
"ME^2 + s^{2}_{f-o}` To understand the behavior of MSE, it is important to",
"obs, group) @property def FBAR(self): \"\"\"**The sample mean forecast, FBAR**\"\"\" return self.mean_forecast(self._f) @staticmethod",
"r\"\"\"**The sample mean observation, OBAR** the sample mean observation (OBAR) is defined as,",
"numpy.ndarray, Root-mean-squared error (RMSE) \"\"\" return np.sqrt(np.average(error ** 2)) @property def ESTDEV(self): \"\"\"**Standard",
"def IQR(self): \"\"\"\"**Inter Quartile Range of the Errors (IQR)**\"\"\" return self.inter_quartile_range_of_errors(self.error) @staticmethod def",
"of the errors Percentiles of the errors provide more information about the distribution",
"'KT_CORR', 'MBIAS', ] super(ContinuousVariableVerification, self).__init__(forecast, obs, group) @property def FBAR(self): \"\"\"**The sample mean",
"np.square(np.std(error)) @property def MAE(self): \"\"\"**Mean Absolute Error (MAE)**\"\"\" return self.mean_absolute_error(self.error) @staticmethod def mean_absolute_error(error):",
"------- numpy.ndarray, Percentiles of the errors \"\"\" quantiles = np.array([0.1, 0.25, 0.5, 0.75,",
"forecast-observation squared differences. Returns ------- numpy.ndarray, Bias-Corrected MSE (BCMSE) \"\"\" return np.square(np.std(error)) @property",
"MSE, rather than examining MSE alone. Moreover, MSE can be strongly influenced by",
"None: raise Exception(\"Initialize failed, check forecast and obs and fcsterr values.\") elif forecast",
":math:`\\rho_s` ) is a robust measure of association that is based on the",
"Quartile Range of the Errors (IQR)**\"\"\" return self.inter_quartile_range_of_errors(self.error) @staticmethod def inter_quartile_range_of_errors(error): r\"\"\"**Inter Quartile",
"# @Date: 2020/6/10 14:43 # @Last Modified by: wqshen import numpy as np",
"math:: MSE = (\\bar{f} - \\bar{o})^2 + s^{2}_{f} + s^{2}_{o} -2 s_f s_o",
"= forecast - fcsterr # Not Available, 'BAGSS', 'ANOM_CORR' self._available_score += ['FBAR', 'OBAR',",
"between the forecasts and observations. The Pearson correlation coefficient is defined as: ..",
"to compute a correlation cofficient, analogous to the Pearson correlation cofficient, **r**. A",
"Error Squared** (ME2)\"\"\" return self.mean_error_squared(self.error) @staticmethod def mean_error_squared(error): \"\"\"**The Mean Error Squared** (ME2)",
"**r**, the Spearman rank correlation coe cient ranges between -1 and 1; a",
"deviation (OSTDEV)** The sample variance of the observations is defined as .. math::",
"of the error, as detailed below in the section on BCMSE. It is",
"mean_error_squared(error): \"\"\"**The Mean Error Squared** (ME2) The Mean Error Squared, ME2, is provided",
"of the errors. Percentiles are computed by ordering the errors from smallest to",
"obs) @property def ME(self): \"\"\"**The Mean Error (ME)**\"\"\" return self.mean_error(self.error) @staticmethod def mean_error(error):",
"of MSE, it is important to examine both of the terms of MSE,",
"\"\"\"**The Mean Error (ME)**\"\"\" return self.mean_error(self.error) @staticmethod def mean_error(error): r\"\"\"**The Mean Error (ME)**",
"Error Squared** (ME2) The Mean Error Squared, ME2, is provided to give a",
"perfect negative correlation. - A value of 0 indicates that the forecast and",
"implemented \"\"\" return def list_score(self): \"\"\"list all available score\"\"\" return {k: np.round(getattr(self, k),",
"Deviation (MAD) \"\"\" return np.median(np.abs(error)) @property def BAGSS(self): \"\"\"Bias Adjusted Gilbert Skill Score",
"Gilbert Skill Score (BAGSS)\"\"\" return self.bias_adjusted_gilbert_skill_score(self._f, self._o) @staticmethod def bias_adjusted_gilbert_skill_score(forecast, obs): \"\"\"Bias Adjusted",
"def ME2(self): \"\"\"**The Mean Error Squared** (ME2)\"\"\" return self.mean_error_squared(self.error) @staticmethod def mean_error_squared(error): \"\"\"**The",
"): .. math:: \\rho_s = \\frac{6}{n(n^2 - 1)}\\sum^{n}_{i=1}d^{2}_{i} Like **r**, the Spearman rank",
"observed standard deviation, OSTDEV, is defined as .. math:: s_{o} = \\sqrt{s^{2}_{o}} Returns",
"number of pairs) are assigned. The pairs of forecast-observed ranks are then used",
"None or obs is None) and fcsterr is None: raise Exception(\"Initialize failed, check",
"\\tau = \\frac{N_c - N_p}{n(n-1)/2} where NC is the number of \"concordant\" pairs",
"ME` and :math:`s^{2}_{f} + s^{2}_{o} -2 s_f s_o r_{fo}` is the estimated variance",
"\\frac{\\sum^{T}_{i=1}(f_i - \\bar{f})(o_i - \\bar{o})}{\\sqrt{\\sum{(f_i - \\bar{f})^2}}\\sqrt{\\sum{(o_i - \\bar{o})^2}}} r can range between",
"r\"\"\"**Bias-Corrected MSE (BCMSE)** MSE and RMSE are strongly impacted by large errors. They",
"math:: s^{2}_{o} = \\frac{1}{T-1}\\sum_{i=1}^{T}(o_i - \\bar{o})^2 The observed standard deviation, OSTDEV, is defined",
"return self.mean_error(self.error) @staticmethod def mean_error(error): r\"\"\"**The Mean Error (ME)** The Mean Error, ME,",
"inter_quartile_range_of_errors(error): r\"\"\"**Inter Quartile Range of the Errors (IQR)** The Inter Quartile Range of",
"is provided to give a complete breakdown of MSE in terms of squared",
"examining MSE alone. Moreover, MSE can be strongly influenced by ME, as shown",
"defined as :math:`MAD=median|f_i - o_i|` MAD is an estimate of spread, similar to",
"return np.std(forecast) @property def OSTDEV(self): r\"\"\"**The observed standard deviation (OSTDEV)**\"\"\" return self.observation_standard_deviation(self._o) @staticmethod",
"25) @property def MAD(self): \"\"\"Median Absolute Deviation (MAD)\"\"\" return self.median_absolute_deviation(self.error) @staticmethod def median_absolute_deviation(error):",
"counts adjusted to eliminate as much bias in the forecast as possible. For",
"(\\bar{f} - \\bar{o})^2 + s^{2}_{f} + s^{2}_{o} -2 s_f s_o r_{fo} where :math:`\\bar{f}",
"forecast standard deviation (FSTDEV)**\"\"\" return self.forecast_standard_deviation(self._f) @staticmethod def forecast_standard_deviation(forecast): r\"\"\"**The forecast standard deviation",
"the error (ESTDEV2) is sometimes called the \"Bias-corrected MSE\" (BCMSE) because it removes",
"simply the square root of the MSE, :math:`RMSE = \\sqrt{MSE}` Returns ------- numpy.ndarray,",
"Score (BAGSS)\"\"\" return self.bias_adjusted_gilbert_skill_score(self._f, self._o) @staticmethod def bias_adjusted_gilbert_skill_score(forecast, obs): \"\"\"Bias Adjusted Gilbert Skill",
"\\bar{o})}{\\sqrt{\\sum{(f_i - \\bar{f})^2}}\\sqrt{\\sum{(o_i - \\bar{o})^2}}} r can range between -1 and 1; a",
"r\"\"\"**Inter Quartile Range of the Errors (IQR)** The Inter Quartile Range of the",
"defined as .. math:: ME = \\frac{1}{n}\\sum^{n}_{i=1}(f_i - o_i) = \\bar{f} - \\bar{o}",
"\"\"\" quantiles = np.array([0.1, 0.25, 0.5, 0.75, 0.9]) return np.quantile(error, quantiles) @property def",
"@staticmethod def mean_squared_error(error): r\"\"\"**Mean-squared error (MSE)** MSE measures the average squared error of",
"(0.1, 0.25, 0.5, 0.75, 0.9) of the errors\"\"\" return self.percentile_errors(self.error) @staticmethod def percentile_errors(error):",
"of the means of the forecasts and the observations: .. math:: MBIAS =",
"observations are not correlated. Returns ------- numpy.ndarray, the Spearman correlation coefficient (SP_CORR) \"\"\"",
"def inter_quartile_range_of_errors(error): r\"\"\"**Inter Quartile Range of the Errors (IQR)** The Inter Quartile Range",
".. math:: MBIAS = \\frac{\\bar{f}}{\\bar{o}} Returns ------- numpy.ndarray, Multiplicative bias (MBIAS) \"\"\" return",
"Thus, :math:`MSE = ME^2 + s^{2}_{f-o}` To understand the behavior of MSE, it",
"np.square(np.average(error)) @property def MBIAS(self): \"\"\"**Multiplicative bias (MBIAS)**\"\"\" return self.multiplicative_bias(self._f, self._o) @staticmethod def multiplicative_bias(forecast,",
"values of **f** and **o** are both larger than the value for the",
"similar to standard error, but is less in uenced by large errors and",
"by large bias (ME) values. MSE and RMSE can range from 0 to",
"possible. For details, see `Brill and Messinger, 2009. <https://www.adv-geosci.net/16/137/2008/>`_ Returns ------- Not implemented",
"if (forecast is None or obs is None) and fcsterr is None: raise",
"errors. They also are strongly impacted by large bias (ME) values. MSE and",
"MSE can be strongly influenced by ME, as shown by this decomposition. The",
"is based on differences between the each of the pairs of ranks (denoted",
"\"\"\" return np.square(np.std(error)) @property def MAE(self): \"\"\"**Mean Absolute Error (MAE)**\"\"\" return self.mean_absolute_error(self.error) @staticmethod",
"( :math:`\\tau` ) is a robust measure of the level of association between",
"\"\"\" return np.average(error) @property def ME2(self): \"\"\"**The Mean Error Squared** (ME2)\"\"\" return self.mean_error_squared(self.error)",
"the errors\"\"\" return self.percentile_errors(self.error) @staticmethod def percentile_errors(error): \"\"\"Percentiles of the errors Percentiles of",
"obs)[1, 0] @property def SP_CORR(self): r\"\"\"**The Spearman rank correlation coefficient ( :math:`\\rho_s` ,",
"of linear association between the forecasts and observations. The Pearson correlation coefficient is",
"provide more information about the distribution of errors than can be obtained from",
"numpy.ndaray, Standard deviation of the error \"\"\" return np.std(error) @property def BCMSE(self): \"\"\"**Bias-Corrected",
"\"concordant\" pairs and ND is the number of \"discordant\" pairs. Concordant pairs are",
"of the standard deviation of the error (ESTDEV2) is sometimes called the \"Bias-corrected",
"'MBIAS', ] super(ContinuousVariableVerification, self).__init__(forecast, obs, group) @property def FBAR(self): \"\"\"**The sample mean forecast,",
"ME2. A perfect forecast has ME2 = 0. Returns ------- numpy.ndarray, The Mean",
"both of the terms of MSE, rather than examining MSE alone. Moreover, MSE",
"\\frac{\\sum{(f_i - c)(o_i - c)}} {\\sqrt{\\sum{(f_i - c)^2}} \\sqrt{\\sum{(o_i - c)^2}}} Anomaly correlation",
"Absolute Deviation (MAD)\"\"\" return self.median_absolute_deviation(self.error) @staticmethod def median_absolute_deviation(error): \"\"\"Median Absolute Deviation (MAD) The",
"\"Bias-corrected MSE\" (BCMSE) because it removes the effect of overall bias from the",
"------- numpy.ndarray, the Spearman correlation coefficient (SP_CORR) \"\"\" from scipy.stats import spearmanr return",
"is .. math:: s_{f-o}=\\sqrt{s^{2}_{f-o}}=\\sqrt{s^{2}_{f} + s^{2}_{o} -2 s_f s_o r_{fo}} Note that the",
"0.9) of the errors\"\"\" return self.percentile_errors(self.error) @staticmethod def percentile_errors(error): \"\"\"Percentiles of the errors",
"The Bias Adjusted Gilbert Skill Score (BAGSS) is the Gilbert Skill Score, but",
"obs if obs is None: obs = forecast - fcsterr # Not Available,",
"0. MSE can be re-written as, .. math:: MSE = (\\bar{f} - \\bar{o})^2",
"None: forecast = fcsterr + obs if obs is None: obs = forecast",
"obtained from the mean and standard deviations of the errors. Percentiles are computed",
"A perfect forecast has ME = 0. Returns ------- numpy.ndarray, The Mean Error",
"ignored.\") fcsterr = None self._available_score = ['N', 'ME', 'ME2', 'MSE', 'RMSE', 'ESTDEV', 'BCMSE',",
"as np from logzero import logger from .point_stat_base import PointStatBase class ContinuousVariableVerification(PointStatBase): def",
"+ s^{2}_{o} -2 s_f s_o r_{fo}` is the estimated variance of the error,",
"def standard_deviation_of_error(error): \"\"\"**Standard deviation of the error** (ESTDEV) Returns ------- numpy.ndaray, Standard deviation",
"of the errors are computed. Returns ------- numpy.ndarray, Percentiles of the errors \"\"\"",
"It measures the strength of linear association between the forecast anomolies and observed",
"or obs is None) and fcsterr is None: raise Exception(\"Initialize failed, check forecast",
"of association that is based on the ranks of the forecast and observed",
"association between the forecasts and observations. The Pearson correlation coefficient is defined as:",
"(FBAR) is defined as, .. math:: \\bar{f} = \\frac{1}{n}\\sum_{i=1}^{n}f_i Returns ------ numpy.ndarray, the",
"statistic ( :math:`\\tau` , KT_CORR)** Kendall's Tau statistic ( :math:`\\tau` ) is a",
"MAE is less in uenced by large errors and also does not depend",
"Error (MAE) \"\"\" return np.average(np.abs(error)) @property def IQR(self): \"\"\"\"**Inter Quartile Range of the",
"negative correlation. - A value of 0 indicates that the forecast and observed",
"return np.average(obs) @property def FSTDEV(self): \"\"\"**The forecast standard deviation (FSTDEV)**\"\"\" return self.forecast_standard_deviation(self._f) @staticmethod",
"\"\"\"The Anomaly correlation coefficient (ANOM_CORR)\"\"\" return self.anomaly_correlation_coefficient(self._f, self._o, None) @staticmethod def anomaly_correlation_coefficient(forecast, obs,",
"( :math:`\\tau` , KT_CORR)**\"\"\" return self.kendall_tau_statistic(self._f, self._o) @staticmethod def kendall_tau_statistic(forecast, obs): r\"\"\"**Kendall's Tau",
"\\frac{1}{T-1}\\sum_{i=1}^{T}(f_i - \\bar{f})^2 The forecast standard deviation, FSTDEV, is defined as .. math::",
"def multiplicative_bias(forecast, error): r\"\"\"**Multiplicative bias (MBIAS)** Multiplicative bias is simply the ratio of",
"mean error. A perfect forecast would have IQR = 0. Returns ------- nupmy.ndarray,",
"linear association between the forecast anomolies and observed anomalies. The Anomaly correlation coefficient",
"the counts for all pairs. The total number of possible pairs is ;",
"defined as .. math:: s_{f} = \\sqrt{s^{2}_{f}} Returns ------- numpy.ndarray, the forecast standard",
":math:`\\tau` , KT_CORR)**\"\"\" return self.kendall_tau_statistic(self._f, self._o) @staticmethod def kendall_tau_statistic(forecast, obs): r\"\"\"**Kendall's Tau statistic",
"samples are ordered from smallest to largest and rank values (from 1 to",
". Like **r** and :math:`\\rho_s` , Kendall's Tau ( :math:`\\tau` ) ranges between",
"numpy.ndarray, the observed standard deviation (OSTDEV) \"\"\" return np.std(obs) @property def PR_CORR(self): r\"\"\"**The",
"is not None: logger.warning(\"You give forecast, obs and fcsterr, but the fcsterr will",
"the error** (ESTDEV)\"\"\" return self.standard_deviation_of_error(self.error) @staticmethod def standard_deviation_of_error(error): \"\"\"**Standard deviation of the error**",
"a climatology (**c**) of some variety. It measures the strength of linear association",
"of 0 indicates that the forecasts and observations are not correlated. Returns -------",
"Returns ------- numpy.ndarray, The Mean Error (ME) \"\"\" return np.average(error) @property def ME2(self):",
"for the current pair). Once this is done, Nc is computed by summing",
"------- numpy.ndarray, Multiplicative bias (MBIAS) \"\"\" return np.average(forecast) / np.average(error) @property def MSE(self):",
"the 75th and 25th percentiles of the errors. It is de ned as",
"variables; in particular ME = Bias. It is defined as .. math:: ME",
"that both the forecasts and observations are first adjusted according to a climatology",
"breakdown of MSE in terms of squared Bias plus estimated variance of the",
"mean observation (OBAR) \"\"\" return np.average(obs) @property def FSTDEV(self): \"\"\"**The forecast standard deviation",
"fcsterr = None self._available_score = ['N', 'ME', 'ME2', 'MSE', 'RMSE', 'ESTDEV', 'BCMSE', 'MAE',",
"Mean Absolute Error (MAE) is defined as :math:`MAE = \\frac{1}{n}\\sum{|f_i - o_i|}` MAE",
"the forecasts and observations are not associated. Returns ------- numpy.ndarray, Kendall's Tau statistic",
"forecasts and observations are not associated. Returns ------- numpy.ndarray, Kendall's Tau statistic (",
"pair with all other pairs in the sample; this can be done most",
"s^{2}_{f-o}` To understand the behavior of MSE, it is important to examine both",
"error. A perfect forecast would have MAE = 0. Returns ------- numpy.ndarray, Mean",
"Mean-squared error (MSE) \"\"\" return np.average(error ** 2) @property def RMSE(self): \"\"\"**Root-mean-squared error",
"return self.mean_absolute_error(self.error) @staticmethod def mean_absolute_error(error): r\"\"\"**Mean Absolute Error (MAE)** The Mean Absolute Error",
"(BCMSE) \"\"\" return np.square(np.std(error)) @property def MAE(self): \"\"\"**Mean Absolute Error (MAE)**\"\"\" return self.mean_absolute_error(self.error)",
"forecast = fcsterr + obs if obs is None: obs = forecast -",
"the forecasts and observations are not correlated. Returns ------- numpy.ndarray, the Pearson correlation",
"numpy.ndarray, Multiplicative bias (MBIAS) \"\"\" return np.average(forecast) / np.average(error) @property def MSE(self): \"\"\"**Mean-squared",
"\"\"\"**Multiplicative bias (MBIAS)**\"\"\" return self.multiplicative_bias(self._f, self._o) @staticmethod def multiplicative_bias(forecast, error): r\"\"\"**Multiplicative bias (MBIAS)**",
"That is, the forecast and observed samples are ordered from smallest to largest",
"np.average(error ** 2) @property def RMSE(self): \"\"\"**Root-mean-squared error (RMSE)**\"\"\" return self.root_mean_squared_error(self.error) @staticmethod def",
"@staticmethod def mean_absolute_error(error): r\"\"\"**Mean Absolute Error (MAE)** The Mean Absolute Error (MAE) is",
"MBIAS(self): \"\"\"**Multiplicative bias (MBIAS)**\"\"\" return self.multiplicative_bias(self._f, self._o) @staticmethod def multiplicative_bias(forecast, error): r\"\"\"**Multiplicative bias",
"= 0. Returns ------- numpy.ndarray, Mean Absolute Error (MAE) \"\"\" return np.average(np.abs(error)) @property",
"ME2 = 0. Returns ------- numpy.ndarray, The Mean Error (ME) \"\"\" return np.square(np.average(error))",
"order. The number of concordant matches of a particular pair with other pairs",
"(IQR) \"\"\" return np.percentile(error, 75) - np.percentile(error, 25) @property def MAD(self): \"\"\"Median Absolute",
"@staticmethod def bias_corrected_mse(error): r\"\"\"**Bias-Corrected MSE (BCMSE)** MSE and RMSE are strongly impacted by",
"forecast, FBAR**\"\"\" return self.mean_forecast(self._f) @staticmethod def mean_forecast(forecast): r\"\"\"**The sample mean forecast, FBAR** the",
"(BAGSS) \"\"\" return @property def EPCT(self): \"\"\"Percentiles (0.1, 0.25, 0.5, 0.75, 0.9) of",
"= \\sqrt{MSE}` Returns ------- numpy.ndarray, Root-mean-squared error (RMSE) \"\"\" return np.sqrt(np.average(error ** 2))",
"measure of the level of association between the forecast and observation pairs. It",
"rank to the actual value. Percentiles can also be used to create box",
"@staticmethod def spearman_rank_correlation_cofficient(forecast, obs): r\"\"\"**The Spearman rank correlation coefficient ( :math:`\\rho_s` , SP_CORR)**",
"wqshen # @Email: <EMAIL> # @Date: 2020/6/10 14:43 # @Last Modified by: wqshen",
"# Not Available, 'BAGSS', 'ANOM_CORR' self._available_score += ['FBAR', 'OBAR', 'FSTDEV', 'OSTDEV', 'PR_CORR', 'SP_CORR',",
"Returns ------- numpy.ndarray, the forecast standard deviation (FSTDEV) \"\"\" return np.std(forecast) @property def",
"as .. math:: s^{2}_{f} = \\frac{1}{T-1}\\sum_{i=1}^{T}(f_i - \\bar{f})^2 The forecast standard deviation, FSTDEV,",
"of 1 indicates perfect correlation and a value of -1 indicates perfect negative",
"'PR_CORR', 'SP_CORR', 'KT_CORR', 'MBIAS', ] super(ContinuousVariableVerification, self).__init__(forecast, obs, group) @property def FBAR(self): \"\"\"**The",
"but the fcsterr will be ignored.\") fcsterr = None self._available_score = ['N', 'ME',",
"the mean error. A perfect forecast would have MAE = 0. Returns -------",
"the observations: .. math:: MBIAS = \\frac{\\bar{f}}{\\bar{o}} Returns ------- numpy.ndarray, Multiplicative bias (MBIAS)",
"+ s^{2}_{o} -2 s_f s_o r_{fo}} Note that the square of the standard",
"return kendalltau(forecast, obs) @property def ME(self): \"\"\"**The Mean Error (ME)**\"\"\" return self.mean_error(self.error) @staticmethod",
"defined as .. math:: s^{2}_{o} = \\frac{1}{T-1}\\sum_{i=1}^{T}(o_i - \\bar{o})^2 The observed standard deviation,",
"total number of pairs) are assigned. The pairs of forecast-observed ranks are then",
"obs): \"\"\"Bias Adjusted Gilbert Skill Score (BAGSS) The Bias Adjusted Gilbert Skill Score",
"bias from the forecast-observation squared differences. Returns ------- numpy.ndarray, Bias-Corrected MSE (BCMSE) \"\"\"",
"<EMAIL> # @Date: 2020/6/10 14:43 # @Last Modified by: wqshen import numpy as",
"r\"\"\"**The sample mean forecast, FBAR** the sample mean forecast (FBAR) is defined as,",
"def __init__(self, forecast=None, obs=None, fcsterr=None, group=None): if (forecast is None or obs is",
"ContinuousVariableVerification(PointStatBase): def __init__(self, forecast=None, obs=None, fcsterr=None, group=None): if (forecast is None or obs",
"- fcsterr # Not Available, 'BAGSS', 'ANOM_CORR' self._available_score += ['FBAR', 'OBAR', 'FSTDEV', 'OSTDEV',",
"Tau ( :math:`\\tau` ) ranges between -1 and 1; a value of 1",
"------- Not implemented \"\"\" return def list_score(self): \"\"\"list all available score\"\"\" return {k:",
"{\\sqrt{\\sum{(f_i - c)^2}} \\sqrt{\\sum{(o_i - c)^2}}} Anomaly correlation can range between -1 and",
"MSE alone. Moreover, MSE can be strongly influenced by ME, as shown by",
"observed standard deviation (OSTDEV) \"\"\" return np.std(obs) @property def PR_CORR(self): r\"\"\"**The Pearson correlation",
"\\bar{f})^2}}\\sqrt{\\sum{(o_i - \\bar{o})^2}}} r can range between -1 and 1; a value of",
"# @Email: <EMAIL> # @Date: 2020/6/10 14:43 # @Last Modified by: wqshen import",
"by ordering all of the ( :math:`f_i, o_i` ) pairs according to :math:`f_i`,",
"variance of the forecasts is defined as .. math:: s^{2}_{f} = \\frac{1}{T-1}\\sum_{i=1}^{T}(f_i -",
"of pairs (with larger values) for which the value of oi for the",
"and observations are not associated. Returns ------- numpy.ndarray, Kendall's Tau statistic ( :math:`\\tau`",
"both larger than the value for the current pair). Once this is done,",
"self).__init__(forecast, obs, group) @property def FBAR(self): \"\"\"**The sample mean forecast, FBAR**\"\"\" return self.mean_forecast(self._f)",
"correlation. - A value of 0 indicates that the forecast and observed anomalies",
"0.9]) return np.quantile(error, quantiles) @property def ANOM_CORR(self): \"\"\"The Anomaly correlation coefficient (ANOM_CORR)\"\"\" return",
"the rank to the actual value. Percentiles can also be used to create",
"(IQR)** The Inter Quartile Range of the Errors (IQR) is the difference between",
"from scipy.stats import spearmanr return spearmanr(forecast, obs) @property def KT_CORR(self): r\"\"\"**Kendall's Tau statistic",
"ordered from smallest to largest and rank values (from 1 to **n**, where",
"The Pearson correlation coefficient is defined as: .. math:: r = \\frac{\\sum^{T}_{i=1}(f_i -",
"the sample mean forecast (FBAR) \"\"\" return np.average(forecast) @property def OBAR(self): \"\"\"**The sample",
"ESTDEV(self): \"\"\"**Standard deviation of the error** (ESTDEV)\"\"\" return self.standard_deviation_of_error(self.error) @staticmethod def standard_deviation_of_error(error): \"\"\"**Standard",
"r_{fo} where :math:`\\bar{f} - \\bar{o} = ME` and :math:`s^{2}_{f} + s^{2}_{o} -2 s_f",
"much bias in the forecast as possible. For details, see `Brill and Messinger,",
"to :math:`f_i`, in which case the :math:`o_i`, values won't necessarily be in order.",
"standard deviation, OSTDEV, is defined as .. math:: s_{o} = \\sqrt{s^{2}_{o}} Returns -------",
"Bias plus estimated variance of the error, as detailed below in the section",
"self.median_absolute_deviation(self.error) @staticmethod def median_absolute_deviation(error): \"\"\"Median Absolute Deviation (MAD) The Median Absolute Deviation (MAD)",
"= (\\bar{f} - \\bar{o})^2 + s^{2}_{f} + s^{2}_{o} -2 s_f s_o r_{fo} where",
"other pairs is computed by counting the number of pairs (with larger values)",
"in particular ME = Bias. It is defined as .. math:: ME =",
"Squared, ME2, is provided to give a complete breakdown of MSE in terms",
"return np.std(obs) @property def PR_CORR(self): r\"\"\"**The Pearson correlation coefficient ( :math:`r` , PR_CORR)**\"\"\"",
"is simply the ratio of the means of the forecasts and the observations:",
"numpy.ndarray, The Mean Error (ME) \"\"\" return np.square(np.average(error)) @property def MBIAS(self): \"\"\"**Multiplicative bias",
"that the square of the standard deviation of the error (ESTDEV2) is sometimes",
"to the Pearson correlation cofficient, **r**. A simpler formulation of the Spearman-rank correlation",
"create box plots of the errors. The 0.10th, 0.25th, 0.50th, 0.75th, and 0.90th",
"self.bias_adjusted_gilbert_skill_score(self._f, self._o) @staticmethod def bias_adjusted_gilbert_skill_score(forecast, obs): \"\"\"Bias Adjusted Gilbert Skill Score (BAGSS) The",
"Returns ------- numpy.ndarray, Kendall's Tau statistic ( :math:`\\tau` , KT_CORR) \"\"\" from scipy.stats",
"Returns ------- numpy.ndarray, The Mean Error (ME) \"\"\" return np.square(np.average(error)) @property def MBIAS(self):",
"\"\"\"**The Mean Error Squared** (ME2)\"\"\" return self.mean_error_squared(self.error) @staticmethod def mean_error_squared(error): \"\"\"**The Mean Error",
"(MAE)**\"\"\" return self.mean_absolute_error(self.error) @staticmethod def mean_absolute_error(error): r\"\"\"**Mean Absolute Error (MAE)** The Mean Absolute",
"not depend on the mean error. A perfect forecast would have MAE =",
"it is important to examine both of the terms of MSE, rather than",
"'OSTDEV', 'PR_CORR', 'SP_CORR', 'KT_CORR', 'MBIAS', ] super(ContinuousVariableVerification, self).__init__(forecast, obs, group) @property def FBAR(self):",
"all of the ( :math:`f_i, o_i` ) pairs according to :math:`f_i`, in which",
"observation pairs. It is defined as .. math:: \\tau = \\frac{N_c - N_p}{n(n-1)/2}",
"from scipy.stats import kendalltau return kendalltau(forecast, obs) @property def ME(self): \"\"\"**The Mean Error",
"large errors. They also are strongly impacted by large bias (ME) values. MSE",
"Moreover, MSE can be strongly influenced by ME, as shown by this decomposition.",
"ranks are then used to compute a correlation cofficient, analogous to the Pearson",
"Spearman rank correlation coe cient ranges between -1 and 1; a value of",
"not correlated. Returns ------- Not implemented \"\"\" return def list_score(self): \"\"\"list all available",
", KT_CORR)**\"\"\" return self.kendall_tau_statistic(self._f, self._o) @staticmethod def kendall_tau_statistic(forecast, obs): r\"\"\"**Kendall's Tau statistic (",
"detailed below in the section on BCMSE. It is defined as ME2 =",
"None) @staticmethod def anomaly_correlation_coefficient(forecast, obs, climate): r\"\"\"The Anomaly correlation coefficient (ANOM_CORR) The Anomaly",
"the observed standard deviation (OSTDEV) \"\"\" return np.std(obs) @property def PR_CORR(self): r\"\"\"**The Pearson",
"simply the ratio of the means of the forecasts and the observations: ..",
"fcsterr[~np.isnan(fcsterr)] if forecast is None: forecast = fcsterr + obs if obs is",
"Mean Error (ME) \"\"\" return np.square(np.average(error)) @property def MBIAS(self): \"\"\"**Multiplicative bias (MBIAS)**\"\"\" return",
"'SP_CORR', 'KT_CORR', 'MBIAS', ] super(ContinuousVariableVerification, self).__init__(forecast, obs, group) @property def FBAR(self): \"\"\"**The sample",
"Quartile Range of the Errors (IQR) \"\"\" return np.percentile(error, 75) - np.percentile(error, 25)",
"large errors and also does not depend on the mean error. A perfect",
"adjusted to eliminate as much bias in the forecast as possible. For details,",
"the sample mean forecast (FBAR) is defined as, .. math:: \\bar{f} = \\frac{1}{n}\\sum_{i=1}^{n}f_i",
"does not depend on the mean error. A perfect forecast would have IQR",
"forecast, obs and fcsterr, but the fcsterr will be ignored.\") fcsterr = None",
"by this decomposition. The standard deviation of the error, :math:`s_{f-o}` , is ..",
"s^{2}_{f} + s^{2}_{o} -2 s_f s_o r_{fo} where :math:`\\bar{f} - \\bar{o} = ME`",
"by a climatology (**c**) of some variety. It measures the strength of linear",
"important to examine both of the terms of MSE, rather than examining MSE",
"negative correlation. A value of 0 indicates that the forecasts and observations are",
"climatology (**c**) of some variety. It measures the strength of linear association between",
"the total number of pairs) are assigned. The pairs of forecast-observed ranks are",
"with the contingency table counts adjusted to eliminate as much bias in the",
"the current pair is exceeded (that is, pairs for which the values of",
"return self.observation_standard_deviation(self._o) @staticmethod def observation_standard_deviation(obs): r\"\"\"**The observed standard deviation (OSTDEV)** The sample variance",
"forecast=None, obs=None, fcsterr=None, group=None): if (forecast is None or obs is None) and",
"association between the forecast and observation pairs. It is defined as .. math::",
"continuous variables; in particular ME = Bias. It is defined as .. math::",
"which case the :math:`o_i`, values won't necessarily be in order. The number of",
"\"\"\"**Mean-squared error (MSE)**\"\"\" return self.mean_squared_error(self.error) @staticmethod def mean_squared_error(error): r\"\"\"**Mean-squared error (MSE)** MSE measures",
"for all pairs. The total number of possible pairs is ; thus, the",
"is None: obs = forecast - fcsterr # Not Available, 'BAGSS', 'ANOM_CORR' self._available_score",
"matches of a particular pair with other pairs is computed by counting the",
"The total number of possible pairs is ; thus, the number of discordant",
"= ME2. A perfect forecast has ME2 = 0. Returns ------- numpy.ndarray, The",
"to a climatology value. The anomaly is the difference between the individual forecast",
"is defined as .. math:: \\tau = \\frac{N_c - N_p}{n(n-1)/2} where NC is",
"+ s^{2}_{f} + s^{2}_{o} -2 s_f s_o r_{fo} where :math:`\\bar{f} - \\bar{o} =",
"RMSE can range from 0 to infinity. A perfect forecast would have MSE",
"the error, :math:`s_{f-o}` , is .. math:: s_{f-o}=\\sqrt{s^{2}_{f-o}}=\\sqrt{s^{2}_{f} + s^{2}_{o} -2 s_f s_o",
"pairs in the sample; this can be done most easily by ordering all",
"that the forecasts and observations are not associated. Returns ------- numpy.ndarray, Kendall's Tau",
"from the forecast-observation squared differences. Returns ------- numpy.ndarray, Bias-Corrected MSE (BCMSE) \"\"\" return",
"situation, as measured by a climatology (**c**) of some variety. It measures the",
"measures the strength of linear association between the forecasts and observations. The Pearson",
"@staticmethod def mean_observation(obs): r\"\"\"**The sample mean observation, OBAR** the sample mean observation (OBAR)",
"- c)^2}} \\sqrt{\\sum{(o_i - c)^2}}} Anomaly correlation can range between -1 and 1;",
"of 0 indicates that the forecast and observed anomalies are not correlated. Returns",
"is defined as :math:`MAE = \\frac{1}{n}\\sum{|f_i - o_i|}` MAE is less in uenced",
"Nc is computed by summing the counts for all pairs. The total number",
"value of 1 indicates perfect correlation and - a value of -1 indicates",
"r\"\"\"**The observed standard deviation (OSTDEV)**\"\"\" return self.observation_standard_deviation(self._o) @staticmethod def observation_standard_deviation(obs): r\"\"\"**The observed standard",
". Thus, :math:`MSE = ME^2 + s^{2}_{f-o}` To understand the behavior of MSE,",
"p_{25}(f_i - o_i) IQR is another estimate of spread, similar to standard error,",
"math:: Anomoly Correlation = \\frac{\\sum{(f_i - c)(o_i - c)}} {\\sqrt{\\sum{(f_i - c)^2}} \\sqrt{\\sum{(o_i",
"return self.root_mean_squared_error(self.error) @staticmethod def root_mean_squared_error(error): \"\"\"**Root-mean-squared error (RMSE)** RMSE is simply the square",
"Percentiles can also be used to create box plots of the errors. The",
"numpy.ndarray, Median Absolute Deviation (MAD) \"\"\" return np.median(np.abs(error)) @property def BAGSS(self): \"\"\"Bias Adjusted",
"0 indicates that the forecast and observed anomalies are not correlated. Returns -------",
"\"discordant\" pairs. Concordant pairs are identi ed by comparing each pair with all",
"indicates perfect negative correlation. - A value of 0 indicates that the forecast",
"mean observation (OBAR) is defined as, .. math:: \\bar{o} = \\frac{1}{n}\\sum_{i=1}^{n}o_i Returns -------",
"pairs for which the values of **f** and **o** are both larger than",
"MAE = 0. Returns ------- numpy.ndarray, Mean Absolute Error (MAE) \"\"\" return np.average(np.abs(error))",
"Messinger, 2009. <https://www.adv-geosci.net/16/137/2008/>`_ Returns ------- Not implemented numpy.ndarray, Bias Adjusted Gilbert Skill Score",
"error** (ESTDEV) Returns ------- numpy.ndaray, Standard deviation of the error \"\"\" return np.std(error)",
"the forecast and observation pairs. It is defined as .. math:: \\tau =",
"0.75, 0.9) of the errors\"\"\" return self.percentile_errors(self.error) @staticmethod def percentile_errors(error): \"\"\"Percentiles of the",
"the forecasts and observations. The Pearson correlation coefficient is defined as: .. math::",
"\"\"\"**Standard deviation of the error** (ESTDEV) Returns ------- numpy.ndaray, Standard deviation of the",
"1 indicates perfect correlation and - a value of -1 indicates perfect negative",
":math:`o_i`, values won't necessarily be in order. The number of concordant matches of",
"deviation of the error** (ESTDEV) Returns ------- numpy.ndaray, Standard deviation of the error",
"first adjusted according to a climatology value. The anomaly is the difference between",
"(ME2)\"\"\" return self.mean_error_squared(self.error) @staticmethod def mean_error_squared(error): \"\"\"**The Mean Error Squared** (ME2) The Mean",
"and fcsterr values.\") elif forecast is not None and obs is not None",
"@staticmethod def median_absolute_deviation(error): \"\"\"Median Absolute Deviation (MAD) The Median Absolute Deviation (MAD) is",
"0 indicates that the forecasts and observations are not correlated. Returns ------- numpy.ndarray,",
"between -1 and 1; a value of 1 indicates perfect correlation and a",
"estimated variance of the error, :math:`s^{2}_{fo}` . Thus, :math:`MSE = ME^2 + s^{2}_{f-o}`",
"another estimate of spread, similar to standard error, but is less in uenced",
"math:: s_{f-o}=\\sqrt{s^{2}_{f-o}}=\\sqrt{s^{2}_{f} + s^{2}_{o} -2 s_f s_o r_{fo}} Note that the square of",
"(ANOM_CORR)\"\"\" return self.anomaly_correlation_coefficient(self._f, self._o, None) @staticmethod def anomaly_correlation_coefficient(forecast, obs, climate): r\"\"\"The Anomaly correlation",
"coefficient (ANOM_CORR) The Anomaly correlation coe cient is equivalent to the Pearson correlation",
"distribution of errors than can be obtained from the mean and standard deviations",
"is defined as .. math:: ME = \\frac{1}{n}\\sum^{n}_{i=1}(f_i - o_i) = \\bar{f} -",
"Range of the Errors (IQR)**\"\"\" return self.inter_quartile_range_of_errors(self.error) @staticmethod def inter_quartile_range_of_errors(error): r\"\"\"**Inter Quartile Range",
"numpy.ndarray, the Spearman correlation coefficient (SP_CORR) \"\"\" from scipy.stats import spearmanr return spearmanr(forecast,",
"Anomaly correlation coefficient (ANOM_CORR)\"\"\" return self.anomaly_correlation_coefficient(self._f, self._o, None) @staticmethod def anomaly_correlation_coefficient(forecast, obs, climate):",
"(BCMSE) because it removes the effect of overall bias from the forecast-observation squared",
"\"\"\" return np.percentile(error, 75) - np.percentile(error, 25) @property def MAD(self): \"\"\"Median Absolute Deviation",
"value of -1 indicates perfect negative correlation. A value of 0 indicates that",
"PR_CORR(self): r\"\"\"**The Pearson correlation coefficient ( :math:`r` , PR_CORR)**\"\"\" return self.pearson_correlation_coefficient(self._f, self._o) @staticmethod",
"numpy.ndarray, the sample mean observation (OBAR) \"\"\" return np.average(obs) @property def FSTDEV(self): \"\"\"**The",
"= 0. Returns ------- numpy.ndarray, The Mean Error (ME) \"\"\" return np.square(np.average(error)) @property",
"sample mean forecast, FBAR** the sample mean forecast (FBAR) is defined as, ..",
"A perfect forecast would have MAE = 0. Returns ------- numpy.ndarray, Mean Absolute",
"self.spearman_rank_correlation_cofficient(self._f, self._o) @staticmethod def spearman_rank_correlation_cofficient(forecast, obs): r\"\"\"**The Spearman rank correlation coefficient ( :math:`\\rho_s`",
"np.percentile(error, 75) - np.percentile(error, 25) @property def MAD(self): \"\"\"Median Absolute Deviation (MAD)\"\"\" return",
"are first adjusted according to a climatology value. The anomaly is the difference",
"Inter Quartile Range of the Errors (IQR) is the difference between the 75th",
"are not correlated. Returns ------- Not implemented \"\"\" return def list_score(self): \"\"\"list all",
"r = \\frac{\\sum^{T}_{i=1}(f_i - \\bar{f})(o_i - \\bar{o})}{\\sqrt{\\sum{(f_i - \\bar{f})^2}}\\sqrt{\\sum{(o_i - \\bar{o})^2}}} r can",
"of overall bias from the forecast-observation squared differences. Returns ------- numpy.ndarray, Bias-Corrected MSE",
"between the forecast anomolies and observed anomalies. The Anomaly correlation coefficient is defined",
"fcsterr # Not Available, 'BAGSS', 'ANOM_CORR' self._available_score += ['FBAR', 'OBAR', 'FSTDEV', 'OSTDEV', 'PR_CORR',",
"ratio of the means of the forecasts and the observations: .. math:: MBIAS",
"be ignored.\") fcsterr = None self._available_score = ['N', 'ME', 'ME2', 'MSE', 'RMSE', 'ESTDEV',",
"Percentiles of the errors \"\"\" quantiles = np.array([0.1, 0.25, 0.5, 0.75, 0.9]) return",
"@staticmethod def anomaly_correlation_coefficient(forecast, obs, climate): r\"\"\"The Anomaly correlation coefficient (ANOM_CORR) The Anomaly correlation",
"forecast (FBAR) is defined as, .. math:: \\bar{f} = \\frac{1}{n}\\sum_{i=1}^{n}f_i Returns ------ numpy.ndarray,",
"errors than can be obtained from the mean and standard deviations of the",
"A value of 0 indicates that the forecasts and observations are not associated.",
"the average squared error of the forecasts. Specifically, .. math:: MSE = \\frac{1}{n}\\sum{(f_i",
"(IQR) is the difference between the 75th and 25th percentiles of the errors.",
"Anomaly correlation can range between -1 and 1; - a value of 1",
"won't necessarily be in order. The number of concordant matches of a particular",
"observed values rather than the actual values. That is, the forecast and observed",
"Range of the Errors (IQR) \"\"\" return np.percentile(error, 75) - np.percentile(error, 25) @property",
"the distribution of errors than can be obtained from the mean and standard",
"-1 indicates perfect negative correlation. A value of 0 indicates that the forecasts",
"np.average(forecast) / np.average(error) @property def MSE(self): \"\"\"**Mean-squared error (MSE)**\"\"\" return self.mean_squared_error(self.error) @staticmethod def",
"measure of association that is based on the ranks of the forecast and",
"@property def OBAR(self): \"\"\"**The sample mean observation, OBAR**\"\"\" return self.mean_observation(self._o) @staticmethod def mean_observation(obs):",
"o_i|` MAD is an estimate of spread, similar to standard error, but is",
"fcsterr=None, group=None): if (forecast is None or obs is None) and fcsterr is",
"bias_corrected_mse(error): r\"\"\"**Bias-Corrected MSE (BCMSE)** MSE and RMSE are strongly impacted by large errors.",
"coefficient, **r**, measures the strength of linear association between the forecasts and observations.",
"Error, ME, is a measure of overall bias for continuous variables; in particular",
"(from 1 to **n**, where **n** is the total number of pairs) are",
"def mean_forecast(forecast): r\"\"\"**The sample mean forecast, FBAR** the sample mean forecast (FBAR) is",
"@staticmethod def kendall_tau_statistic(forecast, obs): r\"\"\"**Kendall's Tau statistic ( :math:`\\tau` , KT_CORR)** Kendall's Tau",
"s^{2}_{o} -2 s_f s_o r_{fo} where :math:`\\bar{f} - \\bar{o} = ME` and :math:`s^{2}_{f}",
"Standard deviation of the error \"\"\" return np.std(error) @property def BCMSE(self): \"\"\"**Bias-Corrected MSE",
"MSE in terms of squared Bias plus estimated variance of the error, as",
"**r** and :math:`\\rho_s` , Kendall's Tau ( :math:`\\tau` ) ranges between -1 and",
"MSE (BCMSE)**\"\"\" return self.bias_corrected_mse(self.error) @staticmethod def bias_corrected_mse(error): r\"\"\"**Bias-Corrected MSE (BCMSE)** MSE and RMSE",
"is defined as ME2 = ME2. A perfect forecast has ME2 = 0.",
"- \\bar{o} = ME` and :math:`s^{2}_{f} + s^{2}_{o} -2 s_f s_o r_{fo}` is",
".. math:: \\bar{o} = \\frac{1}{n}\\sum_{i=1}^{n}o_i Returns ------- numpy.ndarray, the sample mean observation (OBAR)",
"Percentiles of the errors provide more information about the distribution of errors than",
"by large errors and also does not depend on the mean error. A",
"@staticmethod def mean_error_squared(error): \"\"\"**The Mean Error Squared** (ME2) The Mean Error Squared, ME2,",
"deviation (FSTDEV)**\"\"\" return self.forecast_standard_deviation(self._f) @staticmethod def forecast_standard_deviation(forecast): r\"\"\"**The forecast standard deviation (FSTDEV)** The",
"= \\frac{1}{T-1}\\sum_{i=1}^{T}(o_i - \\bar{o})^2 The observed standard deviation, OSTDEV, is defined as ..",
"75th and 25th percentiles of the errors. It is de ned as ..",
"\\frac{1}{n}\\sum_{i=1}^{n}f_i Returns ------ numpy.ndarray, the sample mean forecast (FBAR) \"\"\" return np.average(forecast) @property",
"perfect negative correlation. A value of 0 indicates that the forecasts and observations",
"-1 and 1; a value of 1 indicates perfect correlation and a value",
"0. Returns ------- nupmy.ndarray, Inter Quartile Range of the Errors (IQR) \"\"\" return",
"the forecasts. Specifically, .. math:: MSE = \\frac{1}{n}\\sum{(f_i - o_i)^2} Returns ------- numpy.ndarray,",
"of the error** (ESTDEV) Returns ------- numpy.ndaray, Standard deviation of the error \"\"\"",
"indicates perfect correlation and - a value of -1 indicates perfect negative correlation.",
"pairs according to :math:`f_i`, in which case the :math:`o_i`, values won't necessarily be",
"return self.forecast_standard_deviation(self._f) @staticmethod def forecast_standard_deviation(forecast): r\"\"\"**The forecast standard deviation (FSTDEV)** The sample variance",
"forecast-observed ranks are then used to compute a correlation cofficient, analogous to the",
"obs): r\"\"\"**The Spearman rank correlation coefficient ( :math:`\\rho_s` , SP_CORR)** The Spearman rank",
"Tau statistic ( :math:`\\tau` , KT_CORR) \"\"\" from scipy.stats import kendalltau return kendalltau(forecast,",
"and rank values (from 1 to **n**, where **n** is the total number",
"current pair is exceeded (that is, pairs for which the values of **f**",
"is None or obs is None) and fcsterr is None: raise Exception(\"Initialize failed,",
"forecast is not None and obs is not None and fcsterr is not",
"\\bar{f} = \\frac{1}{n}\\sum_{i=1}^{n}f_i Returns ------ numpy.ndarray, the sample mean forecast (FBAR) \"\"\" return",
"to largest and computing the rank location of each percentile in the ordering,",
"for which the value of oi for the current pair is exceeded (that",
"correlation coefficient is defined as: .. math:: r = \\frac{\\sum^{T}_{i=1}(f_i - \\bar{f})(o_i -",
", PR_CORR)** The Pearson correlation coefficient, **r**, measures the strength of linear association",
"to standard error, but is less in uenced by large errors and also",
"which the value of oi for the current pair is exceeded (that is,",
"perfect forecast would have MAE = 0. Returns ------- numpy.ndarray, Mean Absolute Error",
"and fcsterr is not None: logger.warning(\"You give forecast, obs and fcsterr, but the",
"(MSE)**\"\"\" return self.mean_squared_error(self.error) @staticmethod def mean_squared_error(error): r\"\"\"**Mean-squared error (MSE)** MSE measures the average",
"------- numpy.ndarray, Mean-squared error (MSE) \"\"\" return np.average(error ** 2) @property def RMSE(self):",
"is . Like **r** and :math:`\\rho_s` , Kendall's Tau ( :math:`\\tau` ) ranges",
"and RMSE are strongly impacted by large errors. They also are strongly impacted",
"measure of overall bias for continuous variables; in particular ME = Bias. It",
"np.std(forecast) @property def OSTDEV(self): r\"\"\"**The observed standard deviation (OSTDEV)**\"\"\" return self.observation_standard_deviation(self._o) @staticmethod def",
"= \\frac{\\bar{f}}{\\bar{o}} Returns ------- numpy.ndarray, Multiplicative bias (MBIAS) \"\"\" return np.average(forecast) / np.average(error)",
"def root_mean_squared_error(error): \"\"\"**Root-mean-squared error (RMSE)** RMSE is simply the square root of the",
"is a robust measure of association that is based on the ranks of",
":math:`RMSE = \\sqrt{MSE}` Returns ------- numpy.ndarray, Root-mean-squared error (RMSE) \"\"\" return np.sqrt(np.average(error **",
"logzero import logger from .point_stat_base import PointStatBase class ContinuousVariableVerification(PointStatBase): def __init__(self, forecast=None, obs=None,",
"from smallest to largest and rank values (from 1 to **n**, where **n**",
"would have IQR = 0. Returns ------- nupmy.ndarray, Inter Quartile Range of the",
"squared differences. Returns ------- numpy.ndarray, Bias-Corrected MSE (BCMSE) \"\"\" return np.square(np.std(error)) @property def",
"values won't necessarily be in order. The number of concordant matches of a",
"sample mean observation (OBAR) \"\"\" return np.average(obs) @property def FSTDEV(self): \"\"\"**The forecast standard",
"coefficient ( :math:`r` , PR_CORR)** The Pearson correlation coefficient, **r**, measures the strength",
"the difference between the individual forecast or observation and the typical situation, as",
"as ( :math:`d_i` ) ): .. math:: \\rho_s = \\frac{6}{n(n^2 - 1)}\\sum^{n}_{i=1}d^{2}_{i} Like",
"Bias Adjusted Gilbert Skill Score (BAGSS) \"\"\" return @property def EPCT(self): \"\"\"Percentiles (0.1,",
"uenced by large errors and also does not depend on the mean error.",
"forecast and observation pairs. It is defined as .. math:: \\tau = \\frac{N_c",
"forecast standard deviation (FSTDEV) \"\"\" return np.std(forecast) @property def OSTDEV(self): r\"\"\"**The observed standard",
"ordering the errors from smallest to largest and computing the rank location of",
"the current pair). Once this is done, Nc is computed by summing the",
"by large errors. They also are strongly impacted by large bias (ME) values.",
"is computed by summing the counts for all pairs. The total number of",
"values rather than the actual values. That is, the forecast and observed samples",
"Spearman rank correlation cofficient ( :math:`\\rho_s` ) is a robust measure of association",
"from the mean and standard deviations of the errors. Percentiles are computed by",
"s_f s_o r_{fo} where :math:`\\bar{f} - \\bar{o} = ME` and :math:`s^{2}_{f} + s^{2}_{o}",
"s_o r_{fo}} Note that the square of the standard deviation of the error",
"KT_CORR)** Kendall's Tau statistic ( :math:`\\tau` ) is a robust measure of the",
"'IQR', 'MAD', 'EPCT'] if fcsterr is not None: self._error = fcsterr[~np.isnan(fcsterr)] if forecast",
"\\sqrt{s^{2}_{o}} Returns ------- numpy.ndarray, the observed standard deviation (OSTDEV) \"\"\" return np.std(obs) @property",
"= 0. MSE can be re-written as, .. math:: MSE = (\\bar{f} -",
"np.quantile(error, quantiles) @property def ANOM_CORR(self): \"\"\"The Anomaly correlation coefficient (ANOM_CORR)\"\"\" return self.anomaly_correlation_coefficient(self._f, self._o,",
"to give a complete breakdown of MSE in terms of squared Bias plus",
"the values of **f** and **o** are both larger than the value for",
"estimated variance of the error, as detailed below in the section on BCMSE.",
"between the 75th and 25th percentiles of the errors. It is de ned",
"most easily by ordering all of the ( :math:`f_i, o_i` ) pairs according",
"forecast has ME2 = 0. Returns ------- numpy.ndarray, The Mean Error (ME) \"\"\"",
"correlation can range between -1 and 1; - a value of 1 indicates",
"\\frac{1}{T-1}\\sum_{i=1}^{T}(o_i - \\bar{o})^2 The observed standard deviation, OSTDEV, is defined as .. math::",
"( :math:`r` , PR_CORR)**\"\"\" return self.pearson_correlation_coefficient(self._f, self._o) @staticmethod def pearson_correlation_coefficient(forecast, obs): r\"\"\"**The Pearson",
"------- numpy.ndarray, the sample mean observation (OBAR) \"\"\" return np.average(obs) @property def FSTDEV(self):",
"on the mean error. A perfect forecast would have MAD = 0. Returns",
"of the Spearman-rank correlation is based on differences between the each of the",
"of the errors. It is de ned as .. math:: IQR = p_{75}",
"self.standard_deviation_of_error(self.error) @staticmethod def standard_deviation_of_error(error): \"\"\"**Standard deviation of the error** (ESTDEV) Returns ------- numpy.ndaray,",
"defined as, .. math:: \\bar{f} = \\frac{1}{n}\\sum_{i=1}^{n}f_i Returns ------ numpy.ndarray, the sample mean",
"super(ContinuousVariableVerification, self).__init__(forecast, obs, group) @property def FBAR(self): \"\"\"**The sample mean forecast, FBAR**\"\"\" return",
"range from 0 to infinity. A perfect forecast would have MSE = RMSE",
"fcsterr is None: raise Exception(\"Initialize failed, check forecast and obs and fcsterr values.\")",
"squared error of the forecasts. Specifically, .. math:: MSE = \\frac{1}{n}\\sum{(f_i - o_i)^2}",
"the sample mean observation (OBAR) is defined as, .. math:: \\bar{o} = \\frac{1}{n}\\sum_{i=1}^{n}o_i",
"standard deviation of the error, :math:`s_{f-o}` , is .. math:: s_{f-o}=\\sqrt{s^{2}_{f-o}}=\\sqrt{s^{2}_{f} + s^{2}_{o}",
"A value of 0 indicates that the forecasts and observations are not correlated.",
"\"\"\" return np.std(error) @property def BCMSE(self): \"\"\"**Bias-Corrected MSE (BCMSE)**\"\"\" return self.bias_corrected_mse(self.error) @staticmethod def",
"is the difference between the individual forecast or observation and the typical situation,",
"to the actual value. Percentiles can also be used to create box plots",
"forecasts and observations are not correlated. Returns ------- numpy.ndarray, the Pearson correlation coefficient",
"cient is equivalent to the Pearson correlation coefficient, except that both the forecasts",
"comparing each pair with all other pairs in the sample; this can be",
"rank correlation coefficient ( :math:`\\rho_s` , SP_CORR)** The Spearman rank correlation cofficient (",
"influenced by ME, as shown by this decomposition. The standard deviation of the",
"(ME) values. MSE and RMSE can range from 0 to infinity. A perfect",
"removes the effect of overall bias from the forecast-observation squared differences. Returns -------",
".. math:: IQR = p_{75} (f_i - o_i) - p_{25}(f_i - o_i) IQR",
"to the Pearson correlation coefficient, except that both the forecasts and observations are",
"Mean Error, ME, is a measure of overall bias for continuous variables; in",
"between -1 and 1; a value of 1 indicates perfect association (concor-dance) and",
"the Errors (IQR) is the difference between the 75th and 25th percentiles of",
"which the values of **f** and **o** are both larger than the value",
"not correlated. Returns ------- numpy.ndarray, the Spearman correlation coefficient (SP_CORR) \"\"\" from scipy.stats",
"BAGSS(self): \"\"\"Bias Adjusted Gilbert Skill Score (BAGSS)\"\"\" return self.bias_adjusted_gilbert_skill_score(self._f, self._o) @staticmethod def bias_adjusted_gilbert_skill_score(forecast,",
"\\sqrt{MSE}` Returns ------- numpy.ndarray, Root-mean-squared error (RMSE) \"\"\" return np.sqrt(np.average(error ** 2)) @property",
"Returns ------- numpy.ndarray, Multiplicative bias (MBIAS) \"\"\" return np.average(forecast) / np.average(error) @property def",
"(MAD)\"\"\" return self.median_absolute_deviation(self.error) @staticmethod def median_absolute_deviation(error): \"\"\"Median Absolute Deviation (MAD) The Median Absolute",
"-2 s_f s_o r_{fo}} Note that the square of the standard deviation of",
"It is defined as .. math:: ME = \\frac{1}{n}\\sum^{n}_{i=1}(f_i - o_i) = \\bar{f}",
"forecast (FBAR) \"\"\" return np.average(forecast) @property def OBAR(self): \"\"\"**The sample mean observation, OBAR**\"\"\"",
"\\sqrt{s^{2}_{f}} Returns ------- numpy.ndarray, the forecast standard deviation (FSTDEV) \"\"\" return np.std(forecast) @property",
"association (concor-dance) and a value of -1 indicates perfect negative association. A value",
"largest and rank values (from 1 to **n**, where **n** is the total",
":math:`r` , PR_CORR)** The Pearson correlation coefficient, **r**, measures the strength of linear",
"formulation of the Spearman-rank correlation is based on differences between the each of",
"Bias-Corrected MSE (BCMSE) \"\"\" return np.square(np.std(error)) @property def MAE(self): \"\"\"**Mean Absolute Error (MAE)**\"\"\"",
"pairs (with larger values) for which the value of oi for the current",
"Error (MAE)** The Mean Absolute Error (MAE) is defined as :math:`MAE = \\frac{1}{n}\\sum{|f_i",
"by: wqshen import numpy as np from logzero import logger from .point_stat_base import",
"MSE (BCMSE) \"\"\" return np.square(np.std(error)) @property def MAE(self): \"\"\"**Mean Absolute Error (MAE)**\"\"\" return",
"location of each percentile in the ordering, and matching the rank to the",
"depend on the mean error. A perfect forecast would have MAE = 0.",
"cofficient, analogous to the Pearson correlation cofficient, **r**. A simpler formulation of the",
"of 1 indicates perfect association (concor-dance) and a value of -1 indicates perfect",
"deviation (OSTDEV) \"\"\" return np.std(obs) @property def PR_CORR(self): r\"\"\"**The Pearson correlation coefficient (",
"ranges between -1 and 1; a value of 1 indicates perfect association (concor-dance)",
"the Pearson correlation cofficient, **r**. A simpler formulation of the Spearman-rank correlation is",
"defined as .. math:: \\tau = \\frac{N_c - N_p}{n(n-1)/2} where NC is the",
"self._o) @staticmethod def spearman_rank_correlation_cofficient(forecast, obs): r\"\"\"**The Spearman rank correlation coefficient ( :math:`\\rho_s` ,",
"pairs. It is defined as .. math:: \\tau = \\frac{N_c - N_p}{n(n-1)/2} where",
"correlation coefficient ( :math:`r` , PR_CORR)** The Pearson correlation coefficient, **r**, measures the",
"then used to compute a correlation cofficient, analogous to the Pearson correlation cofficient,",
"the forecasts and the observations: .. math:: MBIAS = \\frac{\\bar{f}}{\\bar{o}} Returns ------- numpy.ndarray,",
"bias (ME) values. MSE and RMSE can range from 0 to infinity. A",
"case the :math:`o_i`, values won't necessarily be in order. The number of concordant",
"Absolute Error (MAE) \"\"\" return np.average(np.abs(error)) @property def IQR(self): \"\"\"\"**Inter Quartile Range of",
"indicates perfect correlation and a value of -1 indicates perfect negative correlation. A",
"because it removes the effect of overall bias from the forecast-observation squared differences.",
"Absolute Deviation (MAD) \"\"\" return np.median(np.abs(error)) @property def BAGSS(self): \"\"\"Bias Adjusted Gilbert Skill",
"fcsterr, but the fcsterr will be ignored.\") fcsterr = None self._available_score = ['N',",
"- o_i)^2} Returns ------- numpy.ndarray, Mean-squared error (MSE) \"\"\" return np.average(error ** 2)",
"ME = Bias. It is defined as .. math:: ME = \\frac{1}{n}\\sum^{n}_{i=1}(f_i -",
"(**c**) of some variety. It measures the strength of linear association between the",
"standard error, but is less in uenced by large errors and also does",
"def FSTDEV(self): \"\"\"**The forecast standard deviation (FSTDEV)**\"\"\" return self.forecast_standard_deviation(self._f) @staticmethod def forecast_standard_deviation(forecast): r\"\"\"**The",
"Errors (IQR)**\"\"\" return self.inter_quartile_range_of_errors(self.error) @staticmethod def inter_quartile_range_of_errors(error): r\"\"\"**Inter Quartile Range of the Errors",
"obs is None) and fcsterr is None: raise Exception(\"Initialize failed, check forecast and",
":math:`MSE = ME^2 + s^{2}_{f-o}` To understand the behavior of MSE, it is",
"@property def MAE(self): \"\"\"**Mean Absolute Error (MAE)**\"\"\" return self.mean_absolute_error(self.error) @staticmethod def mean_absolute_error(error): r\"\"\"**Mean",
"Error (ME)**\"\"\" return self.mean_error(self.error) @staticmethod def mean_error(error): r\"\"\"**The Mean Error (ME)** The Mean",
"PR_CORR)**\"\"\" return self.pearson_correlation_coefficient(self._f, self._o) @staticmethod def pearson_correlation_coefficient(forecast, obs): r\"\"\"**The Pearson correlation coefficient (",
"will be ignored.\") fcsterr = None self._available_score = ['N', 'ME', 'ME2', 'MSE', 'RMSE',",
"Specifically, .. math:: MSE = \\frac{1}{n}\\sum{(f_i - o_i)^2} Returns ------- numpy.ndarray, Mean-squared error",
"and obs and fcsterr values.\") elif forecast is not None and obs is",
"is exceeded (that is, pairs for which the values of **f** and **o**",
"current pair). Once this is done, Nc is computed by summing the counts",
"group) @property def FBAR(self): \"\"\"**The sample mean forecast, FBAR**\"\"\" return self.mean_forecast(self._f) @staticmethod def",
"s_f s_o r_{fo}} Note that the square of the standard deviation of the",
"the square of the standard deviation of the error (ESTDEV2) is sometimes called",
"np.std(error) @property def BCMSE(self): \"\"\"**Bias-Corrected MSE (BCMSE)**\"\"\" return self.bias_corrected_mse(self.error) @staticmethod def bias_corrected_mse(error): r\"\"\"**Bias-Corrected",
"0 indicates that the forecasts and observations are not associated. Returns ------- numpy.ndarray,",
"computing the rank location of each percentile in the ordering, and matching the",
"obs = forecast - fcsterr # Not Available, 'BAGSS', 'ANOM_CORR' self._available_score += ['FBAR',",
"the Errors (IQR)** The Inter Quartile Range of the Errors (IQR) is the",
"in the forecast as possible. For details, see `Brill and Messinger, 2009. <https://www.adv-geosci.net/16/137/2008/>`_",
"- o_i) = \\bar{f} - \\bar{o} A perfect forecast has ME = 0.",
"the strength of linear association between the forecasts and observations. The Pearson correlation",
"\"\"\" return np.median(np.abs(error)) @property def BAGSS(self): \"\"\"Bias Adjusted Gilbert Skill Score (BAGSS)\"\"\" return",
"None self._available_score = ['N', 'ME', 'ME2', 'MSE', 'RMSE', 'ESTDEV', 'BCMSE', 'MAE', 'IQR', 'MAD',",
"and fcsterr, but the fcsterr will be ignored.\") fcsterr = None self._available_score =",
"obs and fcsterr values.\") elif forecast is not None and obs is not",
"and observed samples are ordered from smallest to largest and rank values (from",
"the value for the current pair). Once this is done, Nc is computed",
"'ESTDEV', 'BCMSE', 'MAE', 'IQR', 'MAD', 'EPCT'] if fcsterr is not None: self._error =",
"return np.square(np.average(error)) @property def MBIAS(self): \"\"\"**Multiplicative bias (MBIAS)**\"\"\" return self.multiplicative_bias(self._f, self._o) @staticmethod def",
"(FBAR) \"\"\" return np.average(forecast) @property def OBAR(self): \"\"\"**The sample mean observation, OBAR**\"\"\" return",
"(FSTDEV)**\"\"\" return self.forecast_standard_deviation(self._f) @staticmethod def forecast_standard_deviation(forecast): r\"\"\"**The forecast standard deviation (FSTDEV)** The sample",
"The Pearson correlation coefficient, **r**, measures the strength of linear association between the",
"the square root of the MSE, :math:`RMSE = \\sqrt{MSE}` Returns ------- numpy.ndarray, Root-mean-squared",
"None: obs = forecast - fcsterr # Not Available, 'BAGSS', 'ANOM_CORR' self._available_score +=",
"error of the forecasts. Specifically, .. math:: MSE = \\frac{1}{n}\\sum{(f_i - o_i)^2} Returns",
"correlation and - a value of -1 indicates perfect negative correlation. - A",
"of the error \"\"\" return np.std(error) @property def BCMSE(self): \"\"\"**Bias-Corrected MSE (BCMSE)**\"\"\" return",
"of the Errors (IQR)**\"\"\" return self.inter_quartile_range_of_errors(self.error) @staticmethod def inter_quartile_range_of_errors(error): r\"\"\"**Inter Quartile Range of",
"c)}} {\\sqrt{\\sum{(f_i - c)^2}} \\sqrt{\\sum{(o_i - c)^2}}} Anomaly correlation can range between -1",
"impacted by large bias (ME) values. MSE and RMSE can range from 0",
"forecast and observed anomalies are not correlated. Returns ------- Not implemented \"\"\" return",
"are assigned. The pairs of forecast-observed ranks are then used to compute a",
"fcsterr will be ignored.\") fcsterr = None self._available_score = ['N', 'ME', 'ME2', 'MSE',",
"computed by ordering the errors from smallest to largest and computing the rank",
"@staticmethod def inter_quartile_range_of_errors(error): r\"\"\"**Inter Quartile Range of the Errors (IQR)** The Inter Quartile",
"obs is not None and fcsterr is not None: logger.warning(\"You give forecast, obs",
"is sometimes called the \"Bias-corrected MSE\" (BCMSE) because it removes the effect of",
"the Spearman correlation coefficient (SP_CORR) \"\"\" from scipy.stats import spearmanr return spearmanr(forecast, obs)",
"(RMSE)**\"\"\" return self.root_mean_squared_error(self.error) @staticmethod def root_mean_squared_error(error): \"\"\"**Root-mean-squared error (RMSE)** RMSE is simply the",
"(ESTDEV)\"\"\" return self.standard_deviation_of_error(self.error) @staticmethod def standard_deviation_of_error(error): \"\"\"**Standard deviation of the error** (ESTDEV) Returns",
"with all other pairs in the sample; this can be done most easily",
"the mean error. A perfect forecast would have IQR = 0. Returns -------",
"also are strongly impacted by large bias (ME) values. MSE and RMSE can",
"have MSE = RMSE = 0. MSE can be re-written as, .. math::",
"Returns ------- numpy.ndarray, Bias-Corrected MSE (BCMSE) \"\"\" return np.square(np.std(error)) @property def MAE(self): \"\"\"**Mean",
"\\bar{f} - \\bar{o} A perfect forecast has ME = 0. Returns ------- numpy.ndarray,",
"ME2(self): \"\"\"**The Mean Error Squared** (ME2)\"\"\" return self.mean_error_squared(self.error) @staticmethod def mean_error_squared(error): \"\"\"**The Mean",
"; thus, the number of discordant pairs is . Like **r** and :math:`\\rho_s`",
"values of the errors are computed. Returns ------- numpy.ndarray, Percentiles of the errors",
"(PR_CORR) \"\"\" return np.corrcoef(forecast, obs)[1, 0] @property def SP_CORR(self): r\"\"\"**The Spearman rank correlation",
"concordant matches of a particular pair with other pairs is computed by counting",
"cient ranges between -1 and 1; a value of 1 indicates perfect correlation",
"between the forecast and observation pairs. It is defined as .. math:: \\tau",
"of spread, similar to standard error, but is less in uenced by large",
"@property def OSTDEV(self): r\"\"\"**The observed standard deviation (OSTDEV)**\"\"\" return self.observation_standard_deviation(self._o) @staticmethod def observation_standard_deviation(obs):",
"pair). Once this is done, Nc is computed by summing the counts for",
"return self.mean_forecast(self._f) @staticmethod def mean_forecast(forecast): r\"\"\"**The sample mean forecast, FBAR** the sample mean",
":math:`f_i`, in which case the :math:`o_i`, values won't necessarily be in order. The",
"Mean Error (ME)** The Mean Error, ME, is a measure of overall bias",
"indicates that the forecast and observed anomalies are not correlated. Returns ------- Not",
"def PR_CORR(self): r\"\"\"**The Pearson correlation coefficient ( :math:`r` , PR_CORR)**\"\"\" return self.pearson_correlation_coefficient(self._f, self._o)",
"r\"\"\"**The Spearman rank correlation coefficient ( :math:`\\rho_s` , SP_CORR)**\"\"\" return self.spearman_rank_correlation_cofficient(self._f, self._o) @staticmethod",
"Once this is done, Nc is computed by summing the counts for all",
"fcsterr is not None: self._error = fcsterr[~np.isnan(fcsterr)] if forecast is None: forecast =",
"Not implemented numpy.ndarray, Bias Adjusted Gilbert Skill Score (BAGSS) \"\"\" return @property def",
"can be strongly influenced by ME, as shown by this decomposition. The standard",
"of -1 indicates perfect negative correlation. A value of 0 indicates that the",
"and fcsterr is None: raise Exception(\"Initialize failed, check forecast and obs and fcsterr",
"(ME) \"\"\" return np.square(np.average(error)) @property def MBIAS(self): \"\"\"**Multiplicative bias (MBIAS)**\"\"\" return self.multiplicative_bias(self._f, self._o)",
"table counts adjusted to eliminate as much bias in the forecast as possible.",
"@staticmethod def pearson_correlation_coefficient(forecast, obs): r\"\"\"**The Pearson correlation coefficient ( :math:`r` , PR_CORR)** The",
"and Messinger, 2009. <https://www.adv-geosci.net/16/137/2008/>`_ Returns ------- Not implemented numpy.ndarray, Bias Adjusted Gilbert Skill",
"(FSTDEV) \"\"\" return np.std(forecast) @property def OSTDEV(self): r\"\"\"**The observed standard deviation (OSTDEV)**\"\"\" return",
"all pairs. The total number of possible pairs is ; thus, the number",
"The observed standard deviation, OSTDEV, is defined as .. math:: s_{o} = \\sqrt{s^{2}_{o}}",
"(OSTDEV) \"\"\" return np.std(obs) @property def PR_CORR(self): r\"\"\"**The Pearson correlation coefficient ( :math:`r`",
"group=None): if (forecast is None or obs is None) and fcsterr is None:",
"the Errors (IQR)**\"\"\" return self.inter_quartile_range_of_errors(self.error) @staticmethod def inter_quartile_range_of_errors(error): r\"\"\"**Inter Quartile Range of the",
"return self.standard_deviation_of_error(self.error) @staticmethod def standard_deviation_of_error(error): \"\"\"**Standard deviation of the error** (ESTDEV) Returns -------",
"np.percentile(error, 25) @property def MAD(self): \"\"\"Median Absolute Deviation (MAD)\"\"\" return self.median_absolute_deviation(self.error) @staticmethod def",
"return self.spearman_rank_correlation_cofficient(self._f, self._o) @staticmethod def spearman_rank_correlation_cofficient(forecast, obs): r\"\"\"**The Spearman rank correlation coefficient (",
"the ranks of the forecast and observed values rather than the actual values.",
"standard deviation (OSTDEV)** The sample variance of the observations is defined as ..",
"correlated. Returns ------- Not implemented \"\"\" return def list_score(self): \"\"\"list all available score\"\"\"",
"and observed values rather than the actual values. That is, the forecast and",
"and **o** are both larger than the value for the current pair). Once",
"'MSE', 'RMSE', 'ESTDEV', 'BCMSE', 'MAE', 'IQR', 'MAD', 'EPCT'] if fcsterr is not None:",
"(OBAR) \"\"\" return np.average(obs) @property def FSTDEV(self): \"\"\"**The forecast standard deviation (FSTDEV)**\"\"\" return",
"coefficient (PR_CORR) \"\"\" return np.corrcoef(forecast, obs)[1, 0] @property def SP_CORR(self): r\"\"\"**The Spearman rank",
"this can be done most easily by ordering all of the ( :math:`f_i,",
"correlation cofficient, analogous to the Pearson correlation cofficient, **r**. A simpler formulation of",
"error \"\"\" return np.std(error) @property def BCMSE(self): \"\"\"**Bias-Corrected MSE (BCMSE)**\"\"\" return self.bias_corrected_mse(self.error) @staticmethod",
"of the forecasts and the observations: .. math:: MBIAS = \\frac{\\bar{f}}{\\bar{o}} Returns -------",
"a robust measure of the level of association between the forecast and observation",
"where **n** is the total number of pairs) are assigned. The pairs of",
"of the pairs of ranks (denoted as ( :math:`d_i` ) ): .. math::",
"return np.average(error ** 2) @property def RMSE(self): \"\"\"**Root-mean-squared error (RMSE)**\"\"\" return self.root_mean_squared_error(self.error) @staticmethod",
"r\"\"\"**Mean-squared error (MSE)** MSE measures the average squared error of the forecasts. Specifically,",
"the forecast standard deviation (FSTDEV) \"\"\" return np.std(forecast) @property def OSTDEV(self): r\"\"\"**The observed",
"Gilbert Skill Score, but with the contingency table counts adjusted to eliminate as",
"Kendall's Tau statistic ( :math:`\\tau` ) is a robust measure of the level",
"Adjusted Gilbert Skill Score (BAGSS)\"\"\" return self.bias_adjusted_gilbert_skill_score(self._f, self._o) @staticmethod def bias_adjusted_gilbert_skill_score(forecast, obs): \"\"\"Bias",
"correlation cofficient, **r**. A simpler formulation of the Spearman-rank correlation is based on",
":math:`\\rho_s` , Kendall's Tau ( :math:`\\tau` ) ranges between -1 and 1; a",
"coe cient is equivalent to the Pearson correlation coefficient, except that both the",
"all other pairs in the sample; this can be done most easily by",
"is None: forecast = fcsterr + obs if obs is None: obs =",
"import spearmanr return spearmanr(forecast, obs) @property def KT_CORR(self): r\"\"\"**Kendall's Tau statistic ( :math:`\\tau`",
"MSE = RMSE = 0. MSE can be re-written as, .. math:: MSE",
"- \\bar{o})^2 The observed standard deviation, OSTDEV, is defined as .. math:: s_{o}",
"deviation (OSTDEV)**\"\"\" return self.observation_standard_deviation(self._o) @staticmethod def observation_standard_deviation(obs): r\"\"\"**The observed standard deviation (OSTDEV)** The",
"ranks (denoted as ( :math:`d_i` ) ): .. math:: \\rho_s = \\frac{6}{n(n^2 -",
"obs): r\"\"\"**Kendall's Tau statistic ( :math:`\\tau` , KT_CORR)** Kendall's Tau statistic ( :math:`\\tau`",
"anomolies and observed anomalies. The Anomaly correlation coefficient is defined as: .. math::",
"**f** and **o** are both larger than the value for the current pair).",
"------- numpy.ndarray, the forecast standard deviation (FSTDEV) \"\"\" return np.std(forecast) @property def OSTDEV(self):",
"variety. It measures the strength of linear association between the forecast anomolies and",
"PR_CORR)** The Pearson correlation coefficient, **r**, measures the strength of linear association between",
"+ s^{2}_{o} -2 s_f s_o r_{fo} where :math:`\\bar{f} - \\bar{o} = ME` and",
"range between -1 and 1; - a value of 1 indicates perfect correlation",
"sample variance of the forecasts is defined as .. math:: s^{2}_{f} = \\frac{1}{T-1}\\sum_{i=1}^{T}(f_i",
":math:`\\tau` ) is a robust measure of the level of association between the",
"exceeded (that is, pairs for which the values of **f** and **o** are",
"correlation coefficient ( :math:`\\rho_s` , SP_CORR)**\"\"\" return self.spearman_rank_correlation_cofficient(self._f, self._o) @staticmethod def spearman_rank_correlation_cofficient(forecast, obs):",
"value of 0 indicates that the forecasts and observations are not associated. Returns",
"quantiles) @property def ANOM_CORR(self): \"\"\"The Anomaly correlation coefficient (ANOM_CORR)\"\"\" return self.anomaly_correlation_coefficient(self._f, self._o, None)",
"\"\"\" return np.corrcoef(forecast, obs)[1, 0] @property def SP_CORR(self): r\"\"\"**The Spearman rank correlation coefficient",
"(MAE) \"\"\" return np.average(np.abs(error)) @property def IQR(self): \"\"\"\"**Inter Quartile Range of the Errors",
"the error, as detailed below in the section on BCMSE. It is defined",
"not None: logger.warning(\"You give forecast, obs and fcsterr, but the fcsterr will be",
"math:: s^{2}_{f} = \\frac{1}{T-1}\\sum_{i=1}^{T}(f_i - \\bar{f})^2 The forecast standard deviation, FSTDEV, is defined",
"bias in the forecast as possible. For details, see `Brill and Messinger, 2009.",
"observations: .. math:: MBIAS = \\frac{\\bar{f}}{\\bar{o}} Returns ------- numpy.ndarray, Multiplicative bias (MBIAS) \"\"\"",
"@property def MBIAS(self): \"\"\"**Multiplicative bias (MBIAS)**\"\"\" return self.multiplicative_bias(self._f, self._o) @staticmethod def multiplicative_bias(forecast, error):",
"the rank location of each percentile in the ordering, and matching the rank",
"forecast and observed samples are ordered from smallest to largest and rank values",
"Skill Score (BAGSS) is the Gilbert Skill Score, but with the contingency table",
"is not None and obs is not None and fcsterr is not None:",
"Skill Score, but with the contingency table counts adjusted to eliminate as much",
"s^{2}_{f} = \\frac{1}{T-1}\\sum_{i=1}^{T}(f_i - \\bar{f})^2 The forecast standard deviation, FSTDEV, is defined as",
"are then used to compute a correlation cofficient, analogous to the Pearson correlation",
"(ME) \"\"\" return np.average(error) @property def ME2(self): \"\"\"**The Mean Error Squared** (ME2)\"\"\" return",
"return def list_score(self): \"\"\"list all available score\"\"\" return {k: np.round(getattr(self, k), self.round) for",
"ME, is a measure of overall bias for continuous variables; in particular ME",
"the difference between the 75th and 25th percentiles of the errors. It is",
"is the total number of pairs) are assigned. The pairs of forecast-observed ranks",
"self.mean_error(self.error) @staticmethod def mean_error(error): r\"\"\"**The Mean Error (ME)** The Mean Error, ME, is",
"total number of possible pairs is ; thus, the number of discordant pairs",
"(denoted as ( :math:`d_i` ) ): .. math:: \\rho_s = \\frac{6}{n(n^2 - 1)}\\sum^{n}_{i=1}d^{2}_{i}",
"@property def IQR(self): \"\"\"\"**Inter Quartile Range of the Errors (IQR)**\"\"\" return self.inter_quartile_range_of_errors(self.error) @staticmethod",
"number of possible pairs is ; thus, the number of discordant pairs is",
"self.mean_forecast(self._f) @staticmethod def mean_forecast(forecast): r\"\"\"**The sample mean forecast, FBAR** the sample mean forecast",
"done most easily by ordering all of the ( :math:`f_i, o_i` ) pairs",
"not associated. Returns ------- numpy.ndarray, Kendall's Tau statistic ( :math:`\\tau` , KT_CORR) \"\"\"",
"= ME` and :math:`s^{2}_{f} + s^{2}_{o} -2 s_f s_o r_{fo}` is the estimated",
"A perfect forecast has ME2 = 0. Returns ------- numpy.ndarray, The Mean Error",
"c)(o_i - c)}} {\\sqrt{\\sum{(f_i - c)^2}} \\sqrt{\\sum{(o_i - c)^2}}} Anomaly correlation can range",
"Returns ------- numpy.ndarray, the sample mean observation (OBAR) \"\"\" return np.average(obs) @property def",
"the individual forecast or observation and the typical situation, as measured by a",
"scipy.stats import spearmanr return spearmanr(forecast, obs) @property def KT_CORR(self): r\"\"\"**Kendall's Tau statistic (",
"Returns ------- numpy.ndarray, Percentiles of the errors \"\"\" quantiles = np.array([0.1, 0.25, 0.5,",
"@staticmethod def multiplicative_bias(forecast, error): r\"\"\"**Multiplicative bias (MBIAS)** Multiplicative bias is simply the ratio",
"( :math:`\\rho_s` , SP_CORR)**\"\"\" return self.spearman_rank_correlation_cofficient(self._f, self._o) @staticmethod def spearman_rank_correlation_cofficient(forecast, obs): r\"\"\"**The Spearman",
"obs=None, fcsterr=None, group=None): if (forecast is None or obs is None) and fcsterr",
"- p_{25}(f_i - o_i) IQR is another estimate of spread, similar to standard",
"------- numpy.ndaray, Standard deviation of the error \"\"\" return np.std(error) @property def BCMSE(self):",
"0.75, 0.9]) return np.quantile(error, quantiles) @property def ANOM_CORR(self): \"\"\"The Anomaly correlation coefficient (ANOM_CORR)\"\"\"",
"errors. It is de ned as .. math:: IQR = p_{75} (f_i -",
"# @Author: wqshen # @Email: <EMAIL> # @Date: 2020/6/10 14:43 # @Last Modified",
"perfect forecast would have MSE = RMSE = 0. MSE can be re-written",
"can range between -1 and 1; - a value of 1 indicates perfect",
"Error (MAE)**\"\"\" return self.mean_absolute_error(self.error) @staticmethod def mean_absolute_error(error): r\"\"\"**Mean Absolute Error (MAE)** The Mean",
"as: .. math:: Anomoly Correlation = \\frac{\\sum{(f_i - c)(o_i - c)}} {\\sqrt{\\sum{(f_i -",
"correlation coefficient ( :math:`\\rho_s` , SP_CORR)** The Spearman rank correlation cofficient ( :math:`\\rho_s`",
"\\bar{o} = \\frac{1}{n}\\sum_{i=1}^{n}o_i Returns ------- numpy.ndarray, the sample mean observation (OBAR) \"\"\" return",
"of pairs) are assigned. The pairs of forecast-observed ranks are then used to",
"(MBIAS)**\"\"\" return self.multiplicative_bias(self._f, self._o) @staticmethod def multiplicative_bias(forecast, error): r\"\"\"**Multiplicative bias (MBIAS)** Multiplicative bias",
"Range of the Errors (IQR) is the difference between the 75th and 25th",
"def MBIAS(self): \"\"\"**Multiplicative bias (MBIAS)**\"\"\" return self.multiplicative_bias(self._f, self._o) @staticmethod def multiplicative_bias(forecast, error): r\"\"\"**Multiplicative",
"value for the current pair). Once this is done, Nc is computed by",
"def RMSE(self): \"\"\"**Root-mean-squared error (RMSE)**\"\"\" return self.root_mean_squared_error(self.error) @staticmethod def root_mean_squared_error(error): \"\"\"**Root-mean-squared error (RMSE)**",
"of MSE in terms of squared Bias plus estimated variance of the error,",
"np.average(obs) @property def FSTDEV(self): \"\"\"**The forecast standard deviation (FSTDEV)**\"\"\" return self.forecast_standard_deviation(self._f) @staticmethod def",
"Error Squared, ME2, is provided to give a complete breakdown of MSE in",
":math:`s^{2}_{fo}` . Thus, :math:`MSE = ME^2 + s^{2}_{f-o}` To understand the behavior of",
"self.mean_squared_error(self.error) @staticmethod def mean_squared_error(error): r\"\"\"**Mean-squared error (MSE)** MSE measures the average squared error",
"possible pairs is ; thus, the number of discordant pairs is . Like",
"r_{fo}` is the estimated variance of the error, :math:`s^{2}_{fo}` . Thus, :math:`MSE =",
"def observation_standard_deviation(obs): r\"\"\"**The observed standard deviation (OSTDEV)** The sample variance of the observations",
"= np.array([0.1, 0.25, 0.5, 0.75, 0.9]) return np.quantile(error, quantiles) @property def ANOM_CORR(self): \"\"\"The",
"def percentile_errors(error): \"\"\"Percentiles of the errors Percentiles of the errors provide more information",
"defined as, .. math:: \\bar{o} = \\frac{1}{n}\\sum_{i=1}^{n}o_i Returns ------- numpy.ndarray, the sample mean",
"- \\bar{f})(o_i - \\bar{o})}{\\sqrt{\\sum{(f_i - \\bar{f})^2}}\\sqrt{\\sum{(o_i - \\bar{o})^2}}} r can range between -1",
"r\"\"\"**Kendall's Tau statistic ( :math:`\\tau` , KT_CORR)**\"\"\" return self.kendall_tau_statistic(self._f, self._o) @staticmethod def kendall_tau_statistic(forecast,",
"observations are not associated. Returns ------- numpy.ndarray, Kendall's Tau statistic ( :math:`\\tau` ,",
"of the errors provide more information about the distribution of errors than can",
"as much bias in the forecast as possible. For details, see `Brill and",
"the number of discordant pairs is . Like **r** and :math:`\\rho_s` , Kendall's",
"a value of -1 indicates perfect negative association. A value of 0 indicates",
"\"\"\" return np.average(obs) @property def FSTDEV(self): \"\"\"**The forecast standard deviation (FSTDEV)**\"\"\" return self.forecast_standard_deviation(self._f)",
"self.inter_quartile_range_of_errors(self.error) @staticmethod def inter_quartile_range_of_errors(error): r\"\"\"**Inter Quartile Range of the Errors (IQR)** The Inter",
"the Spearman rank correlation coe cient ranges between -1 and 1; a value",
"14:43 # @Last Modified by: wqshen import numpy as np from logzero import",
"KT_CORR(self): r\"\"\"**Kendall's Tau statistic ( :math:`\\tau` , KT_CORR)**\"\"\" return self.kendall_tau_statistic(self._f, self._o) @staticmethod def",
"np.array([0.1, 0.25, 0.5, 0.75, 0.9]) return np.quantile(error, quantiles) @property def ANOM_CORR(self): \"\"\"The Anomaly",
"-2 s_f s_o r_{fo} where :math:`\\bar{f} - \\bar{o} = ME` and :math:`s^{2}_{f} +",
"observed anomalies. The Anomaly correlation coefficient is defined as: .. math:: Anomoly Correlation",
"(BCMSE)**\"\"\" return self.bias_corrected_mse(self.error) @staticmethod def bias_corrected_mse(error): r\"\"\"**Bias-Corrected MSE (BCMSE)** MSE and RMSE are",
"is defined as .. math:: s_{f} = \\sqrt{s^{2}_{f}} Returns ------- numpy.ndarray, the forecast",
"(forecast is None or obs is None) and fcsterr is None: raise Exception(\"Initialize",
"of the observations is defined as .. math:: s^{2}_{o} = \\frac{1}{T-1}\\sum_{i=1}^{T}(o_i - \\bar{o})^2",
"------- numpy.ndarray, the Pearson correlation coefficient (PR_CORR) \"\"\" return np.corrcoef(forecast, obs)[1, 0] @property",
"Returns ------- nupmy.ndarray, Inter Quartile Range of the Errors (IQR) \"\"\" return np.percentile(error,",
"r_{fo}} Note that the square of the standard deviation of the error (ESTDEV2)",
"Pearson correlation coefficient is defined as: .. math:: r = \\frac{\\sum^{T}_{i=1}(f_i - \\bar{f})(o_i",
"class ContinuousVariableVerification(PointStatBase): def __init__(self, forecast=None, obs=None, fcsterr=None, group=None): if (forecast is None or",
"o_i) = \\bar{f} - \\bar{o} A perfect forecast has ME = 0. Returns",
"mean error. A perfect forecast would have MAE = 0. Returns ------- numpy.ndarray,",
"association between the forecast anomolies and observed anomalies. The Anomaly correlation coefficient is",
"sample variance of the observations is defined as .. math:: s^{2}_{o} = \\frac{1}{T-1}\\sum_{i=1}^{T}(o_i",
"of the error, :math:`s^{2}_{fo}` . Thus, :math:`MSE = ME^2 + s^{2}_{f-o}` To understand",
") pairs according to :math:`f_i`, in which case the :math:`o_i`, values won't necessarily",
"actual value. Percentiles can also be used to create box plots of the",
"s_o r_{fo} where :math:`\\bar{f} - \\bar{o} = ME` and :math:`s^{2}_{f} + s^{2}_{o} -2",
"simpler formulation of the Spearman-rank correlation is based on differences between the each",
"return np.average(forecast) @property def OBAR(self): \"\"\"**The sample mean observation, OBAR**\"\"\" return self.mean_observation(self._o) @staticmethod",
"are not correlated. Returns ------- numpy.ndarray, the Spearman correlation coefficient (SP_CORR) \"\"\" from",
"FSTDEV(self): \"\"\"**The forecast standard deviation (FSTDEV)**\"\"\" return self.forecast_standard_deviation(self._f) @staticmethod def forecast_standard_deviation(forecast): r\"\"\"**The forecast",
"It is defined as ME2 = ME2. A perfect forecast has ME2 =",
"strongly influenced by ME, as shown by this decomposition. The standard deviation of",
":math:`s_{f-o}` , is .. math:: s_{f-o}=\\sqrt{s^{2}_{f-o}}=\\sqrt{s^{2}_{f} + s^{2}_{o} -2 s_f s_o r_{fo}} Note",
"s_{o} = \\sqrt{s^{2}_{o}} Returns ------- numpy.ndarray, the observed standard deviation (OSTDEV) \"\"\" return",
"in which case the :math:`o_i`, values won't necessarily be in order. The number",
"return self.inter_quartile_range_of_errors(self.error) @staticmethod def inter_quartile_range_of_errors(error): r\"\"\"**Inter Quartile Range of the Errors (IQR)** The",
"matching the rank to the actual value. Percentiles can also be used to",
".. math:: s_{f-o}=\\sqrt{s^{2}_{f-o}}=\\sqrt{s^{2}_{f} + s^{2}_{o} -2 s_f s_o r_{fo}} Note that the square",
", PR_CORR)**\"\"\" return self.pearson_correlation_coefficient(self._f, self._o) @staticmethod def pearson_correlation_coefficient(forecast, obs): r\"\"\"**The Pearson correlation coefficient",
"bias (MBIAS) \"\"\" return np.average(forecast) / np.average(error) @property def MSE(self): \"\"\"**Mean-squared error (MSE)**\"\"\"",
"coe cient ranges between -1 and 1; a value of 1 indicates perfect",
"( :math:`\\rho_s` ) is a robust measure of association that is based on",
"obs): r\"\"\"**The Pearson correlation coefficient ( :math:`r` , PR_CORR)** The Pearson correlation coefficient,",
"where NC is the number of \"concordant\" pairs and ND is the number",
"- \\bar{o})^2}}} r can range between -1 and 1; a value of 1",
"observed samples are ordered from smallest to largest and rank values (from 1",
"of the ( :math:`f_i, o_i` ) pairs according to :math:`f_i`, in which case",
"0.25, 0.5, 0.75, 0.9]) return np.quantile(error, quantiles) @property def ANOM_CORR(self): \"\"\"The Anomaly correlation",
"Returns ------- Not implemented numpy.ndarray, Bias Adjusted Gilbert Skill Score (BAGSS) \"\"\" return",
"to eliminate as much bias in the forecast as possible. For details, see",
"actual values. That is, the forecast and observed samples are ordered from smallest",
"the Gilbert Skill Score, but with the contingency table counts adjusted to eliminate",
"and the typical situation, as measured by a climatology (**c**) of some variety.",
"to examine both of the terms of MSE, rather than examining MSE alone.",
"s^{2}_{o} -2 s_f s_o r_{fo}` is the estimated variance of the error, :math:`s^{2}_{fo}`",
"Kendall's Tau ( :math:`\\tau` ) ranges between -1 and 1; a value of",
"MSE and RMSE are strongly impacted by large errors. They also are strongly",
"easily by ordering all of the ( :math:`f_i, o_i` ) pairs according to",
"forecasts and observations are first adjusted according to a climatology value. The anomaly",
"The anomaly is the difference between the individual forecast or observation and the",
"and :math:`\\rho_s` , Kendall's Tau ( :math:`\\tau` ) ranges between -1 and 1;",
"self.bias_corrected_mse(self.error) @staticmethod def bias_corrected_mse(error): r\"\"\"**Bias-Corrected MSE (BCMSE)** MSE and RMSE are strongly impacted",
"Mean Error Squared, ME2, is provided to give a complete breakdown of MSE",
"( :math:`\\rho_s` , SP_CORR)** The Spearman rank correlation cofficient ( :math:`\\rho_s` ) is",
"pairs of ranks (denoted as ( :math:`d_i` ) ): .. math:: \\rho_s =",
"Returns ------- numpy.ndaray, Standard deviation of the error \"\"\" return np.std(error) @property def",
"difference between the 75th and 25th percentiles of the errors. It is de",
"\"\"\"**Standard deviation of the error** (ESTDEV)\"\"\" return self.standard_deviation_of_error(self.error) @staticmethod def standard_deviation_of_error(error): \"\"\"**Standard deviation",
"pairs is ; thus, the number of discordant pairs is . Like **r**",
"as ME2 = ME2. A perfect forecast has ME2 = 0. Returns -------",
"coefficient, except that both the forecasts and observations are first adjusted according to",
"counting the number of pairs (with larger values) for which the value of",
"ned as .. math:: IQR = p_{75} (f_i - o_i) - p_{25}(f_i -",
"observations. The Pearson correlation coefficient is defined as: .. math:: r = \\frac{\\sum^{T}_{i=1}(f_i",
"@property def SP_CORR(self): r\"\"\"**The Spearman rank correlation coefficient ( :math:`\\rho_s` , SP_CORR)**\"\"\" return",
"= fcsterr + obs if obs is None: obs = forecast - fcsterr",
"of the forecasts is defined as .. math:: s^{2}_{f} = \\frac{1}{T-1}\\sum_{i=1}^{T}(f_i - \\bar{f})^2",
"def mean_error(error): r\"\"\"**The Mean Error (ME)** The Mean Error, ME, is a measure",
"\"\"\" return np.average(error ** 2) @property def RMSE(self): \"\"\"**Root-mean-squared error (RMSE)**\"\"\" return self.root_mean_squared_error(self.error)",
"Not Available, 'BAGSS', 'ANOM_CORR' self._available_score += ['FBAR', 'OBAR', 'FSTDEV', 'OSTDEV', 'PR_CORR', 'SP_CORR', 'KT_CORR',",
"'ME', 'ME2', 'MSE', 'RMSE', 'ESTDEV', 'BCMSE', 'MAE', 'IQR', 'MAD', 'EPCT'] if fcsterr is",
"return spearmanr(forecast, obs) @property def KT_CORR(self): r\"\"\"**Kendall's Tau statistic ( :math:`\\tau` , KT_CORR)**\"\"\"",
"statistic ( :math:`\\tau` , KT_CORR) \"\"\" from scipy.stats import kendalltau return kendalltau(forecast, obs)",
"correlation coefficient (SP_CORR) \"\"\" from scipy.stats import spearmanr return spearmanr(forecast, obs) @property def",
"percentiles of the errors. It is de ned as .. math:: IQR =",
"is simply the square root of the MSE, :math:`RMSE = \\sqrt{MSE}` Returns -------",
"(BCMSE)** MSE and RMSE are strongly impacted by large errors. They also are",
"pairs is computed by counting the number of pairs (with larger values) for",
"0 to infinity. A perfect forecast would have MSE = RMSE = 0.",
"= \\sqrt{s^{2}_{o}} Returns ------- numpy.ndarray, the observed standard deviation (OSTDEV) \"\"\" return np.std(obs)",
":math:`\\tau` ) ranges between -1 and 1; a value of 1 indicates perfect",
"that the forecast and observed anomalies are not correlated. Returns ------- Not implemented",
"np.average(error) @property def ME2(self): \"\"\"**The Mean Error Squared** (ME2)\"\"\" return self.mean_error_squared(self.error) @staticmethod def",
"that is based on the ranks of the forecast and observed values rather",
"is not None and fcsterr is not None: logger.warning(\"You give forecast, obs and",
"would have MSE = RMSE = 0. MSE can be re-written as, ..",
"differences between the each of the pairs of ranks (denoted as ( :math:`d_i`",
"is based on the ranks of the forecast and observed values rather than",
"a value of 1 indicates perfect correlation and a value of -1 indicates",
"the :math:`o_i`, values won't necessarily be in order. The number of concordant matches",
"- o_i|}` MAE is less in uenced by large errors and also does",
"the forecasts and observations are first adjusted according to a climatology value. The",
"import PointStatBase class ContinuousVariableVerification(PointStatBase): def __init__(self, forecast=None, obs=None, fcsterr=None, group=None): if (forecast is",
"SP_CORR(self): r\"\"\"**The Spearman rank correlation coefficient ( :math:`\\rho_s` , SP_CORR)**\"\"\" return self.spearman_rank_correlation_cofficient(self._f, self._o)",
", SP_CORR)** The Spearman rank correlation cofficient ( :math:`\\rho_s` ) is a robust",
") ): .. math:: \\rho_s = \\frac{6}{n(n^2 - 1)}\\sum^{n}_{i=1}d^{2}_{i} Like **r**, the Spearman",
"None and fcsterr is not None: logger.warning(\"You give forecast, obs and fcsterr, but",
"depend on the mean error. A perfect forecast would have IQR = 0.",
"- \\bar{o} A perfect forecast has ME = 0. Returns ------- numpy.ndarray, The",
"2020/6/10 14:43 # @Last Modified by: wqshen import numpy as np from logzero",
"below in the section on BCMSE. It is defined as ME2 = ME2.",
"as shown by this decomposition. The standard deviation of the error, :math:`s_{f-o}` ,",
"would have MAE = 0. Returns ------- numpy.ndarray, Mean Absolute Error (MAE) \"\"\"",
"of 1 indicates perfect correlation and - a value of -1 indicates perfect",
"depend on the mean error. A perfect forecast would have MAD = 0.",
"number of \"discordant\" pairs. Concordant pairs are identi ed by comparing each pair",
"not None and obs is not None and fcsterr is not None: logger.warning(\"You",
"error** (ESTDEV)\"\"\" return self.standard_deviation_of_error(self.error) @staticmethod def standard_deviation_of_error(error): \"\"\"**Standard deviation of the error** (ESTDEV)",
"Available, 'BAGSS', 'ANOM_CORR' self._available_score += ['FBAR', 'OBAR', 'FSTDEV', 'OSTDEV', 'PR_CORR', 'SP_CORR', 'KT_CORR', 'MBIAS',",
"of the MSE, :math:`RMSE = \\sqrt{MSE}` Returns ------- numpy.ndarray, Root-mean-squared error (RMSE) \"\"\"",
"def MSE(self): \"\"\"**Mean-squared error (MSE)**\"\"\" return self.mean_squared_error(self.error) @staticmethod def mean_squared_error(error): r\"\"\"**Mean-squared error (MSE)**",
".. math:: ME = \\frac{1}{n}\\sum^{n}_{i=1}(f_i - o_i) = \\bar{f} - \\bar{o} A perfect",
"error, as detailed below in the section on BCMSE. It is defined as",
"OSTDEV(self): r\"\"\"**The observed standard deviation (OSTDEV)**\"\"\" return self.observation_standard_deviation(self._o) @staticmethod def observation_standard_deviation(obs): r\"\"\"**The observed",
"in the sample; this can be done most easily by ordering all of",
"of the error (ESTDEV2) is sometimes called the \"Bias-corrected MSE\" (BCMSE) because it",
"observed standard deviation (OSTDEV)** The sample variance of the observations is defined as",
"is a robust measure of the level of association between the forecast and",
"and observed anomalies. The Anomaly correlation coefficient is defined as: .. math:: Anomoly",
"of the Errors (IQR) \"\"\" return np.percentile(error, 75) - np.percentile(error, 25) @property def",
"errors. The 0.10th, 0.25th, 0.50th, 0.75th, and 0.90th quantile values of the errors",
"MSE measures the average squared error of the forecasts. Specifically, .. math:: MSE",
"RMSE are strongly impacted by large errors. They also are strongly impacted by",
"= RMSE = 0. MSE can be re-written as, .. math:: MSE =",
"indicates that the forecasts and observations are not correlated. Returns ------- numpy.ndarray, the",
"forecasts and observations. The Pearson correlation coefficient is defined as: .. math:: r",
"error, :math:`s^{2}_{fo}` . Thus, :math:`MSE = ME^2 + s^{2}_{f-o}` To understand the behavior",
"OBAR** the sample mean observation (OBAR) is defined as, .. math:: \\bar{o} =",
"\"\"\" return @property def EPCT(self): \"\"\"Percentiles (0.1, 0.25, 0.5, 0.75, 0.9) of the",
"Spearman rank correlation coefficient ( :math:`\\rho_s` , SP_CORR)**\"\"\" return self.spearman_rank_correlation_cofficient(self._f, self._o) @staticmethod def",
"mean forecast (FBAR) \"\"\" return np.average(forecast) @property def OBAR(self): \"\"\"**The sample mean observation,",
"IQR(self): \"\"\"\"**Inter Quartile Range of the Errors (IQR)**\"\"\" return self.inter_quartile_range_of_errors(self.error) @staticmethod def inter_quartile_range_of_errors(error):",
"Deviation (MAD) is defined as :math:`MAD=median|f_i - o_i|` MAD is an estimate of",
"percentile in the ordering, and matching the rank to the actual value. Percentiles",
"of -1 indicates perfect negative association. A value of 0 indicates that the",
"The Anomaly correlation coefficient is defined as: .. math:: Anomoly Correlation = \\frac{\\sum{(f_i",
"by counting the number of pairs (with larger values) for which the value",
"and observations are first adjusted according to a climatology value. The anomaly is",
"The Mean Absolute Error (MAE) is defined as :math:`MAE = \\frac{1}{n}\\sum{|f_i - o_i|}`",
"the forecast as possible. For details, see `Brill and Messinger, 2009. <https://www.adv-geosci.net/16/137/2008/>`_ Returns",
"self._o) @staticmethod def kendall_tau_statistic(forecast, obs): r\"\"\"**Kendall's Tau statistic ( :math:`\\tau` , KT_CORR)** Kendall's",
"anomaly_correlation_coefficient(forecast, obs, climate): r\"\"\"The Anomaly correlation coefficient (ANOM_CORR) The Anomaly correlation coe cient",
"measures the average squared error of the forecasts. Specifically, .. math:: MSE =",
"# -*- coding: utf-8 -*- # @Author: wqshen # @Email: <EMAIL> # @Date:",
"fcsterr values.\") elif forecast is not None and obs is not None and",
"FSTDEV, is defined as .. math:: s_{f} = \\sqrt{s^{2}_{f}} Returns ------- numpy.ndarray, the",
"(SP_CORR) \"\"\" from scipy.stats import spearmanr return spearmanr(forecast, obs) @property def KT_CORR(self): r\"\"\"**Kendall's",
"Score (BAGSS) \"\"\" return @property def EPCT(self): \"\"\"Percentiles (0.1, 0.25, 0.5, 0.75, 0.9)",
"standard deviation (FSTDEV)** The sample variance of the forecasts is defined as ..",
"error (MSE)** MSE measures the average squared error of the forecasts. Specifically, ..",
"kendall_tau_statistic(forecast, obs): r\"\"\"**Kendall's Tau statistic ( :math:`\\tau` , KT_CORR)** Kendall's Tau statistic (",
"MSE and RMSE can range from 0 to infinity. A perfect forecast would",
"and 1; a value of 1 indicates perfect association (concor-dance) and a value",
"deviation, OSTDEV, is defined as .. math:: s_{o} = \\sqrt{s^{2}_{o}} Returns ------- numpy.ndarray,",
"import numpy as np from logzero import logger from .point_stat_base import PointStatBase class",
"be in order. The number of concordant matches of a particular pair with",
"the standard deviation of the error (ESTDEV2) is sometimes called the \"Bias-corrected MSE\"",
"less in uenced by large errors and also does not depend on the",
"FBAR** the sample mean forecast (FBAR) is defined as, .. math:: \\bar{f} =",
"(IQR)**\"\"\" return self.inter_quartile_range_of_errors(self.error) @staticmethod def inter_quartile_range_of_errors(error): r\"\"\"**Inter Quartile Range of the Errors (IQR)**",
"For details, see `Brill and Messinger, 2009. <https://www.adv-geosci.net/16/137/2008/>`_ Returns ------- Not implemented numpy.ndarray,",
"where :math:`\\bar{f} - \\bar{o} = ME` and :math:`s^{2}_{f} + s^{2}_{o} -2 s_f s_o",
"mean forecast, FBAR**\"\"\" return self.mean_forecast(self._f) @staticmethod def mean_forecast(forecast): r\"\"\"**The sample mean forecast, FBAR**",
"Returns ------- numpy.ndarray, Root-mean-squared error (RMSE) \"\"\" return np.sqrt(np.average(error ** 2)) @property def",
"values. MSE and RMSE can range from 0 to infinity. A perfect forecast",
"for which the values of **f** and **o** are both larger than the",
"be strongly influenced by ME, as shown by this decomposition. The standard deviation",
"forecasts. Specifically, .. math:: MSE = \\frac{1}{n}\\sum{(f_i - o_i)^2} Returns ------- numpy.ndarray, Mean-squared",
"self._o) @staticmethod def multiplicative_bias(forecast, error): r\"\"\"**Multiplicative bias (MBIAS)** Multiplicative bias is simply the",
"np.average(np.abs(error)) @property def IQR(self): \"\"\"\"**Inter Quartile Range of the Errors (IQR)**\"\"\" return self.inter_quartile_range_of_errors(self.error)",
"also does not depend on the mean error. A perfect forecast would have",
".. math:: s_{o} = \\sqrt{s^{2}_{o}} Returns ------- numpy.ndarray, the observed standard deviation (OSTDEV)",
"1)}\\sum^{n}_{i=1}d^{2}_{i} Like **r**, the Spearman rank correlation coe cient ranges between -1 and",
"\\frac{1}{n}\\sum^{n}_{i=1}(f_i - o_i) = \\bar{f} - \\bar{o} A perfect forecast has ME =",
"correlation coefficient ( :math:`r` , PR_CORR)**\"\"\" return self.pearson_correlation_coefficient(self._f, self._o) @staticmethod def pearson_correlation_coefficient(forecast, obs):",
"self.pearson_correlation_coefficient(self._f, self._o) @staticmethod def pearson_correlation_coefficient(forecast, obs): r\"\"\"**The Pearson correlation coefficient ( :math:`r` ,",
"def KT_CORR(self): r\"\"\"**Kendall's Tau statistic ( :math:`\\tau` , KT_CORR)**\"\"\" return self.kendall_tau_statistic(self._f, self._o) @staticmethod",
"error (ESTDEV2) is sometimes called the \"Bias-corrected MSE\" (BCMSE) because it removes the",
"not None and fcsterr is not None: logger.warning(\"You give forecast, obs and fcsterr,",
"this is done, Nc is computed by summing the counts for all pairs.",
"can range from 0 to infinity. A perfect forecast would have MSE =",
"list_score(self): \"\"\"list all available score\"\"\" return {k: np.round(getattr(self, k), self.round) for k in",
"(BAGSS)\"\"\" return self.bias_adjusted_gilbert_skill_score(self._f, self._o) @staticmethod def bias_adjusted_gilbert_skill_score(forecast, obs): \"\"\"Bias Adjusted Gilbert Skill Score",
"and observed anomalies are not correlated. Returns ------- Not implemented \"\"\" return def",
"differences. Returns ------- numpy.ndarray, Bias-Corrected MSE (BCMSE) \"\"\" return np.square(np.std(error)) @property def MAE(self):",
"standard_deviation_of_error(error): \"\"\"**Standard deviation of the error** (ESTDEV) Returns ------- numpy.ndaray, Standard deviation of",
"@property def ME2(self): \"\"\"**The Mean Error Squared** (ME2)\"\"\" return self.mean_error_squared(self.error) @staticmethod def mean_error_squared(error):",
"The Mean Error (ME) \"\"\" return np.square(np.average(error)) @property def MBIAS(self): \"\"\"**Multiplicative bias (MBIAS)**\"\"\"",
"forecast is None: forecast = fcsterr + obs if obs is None: obs",
"robust measure of the level of association between the forecast and observation pairs.",
"Anomaly correlation coe cient is equivalent to the Pearson correlation coefficient, except that",
"statistic ( :math:`\\tau` , KT_CORR)**\"\"\" return self.kendall_tau_statistic(self._f, self._o) @staticmethod def kendall_tau_statistic(forecast, obs): r\"\"\"**Kendall's",
"return np.median(np.abs(error)) @property def BAGSS(self): \"\"\"Bias Adjusted Gilbert Skill Score (BAGSS)\"\"\" return self.bias_adjusted_gilbert_skill_score(self._f,",
"a particular pair with other pairs is computed by counting the number of",
"\"\"\"**Bias-Corrected MSE (BCMSE)**\"\"\" return self.bias_corrected_mse(self.error) @staticmethod def bias_corrected_mse(error): r\"\"\"**Bias-Corrected MSE (BCMSE)** MSE and",
"value. The anomaly is the difference between the individual forecast or observation and",
"an estimate of spread, similar to standard error, but is less in uenced",
"error. A perfect forecast would have IQR = 0. Returns ------- nupmy.ndarray, Inter",
"coding: utf-8 -*- # @Author: wqshen # @Email: <EMAIL> # @Date: 2020/6/10 14:43",
"perfect negative association. A value of 0 indicates that the forecasts and observations",
"provided to give a complete breakdown of MSE in terms of squared Bias",
"oi for the current pair is exceeded (that is, pairs for which the",
"is None) and fcsterr is None: raise Exception(\"Initialize failed, check forecast and obs",
"\\frac{1}{n}\\sum{(f_i - o_i)^2} Returns ------- numpy.ndarray, Mean-squared error (MSE) \"\"\" return np.average(error **",
"except that both the forecasts and observations are first adjusted according to a",
"error): r\"\"\"**Multiplicative bias (MBIAS)** Multiplicative bias is simply the ratio of the means",
"that the forecasts and observations are not correlated. Returns ------- numpy.ndarray, the Spearman",
"Spearman-rank correlation is based on differences between the each of the pairs of",
"------- numpy.ndarray, the observed standard deviation (OSTDEV) \"\"\" return np.std(obs) @property def PR_CORR(self):",
"the forecast and observed values rather than the actual values. That is, the",
"s_{f} = \\sqrt{s^{2}_{f}} Returns ------- numpy.ndarray, the forecast standard deviation (FSTDEV) \"\"\" return",
"a complete breakdown of MSE in terms of squared Bias plus estimated variance",
"- o_i) - p_{25}(f_i - o_i) IQR is another estimate of spread, similar",
"return self.anomaly_correlation_coefficient(self._f, self._o, None) @staticmethod def anomaly_correlation_coefficient(forecast, obs, climate): r\"\"\"The Anomaly correlation coefficient",
"be used to create box plots of the errors. The 0.10th, 0.25th, 0.50th,",
"correlation coefficient (ANOM_CORR) The Anomaly correlation coe cient is equivalent to the Pearson",
"( :math:`f_i, o_i` ) pairs according to :math:`f_i`, in which case the :math:`o_i`,",
"indicates perfect negative correlation. A value of 0 indicates that the forecasts and",
"spearman_rank_correlation_cofficient(forecast, obs): r\"\"\"**The Spearman rank correlation coefficient ( :math:`\\rho_s` , SP_CORR)** The Spearman",
"\\frac{\\bar{f}}{\\bar{o}} Returns ------- numpy.ndarray, Multiplicative bias (MBIAS) \"\"\" return np.average(forecast) / np.average(error) @property",
"math:: \\rho_s = \\frac{6}{n(n^2 - 1)}\\sum^{n}_{i=1}d^{2}_{i} Like **r**, the Spearman rank correlation coe",
"-1 and 1; a value of 1 indicates perfect association (concor-dance) and a",
"rank values (from 1 to **n**, where **n** is the total number of",
"necessarily be in order. The number of concordant matches of a particular pair",
"r\"\"\"**The observed standard deviation (OSTDEV)** The sample variance of the observations is defined",
"box plots of the errors. The 0.10th, 0.25th, 0.50th, 0.75th, and 0.90th quantile",
"measures the strength of linear association between the forecast anomolies and observed anomalies.",
"Percentiles are computed by ordering the errors from smallest to largest and computing",
"r\"\"\"**Kendall's Tau statistic ( :math:`\\tau` , KT_CORR)** Kendall's Tau statistic ( :math:`\\tau` )",
"\"\"\"**The forecast standard deviation (FSTDEV)**\"\"\" return self.forecast_standard_deviation(self._f) @staticmethod def forecast_standard_deviation(forecast): r\"\"\"**The forecast standard",
"__init__(self, forecast=None, obs=None, fcsterr=None, group=None): if (forecast is None or obs is None)",
"None: logger.warning(\"You give forecast, obs and fcsterr, but the fcsterr will be ignored.\")",
"number of pairs (with larger values) for which the value of oi for",
"of the errors \"\"\" quantiles = np.array([0.1, 0.25, 0.5, 0.75, 0.9]) return np.quantile(error,",
"observation_standard_deviation(obs): r\"\"\"**The observed standard deviation (OSTDEV)** The sample variance of the observations is",
"Mean Error Squared** (ME2) The Mean Error Squared, ME2, is provided to give",
"section on BCMSE. It is defined as ME2 = ME2. A perfect forecast",
"of the error, :math:`s_{f-o}` , is .. math:: s_{f-o}=\\sqrt{s^{2}_{f-o}}=\\sqrt{s^{2}_{f} + s^{2}_{o} -2 s_f",
"ordering, and matching the rank to the actual value. Percentiles can also be",
"observed anomalies are not correlated. Returns ------- Not implemented \"\"\" return def list_score(self):",
"than examining MSE alone. Moreover, MSE can be strongly influenced by ME, as",
"It is de ned as .. math:: IQR = p_{75} (f_i - o_i)",
"alone. Moreover, MSE can be strongly influenced by ME, as shown by this",
"\"\"\"**Root-mean-squared error (RMSE)**\"\"\" return self.root_mean_squared_error(self.error) @staticmethod def root_mean_squared_error(error): \"\"\"**Root-mean-squared error (RMSE)** RMSE is",
"o_i) IQR is another estimate of spread, similar to standard error, but is",
"and matching the rank to the actual value. Percentiles can also be used",
"based on differences between the each of the pairs of ranks (denoted as",
"\"\"\" return np.average(forecast) @property def OBAR(self): \"\"\"**The sample mean observation, OBAR**\"\"\" return self.mean_observation(self._o)",
"the forecast and observed samples are ordered from smallest to largest and rank",
"quantiles = np.array([0.1, 0.25, 0.5, 0.75, 0.9]) return np.quantile(error, quantiles) @property def ANOM_CORR(self):",
"is important to examine both of the terms of MSE, rather than examining",
"'ANOM_CORR' self._available_score += ['FBAR', 'OBAR', 'FSTDEV', 'OSTDEV', 'PR_CORR', 'SP_CORR', 'KT_CORR', 'MBIAS', ] super(ContinuousVariableVerification,",
"kendalltau(forecast, obs) @property def ME(self): \"\"\"**The Mean Error (ME)**\"\"\" return self.mean_error(self.error) @staticmethod def",
"correlation coe cient is equivalent to the Pearson correlation coefficient, except that both",
"information about the distribution of errors than can be obtained from the mean",
"of squared Bias plus estimated variance of the error, as detailed below in",
"smallest to largest and computing the rank location of each percentile in the",
"math:: s_{o} = \\sqrt{s^{2}_{o}} Returns ------- numpy.ndarray, the observed standard deviation (OSTDEV) \"\"\"",
"import logger from .point_stat_base import PointStatBase class ContinuousVariableVerification(PointStatBase): def __init__(self, forecast=None, obs=None, fcsterr=None,",
"------- numpy.ndarray, Root-mean-squared error (RMSE) \"\"\" return np.sqrt(np.average(error ** 2)) @property def ESTDEV(self):",
"a robust measure of association that is based on the ranks of the",
"the \"Bias-corrected MSE\" (BCMSE) because it removes the effect of overall bias from",
"Gilbert Skill Score (BAGSS) \"\"\" return @property def EPCT(self): \"\"\"Percentiles (0.1, 0.25, 0.5,",
"on differences between the each of the pairs of ranks (denoted as (",
"adjusted according to a climatology value. The anomaly is the difference between the",
"larger than the value for the current pair). Once this is done, Nc",
"@property def FBAR(self): \"\"\"**The sample mean forecast, FBAR**\"\"\" return self.mean_forecast(self._f) @staticmethod def mean_forecast(forecast):",
"A perfect forecast would have IQR = 0. Returns ------- nupmy.ndarray, Inter Quartile",
":math:`\\bar{f} - \\bar{o} = ME` and :math:`s^{2}_{f} + s^{2}_{o} -2 s_f s_o r_{fo}`",
"the actual values. That is, the forecast and observed samples are ordered from",
"would have MAD = 0. Returns ------- numpy.ndarray, Median Absolute Deviation (MAD) \"\"\"",
"c)^2}}} Anomaly correlation can range between -1 and 1; - a value of",
"self.forecast_standard_deviation(self._f) @staticmethod def forecast_standard_deviation(forecast): r\"\"\"**The forecast standard deviation (FSTDEV)** The sample variance of",
"defined as .. math:: s_{o} = \\sqrt{s^{2}_{o}} Returns ------- numpy.ndarray, the observed standard",
"------ numpy.ndarray, the sample mean forecast (FBAR) \"\"\" return np.average(forecast) @property def OBAR(self):",
"understand the behavior of MSE, it is important to examine both of the",
"association. A value of 0 indicates that the forecasts and observations are not",
", is .. math:: s_{f-o}=\\sqrt{s^{2}_{f-o}}=\\sqrt{s^{2}_{f} + s^{2}_{o} -2 s_f s_o r_{fo}} Note that",
"or observation and the typical situation, as measured by a climatology (**c**) of",
".. math:: s^{2}_{o} = \\frac{1}{T-1}\\sum_{i=1}^{T}(o_i - \\bar{o})^2 The observed standard deviation, OSTDEV, is",
"variance of the error, :math:`s^{2}_{fo}` . Thus, :math:`MSE = ME^2 + s^{2}_{f-o}` To",
"does not depend on the mean error. A perfect forecast would have MAD",
"def bias_adjusted_gilbert_skill_score(forecast, obs): \"\"\"Bias Adjusted Gilbert Skill Score (BAGSS) The Bias Adjusted Gilbert",
"complete breakdown of MSE in terms of squared Bias plus estimated variance of",
"ANOM_CORR(self): \"\"\"The Anomaly correlation coefficient (ANOM_CORR)\"\"\" return self.anomaly_correlation_coefficient(self._f, self._o, None) @staticmethod def anomaly_correlation_coefficient(forecast,",
"that the forecasts and observations are not correlated. Returns ------- numpy.ndarray, the Pearson",
"to largest and rank values (from 1 to **n**, where **n** is the",
"MSE(self): \"\"\"**Mean-squared error (MSE)**\"\"\" return self.mean_squared_error(self.error) @staticmethod def mean_squared_error(error): r\"\"\"**Mean-squared error (MSE)** MSE",
"\"\"\"**Root-mean-squared error (RMSE)** RMSE is simply the square root of the MSE, :math:`RMSE",
"- \\bar{o})}{\\sqrt{\\sum{(f_i - \\bar{f})^2}}\\sqrt{\\sum{(o_i - \\bar{o})^2}}} r can range between -1 and 1;",
"and observations. The Pearson correlation coefficient is defined as: .. math:: r =",
"0. Returns ------- numpy.ndarray, The Mean Error (ME) \"\"\" return np.square(np.average(error)) @property def",
"standard deviations of the errors. Percentiles are computed by ordering the errors from",
"square root of the MSE, :math:`RMSE = \\sqrt{MSE}` Returns ------- numpy.ndarray, Root-mean-squared error",
"MSE, it is important to examine both of the terms of MSE, rather",
"1 to **n**, where **n** is the total number of pairs) are assigned.",
"\"\"\"Percentiles of the errors Percentiles of the errors provide more information about the",
"np.median(np.abs(error)) @property def BAGSS(self): \"\"\"Bias Adjusted Gilbert Skill Score (BAGSS)\"\"\" return self.bias_adjusted_gilbert_skill_score(self._f, self._o)",
"\"\"\" from scipy.stats import spearmanr return spearmanr(forecast, obs) @property def KT_CORR(self): r\"\"\"**Kendall's Tau",
"mean_squared_error(error): r\"\"\"**Mean-squared error (MSE)** MSE measures the average squared error of the forecasts.",
":math:`MAE = \\frac{1}{n}\\sum{|f_i - o_i|}` MAE is less in uenced by large errors",
"is the number of \"concordant\" pairs and ND is the number of \"discordant\"",
"o_i` ) pairs according to :math:`f_i`, in which case the :math:`o_i`, values won't",
"SP_CORR)**\"\"\" return self.spearman_rank_correlation_cofficient(self._f, self._o) @staticmethod def spearman_rank_correlation_cofficient(forecast, obs): r\"\"\"**The Spearman rank correlation coefficient",
"\\bar{o} = ME` and :math:`s^{2}_{f} + s^{2}_{o} -2 s_f s_o r_{fo}` is the",
"of the errors. The 0.10th, 0.25th, 0.50th, 0.75th, and 0.90th quantile values of",
"rather than the actual values. That is, the forecast and observed samples are",
"scipy.stats import kendalltau return kendalltau(forecast, obs) @property def ME(self): \"\"\"**The Mean Error (ME)**\"\"\"",
"with other pairs is computed by counting the number of pairs (with larger",
"(OSTDEV)**\"\"\" return self.observation_standard_deviation(self._o) @staticmethod def observation_standard_deviation(obs): r\"\"\"**The observed standard deviation (OSTDEV)** The sample",
"(RMSE)** RMSE is simply the square root of the MSE, :math:`RMSE = \\sqrt{MSE}`",
"'MAD', 'EPCT'] if fcsterr is not None: self._error = fcsterr[~np.isnan(fcsterr)] if forecast is",
"the errors. The 0.10th, 0.25th, 0.50th, 0.75th, and 0.90th quantile values of the",
"of association between the forecast and observation pairs. It is defined as ..",
"self._o) @staticmethod def pearson_correlation_coefficient(forecast, obs): r\"\"\"**The Pearson correlation coefficient ( :math:`r` , PR_CORR)**",
"are not correlated. Returns ------- numpy.ndarray, the Pearson correlation coefficient (PR_CORR) \"\"\" return",
"shown by this decomposition. The standard deviation of the error, :math:`s_{f-o}` , is",
"but is less in uenced by large errors and also does not depend",
", KT_CORR) \"\"\" from scipy.stats import kendalltau return kendalltau(forecast, obs) @property def ME(self):",
"(MAE)** The Mean Absolute Error (MAE) is defined as :math:`MAE = \\frac{1}{n}\\sum{|f_i -",
"( :math:`r` , PR_CORR)** The Pearson correlation coefficient, **r**, measures the strength of",
"+ s^{2}_{f-o}` To understand the behavior of MSE, it is important to examine",
"Returns ------- numpy.ndarray, the Pearson correlation coefficient (PR_CORR) \"\"\" return np.corrcoef(forecast, obs)[1, 0]",
"= ['N', 'ME', 'ME2', 'MSE', 'RMSE', 'ESTDEV', 'BCMSE', 'MAE', 'IQR', 'MAD', 'EPCT'] if",
"behavior of MSE, it is important to examine both of the terms of",
"Skill Score (BAGSS)\"\"\" return self.bias_adjusted_gilbert_skill_score(self._f, self._o) @staticmethod def bias_adjusted_gilbert_skill_score(forecast, obs): \"\"\"Bias Adjusted Gilbert",
"can be re-written as, .. math:: MSE = (\\bar{f} - \\bar{o})^2 + s^{2}_{f}",
"FBAR(self): \"\"\"**The sample mean forecast, FBAR**\"\"\" return self.mean_forecast(self._f) @staticmethod def mean_forecast(forecast): r\"\"\"**The sample",
"'ME2', 'MSE', 'RMSE', 'ESTDEV', 'BCMSE', 'MAE', 'IQR', 'MAD', 'EPCT'] if fcsterr is not",
"each percentile in the ordering, and matching the rank to the actual value.",
"value of -1 indicates perfect negative association. A value of 0 indicates that",
"climate): r\"\"\"The Anomaly correlation coefficient (ANOM_CORR) The Anomaly correlation coe cient is equivalent",
"None: self._error = fcsterr[~np.isnan(fcsterr)] if forecast is None: forecast = fcsterr + obs",
"s_f s_o r_{fo}` is the estimated variance of the error, :math:`s^{2}_{fo}` . Thus,",
"numpy.ndarray, the Pearson correlation coefficient (PR_CORR) \"\"\" return np.corrcoef(forecast, obs)[1, 0] @property def",
"has ME = 0. Returns ------- numpy.ndarray, The Mean Error (ME) \"\"\" return",
"error (RMSE) \"\"\" return np.sqrt(np.average(error ** 2)) @property def ESTDEV(self): \"\"\"**Standard deviation of",
"['FBAR', 'OBAR', 'FSTDEV', 'OSTDEV', 'PR_CORR', 'SP_CORR', 'KT_CORR', 'MBIAS', ] super(ContinuousVariableVerification, self).__init__(forecast, obs, group)",
"RMSE = 0. MSE can be re-written as, .. math:: MSE = (\\bar{f}",
"errors from smallest to largest and computing the rank location of each percentile",
":math:`\\rho_s` , SP_CORR)** The Spearman rank correlation cofficient ( :math:`\\rho_s` ) is a",
"can range between -1 and 1; a value of 1 indicates perfect correlation",
"are strongly impacted by large bias (ME) values. MSE and RMSE can range",
"= \\frac{\\sum{(f_i - c)(o_i - c)}} {\\sqrt{\\sum{(f_i - c)^2}} \\sqrt{\\sum{(o_i - c)^2}}} Anomaly",
"value of -1 indicates perfect negative correlation. - A value of 0 indicates",
"= None self._available_score = ['N', 'ME', 'ME2', 'MSE', 'RMSE', 'ESTDEV', 'BCMSE', 'MAE', 'IQR',",
"KT_CORR)**\"\"\" return self.kendall_tau_statistic(self._f, self._o) @staticmethod def kendall_tau_statistic(forecast, obs): r\"\"\"**Kendall's Tau statistic ( :math:`\\tau`",
"return self.percentile_errors(self.error) @staticmethod def percentile_errors(error): \"\"\"Percentiles of the errors Percentiles of the errors",
"forecast or observation and the typical situation, as measured by a climatology (**c**)",
"= \\frac{1}{T-1}\\sum_{i=1}^{T}(f_i - \\bar{f})^2 The forecast standard deviation, FSTDEV, is defined as ..",
"the contingency table counts adjusted to eliminate as much bias in the forecast",
"**r**, measures the strength of linear association between the forecasts and observations. The",
"also be used to create box plots of the errors. The 0.10th, 0.25th,",
"sample mean observation, OBAR**\"\"\" return self.mean_observation(self._o) @staticmethod def mean_observation(obs): r\"\"\"**The sample mean observation,",
"value of 1 indicates perfect correlation and a value of -1 indicates perfect",
"of discordant pairs is . Like **r** and :math:`\\rho_s` , Kendall's Tau (",
"@property def MAD(self): \"\"\"Median Absolute Deviation (MAD)\"\"\" return self.median_absolute_deviation(self.error) @staticmethod def median_absolute_deviation(error): \"\"\"Median",
"The standard deviation of the error, :math:`s_{f-o}` , is .. math:: s_{f-o}=\\sqrt{s^{2}_{f-o}}=\\sqrt{s^{2}_{f} +",
"error, but is less in uenced by large errors and also does not",
"the error, :math:`s^{2}_{fo}` . Thus, :math:`MSE = ME^2 + s^{2}_{f-o}` To understand the",
"according to :math:`f_i`, in which case the :math:`o_i`, values won't necessarily be in",
"and the observations: .. math:: MBIAS = \\frac{\\bar{f}}{\\bar{o}} Returns ------- numpy.ndarray, Multiplicative bias",
"of the forecasts. Specifically, .. math:: MSE = \\frac{1}{n}\\sum{(f_i - o_i)^2} Returns -------",
"math:: ME = \\frac{1}{n}\\sum^{n}_{i=1}(f_i - o_i) = \\bar{f} - \\bar{o} A perfect forecast",
"sample mean observation (OBAR) is defined as, .. math:: \\bar{o} = \\frac{1}{n}\\sum_{i=1}^{n}o_i Returns",
"\"\"\" return np.square(np.average(error)) @property def MBIAS(self): \"\"\"**Multiplicative bias (MBIAS)**\"\"\" return self.multiplicative_bias(self._f, self._o) @staticmethod",
"correlated. Returns ------- numpy.ndarray, the Spearman correlation coefficient (SP_CORR) \"\"\" from scipy.stats import",
"error, :math:`s_{f-o}` , is .. math:: s_{f-o}=\\sqrt{s^{2}_{f-o}}=\\sqrt{s^{2}_{f} + s^{2}_{o} -2 s_f s_o r_{fo}}",
":math:`MAD=median|f_i - o_i|` MAD is an estimate of spread, similar to standard error,",
"Adjusted Gilbert Skill Score (BAGSS) \"\"\" return @property def EPCT(self): \"\"\"Percentiles (0.1, 0.25,",
"wqshen import numpy as np from logzero import logger from .point_stat_base import PointStatBase",
"more information about the distribution of errors than can be obtained from the",
"correlation. A value of 0 indicates that the forecasts and observations are not",
"\"\"\"**The Mean Error Squared** (ME2) The Mean Error Squared, ME2, is provided to",
"@Author: wqshen # @Email: <EMAIL> # @Date: 2020/6/10 14:43 # @Last Modified by:",
".. math:: s_{f} = \\sqrt{s^{2}_{f}} Returns ------- numpy.ndarray, the forecast standard deviation (FSTDEV)",
"details, see `Brill and Messinger, 2009. <https://www.adv-geosci.net/16/137/2008/>`_ Returns ------- Not implemented numpy.ndarray, Bias",
"of forecast-observed ranks are then used to compute a correlation cofficient, analogous to",
"implemented numpy.ndarray, Bias Adjusted Gilbert Skill Score (BAGSS) \"\"\" return @property def EPCT(self):",
"the behavior of MSE, it is important to examine both of the terms",
"forecast, FBAR** the sample mean forecast (FBAR) is defined as, .. math:: \\bar{f}",
"for continuous variables; in particular ME = Bias. It is defined as ..",
"the level of association between the forecast and observation pairs. It is defined",
"pairs and ND is the number of \"discordant\" pairs. Concordant pairs are identi",
"measured by a climatology (**c**) of some variety. It measures the strength of",
"not depend on the mean error. A perfect forecast would have MAD =",
"numpy.ndarray, Bias-Corrected MSE (BCMSE) \"\"\" return np.square(np.std(error)) @property def MAE(self): \"\"\"**Mean Absolute Error",
"The sample variance of the observations is defined as .. math:: s^{2}_{o} =",
"difference between the individual forecast or observation and the typical situation, as measured",
"0. Returns ------- numpy.ndarray, The Mean Error (ME) \"\"\" return np.average(error) @property def",
"ME, as shown by this decomposition. The standard deviation of the error, :math:`s_{f-o}`",
"math:: MSE = \\frac{1}{n}\\sum{(f_i - o_i)^2} Returns ------- numpy.ndarray, Mean-squared error (MSE) \"\"\"",
"climatology value. The anomaly is the difference between the individual forecast or observation",
"and observations are not correlated. Returns ------- numpy.ndarray, the Spearman correlation coefficient (SP_CORR)",
"coefficient (SP_CORR) \"\"\" from scipy.stats import spearmanr return spearmanr(forecast, obs) @property def KT_CORR(self):",
"Mean Absolute Error (MAE) \"\"\" return np.average(np.abs(error)) @property def IQR(self): \"\"\"\"**Inter Quartile Range",
"computed. Returns ------- numpy.ndarray, Percentiles of the errors \"\"\" quantiles = np.array([0.1, 0.25,",
"between -1 and 1; - a value of 1 indicates perfect correlation and",
"@property def RMSE(self): \"\"\"**Root-mean-squared error (RMSE)**\"\"\" return self.root_mean_squared_error(self.error) @staticmethod def root_mean_squared_error(error): \"\"\"**Root-mean-squared error",
"(FSTDEV)** The sample variance of the forecasts is defined as .. math:: s^{2}_{f}",
"rather than examining MSE alone. Moreover, MSE can be strongly influenced by ME,",
"standard deviation (FSTDEV)**\"\"\" return self.forecast_standard_deviation(self._f) @staticmethod def forecast_standard_deviation(forecast): r\"\"\"**The forecast standard deviation (FSTDEV)**",
"The sample variance of the forecasts is defined as .. math:: s^{2}_{f} =",
"elif forecast is not None and obs is not None and fcsterr is",
"return np.std(error) @property def BCMSE(self): \"\"\"**Bias-Corrected MSE (BCMSE)**\"\"\" return self.bias_corrected_mse(self.error) @staticmethod def bias_corrected_mse(error):",
"the mean and standard deviations of the errors. Percentiles are computed by ordering",
"np.average(forecast) @property def OBAR(self): \"\"\"**The sample mean observation, OBAR**\"\"\" return self.mean_observation(self._o) @staticmethod def",
"@property def FSTDEV(self): \"\"\"**The forecast standard deviation (FSTDEV)**\"\"\" return self.forecast_standard_deviation(self._f) @staticmethod def forecast_standard_deviation(forecast):",
"sample mean forecast (FBAR) \"\"\" return np.average(forecast) @property def OBAR(self): \"\"\"**The sample mean",
"is not None: self._error = fcsterr[~np.isnan(fcsterr)] if forecast is None: forecast = fcsterr",
"Absolute Error (MAE)**\"\"\" return self.mean_absolute_error(self.error) @staticmethod def mean_absolute_error(error): r\"\"\"**Mean Absolute Error (MAE)** The",
"math:: \\bar{f} = \\frac{1}{n}\\sum_{i=1}^{n}f_i Returns ------ numpy.ndarray, the sample mean forecast (FBAR) \"\"\"",
"is ; thus, the number of discordant pairs is . Like **r** and",
"def mean_squared_error(error): r\"\"\"**Mean-squared error (MSE)** MSE measures the average squared error of the",
"robust measure of association that is based on the ranks of the forecast",
"correlation coefficient (ANOM_CORR)\"\"\" return self.anomaly_correlation_coefficient(self._f, self._o, None) @staticmethod def anomaly_correlation_coefficient(forecast, obs, climate): r\"\"\"The",
"errors and also does not depend on the mean error. A perfect forecast",
"= 0. Returns ------- numpy.ndarray, The Mean Error (ME) \"\"\" return np.average(error) @property",
"Pearson correlation cofficient, **r**. A simpler formulation of the Spearman-rank correlation is based",
"c)^2}} \\sqrt{\\sum{(o_i - c)^2}}} Anomaly correlation can range between -1 and 1; -",
"MSE\" (BCMSE) because it removes the effect of overall bias from the forecast-observation",
"plus estimated variance of the error, as detailed below in the section on",
"give a complete breakdown of MSE in terms of squared Bias plus estimated",
"RMSE(self): \"\"\"**Root-mean-squared error (RMSE)**\"\"\" return self.root_mean_squared_error(self.error) @staticmethod def root_mean_squared_error(error): \"\"\"**Root-mean-squared error (RMSE)** RMSE",
"2) @property def RMSE(self): \"\"\"**Root-mean-squared error (RMSE)**\"\"\" return self.root_mean_squared_error(self.error) @staticmethod def root_mean_squared_error(error): \"\"\"**Root-mean-squared",
"self._error = fcsterr[~np.isnan(fcsterr)] if forecast is None: forecast = fcsterr + obs if",
"return np.average(error) @property def ME2(self): \"\"\"**The Mean Error Squared** (ME2)\"\"\" return self.mean_error_squared(self.error) @staticmethod",
"pair with other pairs is computed by counting the number of pairs (with",
"\\frac{N_c - N_p}{n(n-1)/2} where NC is the number of \"concordant\" pairs and ND",
"Adjusted Gilbert Skill Score (BAGSS) The Bias Adjusted Gilbert Skill Score (BAGSS) is",
"IQR is another estimate of spread, similar to standard error, but is less",
"1; a value of 1 indicates perfect correlation and a value of -1",
"def mean_error_squared(error): \"\"\"**The Mean Error Squared** (ME2) The Mean Error Squared, ME2, is",
"values) for which the value of oi for the current pair is exceeded",
"(MAD) \"\"\" return np.median(np.abs(error)) @property def BAGSS(self): \"\"\"Bias Adjusted Gilbert Skill Score (BAGSS)\"\"\"",
"the error** (ESTDEV) Returns ------- numpy.ndaray, Standard deviation of the error \"\"\" return",
"Quartile Range of the Errors (IQR)** The Inter Quartile Range of the Errors",
"forecast and obs and fcsterr values.\") elif forecast is not None and obs",
"\\bar{o} A perfect forecast has ME = 0. Returns ------- numpy.ndarray, The Mean",
"MAD(self): \"\"\"Median Absolute Deviation (MAD)\"\"\" return self.median_absolute_deviation(self.error) @staticmethod def median_absolute_deviation(error): \"\"\"Median Absolute Deviation",
"mean observation, OBAR** the sample mean observation (OBAR) is defined as, .. math::",
"\\frac{1}{n}\\sum_{i=1}^{n}o_i Returns ------- numpy.ndarray, the sample mean observation (OBAR) \"\"\" return np.average(obs) @property",
"math:: \\tau = \\frac{N_c - N_p}{n(n-1)/2} where NC is the number of \"concordant\"",
"estimate of spread, similar to standard error, but is less in uenced by",
"perfect correlation and - a value of -1 indicates perfect negative correlation. -",
"and 0.90th quantile values of the errors are computed. Returns ------- numpy.ndarray, Percentiles",
"The Anomaly correlation coe cient is equivalent to the Pearson correlation coefficient, except",
"Absolute Deviation (MAD) The Median Absolute Deviation (MAD) is defined as :math:`MAD=median|f_i -",
"ordering all of the ( :math:`f_i, o_i` ) pairs according to :math:`f_i`, in",
"and computing the rank location of each percentile in the ordering, and matching",
"of the Errors (IQR) is the difference between the 75th and 25th percentiles",
"does not depend on the mean error. A perfect forecast would have MAE",
"1; a value of 1 indicates perfect association (concor-dance) and a value of",
"self.root_mean_squared_error(self.error) @staticmethod def root_mean_squared_error(error): \"\"\"**Root-mean-squared error (RMSE)** RMSE is simply the square root",
"defined as: .. math:: r = \\frac{\\sum^{T}_{i=1}(f_i - \\bar{f})(o_i - \\bar{o})}{\\sqrt{\\sum{(f_i - \\bar{f})^2}}\\sqrt{\\sum{(o_i",
"check forecast and obs and fcsterr values.\") elif forecast is not None and",
"forecast would have IQR = 0. Returns ------- nupmy.ndarray, Inter Quartile Range of",
"Adjusted Gilbert Skill Score (BAGSS) is the Gilbert Skill Score, but with the",
"are computed by ordering the errors from smallest to largest and computing the",
"(MAE) is defined as :math:`MAE = \\frac{1}{n}\\sum{|f_i - o_i|}` MAE is less in",
"the observations is defined as .. math:: s^{2}_{o} = \\frac{1}{T-1}\\sum_{i=1}^{T}(o_i - \\bar{o})^2 The",
"1 indicates perfect correlation and a value of -1 indicates perfect negative correlation.",
"eliminate as much bias in the forecast as possible. For details, see `Brill",
"between the each of the pairs of ranks (denoted as ( :math:`d_i` )",
"**r**. A simpler formulation of the Spearman-rank correlation is based on differences between",
"of the Errors (IQR)** The Inter Quartile Range of the Errors (IQR) is",
"= \\frac{1}{n}\\sum_{i=1}^{n}o_i Returns ------- numpy.ndarray, the sample mean observation (OBAR) \"\"\" return np.average(obs)",
"bias_adjusted_gilbert_skill_score(forecast, obs): \"\"\"Bias Adjusted Gilbert Skill Score (BAGSS) The Bias Adjusted Gilbert Skill",
"forecasts and observations are not correlated. Returns ------- numpy.ndarray, the Spearman correlation coefficient",
"(MSE)** MSE measures the average squared error of the forecasts. Specifically, .. math::",
"the section on BCMSE. It is defined as ME2 = ME2. A perfect",
"but with the contingency table counts adjusted to eliminate as much bias in",
"from smallest to largest and computing the rank location of each percentile in",
"return self.mean_observation(self._o) @staticmethod def mean_observation(obs): r\"\"\"**The sample mean observation, OBAR** the sample mean",
"compute a correlation cofficient, analogous to the Pearson correlation cofficient, **r**. A simpler",
"standard deviation of the error (ESTDEV2) is sometimes called the \"Bias-corrected MSE\" (BCMSE)",
"number of discordant pairs is . Like **r** and :math:`\\rho_s` , Kendall's Tau",
"the number of pairs (with larger values) for which the value of oi",
"bias (MBIAS)** Multiplicative bias is simply the ratio of the means of the",
"logger from .point_stat_base import PointStatBase class ContinuousVariableVerification(PointStatBase): def __init__(self, forecast=None, obs=None, fcsterr=None, group=None):",
"value of 0 indicates that the forecasts and observations are not correlated. Returns",
"The Mean Error (ME) \"\"\" return np.average(error) @property def ME2(self): \"\"\"**The Mean Error",
"A perfect forecast would have MAD = 0. Returns ------- numpy.ndarray, Median Absolute",
"individual forecast or observation and the typical situation, as measured by a climatology",
"obs is None: obs = forecast - fcsterr # Not Available, 'BAGSS', 'ANOM_CORR'",
"on the ranks of the forecast and observed values rather than the actual",
"= \\frac{1}{n}\\sum_{i=1}^{n}f_i Returns ------ numpy.ndarray, the sample mean forecast (FBAR) \"\"\" return np.average(forecast)",
"2)) @property def ESTDEV(self): \"\"\"**Standard deviation of the error** (ESTDEV)\"\"\" return self.standard_deviation_of_error(self.error) @staticmethod",
"mean error. A perfect forecast would have MAD = 0. Returns ------- numpy.ndarray,",
"of \"concordant\" pairs and ND is the number of \"discordant\" pairs. Concordant pairs",
"(concor-dance) and a value of -1 indicates perfect negative association. A value of",
"of the error** (ESTDEV)\"\"\" return self.standard_deviation_of_error(self.error) @staticmethod def standard_deviation_of_error(error): \"\"\"**Standard deviation of the",
"MSE = (\\bar{f} - \\bar{o})^2 + s^{2}_{f} + s^{2}_{o} -2 s_f s_o r_{fo}",
"**o** are both larger than the value for the current pair). Once this",
"<https://www.adv-geosci.net/16/137/2008/>`_ Returns ------- Not implemented numpy.ndarray, Bias Adjusted Gilbert Skill Score (BAGSS) \"\"\"",
"EPCT(self): \"\"\"Percentiles (0.1, 0.25, 0.5, 0.75, 0.9) of the errors\"\"\" return self.percentile_errors(self.error) @staticmethod",
"and also does not depend on the mean error. A perfect forecast would",
"A value of 0 indicates that the forecast and observed anomalies are not",
"particular ME = Bias. It is defined as .. math:: ME = \\frac{1}{n}\\sum^{n}_{i=1}(f_i",
"------- numpy.ndarray, Kendall's Tau statistic ( :math:`\\tau` , KT_CORR) \"\"\" from scipy.stats import",
"particular pair with other pairs is computed by counting the number of pairs",
"MBIAS = \\frac{\\bar{f}}{\\bar{o}} Returns ------- numpy.ndarray, Multiplicative bias (MBIAS) \"\"\" return np.average(forecast) /",
"\"\"\"Median Absolute Deviation (MAD)\"\"\" return self.median_absolute_deviation(self.error) @staticmethod def median_absolute_deviation(error): \"\"\"Median Absolute Deviation (MAD)",
"kendalltau return kendalltau(forecast, obs) @property def ME(self): \"\"\"**The Mean Error (ME)**\"\"\" return self.mean_error(self.error)",
"@property def ESTDEV(self): \"\"\"**Standard deviation of the error** (ESTDEV)\"\"\" return self.standard_deviation_of_error(self.error) @staticmethod def",
"(ME)** The Mean Error, ME, is a measure of overall bias for continuous",
"numpy.ndarray, The Mean Error (ME) \"\"\" return np.average(error) @property def ME2(self): \"\"\"**The Mean",
"/ np.average(error) @property def MSE(self): \"\"\"**Mean-squared error (MSE)**\"\"\" return self.mean_squared_error(self.error) @staticmethod def mean_squared_error(error):",
"observations is defined as .. math:: s^{2}_{o} = \\frac{1}{T-1}\\sum_{i=1}^{T}(o_i - \\bar{o})^2 The observed",
"return self.median_absolute_deviation(self.error) @staticmethod def median_absolute_deviation(error): \"\"\"Median Absolute Deviation (MAD) The Median Absolute Deviation",
"self._o, None) @staticmethod def anomaly_correlation_coefficient(forecast, obs, climate): r\"\"\"The Anomaly correlation coefficient (ANOM_CORR) The",
"Skill Score (BAGSS) The Bias Adjusted Gilbert Skill Score (BAGSS) is the Gilbert",
"if obs is None: obs = forecast - fcsterr # Not Available, 'BAGSS',",
"is computed by counting the number of pairs (with larger values) for which",
"correlated. Returns ------- numpy.ndarray, the Pearson correlation coefficient (PR_CORR) \"\"\" return np.corrcoef(forecast, obs)[1,",
"'EPCT'] if fcsterr is not None: self._error = fcsterr[~np.isnan(fcsterr)] if forecast is None:",
"has ME2 = 0. Returns ------- numpy.ndarray, The Mean Error (ME) \"\"\" return",
"the mean error. A perfect forecast would have MAD = 0. Returns -------",
"in order. The number of concordant matches of a particular pair with other",
"Squared** (ME2) The Mean Error Squared, ME2, is provided to give a complete",
"Quartile Range of the Errors (IQR) is the difference between the 75th and",
"are computed. Returns ------- numpy.ndarray, Percentiles of the errors \"\"\" quantiles = np.array([0.1,",
"value. Percentiles can also be used to create box plots of the errors.",
"OBAR**\"\"\" return self.mean_observation(self._o) @staticmethod def mean_observation(obs): r\"\"\"**The sample mean observation, OBAR** the sample",
"@property def MSE(self): \"\"\"**Mean-squared error (MSE)**\"\"\" return self.mean_squared_error(self.error) @staticmethod def mean_squared_error(error): r\"\"\"**Mean-squared error",
"r\"\"\"**Mean Absolute Error (MAE)** The Mean Absolute Error (MAE) is defined as :math:`MAE",
"computed by summing the counts for all pairs. The total number of possible",
"as .. math:: ME = \\frac{1}{n}\\sum^{n}_{i=1}(f_i - o_i) = \\bar{f} - \\bar{o} A",
"return np.sqrt(np.average(error ** 2)) @property def ESTDEV(self): \"\"\"**Standard deviation of the error** (ESTDEV)\"\"\"",
".. math:: r = \\frac{\\sum^{T}_{i=1}(f_i - \\bar{f})(o_i - \\bar{o})}{\\sqrt{\\sum{(f_i - \\bar{f})^2}}\\sqrt{\\sum{(o_i - \\bar{o})^2}}}",
"quantile values of the errors are computed. Returns ------- numpy.ndarray, Percentiles of the",
"both the forecasts and observations are first adjusted according to a climatology value.",
"math:: IQR = p_{75} (f_i - o_i) - p_{25}(f_i - o_i) IQR is",
"is defined as: .. math:: r = \\frac{\\sum^{T}_{i=1}(f_i - \\bar{f})(o_i - \\bar{o})}{\\sqrt{\\sum{(f_i -",
"perfect forecast would have MAD = 0. Returns ------- numpy.ndarray, Median Absolute Deviation",
"the number of \"concordant\" pairs and ND is the number of \"discordant\" pairs.",
"coefficient ( :math:`r` , PR_CORR)**\"\"\" return self.pearson_correlation_coefficient(self._f, self._o) @staticmethod def pearson_correlation_coefficient(forecast, obs): r\"\"\"**The",
"negative association. A value of 0 indicates that the forecasts and observations are",
"is defined as, .. math:: \\bar{f} = \\frac{1}{n}\\sum_{i=1}^{n}f_i Returns ------ numpy.ndarray, the sample",
"self.mean_error_squared(self.error) @staticmethod def mean_error_squared(error): \"\"\"**The Mean Error Squared** (ME2) The Mean Error Squared,",
"observations are first adjusted according to a climatology value. The anomaly is the",
"to **n**, where **n** is the total number of pairs) are assigned. The",
"Error (ME) \"\"\" return np.square(np.average(error)) @property def MBIAS(self): \"\"\"**Multiplicative bias (MBIAS)**\"\"\" return self.multiplicative_bias(self._f,",
"bias (MBIAS)**\"\"\" return self.multiplicative_bias(self._f, self._o) @staticmethod def multiplicative_bias(forecast, error): r\"\"\"**Multiplicative bias (MBIAS)** Multiplicative",
"-1 indicates perfect negative association. A value of 0 indicates that the forecasts",
"the errors. It is de ned as .. math:: IQR = p_{75} (f_i",
"- \\bar{f})^2 The forecast standard deviation, FSTDEV, is defined as .. math:: s_{f}",
"0.25, 0.5, 0.75, 0.9) of the errors\"\"\" return self.percentile_errors(self.error) @staticmethod def percentile_errors(error): \"\"\"Percentiles",
"other pairs in the sample; this can be done most easily by ordering",
"math:: \\bar{o} = \\frac{1}{n}\\sum_{i=1}^{n}o_i Returns ------- numpy.ndarray, the sample mean observation (OBAR) \"\"\"",
"(MBIAS) \"\"\" return np.average(forecast) / np.average(error) @property def MSE(self): \"\"\"**Mean-squared error (MSE)**\"\"\" return",
"the estimated variance of the error, :math:`s^{2}_{fo}` . Thus, :math:`MSE = ME^2 +",
"the errors from smallest to largest and computing the rank location of each",
"= \\frac{\\sum^{T}_{i=1}(f_i - \\bar{f})(o_i - \\bar{o})}{\\sqrt{\\sum{(f_i - \\bar{f})^2}}\\sqrt{\\sum{(o_i - \\bar{o})^2}}} r can range",
"\"\"\"**The sample mean forecast, FBAR**\"\"\" return self.mean_forecast(self._f) @staticmethod def mean_forecast(forecast): r\"\"\"**The sample mean",
"The Mean Error Squared, ME2, is provided to give a complete breakdown of",
"the forecast-observation squared differences. Returns ------- numpy.ndarray, Bias-Corrected MSE (BCMSE) \"\"\" return np.square(np.std(error))",
"square of the standard deviation of the error (ESTDEV2) is sometimes called the",
"self._available_score += ['FBAR', 'OBAR', 'FSTDEV', 'OSTDEV', 'PR_CORR', 'SP_CORR', 'KT_CORR', 'MBIAS', ] super(ContinuousVariableVerification, self).__init__(forecast,",
", SP_CORR)**\"\"\" return self.spearman_rank_correlation_cofficient(self._f, self._o) @staticmethod def spearman_rank_correlation_cofficient(forecast, obs): r\"\"\"**The Spearman rank correlation",
"deviation of the error (ESTDEV2) is sometimes called the \"Bias-corrected MSE\" (BCMSE) because",
"is the number of \"discordant\" pairs. Concordant pairs are identi ed by comparing",
"as .. math:: IQR = p_{75} (f_i - o_i) - p_{25}(f_i - o_i)",
"forecast would have MAD = 0. Returns ------- numpy.ndarray, Median Absolute Deviation (MAD)",
":math:`s^{2}_{f} + s^{2}_{o} -2 s_f s_o r_{fo}` is the estimated variance of the",
"the errors are computed. Returns ------- numpy.ndarray, Percentiles of the errors \"\"\" quantiles",
"correlation coefficient is defined as: .. math:: Anomoly Correlation = \\frac{\\sum{(f_i - c)(o_i",
"(BAGSS) The Bias Adjusted Gilbert Skill Score (BAGSS) is the Gilbert Skill Score,",
"is defined as .. math:: s^{2}_{o} = \\frac{1}{T-1}\\sum_{i=1}^{T}(o_i - \\bar{o})^2 The observed standard",
"( :math:`\\tau` , KT_CORR) \"\"\" from scipy.stats import kendalltau return kendalltau(forecast, obs) @property",
"0] @property def SP_CORR(self): r\"\"\"**The Spearman rank correlation coefficient ( :math:`\\rho_s` , SP_CORR)**\"\"\"",
"return @property def EPCT(self): \"\"\"Percentiles (0.1, 0.25, 0.5, 0.75, 0.9) of the errors\"\"\"",
"largest and computing the rank location of each percentile in the ordering, and",
"a value of 1 indicates perfect correlation and - a value of -1",
"s_o r_{fo}` is the estimated variance of the error, :math:`s^{2}_{fo}` . Thus, :math:`MSE",
"errors. Percentiles are computed by ordering the errors from smallest to largest and",
".point_stat_base import PointStatBase class ContinuousVariableVerification(PointStatBase): def __init__(self, forecast=None, obs=None, fcsterr=None, group=None): if (forecast",
"failed, check forecast and obs and fcsterr values.\") elif forecast is not None",
"effect of overall bias from the forecast-observation squared differences. Returns ------- numpy.ndarray, Bias-Corrected",
"self.kendall_tau_statistic(self._f, self._o) @staticmethod def kendall_tau_statistic(forecast, obs): r\"\"\"**Kendall's Tau statistic ( :math:`\\tau` , KT_CORR)**",
"pairs. Concordant pairs are identi ed by comparing each pair with all other",
"and 1; a value of 1 indicates perfect correlation and a value of",
"have MAD = 0. Returns ------- numpy.ndarray, Median Absolute Deviation (MAD) \"\"\" return",
"- c)}} {\\sqrt{\\sum{(f_i - c)^2}} \\sqrt{\\sum{(o_i - c)^2}}} Anomaly correlation can range between",
"The forecast standard deviation, FSTDEV, is defined as .. math:: s_{f} = \\sqrt{s^{2}_{f}}",
"return np.average(forecast) / np.average(error) @property def MSE(self): \"\"\"**Mean-squared error (MSE)**\"\"\" return self.mean_squared_error(self.error) @staticmethod",
"the actual value. Percentiles can also be used to create box plots of",
"IQR = 0. Returns ------- nupmy.ndarray, Inter Quartile Range of the Errors (IQR)",
"the forecasts is defined as .. math:: s^{2}_{f} = \\frac{1}{T-1}\\sum_{i=1}^{T}(f_i - \\bar{f})^2 The",
"r\"\"\"**The Mean Error (ME)** The Mean Error, ME, is a measure of overall",
"the typical situation, as measured by a climatology (**c**) of some variety. It",
"@staticmethod def bias_adjusted_gilbert_skill_score(forecast, obs): \"\"\"Bias Adjusted Gilbert Skill Score (BAGSS) The Bias Adjusted",
"def MAD(self): \"\"\"Median Absolute Deviation (MAD)\"\"\" return self.median_absolute_deviation(self.error) @staticmethod def median_absolute_deviation(error): \"\"\"Median Absolute",
"the forecast and observed anomalies are not correlated. Returns ------- Not implemented \"\"\"",
"+ obs if obs is None: obs = forecast - fcsterr # Not",
"between the individual forecast or observation and the typical situation, as measured by",
"of errors than can be obtained from the mean and standard deviations of",
"To understand the behavior of MSE, it is important to examine both of",
"def forecast_standard_deviation(forecast): r\"\"\"**The forecast standard deviation (FSTDEV)** The sample variance of the forecasts",
"of a particular pair with other pairs is computed by counting the number",
"the ordering, and matching the rank to the actual value. Percentiles can also",
"math:: s_{f} = \\sqrt{s^{2}_{f}} Returns ------- numpy.ndarray, the forecast standard deviation (FSTDEV) \"\"\"",
"\"\"\" return np.std(forecast) @property def OSTDEV(self): r\"\"\"**The observed standard deviation (OSTDEV)**\"\"\" return self.observation_standard_deviation(self._o)",
"based on the ranks of the forecast and observed values rather than the",
"-1 and 1; - a value of 1 indicates perfect correlation and -",
"perfect forecast has ME2 = 0. Returns ------- numpy.ndarray, The Mean Error (ME)",
"0.5, 0.75, 0.9) of the errors\"\"\" return self.percentile_errors(self.error) @staticmethod def percentile_errors(error): \"\"\"Percentiles of",
"0.90th quantile values of the errors are computed. Returns ------- numpy.ndarray, Percentiles of",
"and - a value of -1 indicates perfect negative correlation. - A value",
"= fcsterr[~np.isnan(fcsterr)] if forecast is None: forecast = fcsterr + obs if obs",
"The pairs of forecast-observed ranks are then used to compute a correlation cofficient,",
"mean_absolute_error(error): r\"\"\"**Mean Absolute Error (MAE)** The Mean Absolute Error (MAE) is defined as",
"(ESTDEV) Returns ------- numpy.ndaray, Standard deviation of the error \"\"\" return np.std(error) @property",
"the effect of overall bias from the forecast-observation squared differences. Returns ------- numpy.ndarray,",
"average squared error of the forecasts. Specifically, .. math:: MSE = \\frac{1}{n}\\sum{(f_i -",
"error (RMSE)**\"\"\" return self.root_mean_squared_error(self.error) @staticmethod def root_mean_squared_error(error): \"\"\"**Root-mean-squared error (RMSE)** RMSE is simply",
"standard deviation (FSTDEV) \"\"\" return np.std(forecast) @property def OSTDEV(self): r\"\"\"**The observed standard deviation",
"ME2 = ME2. A perfect forecast has ME2 = 0. Returns ------- numpy.ndarray,",
"@property def KT_CORR(self): r\"\"\"**Kendall's Tau statistic ( :math:`\\tau` , KT_CORR)**\"\"\" return self.kendall_tau_statistic(self._f, self._o)",
"are both larger than the value for the current pair). Once this is",
"= ME^2 + s^{2}_{f-o}` To understand the behavior of MSE, it is important",
"@property def EPCT(self): \"\"\"Percentiles (0.1, 0.25, 0.5, 0.75, 0.9) of the errors\"\"\" return",
"@staticmethod def mean_error(error): r\"\"\"**The Mean Error (ME)** The Mean Error, ME, is a",
"of possible pairs is ; thus, the number of discordant pairs is .",
"Returns ------ numpy.ndarray, the sample mean forecast (FBAR) \"\"\" return np.average(forecast) @property def",
"\\bar{o})^2}}} r can range between -1 and 1; a value of 1 indicates",
"deviation (FSTDEV) \"\"\" return np.std(forecast) @property def OSTDEV(self): r\"\"\"**The observed standard deviation (OSTDEV)**\"\"\"",
"- o_i) IQR is another estimate of spread, similar to standard error, but",
"'OBAR', 'FSTDEV', 'OSTDEV', 'PR_CORR', 'SP_CORR', 'KT_CORR', 'MBIAS', ] super(ContinuousVariableVerification, self).__init__(forecast, obs, group) @property",
"math:: MBIAS = \\frac{\\bar{f}}{\\bar{o}} Returns ------- numpy.ndarray, Multiplicative bias (MBIAS) \"\"\" return np.average(forecast)",
"'BAGSS', 'ANOM_CORR' self._available_score += ['FBAR', 'OBAR', 'FSTDEV', 'OSTDEV', 'PR_CORR', 'SP_CORR', 'KT_CORR', 'MBIAS', ]",
"forecast would have MAE = 0. Returns ------- numpy.ndarray, Mean Absolute Error (MAE)",
"be done most easily by ordering all of the ( :math:`f_i, o_i` )",
"pairs. The total number of possible pairs is ; thus, the number of",
"the terms of MSE, rather than examining MSE alone. Moreover, MSE can be",
"as: .. math:: r = \\frac{\\sum^{T}_{i=1}(f_i - \\bar{f})(o_i - \\bar{o})}{\\sqrt{\\sum{(f_i - \\bar{f})^2}}\\sqrt{\\sum{(o_i -",
"ME = \\frac{1}{n}\\sum^{n}_{i=1}(f_i - o_i) = \\bar{f} - \\bar{o} A perfect forecast has",
"Multiplicative bias (MBIAS) \"\"\" return np.average(forecast) / np.average(error) @property def MSE(self): \"\"\"**Mean-squared error",
"0. Returns ------- numpy.ndarray, Mean Absolute Error (MAE) \"\"\" return np.average(np.abs(error)) @property def",
"def EPCT(self): \"\"\"Percentiles (0.1, 0.25, 0.5, 0.75, 0.9) of the errors\"\"\" return self.percentile_errors(self.error)",
"a correlation cofficient, analogous to the Pearson correlation cofficient, **r**. A simpler formulation",
"(that is, pairs for which the values of **f** and **o** are both",
"by ordering the errors from smallest to largest and computing the rank location",
"self._o) @staticmethod def bias_adjusted_gilbert_skill_score(forecast, obs): \"\"\"Bias Adjusted Gilbert Skill Score (BAGSS) The Bias",
"- \\bar{f})^2}}\\sqrt{\\sum{(o_i - \\bar{o})^2}}} r can range between -1 and 1; a value",
"of the level of association between the forecast and observation pairs. It is",
".. math:: s^{2}_{f} = \\frac{1}{T-1}\\sum_{i=1}^{T}(f_i - \\bar{f})^2 The forecast standard deviation, FSTDEV, is",
"on the mean error. A perfect forecast would have MAE = 0. Returns",
"Tau statistic ( :math:`\\tau` , KT_CORR)** Kendall's Tau statistic ( :math:`\\tau` ) is",
"s^{2}_{o} -2 s_f s_o r_{fo}} Note that the square of the standard deviation",
"correlation is based on differences between the each of the pairs of ranks",
"is defined as :math:`MAD=median|f_i - o_i|` MAD is an estimate of spread, similar",
"deviation, FSTDEV, is defined as .. math:: s_{f} = \\sqrt{s^{2}_{f}} Returns ------- numpy.ndarray,",
"Returns ------- numpy.ndarray, the Spearman correlation coefficient (SP_CORR) \"\"\" from scipy.stats import spearmanr",
"r\"\"\"**The forecast standard deviation (FSTDEV)** The sample variance of the forecasts is defined",
"def OBAR(self): \"\"\"**The sample mean observation, OBAR**\"\"\" return self.mean_observation(self._o) @staticmethod def mean_observation(obs): r\"\"\"**The",
"- np.percentile(error, 25) @property def MAD(self): \"\"\"Median Absolute Deviation (MAD)\"\"\" return self.median_absolute_deviation(self.error) @staticmethod",
"'MAE', 'IQR', 'MAD', 'EPCT'] if fcsterr is not None: self._error = fcsterr[~np.isnan(fcsterr)] if",
"the sample mean observation (OBAR) \"\"\" return np.average(obs) @property def FSTDEV(self): \"\"\"**The forecast",
"self.anomaly_correlation_coefficient(self._f, self._o, None) @staticmethod def anomaly_correlation_coefficient(forecast, obs, climate): r\"\"\"The Anomaly correlation coefficient (ANOM_CORR)",
"@property def ME(self): \"\"\"**The Mean Error (ME)**\"\"\" return self.mean_error(self.error) @staticmethod def mean_error(error): r\"\"\"**The",
"defined as :math:`MAE = \\frac{1}{n}\\sum{|f_i - o_i|}` MAE is less in uenced by",
"\\bar{o})^2 + s^{2}_{f} + s^{2}_{o} -2 s_f s_o r_{fo} where :math:`\\bar{f} - \\bar{o}",
"as :math:`MAD=median|f_i - o_i|` MAD is an estimate of spread, similar to standard",
"forecast has ME = 0. Returns ------- numpy.ndarray, The Mean Error (ME) \"\"\"",
"the Pearson correlation coefficient (PR_CORR) \"\"\" return np.corrcoef(forecast, obs)[1, 0] @property def SP_CORR(self):",
"the Errors (IQR) \"\"\" return np.percentile(error, 75) - np.percentile(error, 25) @property def MAD(self):",
"Score, but with the contingency table counts adjusted to eliminate as much bias",
"Anomaly correlation coefficient (ANOM_CORR) The Anomaly correlation coe cient is equivalent to the",
"as, .. math:: \\bar{o} = \\frac{1}{n}\\sum_{i=1}^{n}o_i Returns ------- numpy.ndarray, the sample mean observation",
"def bias_corrected_mse(error): r\"\"\"**Bias-Corrected MSE (BCMSE)** MSE and RMSE are strongly impacted by large",
"of the forecast and observed values rather than the actual values. That is,",
"= \\frac{N_c - N_p}{n(n-1)/2} where NC is the number of \"concordant\" pairs and",
"anomalies are not correlated. Returns ------- Not implemented \"\"\" return def list_score(self): \"\"\"list",
"Pearson correlation coefficient, except that both the forecasts and observations are first adjusted",
"-1 indicates perfect negative correlation. - A value of 0 indicates that the",
"- A value of 0 indicates that the forecast and observed anomalies are",
"a value of -1 indicates perfect negative correlation. A value of 0 indicates",
"------- nupmy.ndarray, Inter Quartile Range of the Errors (IQR) \"\"\" return np.percentile(error, 75)",
"'BCMSE', 'MAE', 'IQR', 'MAD', 'EPCT'] if fcsterr is not None: self._error = fcsterr[~np.isnan(fcsterr)]",
"['N', 'ME', 'ME2', 'MSE', 'RMSE', 'ESTDEV', 'BCMSE', 'MAE', 'IQR', 'MAD', 'EPCT'] if fcsterr",
"observation (OBAR) is defined as, .. math:: \\bar{o} = \\frac{1}{n}\\sum_{i=1}^{n}o_i Returns ------- numpy.ndarray,",
"= \\frac{1}{n}\\sum{|f_i - o_i|}` MAE is less in uenced by large errors and",
"Deviation (MAD)\"\"\" return self.median_absolute_deviation(self.error) @staticmethod def median_absolute_deviation(error): \"\"\"Median Absolute Deviation (MAD) The Median",
"return self.mean_squared_error(self.error) @staticmethod def mean_squared_error(error): r\"\"\"**Mean-squared error (MSE)** MSE measures the average squared",
"the errors \"\"\" quantiles = np.array([0.1, 0.25, 0.5, 0.75, 0.9]) return np.quantile(error, quantiles)",
"of overall bias for continuous variables; in particular ME = Bias. It is",
"o_i) - p_{25}(f_i - o_i) IQR is another estimate of spread, similar to",
"MSE = \\frac{1}{n}\\sum{(f_i - o_i)^2} Returns ------- numpy.ndarray, Mean-squared error (MSE) \"\"\" return",
"np.average(error) @property def MSE(self): \"\"\"**Mean-squared error (MSE)**\"\"\" return self.mean_squared_error(self.error) @staticmethod def mean_squared_error(error): r\"\"\"**Mean-squared",
"discordant pairs is . Like **r** and :math:`\\rho_s` , Kendall's Tau ( :math:`\\tau`",
"Skill Score (BAGSS) \"\"\" return @property def EPCT(self): \"\"\"Percentiles (0.1, 0.25, 0.5, 0.75,",
"1 indicates perfect association (concor-dance) and a value of -1 indicates perfect negative",
"ME2, is provided to give a complete breakdown of MSE in terms of",
"return np.corrcoef(forecast, obs)[1, 0] @property def SP_CORR(self): r\"\"\"**The Spearman rank correlation coefficient (",
"assigned. The pairs of forecast-observed ranks are then used to compute a correlation",
"pairs) are assigned. The pairs of forecast-observed ranks are then used to compute",
"The Mean Error, ME, is a measure of overall bias for continuous variables;",
"\\bar{f})^2 The forecast standard deviation, FSTDEV, is defined as .. math:: s_{f} =",
"and observation pairs. It is defined as .. math:: \\tau = \\frac{N_c -",
"OSTDEV, is defined as .. math:: s_{o} = \\sqrt{s^{2}_{o}} Returns ------- numpy.ndarray, the",
"( :math:`d_i` ) ): .. math:: \\rho_s = \\frac{6}{n(n^2 - 1)}\\sum^{n}_{i=1}d^{2}_{i} Like **r**,",
"decomposition. The standard deviation of the error, :math:`s_{f-o}` , is .. math:: s_{f-o}=\\sqrt{s^{2}_{f-o}}=\\sqrt{s^{2}_{f}",
"done, Nc is computed by summing the counts for all pairs. The total",
"(ESTDEV2) is sometimes called the \"Bias-corrected MSE\" (BCMSE) because it removes the effect",
"of linear association between the forecast anomolies and observed anomalies. The Anomaly correlation",
"np.corrcoef(forecast, obs)[1, 0] @property def SP_CORR(self): r\"\"\"**The Spearman rank correlation coefficient ( :math:`\\rho_s`",
"= \\frac{1}{n}\\sum^{n}_{i=1}(f_i - o_i) = \\bar{f} - \\bar{o} A perfect forecast has ME",
"obs and fcsterr, but the fcsterr will be ignored.\") fcsterr = None self._available_score",
"used to create box plots of the errors. The 0.10th, 0.25th, 0.50th, 0.75th,",
"than can be obtained from the mean and standard deviations of the errors.",
"number of concordant matches of a particular pair with other pairs is computed",
"BCMSE. It is defined as ME2 = ME2. A perfect forecast has ME2",
"It is defined as .. math:: \\tau = \\frac{N_c - N_p}{n(n-1)/2} where NC",
"value of 1 indicates perfect association (concor-dance) and a value of -1 indicates",
"numpy.ndarray, Mean Absolute Error (MAE) \"\"\" return np.average(np.abs(error)) @property def IQR(self): \"\"\"\"**Inter Quartile",
"Returns ------- numpy.ndarray, the observed standard deviation (OSTDEV) \"\"\" return np.std(obs) @property def",
"Errors (IQR) is the difference between the 75th and 25th percentiles of the",
"Mean Error Squared** (ME2)\"\"\" return self.mean_error_squared(self.error) @staticmethod def mean_error_squared(error): \"\"\"**The Mean Error Squared**",
"by summing the counts for all pairs. The total number of possible pairs",
"@Last Modified by: wqshen import numpy as np from logzero import logger from",
"correlation and a value of -1 indicates perfect negative correlation. A value of",
"cofficient, **r**. A simpler formulation of the Spearman-rank correlation is based on differences",
"ND is the number of \"discordant\" pairs. Concordant pairs are identi ed by",
"used to compute a correlation cofficient, analogous to the Pearson correlation cofficient, **r**.",
"sample mean forecast (FBAR) is defined as, .. math:: \\bar{f} = \\frac{1}{n}\\sum_{i=1}^{n}f_i Returns",
"Deviation (MAD) The Median Absolute Deviation (MAD) is defined as :math:`MAD=median|f_i - o_i|`",
"values.\") elif forecast is not None and obs is not None and fcsterr",
"re-written as, .. math:: MSE = (\\bar{f} - \\bar{o})^2 + s^{2}_{f} + s^{2}_{o}",
"of some variety. It measures the strength of linear association between the forecast",
"MSE, :math:`RMSE = \\sqrt{MSE}` Returns ------- numpy.ndarray, Root-mean-squared error (RMSE) \"\"\" return np.sqrt(np.average(error",
"not None: self._error = fcsterr[~np.isnan(fcsterr)] if forecast is None: forecast = fcsterr +",
"perfect association (concor-dance) and a value of -1 indicates perfect negative association. A",
"analogous to the Pearson correlation cofficient, **r**. A simpler formulation of the Spearman-rank",
"mean_error(error): r\"\"\"**The Mean Error (ME)** The Mean Error, ME, is a measure of",
"numpy.ndarray, the forecast standard deviation (FSTDEV) \"\"\" return np.std(forecast) @property def OSTDEV(self): r\"\"\"**The",
"0.75th, and 0.90th quantile values of the errors are computed. Returns ------- numpy.ndarray,",
"forecasts is defined as .. math:: s^{2}_{f} = \\frac{1}{T-1}\\sum_{i=1}^{T}(f_i - \\bar{f})^2 The forecast",
"terms of MSE, rather than examining MSE alone. Moreover, MSE can be strongly",
"rank location of each percentile in the ordering, and matching the rank to",
"contingency table counts adjusted to eliminate as much bias in the forecast as",
"indicates perfect negative association. A value of 0 indicates that the forecasts and",
"None and obs is not None and fcsterr is not None: logger.warning(\"You give",
"number of \"concordant\" pairs and ND is the number of \"discordant\" pairs. Concordant",
"the ( :math:`f_i, o_i` ) pairs according to :math:`f_i`, in which case the",
"correlation coefficient, **r**, measures the strength of linear association between the forecasts and",
"Pearson correlation coefficient, **r**, measures the strength of linear association between the forecasts",
") is a robust measure of the level of association between the forecast",
"\"\"\" return np.average(np.abs(error)) @property def IQR(self): \"\"\"\"**Inter Quartile Range of the Errors (IQR)**\"\"\"",
"def MAE(self): \"\"\"**Mean Absolute Error (MAE)**\"\"\" return self.mean_absolute_error(self.error) @staticmethod def mean_absolute_error(error): r\"\"\"**Mean Absolute",
"0.50th, 0.75th, and 0.90th quantile values of the errors are computed. Returns -------",
"is, pairs for which the values of **f** and **o** are both larger",
"anomaly is the difference between the individual forecast or observation and the typical",
"the each of the pairs of ranks (denoted as ( :math:`d_i` ) ):",
"------- numpy.ndarray, Mean Absolute Error (MAE) \"\"\" return np.average(np.abs(error)) @property def IQR(self): \"\"\"\"**Inter",
"MAD is an estimate of spread, similar to standard error, but is less",
"( :math:`\\tau` , KT_CORR)** Kendall's Tau statistic ( :math:`\\tau` ) is a robust",
"errors \"\"\" quantiles = np.array([0.1, 0.25, 0.5, 0.75, 0.9]) return np.quantile(error, quantiles) @property",
"root of the MSE, :math:`RMSE = \\sqrt{MSE}` Returns ------- numpy.ndarray, Root-mean-squared error (RMSE)",
"have IQR = 0. Returns ------- nupmy.ndarray, Inter Quartile Range of the Errors",
"numpy as np from logzero import logger from .point_stat_base import PointStatBase class ContinuousVariableVerification(PointStatBase):",
"- o_i|` MAD is an estimate of spread, similar to standard error, but",
"\"\"\"list all available score\"\"\" return {k: np.round(getattr(self, k), self.round) for k in self._available_score}",
"forecast_standard_deviation(forecast): r\"\"\"**The forecast standard deviation (FSTDEV)** The sample variance of the forecasts is",
"bias is simply the ratio of the means of the forecasts and the",
"the MSE, :math:`RMSE = \\sqrt{MSE}` Returns ------- numpy.ndarray, Root-mean-squared error (RMSE) \"\"\" return",
"a measure of overall bias for continuous variables; in particular ME = Bias.",
"2009. <https://www.adv-geosci.net/16/137/2008/>`_ Returns ------- Not implemented numpy.ndarray, Bias Adjusted Gilbert Skill Score (BAGSS)",
"(RMSE) \"\"\" return np.sqrt(np.average(error ** 2)) @property def ESTDEV(self): \"\"\"**Standard deviation of the",
"'RMSE', 'ESTDEV', 'BCMSE', 'MAE', 'IQR', 'MAD', 'EPCT'] if fcsterr is not None: self._error",
"Exception(\"Initialize failed, check forecast and obs and fcsterr values.\") elif forecast is not",
", KT_CORR)** Kendall's Tau statistic ( :math:`\\tau` ) is a robust measure of",
"= \\bar{f} - \\bar{o} A perfect forecast has ME = 0. Returns -------",
"Squared** (ME2)\"\"\" return self.mean_error_squared(self.error) @staticmethod def mean_error_squared(error): \"\"\"**The Mean Error Squared** (ME2) The",
"errors are computed. Returns ------- numpy.ndarray, Percentiles of the errors \"\"\" quantiles =",
"sometimes called the \"Bias-corrected MSE\" (BCMSE) because it removes the effect of overall",
"The number of concordant matches of a particular pair with other pairs is",
"by comparing each pair with all other pairs in the sample; this can",
"= p_{75} (f_i - o_i) - p_{25}(f_i - o_i) IQR is another estimate",
"The Median Absolute Deviation (MAD) is defined as :math:`MAD=median|f_i - o_i|` MAD is",
"correlation cofficient ( :math:`\\rho_s` ) is a robust measure of association that is",
"larger values) for which the value of oi for the current pair is",
"Mean Error (ME) \"\"\" return np.average(error) @property def ME2(self): \"\"\"**The Mean Error Squared**",
"(MAD) The Median Absolute Deviation (MAD) is defined as :math:`MAD=median|f_i - o_i|` MAD",
"(MSE) \"\"\" return np.average(error ** 2) @property def RMSE(self): \"\"\"**Root-mean-squared error (RMSE)**\"\"\" return",
"value of 0 indicates that the forecast and observed anomalies are not correlated.",
"rank correlation coefficient ( :math:`\\rho_s` , SP_CORR)**\"\"\" return self.spearman_rank_correlation_cofficient(self._f, self._o) @staticmethod def spearman_rank_correlation_cofficient(forecast,",
"correlation coefficient (PR_CORR) \"\"\" return np.corrcoef(forecast, obs)[1, 0] @property def SP_CORR(self): r\"\"\"**The Spearman",
"forecasts and the observations: .. math:: MBIAS = \\frac{\\bar{f}}{\\bar{o}} Returns ------- numpy.ndarray, Multiplicative",
"are strongly impacted by large errors. They also are strongly impacted by large",
"def kendall_tau_statistic(forecast, obs): r\"\"\"**Kendall's Tau statistic ( :math:`\\tau` , KT_CORR)** Kendall's Tau statistic",
"forecast would have MSE = RMSE = 0. MSE can be re-written as,",
"Median Absolute Deviation (MAD) \"\"\" return np.median(np.abs(error)) @property def BAGSS(self): \"\"\"Bias Adjusted Gilbert",
"Anomaly correlation coefficient is defined as: .. math:: Anomoly Correlation = \\frac{\\sum{(f_i -",
"Errors (IQR)** The Inter Quartile Range of the Errors (IQR) is the difference",
"a value of -1 indicates perfect negative correlation. - A value of 0",
"strength of linear association between the forecasts and observations. The Pearson correlation coefficient",
"return np.average(np.abs(error)) @property def IQR(self): \"\"\"\"**Inter Quartile Range of the Errors (IQR)**\"\"\" return",
"\"\"\" return def list_score(self): \"\"\"list all available score\"\"\" return {k: np.round(getattr(self, k), self.round)",
"is, the forecast and observed samples are ordered from smallest to largest and",
".. math:: MSE = \\frac{1}{n}\\sum{(f_i - o_i)^2} Returns ------- numpy.ndarray, Mean-squared error (MSE)",
"Multiplicative bias is simply the ratio of the means of the forecasts and",
"equivalent to the Pearson correlation coefficient, except that both the forecasts and observations",
"spread, similar to standard error, but is less in uenced by large errors",
"@property def BCMSE(self): \"\"\"**Bias-Corrected MSE (BCMSE)**\"\"\" return self.bias_corrected_mse(self.error) @staticmethod def bias_corrected_mse(error): r\"\"\"**Bias-Corrected MSE",
".. math:: \\rho_s = \\frac{6}{n(n^2 - 1)}\\sum^{n}_{i=1}d^{2}_{i} Like **r**, the Spearman rank correlation",
"it removes the effect of overall bias from the forecast-observation squared differences. Returns",
"of 0 indicates that the forecasts and observations are not associated. Returns -------",
"errors\"\"\" return self.percentile_errors(self.error) @staticmethod def percentile_errors(error): \"\"\"Percentiles of the errors Percentiles of the",
"from .point_stat_base import PointStatBase class ContinuousVariableVerification(PointStatBase): def __init__(self, forecast=None, obs=None, fcsterr=None, group=None): if",
"o_i|}` MAE is less in uenced by large errors and also does not",
"overall bias from the forecast-observation squared differences. Returns ------- numpy.ndarray, Bias-Corrected MSE (BCMSE)",
".. math:: MSE = (\\bar{f} - \\bar{o})^2 + s^{2}_{f} + s^{2}_{o} -2 s_f",
"s_{f-o}=\\sqrt{s^{2}_{f-o}}=\\sqrt{s^{2}_{f} + s^{2}_{o} -2 s_f s_o r_{fo}} Note that the square of the",
"Error (ME) \"\"\" return np.average(error) @property def ME2(self): \"\"\"**The Mean Error Squared** (ME2)\"\"\"",
"infinity. A perfect forecast would have MSE = RMSE = 0. MSE can",
"is the Gilbert Skill Score, but with the contingency table counts adjusted to",
"\"\"\"Median Absolute Deviation (MAD) The Median Absolute Deviation (MAD) is defined as :math:`MAD=median|f_i",
"0. Returns ------- numpy.ndarray, Median Absolute Deviation (MAD) \"\"\" return np.median(np.abs(error)) @property def",
"Like **r** and :math:`\\rho_s` , Kendall's Tau ( :math:`\\tau` ) ranges between -1",
"25th percentiles of the errors. It is de ned as .. math:: IQR",
"counts for all pairs. The total number of possible pairs is ; thus,",
"coefficient (ANOM_CORR)\"\"\" return self.anomaly_correlation_coefficient(self._f, self._o, None) @staticmethod def anomaly_correlation_coefficient(forecast, obs, climate): r\"\"\"The Anomaly",
"= \\sqrt{s^{2}_{f}} Returns ------- numpy.ndarray, the forecast standard deviation (FSTDEV) \"\"\" return np.std(forecast)",
"squared Bias plus estimated variance of the error, as detailed below in the",
"bias for continuous variables; in particular ME = Bias. It is defined as",
"and 1; - a value of 1 indicates perfect correlation and - a",
"observation (OBAR) \"\"\" return np.average(obs) @property def FSTDEV(self): \"\"\"**The forecast standard deviation (FSTDEV)**\"\"\"",
"be obtained from the mean and standard deviations of the errors. Percentiles are",
"pearson_correlation_coefficient(forecast, obs): r\"\"\"**The Pearson correlation coefficient ( :math:`r` , PR_CORR)** The Pearson correlation",
"mean and standard deviations of the errors. Percentiles are computed by ordering the",
"observations are not correlated. Returns ------- numpy.ndarray, the Pearson correlation coefficient (PR_CORR) \"\"\"",
"is defined as .. math:: s^{2}_{f} = \\frac{1}{T-1}\\sum_{i=1}^{T}(f_i - \\bar{f})^2 The forecast standard",
"\"\"\"Percentiles (0.1, 0.25, 0.5, 0.75, 0.9) of the errors\"\"\" return self.percentile_errors(self.error) @staticmethod def",
"@staticmethod def percentile_errors(error): \"\"\"Percentiles of the errors Percentiles of the errors provide more",
"defined as ME2 = ME2. A perfect forecast has ME2 = 0. Returns",
"def list_score(self): \"\"\"list all available score\"\"\" return {k: np.round(getattr(self, k), self.round) for k",
"is the estimated variance of the error, :math:`s^{2}_{fo}` . Thus, :math:`MSE = ME^2",
":math:`\\tau` , KT_CORR) \"\"\" from scipy.stats import kendalltau return kendalltau(forecast, obs) @property def",
"self.percentile_errors(self.error) @staticmethod def percentile_errors(error): \"\"\"Percentiles of the errors Percentiles of the errors provide",
"the means of the forecasts and the observations: .. math:: MBIAS = \\frac{\\bar{f}}{\\bar{o}}",
"self.observation_standard_deviation(self._o) @staticmethod def observation_standard_deviation(obs): r\"\"\"**The observed standard deviation (OSTDEV)** The sample variance of",
"percentile_errors(error): \"\"\"Percentiles of the errors Percentiles of the errors provide more information about",
"def ESTDEV(self): \"\"\"**Standard deviation of the error** (ESTDEV)\"\"\" return self.standard_deviation_of_error(self.error) @staticmethod def standard_deviation_of_error(error):",
"SP_CORR)** The Spearman rank correlation cofficient ( :math:`\\rho_s` ) is a robust measure",
"means of the forecasts and the observations: .. math:: MBIAS = \\frac{\\bar{f}}{\\bar{o}} Returns",
"from logzero import logger from .point_stat_base import PointStatBase class ContinuousVariableVerification(PointStatBase): def __init__(self, forecast=None,",
"- 1)}\\sum^{n}_{i=1}d^{2}_{i} Like **r**, the Spearman rank correlation coe cient ranges between -1",
"**n**, where **n** is the total number of pairs) are assigned. The pairs",
"\"\"\"**Mean Absolute Error (MAE)**\"\"\" return self.mean_absolute_error(self.error) @staticmethod def mean_absolute_error(error): r\"\"\"**Mean Absolute Error (MAE)**",
"root_mean_squared_error(error): \"\"\"**Root-mean-squared error (RMSE)** RMSE is simply the square root of the MSE,",
"'FSTDEV', 'OSTDEV', 'PR_CORR', 'SP_CORR', 'KT_CORR', 'MBIAS', ] super(ContinuousVariableVerification, self).__init__(forecast, obs, group) @property def",
", Kendall's Tau ( :math:`\\tau` ) ranges between -1 and 1; a value",
"@staticmethod def standard_deviation_of_error(error): \"\"\"**Standard deviation of the error** (ESTDEV) Returns ------- numpy.ndaray, Standard",
"return self.kendall_tau_statistic(self._f, self._o) @staticmethod def kendall_tau_statistic(forecast, obs): r\"\"\"**Kendall's Tau statistic ( :math:`\\tau` ,",
"is defined as .. math:: s_{o} = \\sqrt{s^{2}_{o}} Returns ------- numpy.ndarray, the observed",
"pair is exceeded (that is, pairs for which the values of **f** and",
"is less in uenced by large errors and also does not depend on",
"is defined as, .. math:: \\bar{o} = \\frac{1}{n}\\sum_{i=1}^{n}o_i Returns ------- numpy.ndarray, the sample",
"standard deviation (OSTDEV)**\"\"\" return self.observation_standard_deviation(self._o) @staticmethod def observation_standard_deviation(obs): r\"\"\"**The observed standard deviation (OSTDEV)**",
"not correlated. Returns ------- numpy.ndarray, the Pearson correlation coefficient (PR_CORR) \"\"\" return np.corrcoef(forecast,",
"terms of squared Bias plus estimated variance of the error, as detailed below",
"as .. math:: \\tau = \\frac{N_c - N_p}{n(n-1)/2} where NC is the number",
"Returns ------- Not implemented \"\"\" return def list_score(self): \"\"\"list all available score\"\"\" return",
"of MSE, rather than examining MSE alone. Moreover, MSE can be strongly influenced",
"according to a climatology value. The anomaly is the difference between the individual",
"Correlation = \\frac{\\sum{(f_i - c)(o_i - c)}} {\\sqrt{\\sum{(f_i - c)^2}} \\sqrt{\\sum{(o_i - c)^2}}}",
"numpy.ndarray, Kendall's Tau statistic ( :math:`\\tau` , KT_CORR) \"\"\" from scipy.stats import kendalltau",
"FBAR**\"\"\" return self.mean_forecast(self._f) @staticmethod def mean_forecast(forecast): r\"\"\"**The sample mean forecast, FBAR** the sample",
"Like **r**, the Spearman rank correlation coe cient ranges between -1 and 1;",
"a climatology value. The anomaly is the difference between the individual forecast or",
"Root-mean-squared error (RMSE) \"\"\" return np.sqrt(np.average(error ** 2)) @property def ESTDEV(self): \"\"\"**Standard deviation",
"( :math:`\\tau` ) ranges between -1 and 1; a value of 1 indicates",
"- \\bar{o})^2 + s^{2}_{f} + s^{2}_{o} -2 s_f s_o r_{fo} where :math:`\\bar{f} -",
"observation, OBAR** the sample mean observation (OBAR) is defined as, .. math:: \\bar{o}",
"coefficient ( :math:`\\rho_s` , SP_CORR)**\"\"\" return self.spearman_rank_correlation_cofficient(self._f, self._o) @staticmethod def spearman_rank_correlation_cofficient(forecast, obs): r\"\"\"**The",
"is the difference between the 75th and 25th percentiles of the errors. It",
"of concordant matches of a particular pair with other pairs is computed by",
"(ME2) The Mean Error Squared, ME2, is provided to give a complete breakdown",
"error (RMSE)** RMSE is simply the square root of the MSE, :math:`RMSE =",
"return self.pearson_correlation_coefficient(self._f, self._o) @staticmethod def pearson_correlation_coefficient(forecast, obs): r\"\"\"**The Pearson correlation coefficient ( :math:`r`",
"values. That is, the forecast and observed samples are ordered from smallest to",
"return np.quantile(error, quantiles) @property def ANOM_CORR(self): \"\"\"The Anomaly correlation coefficient (ANOM_CORR)\"\"\" return self.anomaly_correlation_coefficient(self._f,",
"statistic ( :math:`\\tau` ) is a robust measure of the level of association",
"The 0.10th, 0.25th, 0.50th, 0.75th, and 0.90th quantile values of the errors are",
"Inter Quartile Range of the Errors (IQR) \"\"\" return np.percentile(error, 75) - np.percentile(error,",
"Range of the Errors (IQR)** The Inter Quartile Range of the Errors (IQR)",
"forecast standard deviation (FSTDEV)** The sample variance of the forecasts is defined as",
"observation and the typical situation, as measured by a climatology (**c**) of some",
"mean_observation(obs): r\"\"\"**The sample mean observation, OBAR** the sample mean observation (OBAR) is defined",
"the forecasts and observations are not correlated. Returns ------- numpy.ndarray, the Spearman correlation",
"@property def PR_CORR(self): r\"\"\"**The Pearson correlation coefficient ( :math:`r` , PR_CORR)**\"\"\" return self.pearson_correlation_coefficient(self._f,",
"s^{2}_{o} = \\frac{1}{T-1}\\sum_{i=1}^{T}(o_i - \\bar{o})^2 The observed standard deviation, OSTDEV, is defined as",
"coefficient is defined as: .. math:: Anomoly Correlation = \\frac{\\sum{(f_i - c)(o_i -",
"self._available_score = ['N', 'ME', 'ME2', 'MSE', 'RMSE', 'ESTDEV', 'BCMSE', 'MAE', 'IQR', 'MAD', 'EPCT']",
"the errors Percentiles of the errors provide more information about the distribution of",
"overall bias for continuous variables; in particular ME = Bias. It is defined",
"numpy.ndarray, Mean-squared error (MSE) \"\"\" return np.average(error ** 2) @property def RMSE(self): \"\"\"**Root-mean-squared",
"Note that the square of the standard deviation of the error (ESTDEV2) is",
"\"\"\" return np.average(forecast) / np.average(error) @property def MSE(self): \"\"\"**Mean-squared error (MSE)**\"\"\" return self.mean_squared_error(self.error)",
"plots of the errors. The 0.10th, 0.25th, 0.50th, 0.75th, and 0.90th quantile values",
"on the mean error. A perfect forecast would have IQR = 0. Returns",
"is equivalent to the Pearson correlation coefficient, except that both the forecasts and",
"associated. Returns ------- numpy.ndarray, Kendall's Tau statistic ( :math:`\\tau` , KT_CORR) \"\"\" from",
"def pearson_correlation_coefficient(forecast, obs): r\"\"\"**The Pearson correlation coefficient ( :math:`r` , PR_CORR)** The Pearson",
"r\"\"\"**The Pearson correlation coefficient ( :math:`r` , PR_CORR)** The Pearson correlation coefficient, **r**,",
"as .. math:: s_{o} = \\sqrt{s^{2}_{o}} Returns ------- numpy.ndarray, the observed standard deviation",
"range between -1 and 1; a value of 1 indicates perfect correlation and",
"ME = 0. Returns ------- numpy.ndarray, The Mean Error (ME) \"\"\" return np.average(error)",
"each of the pairs of ranks (denoted as ( :math:`d_i` ) ): ..",
"@property def ANOM_CORR(self): \"\"\"The Anomaly correlation coefficient (ANOM_CORR)\"\"\" return self.anomaly_correlation_coefficient(self._f, self._o, None) @staticmethod",
":math:`d_i` ) ): .. math:: \\rho_s = \\frac{6}{n(n^2 - 1)}\\sum^{n}_{i=1}d^{2}_{i} Like **r**, the",
"def BAGSS(self): \"\"\"Bias Adjusted Gilbert Skill Score (BAGSS)\"\"\" return self.bias_adjusted_gilbert_skill_score(self._f, self._o) @staticmethod def",
"mean forecast, FBAR** the sample mean forecast (FBAR) is defined as, .. math::",
"cofficient ( :math:`\\rho_s` ) is a robust measure of association that is based",
"MAE(self): \"\"\"**Mean Absolute Error (MAE)**\"\"\" return self.mean_absolute_error(self.error) @staticmethod def mean_absolute_error(error): r\"\"\"**Mean Absolute Error",
") is a robust measure of association that is based on the ranks",
"as .. math:: s^{2}_{o} = \\frac{1}{T-1}\\sum_{i=1}^{T}(o_i - \\bar{o})^2 The observed standard deviation, OSTDEV,",
"forecast as possible. For details, see `Brill and Messinger, 2009. <https://www.adv-geosci.net/16/137/2008/>`_ Returns -------",
"called the \"Bias-corrected MSE\" (BCMSE) because it removes the effect of overall bias",
"def mean_absolute_error(error): r\"\"\"**Mean Absolute Error (MAE)** The Mean Absolute Error (MAE) is defined",
"-*- # @Author: wqshen # @Email: <EMAIL> # @Date: 2020/6/10 14:43 # @Last",
"= \\frac{1}{n}\\sum{(f_i - o_i)^2} Returns ------- numpy.ndarray, Mean-squared error (MSE) \"\"\" return np.average(error",
"nupmy.ndarray, Inter Quartile Range of the Errors (IQR) \"\"\" return np.percentile(error, 75) -",
"Median Absolute Deviation (MAD) is defined as :math:`MAD=median|f_i - o_i|` MAD is an",
"(BAGSS) is the Gilbert Skill Score, but with the contingency table counts adjusted",
"`Brill and Messinger, 2009. <https://www.adv-geosci.net/16/137/2008/>`_ Returns ------- Not implemented numpy.ndarray, Bias Adjusted Gilbert",
"return self.bias_corrected_mse(self.error) @staticmethod def bias_corrected_mse(error): r\"\"\"**Bias-Corrected MSE (BCMSE)** MSE and RMSE are strongly",
"strength of linear association between the forecast anomolies and observed anomalies. The Anomaly",
"the error \"\"\" return np.std(error) @property def BCMSE(self): \"\"\"**Bias-Corrected MSE (BCMSE)**\"\"\" return self.bias_corrected_mse(self.error)",
"Returns ------- numpy.ndarray, Mean-squared error (MSE) \"\"\" return np.average(error ** 2) @property def",
"defined as .. math:: s^{2}_{f} = \\frac{1}{T-1}\\sum_{i=1}^{T}(f_i - \\bar{f})^2 The forecast standard deviation,",
"Absolute Error (MAE) is defined as :math:`MAE = \\frac{1}{n}\\sum{|f_i - o_i|}` MAE is",
"deviation of the error \"\"\" return np.std(error) @property def BCMSE(self): \"\"\"**Bias-Corrected MSE (BCMSE)**\"\"\"",
"r\"\"\"**The Pearson correlation coefficient ( :math:`r` , PR_CORR)**\"\"\" return self.pearson_correlation_coefficient(self._f, self._o) @staticmethod def",
"@staticmethod def mean_forecast(forecast): r\"\"\"**The sample mean forecast, FBAR** the sample mean forecast (FBAR)",
"@Email: <EMAIL> # @Date: 2020/6/10 14:43 # @Last Modified by: wqshen import numpy",
"MSE can be re-written as, .. math:: MSE = (\\bar{f} - \\bar{o})^2 +",
"def mean_observation(obs): r\"\"\"**The sample mean observation, OBAR** the sample mean observation (OBAR) is",
"standard deviation (OSTDEV) \"\"\" return np.std(obs) @property def PR_CORR(self): r\"\"\"**The Pearson correlation coefficient",
"r\"\"\"The Anomaly correlation coefficient (ANOM_CORR) The Anomaly correlation coe cient is equivalent to",
"value of oi for the current pair is exceeded (that is, pairs for",
"def ANOM_CORR(self): \"\"\"The Anomaly correlation coefficient (ANOM_CORR)\"\"\" return self.anomaly_correlation_coefficient(self._f, self._o, None) @staticmethod def",
":math:`f_i, o_i` ) pairs according to :math:`f_i`, in which case the :math:`o_i`, values",
"rank correlation coe cient ranges between -1 and 1; a value of 1",
"strongly impacted by large errors. They also are strongly impacted by large bias",
"the fcsterr will be ignored.\") fcsterr = None self._available_score = ['N', 'ME', 'ME2',",
"typical situation, as measured by a climatology (**c**) of some variety. It measures",
"deviations of the errors. Percentiles are computed by ordering the errors from smallest",
"coefficient ( :math:`\\rho_s` , SP_CORR)** The Spearman rank correlation cofficient ( :math:`\\rho_s` )",
"Tau statistic ( :math:`\\tau` , KT_CORR)**\"\"\" return self.kendall_tau_statistic(self._f, self._o) @staticmethod def kendall_tau_statistic(forecast, obs):",
"= Bias. It is defined as .. math:: ME = \\frac{1}{n}\\sum^{n}_{i=1}(f_i - o_i)",
"np.std(obs) @property def PR_CORR(self): r\"\"\"**The Pearson correlation coefficient ( :math:`r` , PR_CORR)**\"\"\" return",
"Spearman correlation coefficient (SP_CORR) \"\"\" from scipy.stats import spearmanr return spearmanr(forecast, obs) @property",
"indicates that the forecasts and observations are not associated. Returns ------- numpy.ndarray, Kendall's",
"Pearson correlation coefficient (PR_CORR) \"\"\" return np.corrcoef(forecast, obs)[1, 0] @property def SP_CORR(self): r\"\"\"**The",
"Mean Error (ME)**\"\"\" return self.mean_error(self.error) @staticmethod def mean_error(error): r\"\"\"**The Mean Error (ME)** The",
"Modified by: wqshen import numpy as np from logzero import logger from .point_stat_base",
"utf-8 -*- # @Author: wqshen # @Email: <EMAIL> # @Date: 2020/6/10 14:43 #",
"examine both of the terms of MSE, rather than examining MSE alone. Moreover,",
"MAD = 0. Returns ------- numpy.ndarray, Median Absolute Deviation (MAD) \"\"\" return np.median(np.abs(error))",
"can also be used to create box plots of the errors. The 0.10th,",
"the forecast anomolies and observed anomalies. The Anomaly correlation coefficient is defined as:",
"o_i)^2} Returns ------- numpy.ndarray, Mean-squared error (MSE) \"\"\" return np.average(error ** 2) @property",
"OBAR(self): \"\"\"**The sample mean observation, OBAR**\"\"\" return self.mean_observation(self._o) @staticmethod def mean_observation(obs): r\"\"\"**The sample",
"@staticmethod def observation_standard_deviation(obs): r\"\"\"**The observed standard deviation (OSTDEV)** The sample variance of the",
"Pearson correlation coefficient ( :math:`r` , PR_CORR)** The Pearson correlation coefficient, **r**, measures",
"(MAD) is defined as :math:`MAD=median|f_i - o_i|` MAD is an estimate of spread,",
"= 0. Returns ------- nupmy.ndarray, Inter Quartile Range of the Errors (IQR) \"\"\"",
"np.sqrt(np.average(error ** 2)) @property def ESTDEV(self): \"\"\"**Standard deviation of the error** (ESTDEV)\"\"\" return",
"math:: r = \\frac{\\sum^{T}_{i=1}(f_i - \\bar{f})(o_i - \\bar{o})}{\\sqrt{\\sum{(f_i - \\bar{f})^2}}\\sqrt{\\sum{(o_i - \\bar{o})^2}}} r",
"of the errors\"\"\" return self.percentile_errors(self.error) @staticmethod def percentile_errors(error): \"\"\"Percentiles of the errors Percentiles",
":math:`r` , PR_CORR)**\"\"\" return self.pearson_correlation_coefficient(self._f, self._o) @staticmethod def pearson_correlation_coefficient(forecast, obs): r\"\"\"**The Pearson correlation",
"obs) @property def KT_CORR(self): r\"\"\"**Kendall's Tau statistic ( :math:`\\tau` , KT_CORR)**\"\"\" return self.kendall_tau_statistic(self._f,",
"+= ['FBAR', 'OBAR', 'FSTDEV', 'OSTDEV', 'PR_CORR', 'SP_CORR', 'KT_CORR', 'MBIAS', ] super(ContinuousVariableVerification, self).__init__(forecast, obs,",
"the errors. Percentiles are computed by ordering the errors from smallest to largest",
"and RMSE can range from 0 to infinity. A perfect forecast would have",
"as :math:`MAE = \\frac{1}{n}\\sum{|f_i - o_i|}` MAE is less in uenced by large",
"def median_absolute_deviation(error): \"\"\"Median Absolute Deviation (MAD) The Median Absolute Deviation (MAD) is defined",
"(OBAR) is defined as, .. math:: \\bar{o} = \\frac{1}{n}\\sum_{i=1}^{n}o_i Returns ------- numpy.ndarray, the",
"obs, climate): r\"\"\"The Anomaly correlation coefficient (ANOM_CORR) The Anomaly correlation coe cient is",
"(ANOM_CORR) The Anomaly correlation coe cient is equivalent to the Pearson correlation coefficient,",
"can be done most easily by ordering all of the ( :math:`f_i, o_i`",
"------- numpy.ndarray, Bias-Corrected MSE (BCMSE) \"\"\" return np.square(np.std(error)) @property def MAE(self): \"\"\"**Mean Absolute",
"\"\"\"Bias Adjusted Gilbert Skill Score (BAGSS) The Bias Adjusted Gilbert Skill Score (BAGSS)",
"-*- coding: utf-8 -*- # @Author: wqshen # @Email: <EMAIL> # @Date: 2020/6/10",
"and a value of -1 indicates perfect negative correlation. A value of 0",
"perfect correlation and a value of -1 indicates perfect negative correlation. A value",
"= 0. Returns ------- numpy.ndarray, Median Absolute Deviation (MAD) \"\"\" return np.median(np.abs(error)) @property",
"------- numpy.ndarray, The Mean Error (ME) \"\"\" return np.square(np.average(error)) @property def MBIAS(self): \"\"\"**Multiplicative",
"Bias. It is defined as .. math:: ME = \\frac{1}{n}\\sum^{n}_{i=1}(f_i - o_i) =",
"Spearman rank correlation coefficient ( :math:`\\rho_s` , SP_CORR)** The Spearman rank correlation cofficient",
"forecast standard deviation, FSTDEV, is defined as .. math:: s_{f} = \\sqrt{s^{2}_{f}} Returns",
".. math:: \\bar{f} = \\frac{1}{n}\\sum_{i=1}^{n}f_i Returns ------ numpy.ndarray, the sample mean forecast (FBAR)",
"as .. math:: s_{f} = \\sqrt{s^{2}_{f}} Returns ------- numpy.ndarray, the forecast standard deviation",
"return np.percentile(error, 75) - np.percentile(error, 25) @property def MAD(self): \"\"\"Median Absolute Deviation (MAD)\"\"\"",
"\\frac{6}{n(n^2 - 1)}\\sum^{n}_{i=1}d^{2}_{i} Like **r**, the Spearman rank correlation coe cient ranges between",
"Pearson correlation coefficient ( :math:`r` , PR_CORR)**\"\"\" return self.pearson_correlation_coefficient(self._f, self._o) @staticmethod def pearson_correlation_coefficient(forecast,",
"def spearman_rank_correlation_cofficient(forecast, obs): r\"\"\"**The Spearman rank correlation coefficient ( :math:`\\rho_s` , SP_CORR)** The",
"\"\"\" return np.sqrt(np.average(error ** 2)) @property def ESTDEV(self): \"\"\"**Standard deviation of the error**",
"KT_CORR) \"\"\" from scipy.stats import kendalltau return kendalltau(forecast, obs) @property def ME(self): \"\"\"**The",
"each pair with all other pairs in the sample; this can be done",
"Returns ------- numpy.ndarray, Median Absolute Deviation (MAD) \"\"\" return np.median(np.abs(error)) @property def BAGSS(self):",
"def FBAR(self): \"\"\"**The sample mean forecast, FBAR**\"\"\" return self.mean_forecast(self._f) @staticmethod def mean_forecast(forecast): r\"\"\"**The",
"not depend on the mean error. A perfect forecast would have IQR =",
"thus, the number of discordant pairs is . Like **r** and :math:`\\rho_s` ,",
"def BCMSE(self): \"\"\"**Bias-Corrected MSE (BCMSE)**\"\"\" return self.bias_corrected_mse(self.error) @staticmethod def bias_corrected_mse(error): r\"\"\"**Bias-Corrected MSE (BCMSE)**",
"values (from 1 to **n**, where **n** is the total number of pairs)",
"smallest to largest and rank values (from 1 to **n**, where **n** is",
"------- Not implemented numpy.ndarray, Bias Adjusted Gilbert Skill Score (BAGSS) \"\"\" return @property",
"in the ordering, and matching the rank to the actual value. Percentiles can",
"\\rho_s = \\frac{6}{n(n^2 - 1)}\\sum^{n}_{i=1}d^{2}_{i} Like **r**, the Spearman rank correlation coe cient",
"0.25th, 0.50th, 0.75th, and 0.90th quantile values of the errors are computed. Returns",
"error (MSE)**\"\"\" return self.mean_squared_error(self.error) @staticmethod def mean_squared_error(error): r\"\"\"**Mean-squared error (MSE)** MSE measures the",
"as measured by a climatology (**c**) of some variety. It measures the strength",
"N_p}{n(n-1)/2} where NC is the number of \"concordant\" pairs and ND is the",
"- a value of -1 indicates perfect negative correlation. - A value of",
"self.mean_absolute_error(self.error) @staticmethod def mean_absolute_error(error): r\"\"\"**Mean Absolute Error (MAE)** The Mean Absolute Error (MAE)",
"** 2)) @property def ESTDEV(self): \"\"\"**Standard deviation of the error** (ESTDEV)\"\"\" return self.standard_deviation_of_error(self.error)",
"Errors (IQR) \"\"\" return np.percentile(error, 75) - np.percentile(error, 25) @property def MAD(self): \"\"\"Median",
"variance of the observations is defined as .. math:: s^{2}_{o} = \\frac{1}{T-1}\\sum_{i=1}^{T}(o_i -",
"Concordant pairs are identi ed by comparing each pair with all other pairs",
"in uenced by large errors and also does not depend on the mean",
"the pairs of ranks (denoted as ( :math:`d_i` ) ): .. math:: \\rho_s",
"errors provide more information about the distribution of errors than can be obtained",
"variance of the error, as detailed below in the section on BCMSE. It",
"# @Last Modified by: wqshen import numpy as np from logzero import logger",
"ed by comparing each pair with all other pairs in the sample; this",
"Score (BAGSS) is the Gilbert Skill Score, but with the contingency table counts",
"pairs of forecast-observed ranks are then used to compute a correlation cofficient, analogous",
"forecast - fcsterr # Not Available, 'BAGSS', 'ANOM_CORR' self._available_score += ['FBAR', 'OBAR', 'FSTDEV',",
"sample; this can be done most easily by ordering all of the (",
"the Spearman-rank correlation is based on differences between the each of the pairs",
"Bias Adjusted Gilbert Skill Score (BAGSS) is the Gilbert Skill Score, but with",
"is an estimate of spread, similar to standard error, but is less in",
"\"\"\"Bias Adjusted Gilbert Skill Score (BAGSS)\"\"\" return self.bias_adjusted_gilbert_skill_score(self._f, self._o) @staticmethod def bias_adjusted_gilbert_skill_score(forecast, obs):",
"summing the counts for all pairs. The total number of possible pairs is",
"to infinity. A perfect forecast would have MSE = RMSE = 0. MSE",
"from 0 to infinity. A perfect forecast would have MSE = RMSE =",
"be re-written as, .. math:: MSE = (\\bar{f} - \\bar{o})^2 + s^{2}_{f} +",
"as detailed below in the section on BCMSE. It is defined as ME2",
"Returns ------- numpy.ndarray, Mean Absolute Error (MAE) \"\"\" return np.average(np.abs(error)) @property def IQR(self):",
"- a value of 1 indicates perfect correlation and - a value of",
"error. A perfect forecast would have MAD = 0. Returns ------- numpy.ndarray, Median",
"MSE (BCMSE)** MSE and RMSE are strongly impacted by large errors. They also",
"mean_forecast(forecast): r\"\"\"**The sample mean forecast, FBAR** the sample mean forecast (FBAR) is defined",
"(MBIAS)** Multiplicative bias is simply the ratio of the means of the forecasts",
"Tau statistic ( :math:`\\tau` ) is a robust measure of the level of",
"def SP_CORR(self): r\"\"\"**The Spearman rank correlation coefficient ( :math:`\\rho_s` , SP_CORR)**\"\"\" return self.spearman_rank_correlation_cofficient(self._f,",
":math:`\\rho_s` , SP_CORR)**\"\"\" return self.spearman_rank_correlation_cofficient(self._f, self._o) @staticmethod def spearman_rank_correlation_cofficient(forecast, obs): r\"\"\"**The Spearman rank",
"forecast and observed values rather than the actual values. That is, the forecast",
"- N_p}{n(n-1)/2} where NC is the number of \"concordant\" pairs and ND is",
"deviation of the error, :math:`s_{f-o}` , is .. math:: s_{f-o}=\\sqrt{s^{2}_{f-o}}=\\sqrt{s^{2}_{f} + s^{2}_{o} -2",
"1; - a value of 1 indicates perfect correlation and - a value",
"for the current pair is exceeded (that is, pairs for which the values",
"of **f** and **o** are both larger than the value for the current",
"and a value of -1 indicates perfect negative association. A value of 0",
"if forecast is None: forecast = fcsterr + obs if obs is None:",
") ranges between -1 and 1; a value of 1 indicates perfect association",
"error (MSE) \"\"\" return np.average(error ** 2) @property def RMSE(self): \"\"\"**Root-mean-squared error (RMSE)**\"\"\"",
"import kendalltau return kendalltau(forecast, obs) @property def ME(self): \"\"\"**The Mean Error (ME)**\"\"\" return",
"return self.mean_error_squared(self.error) @staticmethod def mean_error_squared(error): \"\"\"**The Mean Error Squared** (ME2) The Mean Error",
"Absolute Error (MAE)** The Mean Absolute Error (MAE) is defined as :math:`MAE =",
"standard deviation, FSTDEV, is defined as .. math:: s_{f} = \\sqrt{s^{2}_{f}} Returns -------",
"\\bar{o})^2 The observed standard deviation, OSTDEV, is defined as .. math:: s_{o} =",
"defined as: .. math:: Anomoly Correlation = \\frac{\\sum{(f_i - c)(o_i - c)}} {\\sqrt{\\sum{(f_i",
"by ME, as shown by this decomposition. The standard deviation of the error,",
"and ND is the number of \"discordant\" pairs. Concordant pairs are identi ed",
"perfect forecast has ME = 0. Returns ------- numpy.ndarray, The Mean Error (ME)",
"as, .. math:: MSE = (\\bar{f} - \\bar{o})^2 + s^{2}_{f} + s^{2}_{o} -2",
"coefficient is defined as: .. math:: r = \\frac{\\sum^{T}_{i=1}(f_i - \\bar{f})(o_i - \\bar{o})}{\\sqrt{\\sum{(f_i",
"\"\"\" return np.std(obs) @property def PR_CORR(self): r\"\"\"**The Pearson correlation coefficient ( :math:`r` ,",
"are ordered from smallest to largest and rank values (from 1 to **n**,",
"r can range between -1 and 1; a value of 1 indicates perfect",
"deviation of the error** (ESTDEV)\"\"\" return self.standard_deviation_of_error(self.error) @staticmethod def standard_deviation_of_error(error): \"\"\"**Standard deviation of",
"@staticmethod def forecast_standard_deviation(forecast): r\"\"\"**The forecast standard deviation (FSTDEV)** The sample variance of the",
"mean observation, OBAR**\"\"\" return self.mean_observation(self._o) @staticmethod def mean_observation(obs): r\"\"\"**The sample mean observation, OBAR**",
"------- numpy.ndarray, Median Absolute Deviation (MAD) \"\"\" return np.median(np.abs(error)) @property def BAGSS(self): \"\"\"Bias",
"numpy.ndarray, Percentiles of the errors \"\"\" quantiles = np.array([0.1, 0.25, 0.5, 0.75, 0.9])",
"def OSTDEV(self): r\"\"\"**The observed standard deviation (OSTDEV)**\"\"\" return self.observation_standard_deviation(self._o) @staticmethod def observation_standard_deviation(obs): r\"\"\"**The",
"and obs is not None and fcsterr is not None: logger.warning(\"You give forecast,",
"The Inter Quartile Range of the Errors (IQR) is the difference between the",
"None) and fcsterr is None: raise Exception(\"Initialize failed, check forecast and obs and",
"np from logzero import logger from .point_stat_base import PointStatBase class ContinuousVariableVerification(PointStatBase): def __init__(self,",
"association that is based on the ranks of the forecast and observed values",
"de ned as .. math:: IQR = p_{75} (f_i - o_i) - p_{25}(f_i",
"Gilbert Skill Score (BAGSS) The Bias Adjusted Gilbert Skill Score (BAGSS) is the",
"The Spearman rank correlation cofficient ( :math:`\\rho_s` ) is a robust measure of",
"Kendall's Tau statistic ( :math:`\\tau` , KT_CORR) \"\"\" from scipy.stats import kendalltau return",
"self.multiplicative_bias(self._f, self._o) @staticmethod def multiplicative_bias(forecast, error): r\"\"\"**Multiplicative bias (MBIAS)** Multiplicative bias is simply",
"about the distribution of errors than can be obtained from the mean and",
"if fcsterr is not None: self._error = fcsterr[~np.isnan(fcsterr)] if forecast is None: forecast",
"on BCMSE. It is defined as ME2 = ME2. A perfect forecast has",
"strongly impacted by large bias (ME) values. MSE and RMSE can range from",
"Error (ME)** The Mean Error, ME, is a measure of overall bias for",
"\\bar{f})(o_i - \\bar{o})}{\\sqrt{\\sum{(f_i - \\bar{f})^2}}\\sqrt{\\sum{(o_i - \\bar{o})^2}}} r can range between -1 and",
"pairs are identi ed by comparing each pair with all other pairs in",
"and 25th percentiles of the errors. It is de ned as .. math::",
"- c)(o_i - c)}} {\\sqrt{\\sum{(f_i - c)^2}} \\sqrt{\\sum{(o_i - c)^2}}} Anomaly correlation can",
"PointStatBase class ContinuousVariableVerification(PointStatBase): def __init__(self, forecast=None, obs=None, fcsterr=None, group=None): if (forecast is None",
"see `Brill and Messinger, 2009. <https://www.adv-geosci.net/16/137/2008/>`_ Returns ------- Not implemented numpy.ndarray, Bias Adjusted",
"= \\frac{6}{n(n^2 - 1)}\\sum^{n}_{i=1}d^{2}_{i} Like **r**, the Spearman rank correlation coe cient ranges",
"return self.multiplicative_bias(self._f, self._o) @staticmethod def multiplicative_bias(forecast, error): r\"\"\"**Multiplicative bias (MBIAS)** Multiplicative bias is",
"numpy.ndarray, Bias Adjusted Gilbert Skill Score (BAGSS) \"\"\" return @property def EPCT(self): \"\"\"Percentiles",
"@Date: 2020/6/10 14:43 # @Last Modified by: wqshen import numpy as np from",
"have MAE = 0. Returns ------- numpy.ndarray, Mean Absolute Error (MAE) \"\"\" return",
"Absolute Deviation (MAD) is defined as :math:`MAD=median|f_i - o_i|` MAD is an estimate",
"is done, Nc is computed by summing the counts for all pairs. The",
"impacted by large errors. They also are strongly impacted by large bias (ME)",
"numpy.ndarray, the sample mean forecast (FBAR) \"\"\" return np.average(forecast) @property def OBAR(self): \"\"\"**The",
"pairs is . Like **r** and :math:`\\rho_s` , Kendall's Tau ( :math:`\\tau` )",
"correlation coefficient, except that both the forecasts and observations are first adjusted according",
"in the section on BCMSE. It is defined as ME2 = ME2. A",
"(f_i - o_i) - p_{25}(f_i - o_i) IQR is another estimate of spread,",
"and standard deviations of the errors. Percentiles are computed by ordering the errors",
"return self.bias_adjusted_gilbert_skill_score(self._f, self._o) @staticmethod def bias_adjusted_gilbert_skill_score(forecast, obs): \"\"\"Bias Adjusted Gilbert Skill Score (BAGSS)",
"0.10th, 0.25th, 0.50th, 0.75th, and 0.90th quantile values of the errors are computed.",
"(OSTDEV)** The sample variance of the observations is defined as .. math:: s^{2}_{o}",
"of \"discordant\" pairs. Concordant pairs are identi ed by comparing each pair with",
"Gilbert Skill Score (BAGSS) is the Gilbert Skill Score, but with the contingency",
"and :math:`s^{2}_{f} + s^{2}_{o} -2 s_f s_o r_{fo}` is the estimated variance of",
"the Pearson correlation coefficient, except that both the forecasts and observations are first",
"A simpler formulation of the Spearman-rank correlation is based on differences between the",
"(ME)**\"\"\" return self.mean_error(self.error) @staticmethod def mean_error(error): r\"\"\"**The Mean Error (ME)** The Mean Error,",
"are identi ed by comparing each pair with all other pairs in the",
"IQR = p_{75} (f_i - o_i) - p_{25}(f_i - o_i) IQR is another",
"is defined as: .. math:: Anomoly Correlation = \\frac{\\sum{(f_i - c)(o_i - c)}}",
"the sample; this can be done most easily by ordering all of the",
"of -1 indicates perfect negative correlation. - A value of 0 indicates that",
"] super(ContinuousVariableVerification, self).__init__(forecast, obs, group) @property def FBAR(self): \"\"\"**The sample mean forecast, FBAR**\"\"\"",
"and observations are not correlated. Returns ------- numpy.ndarray, the Pearson correlation coefficient (PR_CORR)",
"the number of \"discordant\" pairs. Concordant pairs are identi ed by comparing each",
"\\frac{1}{n}\\sum{|f_i - o_i|}` MAE is less in uenced by large errors and also",
"fcsterr + obs if obs is None: obs = forecast - fcsterr #",
"correlation coe cient ranges between -1 and 1; a value of 1 indicates",
"ME(self): \"\"\"**The Mean Error (ME)**\"\"\" return self.mean_error(self.error) @staticmethod def mean_error(error): r\"\"\"**The Mean Error",
"is None: raise Exception(\"Initialize failed, check forecast and obs and fcsterr values.\") elif",
"is another estimate of spread, similar to standard error, but is less in",
"def anomaly_correlation_coefficient(forecast, obs, climate): r\"\"\"The Anomaly correlation coefficient (ANOM_CORR) The Anomaly correlation coe",
"observation, OBAR**\"\"\" return self.mean_observation(self._o) @staticmethod def mean_observation(obs): r\"\"\"**The sample mean observation, OBAR** the",
"level of association between the forecast and observation pairs. It is defined as",
"def ME(self): \"\"\"**The Mean Error (ME)**\"\"\" return self.mean_error(self.error) @staticmethod def mean_error(error): r\"\"\"**The Mean",
"BCMSE(self): \"\"\"**Bias-Corrected MSE (BCMSE)**\"\"\" return self.bias_corrected_mse(self.error) @staticmethod def bias_corrected_mse(error): r\"\"\"**Bias-Corrected MSE (BCMSE)** MSE",
"logger.warning(\"You give forecast, obs and fcsterr, but the fcsterr will be ignored.\") fcsterr",
"the strength of linear association between the forecast anomolies and observed anomalies. The",
"to create box plots of the errors. The 0.10th, 0.25th, 0.50th, 0.75th, and",
"** 2) @property def RMSE(self): \"\"\"**Root-mean-squared error (RMSE)**\"\"\" return self.root_mean_squared_error(self.error) @staticmethod def root_mean_squared_error(error):",
"forecast anomolies and observed anomalies. The Anomaly correlation coefficient is defined as: ..",
"is de ned as .. math:: IQR = p_{75} (f_i - o_i) -",
"median_absolute_deviation(error): \"\"\"Median Absolute Deviation (MAD) The Median Absolute Deviation (MAD) is defined as",
"(with larger values) for which the value of oi for the current pair",
"than the actual values. That is, the forecast and observed samples are ordered",
"75) - np.percentile(error, 25) @property def MAD(self): \"\"\"Median Absolute Deviation (MAD)\"\"\" return self.median_absolute_deviation(self.error)",
"mean forecast (FBAR) is defined as, .. math:: \\bar{f} = \\frac{1}{n}\\sum_{i=1}^{n}f_i Returns ------",
":math:`\\tau` , KT_CORR)** Kendall's Tau statistic ( :math:`\\tau` ) is a robust measure",
"of the terms of MSE, rather than examining MSE alone. Moreover, MSE can",
"RMSE is simply the square root of the MSE, :math:`RMSE = \\sqrt{MSE}` Returns",
"spearmanr(forecast, obs) @property def KT_CORR(self): r\"\"\"**Kendall's Tau statistic ( :math:`\\tau` , KT_CORR)**\"\"\" return",
"rank correlation cofficient ( :math:`\\rho_s` ) is a robust measure of association that",
"observed standard deviation (OSTDEV)**\"\"\" return self.observation_standard_deviation(self._o) @staticmethod def observation_standard_deviation(obs): r\"\"\"**The observed standard deviation",
"-2 s_f s_o r_{fo}` is the estimated variance of the error, :math:`s^{2}_{fo}` .",
"p_{75} (f_i - o_i) - p_{25}(f_i - o_i) IQR is another estimate of",
"sample mean forecast, FBAR**\"\"\" return self.mean_forecast(self._f) @staticmethod def mean_forecast(forecast): r\"\"\"**The sample mean forecast,",
"the errors provide more information about the distribution of errors than can be",
"Error (MAE) is defined as :math:`MAE = \\frac{1}{n}\\sum{|f_i - o_i|}` MAE is less",
"are not associated. Returns ------- numpy.ndarray, Kendall's Tau statistic ( :math:`\\tau` , KT_CORR)",
"\\sqrt{\\sum{(o_i - c)^2}}} Anomaly correlation can range between -1 and 1; - a",
"of each percentile in the ordering, and matching the rank to the actual",
"spearmanr return spearmanr(forecast, obs) @property def KT_CORR(self): r\"\"\"**Kendall's Tau statistic ( :math:`\\tau` ,",
"linear association between the forecasts and observations. The Pearson correlation coefficient is defined",
"this decomposition. The standard deviation of the error, :math:`s_{f-o}` , is .. math::",
"a value of 1 indicates perfect association (concor-dance) and a value of -1",
"computed by counting the number of pairs (with larger values) for which the",
"some variety. It measures the strength of linear association between the forecast anomolies",
"than the value for the current pair). Once this is done, Nc is",
"multiplicative_bias(forecast, error): r\"\"\"**Multiplicative bias (MBIAS)** Multiplicative bias is simply the ratio of the",
"of oi for the current pair is exceeded (that is, pairs for which",
".. math:: Anomoly Correlation = \\frac{\\sum{(f_i - c)(o_i - c)}} {\\sqrt{\\sum{(f_i - c)^2}}",
"self.mean_observation(self._o) @staticmethod def mean_observation(obs): r\"\"\"**The sample mean observation, OBAR** the sample mean observation",
"- c)^2}}} Anomaly correlation can range between -1 and 1; - a value",
"give forecast, obs and fcsterr, but the fcsterr will be ignored.\") fcsterr =",
"indicates perfect association (concor-dance) and a value of -1 indicates perfect negative association.",
"in terms of squared Bias plus estimated variance of the error, as detailed",
"Score (BAGSS) The Bias Adjusted Gilbert Skill Score (BAGSS) is the Gilbert Skill",
"can be obtained from the mean and standard deviations of the errors. Percentiles",
"return np.square(np.std(error)) @property def MAE(self): \"\"\"**Mean Absolute Error (MAE)**\"\"\" return self.mean_absolute_error(self.error) @staticmethod def",
"They also are strongly impacted by large bias (ME) values. MSE and RMSE",
"\"\"\"\"**Inter Quartile Range of the Errors (IQR)**\"\"\" return self.inter_quartile_range_of_errors(self.error) @staticmethod def inter_quartile_range_of_errors(error): r\"\"\"**Inter",
"as, .. math:: \\bar{f} = \\frac{1}{n}\\sum_{i=1}^{n}f_i Returns ------ numpy.ndarray, the sample mean forecast",
"**n** is the total number of pairs) are assigned. The pairs of forecast-observed",
"large bias (ME) values. MSE and RMSE can range from 0 to infinity.",
"raise Exception(\"Initialize failed, check forecast and obs and fcsterr values.\") elif forecast is",
"identi ed by comparing each pair with all other pairs in the sample;",
"errors Percentiles of the errors provide more information about the distribution of errors",
"\"\"\" from scipy.stats import kendalltau return kendalltau(forecast, obs) @property def ME(self): \"\"\"**The Mean",
"ranges between -1 and 1; a value of 1 indicates perfect correlation and",
"\"\"\"**The sample mean observation, OBAR**\"\"\" return self.mean_observation(self._o) @staticmethod def mean_observation(obs): r\"\"\"**The sample mean",
"as possible. For details, see `Brill and Messinger, 2009. <https://www.adv-geosci.net/16/137/2008/>`_ Returns ------- Not",
"Not implemented \"\"\" return def list_score(self): \"\"\"list all available score\"\"\" return {k: np.round(getattr(self,",
"anomalies. The Anomaly correlation coefficient is defined as: .. math:: Anomoly Correlation =",
"ranks of the forecast and observed values rather than the actual values. That",
"the ratio of the means of the forecasts and the observations: .. math::",
"the value of oi for the current pair is exceeded (that is, pairs",
"r\"\"\"**The Spearman rank correlation coefficient ( :math:`\\rho_s` , SP_CORR)** The Spearman rank correlation",
"perfect forecast would have IQR = 0. Returns ------- nupmy.ndarray, Inter Quartile Range",
"Anomoly Correlation = \\frac{\\sum{(f_i - c)(o_i - c)}} {\\sqrt{\\sum{(f_i - c)^2}} \\sqrt{\\sum{(o_i -",
"r\"\"\"**Multiplicative bias (MBIAS)** Multiplicative bias is simply the ratio of the means of",
"NC is the number of \"concordant\" pairs and ND is the number of",
"0.5, 0.75, 0.9]) return np.quantile(error, quantiles) @property def ANOM_CORR(self): \"\"\"The Anomaly correlation coefficient",
"of ranks (denoted as ( :math:`d_i` ) ): .. math:: \\rho_s = \\frac{6}{n(n^2"
] |
[
"SIR(t, X): #The main set of equations Y = np.zeros((3)) Y[0] = -b",
"their contacts contacts = randint(N, size=b) for j in contacts: if not pop[j].is_removed():",
"2 = removed \"\"\" def __init__(self,startpos=None): self.status = 0 if startpos==None: self.pos =",
"* X[2] - (k * X[2]) + r * X[1] return Y t_eval",
"p: # pop[j].infection() if pop[j].is_removed(): if rand()<pop[j].reinfectionrate(): pop[j].infection() if rand()< k: pop[i].remove() pop[i].immunization(rand())",
"r * X[1] Y[2] = b * X[0] * X[2] - (k *",
"b * X[0] * X[2] - (k * X[2]) + r * X[1]",
"return sum(p.is_susceptible() for p in pop) def count_infected(pop): \"\"\" counts number of infected",
"## Discrete class Person_reinfection(Person): \"\"\" An agent representing a person. By default, a",
"__init__(self,startpos=None): self.status = 0 if startpos==None: self.pos = np.random.rand(2) else: self.pos = np.array(startpos)",
"\"\"\" def SIR(t, X): #The main set of equations Y = np.zeros((3)) Y[0]",
"+ r * X[1] return Y t_eval = np.linspace(0, time, time) sol1 =",
"counts number of infected \"\"\" return sum(p.is_infected() for p in pop) def count_removed(pop):",
"import numpy as np from scipy.integrate import solve_ivp import matplotlib.pyplot as plt from",
"solve_ivp(SIR, [0, time], [1-ii, 0, ii], method='RK45', t_eval=t_eval) # solve the equation return",
"def reinfectionrate(self): return self.reinfection def immunization(self,p): q=self.reinfection-p if q<0: q=0 self.reinfection=q def count_susceptible(pop):",
"if startpos==None: self.pos = np.random.rand(2) else: self.pos = np.array(startpos) self.reinfection=1 def reinfectionrate(self): return",
"N = Total number of people ii = initial percentage of infected b",
"sir import * def SIR_continuous_reinfected(b,k,time,ii,r): \"\"\" Simulates continuous SIR model ii = initial",
"self.reinfection=1 def reinfectionrate(self): return self.reinfection def immunization(self,p): q=self.reinfection-p if q<0: q=0 self.reinfection=q def",
"q=0 self.reinfection=q def count_susceptible(pop): \"\"\" counts number of susceptible \"\"\" return sum(p.is_susceptible() for",
"[count_infected(pop)] counts_removed = [count_removed(pop)] for t in range(T): # update the population for",
"pop[j].is_removed(): pop[j].infection() #if rand() < p: # pop[j].infection() if pop[j].is_removed(): if rand()<pop[j].reinfectionrate(): pop[j].infection()",
"can become infectious by exposing with disease method. Status: 0 = susceptible 1",
"= removed \"\"\" def __init__(self,startpos=None): self.status = 0 if startpos==None: self.pos = np.random.rand(2)",
"p in pop) def count_removed(pop): \"\"\" counts number of removed \"\"\" return sum(p.is_removed()",
"become infectious by exposing with disease method. Status: 0 = susceptible 1 =",
"model N = Total number of people ii = initial percentage of infected",
"\"\"\" counts number of infected \"\"\" return sum(p.is_infected() for p in pop) def",
"def SIR(t, X): #The main set of equations Y = np.zeros((3)) Y[0] =",
"for j in contacts: if not pop[j].is_removed(): pop[j].infection() #if rand() < p: #",
"removed \"\"\" def __init__(self,startpos=None): self.status = 0 if startpos==None: self.pos = np.random.rand(2) else:",
"* def SIR_continuous_reinfected(b,k,time,ii,r): \"\"\" Simulates continuous SIR model ii = initial percentage of",
"ii = initial percentage of infected b = number of contacts per day",
"from sir import * def SIR_continuous_reinfected(b,k,time,ii,r): \"\"\" Simulates continuous SIR model ii =",
"susceptible but not infectious. They can become infectious by exposing with disease method.",
"contacts = randint(N, size=b) for j in contacts: if not pop[j].is_removed(): pop[j].infection() #if",
"np.zeros((3)) Y[0] = -b * X[0] * X[2] Y[1] = k * X[2]",
"scipy.integrate import solve_ivp import matplotlib.pyplot as plt from numpy.random import randint, rand from",
"SIR_discrete_reinfection(N,ii,b,T,k): \"\"\" Simulates discrete SIR model N = Total number of people ii",
"infectious by exposing with disease method. Status: 0 = susceptible 1 = infected",
"contacts per day T = Days of simulation k = probability that people",
"def immunization(self,p): q=self.reinfection-p if q<0: q=0 self.reinfection=q def count_susceptible(pop): \"\"\" counts number of",
"for i in range(N)] initial_infection = randint(N,size=np.int(N*ii)) for i in initial_infection: pop[i].infection() counts_susceptible",
"r * X[1] return Y t_eval = np.linspace(0, time, time) sol1 = solve_ivp(SIR,",
"Discrete class Person_reinfection(Person): \"\"\" An agent representing a person. By default, a person",
"def count_infected(pop): \"\"\" counts number of infected \"\"\" return sum(p.is_infected() for p in",
"counts_infected = [count_infected(pop)] counts_removed = [count_removed(pop)] for t in range(T): # update the",
"of removed \"\"\" return sum(p.is_removed() for p in pop) def SIR_discrete_reinfection(N,ii,b,T,k): \"\"\" Simulates",
"counts number of removed \"\"\" return sum(p.is_removed() for p in pop) def SIR_discrete_reinfection(N,ii,b,T,k):",
"rand() < p: # pop[j].infection() if pop[j].is_removed(): if rand()<pop[j].reinfectionrate(): pop[j].infection() if rand()< k:",
"a person is susceptible but not infectious. They can become infectious by exposing",
"for t in range(T): # update the population for i in range(N): if",
"rand from sir import * def SIR_continuous_reinfected(b,k,time,ii,r): \"\"\" Simulates continuous SIR model ii",
"sum(p.is_infected() for p in pop) def count_removed(pop): \"\"\" counts number of removed \"\"\"",
"probability returns sol from solve_ivp \"\"\" def SIR(t, X): #The main set of",
"disease method. Status: 0 = susceptible 1 = infected 2 = removed \"\"\"",
"b = number of contacts per day T = Days of simulation k",
"time) sol1 = solve_ivp(SIR, [0, time], [1-ii, 0, ii], method='RK45', t_eval=t_eval) # solve",
"time, time) sol1 = solve_ivp(SIR, [0, time], [1-ii, 0, ii], method='RK45', t_eval=t_eval) #",
"#if rand() < p: # pop[j].infection() if pop[j].is_removed(): if rand()<pop[j].reinfectionrate(): pop[j].infection() if rand()<",
"Y[1] = k * X[2] - r * X[1] Y[2] = b *",
"i in range(N)] initial_infection = randint(N,size=np.int(N*ii)) for i in initial_infection: pop[i].infection() counts_susceptible =",
"from scipy.integrate import solve_ivp import matplotlib.pyplot as plt from numpy.random import randint, rand",
"= reinfected probability returns sol from solve_ivp \"\"\" def SIR(t, X): #The main",
"time = Days of simulation b = probability that people getting infectious k",
"Y[0] = -b * X[0] * X[2] Y[1] = k * X[2] -",
"return sum(p.is_removed() for p in pop) def SIR_discrete_reinfection(N,ii,b,T,k): \"\"\" Simulates discrete SIR model",
"initial_infection = randint(N,size=np.int(N*ii)) for i in initial_infection: pop[i].infection() counts_susceptible = [count_susceptible(pop)] counts_infected =",
"Person_reinfection(Person): \"\"\" An agent representing a person. By default, a person is susceptible",
"* X[1] return Y t_eval = np.linspace(0, time, time) sol1 = solve_ivp(SIR, [0,",
"X): #The main set of equations Y = np.zeros((3)) Y[0] = -b *",
"for i in initial_infection: pop[i].infection() counts_susceptible = [count_susceptible(pop)] counts_infected = [count_infected(pop)] counts_removed =",
"pop[j].infection() #if rand() < p: # pop[j].infection() if pop[j].is_removed(): if rand()<pop[j].reinfectionrate(): pop[j].infection() if",
"pop) def count_infected(pop): \"\"\" counts number of infected \"\"\" return sum(p.is_infected() for p",
"of susceptible \"\"\" return sum(p.is_susceptible() for p in pop) def count_infected(pop): \"\"\" counts",
"# update the population for i in range(N): if pop[i].is_infected(): # person i",
"count_removed(pop): \"\"\" counts number of removed \"\"\" return sum(p.is_removed() for p in pop)",
"probability that people getting infectious k = probability that people getting recovered r",
"sum(p.is_susceptible() for p in pop) def count_infected(pop): \"\"\" counts number of infected \"\"\"",
"probability that people getting recovered r = reinfected probability returns sol from solve_ivp",
"\"\"\" return sum(p.is_removed() for p in pop) def SIR_discrete_reinfection(N,ii,b,T,k): \"\"\" Simulates discrete SIR",
"infectious k = probability that people getting recovered r = reinfected probability returns",
"X[1] Y[2] = b * X[0] * X[2] - (k * X[2]) +",
"SIR_continuous_reinfected(b,k,time,ii,r): \"\"\" Simulates continuous SIR model ii = initial percentage of infected time",
"randint(N,size=np.int(N*ii)) for i in initial_infection: pop[i].infection() counts_susceptible = [count_susceptible(pop)] counts_infected = [count_infected(pop)] counts_removed",
"randint, rand from sir import * def SIR_continuous_reinfected(b,k,time,ii,r): \"\"\" Simulates continuous SIR model",
"representing a person. By default, a person is susceptible but not infectious. They",
"= probability that people getting recovered r = reinfected probability returns sol from",
"a person. By default, a person is susceptible but not infectious. They can",
"By default, a person is susceptible but not infectious. They can become infectious",
"Y = np.zeros((3)) Y[0] = -b * X[0] * X[2] Y[1] = k",
"k = probability that people getting recovered returns list of s,i,r \"\"\" pop",
"def count_susceptible(pop): \"\"\" counts number of susceptible \"\"\" return sum(p.is_susceptible() for p in",
"np from scipy.integrate import solve_ivp import matplotlib.pyplot as plt from numpy.random import randint,",
"method. Status: 0 = susceptible 1 = infected 2 = removed \"\"\" def",
"Total number of people ii = initial percentage of infected b = number",
"- r * X[1] Y[2] = b * X[0] * X[2] - (k",
"class Person_reinfection(Person): \"\"\" An agent representing a person. By default, a person is",
"number of infected \"\"\" return sum(p.is_infected() for p in pop) def count_removed(pop): \"\"\"",
"in range(N): if pop[i].is_infected(): # person i infected all their contacts contacts =",
"percentage of infected time = Days of simulation b = probability that people",
"self.reinfection=q def count_susceptible(pop): \"\"\" counts number of susceptible \"\"\" return sum(p.is_susceptible() for p",
"pop) def count_removed(pop): \"\"\" counts number of removed \"\"\" return sum(p.is_removed() for p",
"that people getting recovered returns list of s,i,r \"\"\" pop = [Person_reinfection() for",
"k: pop[i].remove() pop[i].immunization(rand()) # add to our counts counts_susceptible.append(count_susceptible(pop)) counts_infected.append(count_infected(pop)) counts_removed.append(count_removed(pop)) return np.array([counts_susceptible,counts_infected,counts_removed])",
"i in range(N): if pop[i].is_infected(): # person i infected all their contacts contacts",
"def __init__(self,startpos=None): self.status = 0 if startpos==None: self.pos = np.random.rand(2) else: self.pos =",
"count_susceptible(pop): \"\"\" counts number of susceptible \"\"\" return sum(p.is_susceptible() for p in pop)",
"= -b * X[0] * X[2] Y[1] = k * X[2] - r",
"pop[i].is_infected(): # person i infected all their contacts contacts = randint(N, size=b) for",
"for i in range(N): if pop[i].is_infected(): # person i infected all their contacts",
"as plt from numpy.random import randint, rand from sir import * def SIR_continuous_reinfected(b,k,time,ii,r):",
"immunization(self,p): q=self.reinfection-p if q<0: q=0 self.reinfection=q def count_susceptible(pop): \"\"\" counts number of susceptible",
"sol1 ## Discrete class Person_reinfection(Person): \"\"\" An agent representing a person. By default,",
"of infected time = Days of simulation b = probability that people getting",
"\"\"\" Simulates continuous SIR model ii = initial percentage of infected time =",
"[0, time], [1-ii, 0, ii], method='RK45', t_eval=t_eval) # solve the equation return sol1",
"X[0] * X[2] Y[1] = k * X[2] - r * X[1] Y[2]",
"#The main set of equations Y = np.zeros((3)) Y[0] = -b * X[0]",
"[count_susceptible(pop)] counts_infected = [count_infected(pop)] counts_removed = [count_removed(pop)] for t in range(T): # update",
"= np.zeros((3)) Y[0] = -b * X[0] * X[2] Y[1] = k *",
"1 = infected 2 = removed \"\"\" def __init__(self,startpos=None): self.status = 0 if",
"for p in pop) def count_removed(pop): \"\"\" counts number of removed \"\"\" return",
"recovered returns list of s,i,r \"\"\" pop = [Person_reinfection() for i in range(N)]",
"Days of simulation k = probability that people getting recovered returns list of",
"continuous SIR model ii = initial percentage of infected time = Days of",
"= probability that people getting recovered returns list of s,i,r \"\"\" pop =",
"person is susceptible but not infectious. They can become infectious by exposing with",
"* X[1] Y[2] = b * X[0] * X[2] - (k * X[2])",
"Status: 0 = susceptible 1 = infected 2 = removed \"\"\" def __init__(self,startpos=None):",
"of contacts per day T = Days of simulation k = probability that",
"if rand()<pop[j].reinfectionrate(): pop[j].infection() if rand()< k: pop[i].remove() pop[i].immunization(rand()) # add to our counts",
"* X[2]) + r * X[1] return Y t_eval = np.linspace(0, time, time)",
"t in range(T): # update the population for i in range(N): if pop[i].is_infected():",
"removed \"\"\" return sum(p.is_removed() for p in pop) def SIR_discrete_reinfection(N,ii,b,T,k): \"\"\" Simulates discrete",
"pop[i].infection() counts_susceptible = [count_susceptible(pop)] counts_infected = [count_infected(pop)] counts_removed = [count_removed(pop)] for t in",
"population for i in range(N): if pop[i].is_infected(): # person i infected all their",
"contacts contacts = randint(N, size=b) for j in contacts: if not pop[j].is_removed(): pop[j].infection()",
"plt from numpy.random import randint, rand from sir import * def SIR_continuous_reinfected(b,k,time,ii,r): \"\"\"",
"\"\"\" Simulates discrete SIR model N = Total number of people ii =",
"matplotlib.pyplot as plt from numpy.random import randint, rand from sir import * def",
"for p in pop) def SIR_discrete_reinfection(N,ii,b,T,k): \"\"\" Simulates discrete SIR model N =",
"s,i,r \"\"\" pop = [Person_reinfection() for i in range(N)] initial_infection = randint(N,size=np.int(N*ii)) for",
"all their contacts contacts = randint(N, size=b) for j in contacts: if not",
"the equation return sol1 ## Discrete class Person_reinfection(Person): \"\"\" An agent representing a",
"reinfected probability returns sol from solve_ivp \"\"\" def SIR(t, X): #The main set",
"people getting recovered r = reinfected probability returns sol from solve_ivp \"\"\" def",
"SIR model N = Total number of people ii = initial percentage of",
"sum(p.is_removed() for p in pop) def SIR_discrete_reinfection(N,ii,b,T,k): \"\"\" Simulates discrete SIR model N",
"people getting recovered returns list of s,i,r \"\"\" pop = [Person_reinfection() for i",
"model ii = initial percentage of infected time = Days of simulation b",
"getting recovered r = reinfected probability returns sol from solve_ivp \"\"\" def SIR(t,",
"They can become infectious by exposing with disease method. Status: 0 = susceptible",
"if pop[i].is_infected(): # person i infected all their contacts contacts = randint(N, size=b)",
"of infected b = number of contacts per day T = Days of",
"return self.reinfection def immunization(self,p): q=self.reinfection-p if q<0: q=0 self.reinfection=q def count_susceptible(pop): \"\"\" counts",
"p in pop) def count_infected(pop): \"\"\" counts number of infected \"\"\" return sum(p.is_infected()",
"def SIR_discrete_reinfection(N,ii,b,T,k): \"\"\" Simulates discrete SIR model N = Total number of people",
"time], [1-ii, 0, ii], method='RK45', t_eval=t_eval) # solve the equation return sol1 ##",
"number of removed \"\"\" return sum(p.is_removed() for p in pop) def SIR_discrete_reinfection(N,ii,b,T,k): \"\"\"",
"[Person_reinfection() for i in range(N)] initial_infection = randint(N,size=np.int(N*ii)) for i in initial_infection: pop[i].infection()",
"initial percentage of infected b = number of contacts per day T =",
"* X[2] Y[1] = k * X[2] - r * X[1] Y[2] =",
"import solve_ivp import matplotlib.pyplot as plt from numpy.random import randint, rand from sir",
"= 0 if startpos==None: self.pos = np.random.rand(2) else: self.pos = np.array(startpos) self.reinfection=1 def",
"Simulates discrete SIR model N = Total number of people ii = initial",
"p in pop) def SIR_discrete_reinfection(N,ii,b,T,k): \"\"\" Simulates discrete SIR model N = Total",
"percentage of infected b = number of contacts per day T = Days",
"not pop[j].is_removed(): pop[j].infection() #if rand() < p: # pop[j].infection() if pop[j].is_removed(): if rand()<pop[j].reinfectionrate():",
"np.random.rand(2) else: self.pos = np.array(startpos) self.reinfection=1 def reinfectionrate(self): return self.reinfection def immunization(self,p): q=self.reinfection-p",
"= b * X[0] * X[2] - (k * X[2]) + r *",
"if pop[j].is_removed(): if rand()<pop[j].reinfectionrate(): pop[j].infection() if rand()< k: pop[i].remove() pop[i].immunization(rand()) # add to",
"in initial_infection: pop[i].infection() counts_susceptible = [count_susceptible(pop)] counts_infected = [count_infected(pop)] counts_removed = [count_removed(pop)] for",
"set of equations Y = np.zeros((3)) Y[0] = -b * X[0] * X[2]",
"update the population for i in range(N): if pop[i].is_infected(): # person i infected",
"with disease method. Status: 0 = susceptible 1 = infected 2 = removed",
"return sum(p.is_infected() for p in pop) def count_removed(pop): \"\"\" counts number of removed",
"people getting infectious k = probability that people getting recovered r = reinfected",
"= initial percentage of infected b = number of contacts per day T",
"= [count_susceptible(pop)] counts_infected = [count_infected(pop)] counts_removed = [count_removed(pop)] for t in range(T): #",
"\"\"\" return sum(p.is_infected() for p in pop) def count_removed(pop): \"\"\" counts number of",
"pop[j].infection() if pop[j].is_removed(): if rand()<pop[j].reinfectionrate(): pop[j].infection() if rand()< k: pop[i].remove() pop[i].immunization(rand()) # add",
"pop[j].is_removed(): if rand()<pop[j].reinfectionrate(): pop[j].infection() if rand()< k: pop[i].remove() pop[i].immunization(rand()) # add to our",
"import randint, rand from sir import * def SIR_continuous_reinfected(b,k,time,ii,r): \"\"\" Simulates continuous SIR",
"returns list of s,i,r \"\"\" pop = [Person_reinfection() for i in range(N)] initial_infection",
"equations Y = np.zeros((3)) Y[0] = -b * X[0] * X[2] Y[1] =",
"counts number of susceptible \"\"\" return sum(p.is_susceptible() for p in pop) def count_infected(pop):",
"An agent representing a person. By default, a person is susceptible but not",
"# solve the equation return sol1 ## Discrete class Person_reinfection(Person): \"\"\" An agent",
"the population for i in range(N): if pop[i].is_infected(): # person i infected all",
"equation return sol1 ## Discrete class Person_reinfection(Person): \"\"\" An agent representing a person.",
"infected all their contacts contacts = randint(N, size=b) for j in contacts: if",
"rand()< k: pop[i].remove() pop[i].immunization(rand()) # add to our counts counts_susceptible.append(count_susceptible(pop)) counts_infected.append(count_infected(pop)) counts_removed.append(count_removed(pop)) return",
"self.pos = np.random.rand(2) else: self.pos = np.array(startpos) self.reinfection=1 def reinfectionrate(self): return self.reinfection def",
"default, a person is susceptible but not infectious. They can become infectious by",
"-b * X[0] * X[2] Y[1] = k * X[2] - r *",
"person. By default, a person is susceptible but not infectious. They can become",
"= Total number of people ii = initial percentage of infected b =",
"SIR model ii = initial percentage of infected time = Days of simulation",
"ii = initial percentage of infected time = Days of simulation b =",
"= np.linspace(0, time, time) sol1 = solve_ivp(SIR, [0, time], [1-ii, 0, ii], method='RK45',",
"(k * X[2]) + r * X[1] return Y t_eval = np.linspace(0, time,",
"but not infectious. They can become infectious by exposing with disease method. Status:",
"* X[2] - r * X[1] Y[2] = b * X[0] * X[2]",
"= probability that people getting infectious k = probability that people getting recovered",
"\"\"\" counts number of removed \"\"\" return sum(p.is_removed() for p in pop) def",
"= randint(N,size=np.int(N*ii)) for i in initial_infection: pop[i].infection() counts_susceptible = [count_susceptible(pop)] counts_infected = [count_infected(pop)]",
"= solve_ivp(SIR, [0, time], [1-ii, 0, ii], method='RK45', t_eval=t_eval) # solve the equation",
"counts_susceptible = [count_susceptible(pop)] counts_infected = [count_infected(pop)] counts_removed = [count_removed(pop)] for t in range(T):",
"contacts: if not pop[j].is_removed(): pop[j].infection() #if rand() < p: # pop[j].infection() if pop[j].is_removed():",
"self.status = 0 if startpos==None: self.pos = np.random.rand(2) else: self.pos = np.array(startpos) self.reinfection=1",
"rand()<pop[j].reinfectionrate(): pop[j].infection() if rand()< k: pop[i].remove() pop[i].immunization(rand()) # add to our counts counts_susceptible.append(count_susceptible(pop))",
"from solve_ivp \"\"\" def SIR(t, X): #The main set of equations Y =",
"infected 2 = removed \"\"\" def __init__(self,startpos=None): self.status = 0 if startpos==None: self.pos",
"< p: # pop[j].infection() if pop[j].is_removed(): if rand()<pop[j].reinfectionrate(): pop[j].infection() if rand()< k: pop[i].remove()",
"for p in pop) def count_infected(pop): \"\"\" counts number of infected \"\"\" return",
"= [Person_reinfection() for i in range(N)] initial_infection = randint(N,size=np.int(N*ii)) for i in initial_infection:",
"agent representing a person. By default, a person is susceptible but not infectious.",
"in pop) def SIR_discrete_reinfection(N,ii,b,T,k): \"\"\" Simulates discrete SIR model N = Total number",
"= [count_removed(pop)] for t in range(T): # update the population for i in",
"# person i infected all their contacts contacts = randint(N, size=b) for j",
"is susceptible but not infectious. They can become infectious by exposing with disease",
"= Days of simulation k = probability that people getting recovered returns list",
"i in initial_infection: pop[i].infection() counts_susceptible = [count_susceptible(pop)] counts_infected = [count_infected(pop)] counts_removed = [count_removed(pop)]",
"Simulates continuous SIR model ii = initial percentage of infected time = Days",
"import * def SIR_continuous_reinfected(b,k,time,ii,r): \"\"\" Simulates continuous SIR model ii = initial percentage",
"exposing with disease method. Status: 0 = susceptible 1 = infected 2 =",
"X[1] return Y t_eval = np.linspace(0, time, time) sol1 = solve_ivp(SIR, [0, time],",
"\"\"\" An agent representing a person. By default, a person is susceptible but",
"= k * X[2] - r * X[1] Y[2] = b * X[0]",
"initial percentage of infected time = Days of simulation b = probability that",
"* X[0] * X[2] - (k * X[2]) + r * X[1] return",
"- (k * X[2]) + r * X[1] return Y t_eval = np.linspace(0,",
"simulation k = probability that people getting recovered returns list of s,i,r \"\"\"",
"pop[j].infection() if rand()< k: pop[i].remove() pop[i].immunization(rand()) # add to our counts counts_susceptible.append(count_susceptible(pop)) counts_infected.append(count_infected(pop))",
"[1-ii, 0, ii], method='RK45', t_eval=t_eval) # solve the equation return sol1 ## Discrete",
"= randint(N, size=b) for j in contacts: if not pop[j].is_removed(): pop[j].infection() #if rand()",
"b = probability that people getting infectious k = probability that people getting",
"= np.array(startpos) self.reinfection=1 def reinfectionrate(self): return self.reinfection def immunization(self,p): q=self.reinfection-p if q<0: q=0",
"j in contacts: if not pop[j].is_removed(): pop[j].infection() #if rand() < p: # pop[j].infection()",
"in range(N)] initial_infection = randint(N,size=np.int(N*ii)) for i in initial_infection: pop[i].infection() counts_susceptible = [count_susceptible(pop)]",
"r = reinfected probability returns sol from solve_ivp \"\"\" def SIR(t, X): #The",
"simulation b = probability that people getting infectious k = probability that people",
"= [count_infected(pop)] counts_removed = [count_removed(pop)] for t in range(T): # update the population",
"solve_ivp \"\"\" def SIR(t, X): #The main set of equations Y = np.zeros((3))",
"returns sol from solve_ivp \"\"\" def SIR(t, X): #The main set of equations",
"numpy as np from scipy.integrate import solve_ivp import matplotlib.pyplot as plt from numpy.random",
"as np from scipy.integrate import solve_ivp import matplotlib.pyplot as plt from numpy.random import",
"else: self.pos = np.array(startpos) self.reinfection=1 def reinfectionrate(self): return self.reinfection def immunization(self,p): q=self.reinfection-p if",
"in contacts: if not pop[j].is_removed(): pop[j].infection() #if rand() < p: # pop[j].infection() if",
"t_eval=t_eval) # solve the equation return sol1 ## Discrete class Person_reinfection(Person): \"\"\" An",
"X[2] - r * X[1] Y[2] = b * X[0] * X[2] -",
"that people getting infectious k = probability that people getting recovered r =",
"self.reinfection def immunization(self,p): q=self.reinfection-p if q<0: q=0 self.reinfection=q def count_susceptible(pop): \"\"\" counts number",
"people ii = initial percentage of infected b = number of contacts per",
"\"\"\" pop = [Person_reinfection() for i in range(N)] initial_infection = randint(N,size=np.int(N*ii)) for i",
"pop) def SIR_discrete_reinfection(N,ii,b,T,k): \"\"\" Simulates discrete SIR model N = Total number of",
"of simulation k = probability that people getting recovered returns list of s,i,r",
"solve_ivp import matplotlib.pyplot as plt from numpy.random import randint, rand from sir import",
"probability that people getting recovered returns list of s,i,r \"\"\" pop = [Person_reinfection()",
"t_eval = np.linspace(0, time, time) sol1 = solve_ivp(SIR, [0, time], [1-ii, 0, ii],",
"range(N): if pop[i].is_infected(): # person i infected all their contacts contacts = randint(N,",
"counts_removed = [count_removed(pop)] for t in range(T): # update the population for i",
"Days of simulation b = probability that people getting infectious k = probability",
"person i infected all their contacts contacts = randint(N, size=b) for j in",
"i infected all their contacts contacts = randint(N, size=b) for j in contacts:",
"that people getting recovered r = reinfected probability returns sol from solve_ivp \"\"\"",
"def count_removed(pop): \"\"\" counts number of removed \"\"\" return sum(p.is_removed() for p in",
"of simulation b = probability that people getting infectious k = probability that",
"susceptible \"\"\" return sum(p.is_susceptible() for p in pop) def count_infected(pop): \"\"\" counts number",
"initial_infection: pop[i].infection() counts_susceptible = [count_susceptible(pop)] counts_infected = [count_infected(pop)] counts_removed = [count_removed(pop)] for t",
"of infected \"\"\" return sum(p.is_infected() for p in pop) def count_removed(pop): \"\"\" counts",
"infected b = number of contacts per day T = Days of simulation",
"0 if startpos==None: self.pos = np.random.rand(2) else: self.pos = np.array(startpos) self.reinfection=1 def reinfectionrate(self):",
"return Y t_eval = np.linspace(0, time, time) sol1 = solve_ivp(SIR, [0, time], [1-ii,",
"* X[0] * X[2] Y[1] = k * X[2] - r * X[1]",
"[count_removed(pop)] for t in range(T): # update the population for i in range(N):",
"range(N)] initial_infection = randint(N,size=np.int(N*ii)) for i in initial_infection: pop[i].infection() counts_susceptible = [count_susceptible(pop)] counts_infected",
"solve the equation return sol1 ## Discrete class Person_reinfection(Person): \"\"\" An agent representing",
"by exposing with disease method. Status: 0 = susceptible 1 = infected 2",
"# pop[j].infection() if pop[j].is_removed(): if rand()<pop[j].reinfectionrate(): pop[j].infection() if rand()< k: pop[i].remove() pop[i].immunization(rand()) #",
"number of people ii = initial percentage of infected b = number of",
"self.pos = np.array(startpos) self.reinfection=1 def reinfectionrate(self): return self.reinfection def immunization(self,p): q=self.reinfection-p if q<0:",
"infected time = Days of simulation b = probability that people getting infectious",
"np.array(startpos) self.reinfection=1 def reinfectionrate(self): return self.reinfection def immunization(self,p): q=self.reinfection-p if q<0: q=0 self.reinfection=q",
"in pop) def count_infected(pop): \"\"\" counts number of infected \"\"\" return sum(p.is_infected() for",
"= infected 2 = removed \"\"\" def __init__(self,startpos=None): self.status = 0 if startpos==None:",
"\"\"\" return sum(p.is_susceptible() for p in pop) def count_infected(pop): \"\"\" counts number of",
"of s,i,r \"\"\" pop = [Person_reinfection() for i in range(N)] initial_infection = randint(N,size=np.int(N*ii))",
"not infectious. They can become infectious by exposing with disease method. Status: 0",
"k = probability that people getting recovered r = reinfected probability returns sol",
"getting infectious k = probability that people getting recovered r = reinfected probability",
"\"\"\" counts number of susceptible \"\"\" return sum(p.is_susceptible() for p in pop) def",
"of equations Y = np.zeros((3)) Y[0] = -b * X[0] * X[2] Y[1]",
"randint(N, size=b) for j in contacts: if not pop[j].is_removed(): pop[j].infection() #if rand() <",
"= np.random.rand(2) else: self.pos = np.array(startpos) self.reinfection=1 def reinfectionrate(self): return self.reinfection def immunization(self,p):",
"= Days of simulation b = probability that people getting infectious k =",
"Y t_eval = np.linspace(0, time, time) sol1 = solve_ivp(SIR, [0, time], [1-ii, 0,",
"day T = Days of simulation k = probability that people getting recovered",
"if q<0: q=0 self.reinfection=q def count_susceptible(pop): \"\"\" counts number of susceptible \"\"\" return",
"X[0] * X[2] - (k * X[2]) + r * X[1] return Y",
"sol1 = solve_ivp(SIR, [0, time], [1-ii, 0, ii], method='RK45', t_eval=t_eval) # solve the",
"= number of contacts per day T = Days of simulation k =",
"recovered r = reinfected probability returns sol from solve_ivp \"\"\" def SIR(t, X):",
"of people ii = initial percentage of infected b = number of contacts",
"number of contacts per day T = Days of simulation k = probability",
"k * X[2] - r * X[1] Y[2] = b * X[0] *",
"list of s,i,r \"\"\" pop = [Person_reinfection() for i in range(N)] initial_infection =",
"main set of equations Y = np.zeros((3)) Y[0] = -b * X[0] *",
"q=self.reinfection-p if q<0: q=0 self.reinfection=q def count_susceptible(pop): \"\"\" counts number of susceptible \"\"\"",
"number of susceptible \"\"\" return sum(p.is_susceptible() for p in pop) def count_infected(pop): \"\"\"",
"= initial percentage of infected time = Days of simulation b = probability",
"getting recovered returns list of s,i,r \"\"\" pop = [Person_reinfection() for i in",
"T = Days of simulation k = probability that people getting recovered returns",
"startpos==None: self.pos = np.random.rand(2) else: self.pos = np.array(startpos) self.reinfection=1 def reinfectionrate(self): return self.reinfection",
"X[2] - (k * X[2]) + r * X[1] return Y t_eval =",
"pop = [Person_reinfection() for i in range(N)] initial_infection = randint(N,size=np.int(N*ii)) for i in",
"import matplotlib.pyplot as plt from numpy.random import randint, rand from sir import *",
"in range(T): # update the population for i in range(N): if pop[i].is_infected(): #",
"range(T): # update the population for i in range(N): if pop[i].is_infected(): # person",
"infectious. They can become infectious by exposing with disease method. Status: 0 =",
"size=b) for j in contacts: if not pop[j].is_removed(): pop[j].infection() #if rand() < p:",
"from numpy.random import randint, rand from sir import * def SIR_continuous_reinfected(b,k,time,ii,r): \"\"\" Simulates",
"ii], method='RK45', t_eval=t_eval) # solve the equation return sol1 ## Discrete class Person_reinfection(Person):",
"sol from solve_ivp \"\"\" def SIR(t, X): #The main set of equations Y",
"infected \"\"\" return sum(p.is_infected() for p in pop) def count_removed(pop): \"\"\" counts number",
"return sol1 ## Discrete class Person_reinfection(Person): \"\"\" An agent representing a person. By",
"per day T = Days of simulation k = probability that people getting",
"\"\"\" def __init__(self,startpos=None): self.status = 0 if startpos==None: self.pos = np.random.rand(2) else: self.pos",
"np.linspace(0, time, time) sol1 = solve_ivp(SIR, [0, time], [1-ii, 0, ii], method='RK45', t_eval=t_eval)",
"numpy.random import randint, rand from sir import * def SIR_continuous_reinfected(b,k,time,ii,r): \"\"\" Simulates continuous",
"X[2]) + r * X[1] return Y t_eval = np.linspace(0, time, time) sol1",
"if not pop[j].is_removed(): pop[j].infection() #if rand() < p: # pop[j].infection() if pop[j].is_removed(): if",
"q<0: q=0 self.reinfection=q def count_susceptible(pop): \"\"\" counts number of susceptible \"\"\" return sum(p.is_susceptible()",
"method='RK45', t_eval=t_eval) # solve the equation return sol1 ## Discrete class Person_reinfection(Person): \"\"\"",
"Y[2] = b * X[0] * X[2] - (k * X[2]) + r",
"discrete SIR model N = Total number of people ii = initial percentage",
"= susceptible 1 = infected 2 = removed \"\"\" def __init__(self,startpos=None): self.status =",
"if rand()< k: pop[i].remove() pop[i].immunization(rand()) # add to our counts counts_susceptible.append(count_susceptible(pop)) counts_infected.append(count_infected(pop)) counts_removed.append(count_removed(pop))",
"in pop) def count_removed(pop): \"\"\" counts number of removed \"\"\" return sum(p.is_removed() for",
"count_infected(pop): \"\"\" counts number of infected \"\"\" return sum(p.is_infected() for p in pop)",
"def SIR_continuous_reinfected(b,k,time,ii,r): \"\"\" Simulates continuous SIR model ii = initial percentage of infected",
"X[2] Y[1] = k * X[2] - r * X[1] Y[2] = b",
"0 = susceptible 1 = infected 2 = removed \"\"\" def __init__(self,startpos=None): self.status",
"susceptible 1 = infected 2 = removed \"\"\" def __init__(self,startpos=None): self.status = 0",
"0, ii], method='RK45', t_eval=t_eval) # solve the equation return sol1 ## Discrete class",
"reinfectionrate(self): return self.reinfection def immunization(self,p): q=self.reinfection-p if q<0: q=0 self.reinfection=q def count_susceptible(pop): \"\"\""
] |
[
"self._map_object = map_object self._part = part def flip(self): self._map_object.invalidate_geometry() with self._undo_stack.property_change( \"Sprite/Wall Flip\",",
"self._part, \"xflip\", \"yflip\" ): if self._stat.xflip and self._stat.yflip: self._stat.xflip = 0 elif self._stat.xflip:",
"__init__( self, undo_stack: UndoStack, map_object: map_objects.EmptyObject, part: str ): self._undo_stack = undo_stack self._map_object",
"elif self._stat.xflip: self._stat.xflip = 1 self._stat.yflip = 1 elif self._stat.yflip: self._stat.yflip = 0",
"self._stat.yflip: self._stat.xflip = 0 elif self._stat.xflip: self._stat.xflip = 1 self._stat.yflip = 1 elif",
"from ..undo_stack import SimpleUndoableOperation, UndoStack class Flip: def __init__( self, undo_stack: UndoStack, map_object:",
".. import map_objects from ..undo_stack import SimpleUndoableOperation, UndoStack class Flip: def __init__( self,",
"= 0 elif self._stat.xflip: self._stat.xflip = 1 self._stat.yflip = 1 elif self._stat.yflip: self._stat.yflip",
"and self._stat.yflip: self._stat.xflip = 0 elif self._stat.xflip: self._stat.xflip = 1 self._stat.yflip = 1",
"UndoStack class Flip: def __init__( self, undo_stack: UndoStack, map_object: map_objects.EmptyObject, part: str ):",
"map_objects.EmptyObject, part: str ): self._undo_stack = undo_stack self._map_object = map_object self._part = part",
"self._undo_stack.property_change( \"Sprite/Wall Flip\", self._map_object, self._part, \"xflip\", \"yflip\" ): if self._stat.xflip and self._stat.yflip: self._stat.xflip",
"Flip\", self._map_object, self._part, \"xflip\", \"yflip\" ): if self._stat.xflip and self._stat.yflip: self._stat.xflip = 0",
"self._stat.xflip: self._stat.xflip = 1 self._stat.yflip = 1 elif self._stat.yflip: self._stat.yflip = 0 else:",
"# Copyright 2020 <NAME> # SPDX-License-Identifier: Apache-2.0 from .. import map_objects from ..undo_stack",
"..undo_stack import SimpleUndoableOperation, UndoStack class Flip: def __init__( self, undo_stack: UndoStack, map_object: map_objects.EmptyObject,",
"import SimpleUndoableOperation, UndoStack class Flip: def __init__( self, undo_stack: UndoStack, map_object: map_objects.EmptyObject, part:",
"<reponame>thomasrogers03/bloom # Copyright 2020 <NAME> # SPDX-License-Identifier: Apache-2.0 from .. import map_objects from",
"\"xflip\", \"yflip\" ): if self._stat.xflip and self._stat.yflip: self._stat.xflip = 0 elif self._stat.xflip: self._stat.xflip",
"undo_stack: UndoStack, map_object: map_objects.EmptyObject, part: str ): self._undo_stack = undo_stack self._map_object = map_object",
"self._stat.xflip = 1 self._stat.yflip = 1 elif self._stat.yflip: self._stat.yflip = 0 else: self._stat.xflip",
"= part def flip(self): self._map_object.invalidate_geometry() with self._undo_stack.property_change( \"Sprite/Wall Flip\", self._map_object, self._part, \"xflip\", \"yflip\"",
"UndoStack, map_object: map_objects.EmptyObject, part: str ): self._undo_stack = undo_stack self._map_object = map_object self._part",
"self._part = part def flip(self): self._map_object.invalidate_geometry() with self._undo_stack.property_change( \"Sprite/Wall Flip\", self._map_object, self._part, \"xflip\",",
"with self._undo_stack.property_change( \"Sprite/Wall Flip\", self._map_object, self._part, \"xflip\", \"yflip\" ): if self._stat.xflip and self._stat.yflip:",
"SPDX-License-Identifier: Apache-2.0 from .. import map_objects from ..undo_stack import SimpleUndoableOperation, UndoStack class Flip:",
"SimpleUndoableOperation, UndoStack class Flip: def __init__( self, undo_stack: UndoStack, map_object: map_objects.EmptyObject, part: str",
"1 elif self._stat.yflip: self._stat.yflip = 0 else: self._stat.xflip = 1 @property def _stat(self):",
"self._undo_stack = undo_stack self._map_object = map_object self._part = part def flip(self): self._map_object.invalidate_geometry() with",
"self._stat.yflip: self._stat.yflip = 0 else: self._stat.xflip = 1 @property def _stat(self): return self._map_object.get_stat_for_part(self._part)",
"= 1 elif self._stat.yflip: self._stat.yflip = 0 else: self._stat.xflip = 1 @property def",
"if self._stat.xflip and self._stat.yflip: self._stat.xflip = 0 elif self._stat.xflip: self._stat.xflip = 1 self._stat.yflip",
"self._map_object.invalidate_geometry() with self._undo_stack.property_change( \"Sprite/Wall Flip\", self._map_object, self._part, \"xflip\", \"yflip\" ): if self._stat.xflip and",
"self, undo_stack: UndoStack, map_object: map_objects.EmptyObject, part: str ): self._undo_stack = undo_stack self._map_object =",
"Apache-2.0 from .. import map_objects from ..undo_stack import SimpleUndoableOperation, UndoStack class Flip: def",
"flip(self): self._map_object.invalidate_geometry() with self._undo_stack.property_change( \"Sprite/Wall Flip\", self._map_object, self._part, \"xflip\", \"yflip\" ): if self._stat.xflip",
"map_object self._part = part def flip(self): self._map_object.invalidate_geometry() with self._undo_stack.property_change( \"Sprite/Wall Flip\", self._map_object, self._part,",
"part def flip(self): self._map_object.invalidate_geometry() with self._undo_stack.property_change( \"Sprite/Wall Flip\", self._map_object, self._part, \"xflip\", \"yflip\" ):",
"class Flip: def __init__( self, undo_stack: UndoStack, map_object: map_objects.EmptyObject, part: str ): self._undo_stack",
"= undo_stack self._map_object = map_object self._part = part def flip(self): self._map_object.invalidate_geometry() with self._undo_stack.property_change(",
"part: str ): self._undo_stack = undo_stack self._map_object = map_object self._part = part def",
"): if self._stat.xflip and self._stat.yflip: self._stat.xflip = 0 elif self._stat.xflip: self._stat.xflip = 1",
"= map_object self._part = part def flip(self): self._map_object.invalidate_geometry() with self._undo_stack.property_change( \"Sprite/Wall Flip\", self._map_object,",
"): self._undo_stack = undo_stack self._map_object = map_object self._part = part def flip(self): self._map_object.invalidate_geometry()",
"\"Sprite/Wall Flip\", self._map_object, self._part, \"xflip\", \"yflip\" ): if self._stat.xflip and self._stat.yflip: self._stat.xflip =",
"def flip(self): self._map_object.invalidate_geometry() with self._undo_stack.property_change( \"Sprite/Wall Flip\", self._map_object, self._part, \"xflip\", \"yflip\" ): if",
"map_objects from ..undo_stack import SimpleUndoableOperation, UndoStack class Flip: def __init__( self, undo_stack: UndoStack,",
"2020 <NAME> # SPDX-License-Identifier: Apache-2.0 from .. import map_objects from ..undo_stack import SimpleUndoableOperation,",
"map_object: map_objects.EmptyObject, part: str ): self._undo_stack = undo_stack self._map_object = map_object self._part =",
"import map_objects from ..undo_stack import SimpleUndoableOperation, UndoStack class Flip: def __init__( self, undo_stack:",
"1 self._stat.yflip = 1 elif self._stat.yflip: self._stat.yflip = 0 else: self._stat.xflip = 1",
"self._stat.yflip = 1 elif self._stat.yflip: self._stat.yflip = 0 else: self._stat.xflip = 1 @property",
"0 elif self._stat.xflip: self._stat.xflip = 1 self._stat.yflip = 1 elif self._stat.yflip: self._stat.yflip =",
"# SPDX-License-Identifier: Apache-2.0 from .. import map_objects from ..undo_stack import SimpleUndoableOperation, UndoStack class",
"elif self._stat.yflip: self._stat.yflip = 0 else: self._stat.xflip = 1 @property def _stat(self): return",
"\"yflip\" ): if self._stat.xflip and self._stat.yflip: self._stat.xflip = 0 elif self._stat.xflip: self._stat.xflip =",
"def __init__( self, undo_stack: UndoStack, map_object: map_objects.EmptyObject, part: str ): self._undo_stack = undo_stack",
"undo_stack self._map_object = map_object self._part = part def flip(self): self._map_object.invalidate_geometry() with self._undo_stack.property_change( \"Sprite/Wall",
"from .. import map_objects from ..undo_stack import SimpleUndoableOperation, UndoStack class Flip: def __init__(",
"= 1 self._stat.yflip = 1 elif self._stat.yflip: self._stat.yflip = 0 else: self._stat.xflip =",
"<NAME> # SPDX-License-Identifier: Apache-2.0 from .. import map_objects from ..undo_stack import SimpleUndoableOperation, UndoStack",
"Copyright 2020 <NAME> # SPDX-License-Identifier: Apache-2.0 from .. import map_objects from ..undo_stack import",
"Flip: def __init__( self, undo_stack: UndoStack, map_object: map_objects.EmptyObject, part: str ): self._undo_stack =",
"self._stat.xflip = 0 elif self._stat.xflip: self._stat.xflip = 1 self._stat.yflip = 1 elif self._stat.yflip:",
"str ): self._undo_stack = undo_stack self._map_object = map_object self._part = part def flip(self):",
"self._map_object, self._part, \"xflip\", \"yflip\" ): if self._stat.xflip and self._stat.yflip: self._stat.xflip = 0 elif",
"self._stat.xflip and self._stat.yflip: self._stat.xflip = 0 elif self._stat.xflip: self._stat.xflip = 1 self._stat.yflip ="
] |
[
"the second number:\") s_num = int(input()) subtraction = f_num - s_num print (\"The",
"second number:\") s_num = int(input()) subtraction = f_num - s_num print (\"The value",
"f_num = int(input()) print(\"Enter the second number:\") s_num = int(input()) subtraction = f_num",
"the first number:\") f_num = int(input()) print(\"Enter the second number:\") s_num = int(input())",
"= int(input()) print(\"Enter the second number:\") s_num = int(input()) subtraction = f_num -",
"number:\") f_num = int(input()) print(\"Enter the second number:\") s_num = int(input()) subtraction =",
"int(input()) print(\"Enter the second number:\") s_num = int(input()) subtraction = f_num - s_num",
"s_num = int(input()) subtraction = f_num - s_num print (\"The value is:\") print",
"int(input()) subtraction = f_num - s_num print (\"The value is:\") print ( subtraction",
"= int(input()) subtraction = f_num - s_num print (\"The value is:\") print (",
"subtraction = f_num - s_num print (\"The value is:\") print ( subtraction )",
"first number:\") f_num = int(input()) print(\"Enter the second number:\") s_num = int(input()) subtraction",
"print(\"Enter the second number:\") s_num = int(input()) subtraction = f_num - s_num print",
"number:\") s_num = int(input()) subtraction = f_num - s_num print (\"The value is:\")",
"print(\"Enter the first number:\") f_num = int(input()) print(\"Enter the second number:\") s_num ="
] |
[
"\"\"\" count = 0 for i in range(0, 32): if num & 1:",
"countOnes(self, num): # write your code here \"\"\" count=0 while num!=0: num =",
"if num & 1: count = count + 1 num = num >>",
"in range(0, 32): if num & 1: count = count + 1 num",
"Solution: \"\"\" @param: num: An integer @return: An integer \"\"\" def countOnes(self, num):",
"& (num-1) count+=1 return count \"\"\" count = 0 for i in range(0,",
"0 for i in range(0, 32): if num & 1: count = count",
"num): # write your code here \"\"\" count=0 while num!=0: num = num",
"return count \"\"\" count = 0 for i in range(0, 32): if num",
"& 1: count = count + 1 num = num >> 1 return",
"\"\"\" def countOnes(self, num): # write your code here \"\"\" count=0 while num!=0:",
"\"\"\" @param: num: An integer @return: An integer \"\"\" def countOnes(self, num): #",
"count=0 while num!=0: num = num & (num-1) count+=1 return count \"\"\" count",
"num & (num-1) count+=1 return count \"\"\" count = 0 for i in",
"= 0 for i in range(0, 32): if num & 1: count =",
"num & 1: count = count + 1 num = num >> 1",
"while num!=0: num = num & (num-1) count+=1 return count \"\"\" count =",
"# write your code here \"\"\" count=0 while num!=0: num = num &",
"def countOnes(self, num): # write your code here \"\"\" count=0 while num!=0: num",
"<filename>Algorithm/Easy/1-500/365Count1inBinary.py<gh_stars>0 class Solution: \"\"\" @param: num: An integer @return: An integer \"\"\" def",
"your code here \"\"\" count=0 while num!=0: num = num & (num-1) count+=1",
"integer @return: An integer \"\"\" def countOnes(self, num): # write your code here",
"class Solution: \"\"\" @param: num: An integer @return: An integer \"\"\" def countOnes(self,",
"(num-1) count+=1 return count \"\"\" count = 0 for i in range(0, 32):",
"num = num & (num-1) count+=1 return count \"\"\" count = 0 for",
"count = 0 for i in range(0, 32): if num & 1: count",
"@return: An integer \"\"\" def countOnes(self, num): # write your code here \"\"\"",
"An integer \"\"\" def countOnes(self, num): # write your code here \"\"\" count=0",
"range(0, 32): if num & 1: count = count + 1 num =",
"write your code here \"\"\" count=0 while num!=0: num = num & (num-1)",
"count+=1 return count \"\"\" count = 0 for i in range(0, 32): if",
"1: count = count + 1 num = num >> 1 return count",
"An integer @return: An integer \"\"\" def countOnes(self, num): # write your code",
"@param: num: An integer @return: An integer \"\"\" def countOnes(self, num): # write",
"\"\"\" count=0 while num!=0: num = num & (num-1) count+=1 return count \"\"\"",
"count \"\"\" count = 0 for i in range(0, 32): if num &",
"= num & (num-1) count+=1 return count \"\"\" count = 0 for i",
"num: An integer @return: An integer \"\"\" def countOnes(self, num): # write your",
"num!=0: num = num & (num-1) count+=1 return count \"\"\" count = 0",
"for i in range(0, 32): if num & 1: count = count +",
"32): if num & 1: count = count + 1 num = num",
"i in range(0, 32): if num & 1: count = count + 1",
"integer \"\"\" def countOnes(self, num): # write your code here \"\"\" count=0 while",
"here \"\"\" count=0 while num!=0: num = num & (num-1) count+=1 return count",
"code here \"\"\" count=0 while num!=0: num = num & (num-1) count+=1 return"
] |
[
"web.args['name'], float(web.args['lat']), float(web.args['lon']) location[i].name, location[i].lat, location[i].lon = args location[i].flush() except Exception as e:",
"int(web.args['idx']) args = web.args['name'], float(web.args['lat']), float(web.args['lon']) location[i].name, location[i].lat, location[i].lon = args location[i].flush() except",
"page(web): try: i = int(web.args['idx']) args = web.args['name'], float(web.args['lat']), float(web.args['lon']) location[i].name, location[i].lat, location[i].lon",
"<reponame>ondiiik/meteoink<filename>simulator/web/lset.py from config import location from log import dump_exception def page(web): try: i",
"location[i].lon = args location[i].flush() except Exception as e: dump_exception('WEB error:', e) yield web.index",
"dump_exception def page(web): try: i = int(web.args['idx']) args = web.args['name'], float(web.args['lat']), float(web.args['lon']) location[i].name,",
"config import location from log import dump_exception def page(web): try: i = int(web.args['idx'])",
"from config import location from log import dump_exception def page(web): try: i =",
"from log import dump_exception def page(web): try: i = int(web.args['idx']) args = web.args['name'],",
"args = web.args['name'], float(web.args['lat']), float(web.args['lon']) location[i].name, location[i].lat, location[i].lon = args location[i].flush() except Exception",
"location[i].name, location[i].lat, location[i].lon = args location[i].flush() except Exception as e: dump_exception('WEB error:', e)",
"i = int(web.args['idx']) args = web.args['name'], float(web.args['lat']), float(web.args['lon']) location[i].name, location[i].lat, location[i].lon = args",
"import dump_exception def page(web): try: i = int(web.args['idx']) args = web.args['name'], float(web.args['lat']), float(web.args['lon'])",
"import location from log import dump_exception def page(web): try: i = int(web.args['idx']) args",
"location[i].lat, location[i].lon = args location[i].flush() except Exception as e: dump_exception('WEB error:', e) yield",
"float(web.args['lat']), float(web.args['lon']) location[i].name, location[i].lat, location[i].lon = args location[i].flush() except Exception as e: dump_exception('WEB",
"location from log import dump_exception def page(web): try: i = int(web.args['idx']) args =",
"= int(web.args['idx']) args = web.args['name'], float(web.args['lat']), float(web.args['lon']) location[i].name, location[i].lat, location[i].lon = args location[i].flush()",
"= web.args['name'], float(web.args['lat']), float(web.args['lon']) location[i].name, location[i].lat, location[i].lon = args location[i].flush() except Exception as",
"try: i = int(web.args['idx']) args = web.args['name'], float(web.args['lat']), float(web.args['lon']) location[i].name, location[i].lat, location[i].lon =",
"def page(web): try: i = int(web.args['idx']) args = web.args['name'], float(web.args['lat']), float(web.args['lon']) location[i].name, location[i].lat,",
"float(web.args['lon']) location[i].name, location[i].lat, location[i].lon = args location[i].flush() except Exception as e: dump_exception('WEB error:',",
"log import dump_exception def page(web): try: i = int(web.args['idx']) args = web.args['name'], float(web.args['lat']),"
] |
[
"wait for input from user. Each queue has a number associated with it,",
"instance, which will be used to manipulate queues. Other attributes, that may be",
"inside of script's help (run with -h argument); * client_method_name (str) - name",
"(seperated by space) / ' '\"all\" to choose all queues.', 'nargs': '*', },",
"= ['q', 'quit', 'exit', 'e'] choose_all_commands = ['a', 'all'] # set to True,",
"= self._get_user_input(mapping) parsed_input = self._parse_input(user_input) except StopReceivingInput: print 'bye' break if parsed_input: selected_mapping",
"nr, queue in mapping.iteritems(): print '[{}] {}'.format(nr, queue) user_input = raw_input(\"Queue number ('all'",
"numbers should not be mixed in one input. \"\"\" config_section = 'rabbit_tools' client_method_name",
"queue has a number associated with it, so in this mode user should",
"more spaces: 2 - 5 (will chose: 2, 3, 4, 5) IMPORTANT: list",
"= self.single_choice_regex.search(user_input) if single_choice: return [int(single_choice.group(0))] range_choice = self.range_choice_regex.search(user_input) if range_choice: return range(int(range_choice.group(1)),",
"* queues_affected_msg (str) - message to log, to show, which queues were successfully",
"is no need to define every time options like API address or user",
"queues to choose.') raise StopReceivingInput def _parse_input(self, user_input): if user_input in self.quitting_commands: raise",
"not selected_mapping: logger.error('No queues were selected.') return None return selected_mapping elif parsed_input ==",
"chosen_queues = all_queues else: chosen_queues = queue_names affected_queues = [] for queue in",
"queue) else: logger.warning(\"%s: %r.\", self.queue_not_affected_msg, queue) else: affected_queues.append(queue) else: logger.info(\"%s: %s\", self.queues_affected_msg, ',",
"port) cl = Client(api_url, user, password) return cl @staticmethod def _get_api_url(host, port): return",
"(x['name'] for x in self.client.get_queues(self._vhost)) def _get_queue_mapping(self): queue_names = list(self._yield_queue_list()) if not queue_names:",
"re.compile(r'^((\\d+)*[ ]*,?[ ]*){2,}$') multi_choice_inner_regex = re.compile(r'\\b(\\d+)\\b') def __init__(self): try: self.config = Config(self.config_section) except",
"'\"all\" to choose all queues.', 'nargs': '*', }, } queue_not_affected_msg = 'Queue not",
"mixed in one input. \"\"\" config_section = 'rabbit_tools' client_method_name = NotImplemented description =",
"import re import sys from collections import Sequence from pyrabbit import Client from",
"= [] chosen_numbers = [] for queue_number, queue_name in chosen_queues.iteritems(): try: self._method_to_call(self._vhost, queue_name)",
"comma or space and comma (number of spaces does not matter, there can",
"%r does not exist.\", queue) else: logger.warning(\"%s: %r.\", self.queue_not_affected_msg, queue) else: affected_queues.append(queue) else:",
"else: logger.warning(\"%s: %r.\", self.queue_not_affected_msg, queue_name) else: affected_queues.append(queue_name) chosen_numbers.append(queue_number) if affected_queues: logger.info(\"%s: %s.\", self.queues_affected_msg,",
"associated number should not be shown anymore do_remove_chosen_numbers = False single_choice_regex = re.compile(r'^\\d+$')",
"formatted differently. If not overridden in a subclass, default messages will be logged.",
"%s\", self.queues_affected_msg, ', '.join(affected_queues)) def make_action(self, chosen_queues): affected_queues = [] chosen_numbers = []",
"queue has a number assigned, so user inputs proper number, not a whole",
"number, not a whole name. Input can be a single number, list of",
"self._parse_input(user_input) except StopReceivingInput: print 'bye' break if parsed_input: selected_mapping = self._get_selected_mapping(mapping, parsed_input) if",
"it.') self._parsed_args = self._get_parsed_args() self._vhost = self.config['vhost'] self.client = self._get_client(**self.config) self._method_to_call = getattr(self.client,",
"or there are no queues left. In each iteration of the loop, the",
"list(self._yield_queue_list()) if not queue_names: raise StopReceivingInput full_range = range(1, len(queue_names) + len(self._chosen_numbers) +",
"wrong selections (like in case of deleting queues); * queue_not_affected_msg (str) - message",
"all_queues = self._yield_queue_list() self.make_action_from_args(all_queues, queue_names) else: while True: try: mapping = self._get_queue_mapping() user_input",
"queue_names): if len(queue_names) == 1 and queue_names[0] in self.choose_all_commands: chosen_queues = all_queues else:",
"not exist.\", queue) else: logger.warning(\"%s: %r.\", self.queue_not_affected_msg, queue) else: affected_queues.append(queue) else: logger.info(\"%s: %s\",",
"\"\"\" Raised when no queues are left, or user typed a quitting command.",
"selected.') return None return selected_mapping elif parsed_input == 'all': return mapping return None",
"by one or more spaces: 2 - 5 (will chose: 2, 3, 4,",
"list and range of numbers should not be mixed in one input. \"\"\"",
"(number of spaces does not matter, there can be more than one, before",
"log, when an action was unsuccessful for a current queue; * queues_affected_msg (str)",
"when there was no success with any of chosen queues; Note that some",
"all / 'q' to quit'): \") user_input = user_input.strip().lower() return user_input else: logger.info('No",
"self.choose_all_commands: chosen_queues = all_queues else: chosen_queues = queue_names affected_queues = [] for queue",
"other command line tools, provided with RabbitMQ. Concrete classes provide, most of all,",
"RabbitMQ. Concrete classes provide, most of all, a method of client instance, which",
"description of the tool, which will be shown inside of script's help (run",
"Subclasses of the class have to implement attributes: * description (str) - description",
"= getattr(self.client, self.client_method_name) self._chosen_numbers = set() def _get_parsed_args(self): parser = argparse.ArgumentParser(description=self.description) for arg_name,",
"in self.choose_all_commands: return 'all' single_choice = self.single_choice_regex.search(user_input) if single_choice: return [int(single_choice.group(0))] range_choice =",
"queue_names affected_queues = [] for queue in chosen_queues: try: self._method_to_call(self._vhost, queue) except HTTPError",
"- 5 (will chose: 2, 3, 4, 5) IMPORTANT: list and range of",
"= re.compile(r'^\\d+$') range_choice_regex = re.compile(r'^(\\d+)[ ]*-[ ]*(\\d+)$') multi_choice_regex = re.compile(r'^((\\d+)*[ ]*,?[ ]*){2,}$') multi_choice_inner_regex",
"parsed.') return None @staticmethod def _get_selected_mapping(mapping, parsed_input): if isinstance(parsed_input, Sequence): selected_mapping = {nr:",
"using these numbers. Additional comfort of usage comes from: * using the config",
"for x in self.client.get_queues(self._vhost)) def _get_queue_mapping(self): queue_names = list(self._yield_queue_list()) if not queue_names: raise",
"script's help (run with -h argument); * client_method_name (str) - name of a",
"queues. The other way is to run a tool with no arguments, so",
"queue) except HTTPError as e: if e.status == 404: logger.error(\"Queue %r does not",
"method of client instance, which will be used to manipulate chosen queues. Subclasses",
"affected' queues_affected_msg = 'Queues affected' no_queues_affected_msg = 'No queues have been affected.' quitting_commands",
"user_input in self.quitting_commands: raise StopReceivingInput if user_input in self.choose_all_commands: return 'all' single_choice =",
"not be parsed.') return None @staticmethod def _get_selected_mapping(mapping, parsed_input): if isinstance(parsed_input, Sequence): selected_mapping",
"after an action, # and the associated number should not be shown anymore",
"self.quitting_commands: raise StopReceivingInput if user_input in self.choose_all_commands: return 'all' single_choice = self.single_choice_regex.search(user_input) if",
"in a subclass, default messages will be logged. ** Usage There are two",
"run(self): queue_names = self._parsed_args.queue_name if queue_names: all_queues = self._yield_queue_list() self.make_action_from_args(all_queues, queue_names) else: while",
"assigned, so user inputs proper number, not a whole name. Input can be",
"log, to show, which queues were successfully affected by an action; * no_queues_affected_msg",
"and range of numbers should not be mixed in one input. \"\"\" config_section",
"user inputs proper number, not a whole name. Input can be a single",
"set(full_range) - self._chosen_numbers else: output_range = full_range return dict(zip(output_range, queue_names)) @staticmethod def _get_user_input(mapping):",
"4 (will chose numbers: 1, 2, 3, 4) The range of numbers is",
"def _get_user_input(mapping): if mapping: for nr, queue in mapping.iteritems(): print '[{}] {}'.format(nr, queue)",
"selected_mapping = {nr: mapping[nr] for nr in parsed_input if nr in mapping} if",
"choose_all_commands = ['a', 'all'] # set to True, if queues are deleted after",
"\"rabbit_tools_config\" command' ' to generate it.') self._parsed_args = self._get_parsed_args() self._vhost = self.config['vhost'] self.client",
"for queue_number, queue_name in chosen_queues.iteritems(): try: self._method_to_call(self._vhost, queue_name) except HTTPError as e: if",
"queue_names[0] in self.choose_all_commands: chosen_queues = all_queues else: chosen_queues = queue_names affected_queues = []",
"which queues were successfully affected by an action; * no_queues_affected_msg (str) - message",
"logger = logging.getLogger(__name__) class StopReceivingInput(Exception): \"\"\" Raised when no queues are left, or",
"two ways of using Rabbit Tools. The first is to pass a known",
"to define every time options like API address or user credentials; * ability",
"Numbers and the symbol of dash can be separated by one or more",
"them should not be bound to other names to avoid wrong selections (like",
"in a loop, until user quits or there are no queues left. In",
"HTTPError as e: if e.status == 404: logger.error(\"Queue %r does not exist.\", queue)",
"be shown and it will wait for input from user. Each queue has",
"be a single number, list of numbers or range. In the list of",
"any of chosen queues; Note that some messages end with dot, other not,",
"queue_name) except HTTPError as e: if e.status == 404: logger.error(\"Queue %r does not",
"parser.parse_args() def _get_client(self, host, port, user, password, **kwargs): api_url = self._get_api_url(host, port) cl",
"has not been found. Use the \"rabbit_tools_config\" command' ' to generate it.') self._parsed_args",
"space, or \"all\" string, to choose all queues. The other way is to",
"client_method_name (str) - name of a method of PyRabbit's client instance, which will",
"or many queue names, separated by space, or \"all\" string, to choose all",
"== 'all': return mapping return None def make_action_from_args(self, all_queues, queue_names): if len(queue_names) ==",
"mapping: for nr, queue in mapping.iteritems(): print '[{}] {}'.format(nr, queue) user_input = raw_input(\"Queue",
"if multi_choice: raw_numbers = multi_choice.group(0) return map(int, self.multi_choice_inner_regex.findall(raw_numbers)) logger.error('Input could not be parsed.')",
"tool, which will be shown inside of script's help (run with -h argument);",
"user_input else: logger.info('No more queues to choose.') raise StopReceivingInput def _parse_input(self, user_input): if",
"of one or more queues (seperated by space) / ' '\"all\" to choose",
"comma (number of spaces does not matter, there can be more than one,",
"of numbers should not be mixed in one input. \"\"\" config_section = 'rabbit_tools'",
"and comma (number of spaces does not matter, there can be more than",
"action; * no_queues_affected_msg (str) - message logged, when there was no success with",
"the tool, which will be shown inside of script's help (run with -h",
"number associated with it, so in this mode user should choose queues using",
"= NotImplemented args = { 'queue_name': { 'help': 'Name of one or more",
"None @staticmethod def _get_selected_mapping(mapping, parsed_input): if isinstance(parsed_input, Sequence): selected_mapping = {nr: mapping[nr] for",
"1, 2, 3, 4) The range of numbers is presented as two numbers",
"pyrabbit import Client from pyrabbit.http import HTTPError from rabbit_tools.config import ( Config, ConfigFileMissingException,",
"return (x['name'] for x in self.client.get_queues(self._vhost)) def _get_queue_mapping(self): queue_names = list(self._yield_queue_list()) if not",
"return 'all' single_choice = self.single_choice_regex.search(user_input) if single_choice: return [int(single_choice.group(0))] range_choice = self.range_choice_regex.search(user_input) if",
"not exist.\", queue_name) chosen_numbers.append(queue_number) else: logger.warning(\"%s: %r.\", self.queue_not_affected_msg, queue_name) else: affected_queues.append(queue_name) chosen_numbers.append(queue_number) if",
"expected, that successfully manipulated queues will disappear from the list, and numbers associated",
"(will chose: 2, 3, 4, 5) IMPORTANT: list and range of numbers should",
"to generate it.') self._parsed_args = self._get_parsed_args() self._vhost = self.config['vhost'] self.client = self._get_client(**self.config) self._method_to_call",
"if single_choice: return [int(single_choice.group(0))] range_choice = self.range_choice_regex.search(user_input) if range_choice: return range(int(range_choice.group(1)), int(range_choice.group(2))+1) multi_choice",
"= 'rabbit_tools' client_method_name = NotImplemented description = NotImplemented args = { 'queue_name': {",
"of script's help (run with -h argument); * client_method_name (str) - name of",
"or space and comma (number of spaces does not matter, there can be",
"subclass: * do_remove_chosen_numbers (bool) - set to True, if it is expected, that",
"other way is to run a tool with no arguments, so current list",
"2 - 5 (will chose: 2, 3, 4, 5) IMPORTANT: list and range",
"= re.compile(r'^((\\d+)*[ ]*,?[ ]*){2,}$') multi_choice_inner_regex = re.compile(r'\\b(\\d+)\\b') def __init__(self): try: self.config = Config(self.config_section)",
"after the comma): 1, 2 3 , 4 (will chose numbers: 1, 2,",
"most of all, a method of client instance, which will be used to",
"associated with them should not be bound to other names to avoid wrong",
"tools, provided with RabbitMQ. Concrete classes provide, most of all, a method of",
"'exit', 'e'] choose_all_commands = ['a', 'all'] # set to True, if queues are",
"first is to pass a known queue name or many queue names, separated",
"exist.\", queue_name) chosen_numbers.append(queue_number) else: logger.warning(\"%s: %r.\", self.queue_not_affected_msg, queue_name) else: affected_queues.append(queue_name) chosen_numbers.append(queue_number) if affected_queues:",
"left, or user typed a quitting command. \"\"\" class RabbitToolBase(object): \"\"\" Base class",
"name of a method of PyRabbit's client instance, which will be used to",
"be overridden in a subclass: * do_remove_chosen_numbers (bool) - set to True, if",
"is to run a tool with no arguments, so current list of queues",
"config file, so there is no need to define every time options like",
"can be a single number, list of numbers or range. In the list",
"'Name of one or more queues (seperated by space) / ' '\"all\" to",
"port): return '{0}:{1}'.format(host, str(port)) def _yield_queue_list(self): return (x['name'] for x in self.client.get_queues(self._vhost)) def",
"if queue_names: all_queues = self._yield_queue_list() self.make_action_from_args(all_queues, queue_names) else: while True: try: mapping =",
"@staticmethod def _get_api_url(host, port): return '{0}:{1}'.format(host, str(port)) def _yield_queue_list(self): return (x['name'] for x",
"= [] for queue_number, queue_name in chosen_queues.iteritems(): try: self._method_to_call(self._vhost, queue_name) except HTTPError as",
"a known queue name or many queue names, separated by space, or \"all\"",
"range(1, len(queue_names) + len(self._chosen_numbers) + 1) if self.do_remove_chosen_numbers: output_range = set(full_range) - self._chosen_numbers",
"loop, until user quits or there are no queues left. In each iteration",
"argparse.ArgumentParser(description=self.description) for arg_name, arg_opts in self.args.iteritems(): parser.add_argument(arg_name, **arg_opts) return parser.parse_args() def _get_client(self, host,",
"shown anymore do_remove_chosen_numbers = False single_choice_regex = re.compile(r'^\\d+$') range_choice_regex = re.compile(r'^(\\d+)[ ]*-[ ]*(\\d+)$')",
"one, before and after the comma): 1, 2 3 , 4 (will chose",
"return None @staticmethod def _get_selected_mapping(mapping, parsed_input): if isinstance(parsed_input, Sequence): selected_mapping = {nr: mapping[nr]",
"which will be used to manipulate chosen queues. Subclasses of the class have",
"from rabbit_tools.config import ( Config, ConfigFileMissingException, ) logger = logging.getLogger(__name__) class StopReceivingInput(Exception): \"\"\"",
"[int(single_choice.group(0))] range_choice = self.range_choice_regex.search(user_input) if range_choice: return range(int(range_choice.group(1)), int(range_choice.group(2))+1) multi_choice = self.multi_choice_regex.search(user_input) if",
"chosen_queues): affected_queues = [] chosen_numbers = [] for queue_number, queue_name in chosen_queues.iteritems(): try:",
"selections (like in case of deleting queues); * queue_not_affected_msg (str) - message to",
"Use the \"rabbit_tools_config\" command' ' to generate it.') self._parsed_args = self._get_parsed_args() self._vhost =",
"deleting queues); * queue_not_affected_msg (str) - message to log, when an action was",
"by dash (-). Numbers and the symbol of dash can be separated by",
"config_section = 'rabbit_tools' client_method_name = NotImplemented description = NotImplemented args = { 'queue_name':",
"e.status == 404: logger.error(\"Queue %r does not exist.\", queue) else: logger.warning(\"%s: %r.\", self.queue_not_affected_msg,",
"# set to True, if queues are deleted after an action, # and",
"in parsed_input if nr in mapping} if not selected_mapping: logger.error('No queues were selected.')",
"shown, each queue has a number assigned, so user inputs proper number, not",
"each number should be separated by space, comma or space and comma (number",
"to choose all queues. The other way is to run a tool with",
"providing AMQP communication, parsing of user input and applying some action to chosen",
"chosen queues. Subclasses of the class have to implement attributes: * description (str)",
"return mapping return None def make_action_from_args(self, all_queues, queue_names): if len(queue_names) == 1 and",
"self.client = self._get_client(**self.config) self._method_to_call = getattr(self.client, self.client_method_name) self._chosen_numbers = set() def _get_parsed_args(self): parser",
"re.compile(r'\\b(\\d+)\\b') def __init__(self): try: self.config = Config(self.config_section) except ConfigFileMissingException: sys.exit('Config file has not",
"class RabbitToolBase(object): \"\"\" Base class providing AMQP communication, parsing of user input and",
"other not, because they are formatted differently. If not overridden in a subclass,",
"def _yield_queue_list(self): return (x['name'] for x in self.client.get_queues(self._vhost)) def _get_queue_mapping(self): queue_names = list(self._yield_queue_list())",
"' to generate it.') self._parsed_args = self._get_parsed_args() self._vhost = self.config['vhost'] self.client = self._get_client(**self.config)",
"will be used to manipulate queues. Other attributes, that may be overridden in",
"are deleted after an action, # and the associated number should not be",
"choose all / 'q' to quit'): \") user_input = user_input.strip().lower() return user_input else:",
"separated by space, or \"all\" string, to choose all queues. The other way",
"{ 'help': 'Name of one or more queues (seperated by space) / '",
"make_action(self, chosen_queues): affected_queues = [] chosen_numbers = [] for queue_number, queue_name in chosen_queues.iteritems():",
"if not queue_names: raise StopReceivingInput full_range = range(1, len(queue_names) + len(self._chosen_numbers) + 1)",
"= self.config['vhost'] self.client = self._get_client(**self.config) self._method_to_call = getattr(self.client, self.client_method_name) self._chosen_numbers = set() def",
"3 , 4 (will chose numbers: 1, 2, 3, 4) The range of",
"all queues. The other way is to run a tool with no arguments,",
"more queues to choose.') raise StopReceivingInput def _parse_input(self, user_input): if user_input in self.quitting_commands:",
"self.choose_all_commands: return 'all' single_choice = self.single_choice_regex.search(user_input) if single_choice: return [int(single_choice.group(0))] range_choice = self.range_choice_regex.search(user_input)",
"so there is no need to define every time options like API address",
"to avoid wrong selections (like in case of deleting queues); * queue_not_affected_msg (str)",
"* queue_not_affected_msg (str) - message to log, when an action was unsuccessful for",
"as e: if e.status == 404: logger.error(\"Queue %r does not exist.\", queue) else:",
"logger.info(\"%s: %s\", self.queues_affected_msg, ', '.join(affected_queues)) def make_action(self, chosen_queues): affected_queues = [] chosen_numbers =",
"to implement attributes: * description (str) - description of the tool, which will",
"was no success with any of chosen queues; Note that some messages end",
"time options like API address or user credentials; * ability to choose ranges",
"def _get_parsed_args(self): parser = argparse.ArgumentParser(description=self.description) for arg_name, arg_opts in self.args.iteritems(): parser.add_argument(arg_name, **arg_opts) return",
"be shown inside of script's help (run with -h argument); * client_method_name (str)",
"list of queues will be shown and it will wait for input from",
"= [] for queue in chosen_queues: try: self._method_to_call(self._vhost, queue) except HTTPError as e:",
"user. Each queue has a number associated with it, so in this mode",
"they are formatted differently. If not overridden in a subclass, default messages will",
"of queue numbers. ** Choosing queues in the interactive mode: In this mode",
"Config, ConfigFileMissingException, ) logger = logging.getLogger(__name__) class StopReceivingInput(Exception): \"\"\" Raised when no queues",
"single_choice = self.single_choice_regex.search(user_input) if single_choice: return [int(single_choice.group(0))] range_choice = self.range_choice_regex.search(user_input) if range_choice: return",
"not be bound to other names to avoid wrong selections (like in case",
"not been found. Use the \"rabbit_tools_config\" command' ' to generate it.') self._parsed_args =",
"set to True, if it is expected, that successfully manipulated queues will disappear",
"for nr, queue in mapping.iteritems(): print '[{}] {}'.format(nr, queue) user_input = raw_input(\"Queue number",
"try: self._method_to_call(self._vhost, queue) except HTTPError as e: if e.status == 404: logger.error(\"Queue %r",
"else: logger.warning(self.no_queues_affected_msg) return chosen_numbers def run(self): queue_names = self._parsed_args.queue_name if queue_names: all_queues =",
"_get_parsed_args(self): parser = argparse.ArgumentParser(description=self.description) for arg_name, arg_opts in self.args.iteritems(): parser.add_argument(arg_name, **arg_opts) return parser.parse_args()",
"queue_names: all_queues = self._yield_queue_list() self.make_action_from_args(all_queues, queue_names) else: while True: try: mapping = self._get_queue_mapping()",
"(str) - message logged, when there was no success with any of chosen",
"is expected, that successfully manipulated queues will disappear from the list, and numbers",
"self._get_queue_mapping() user_input = self._get_user_input(mapping) parsed_input = self._parse_input(user_input) except StopReceivingInput: print 'bye' break if",
"the list, and numbers associated with them should not be bound to other",
"1) if self.do_remove_chosen_numbers: output_range = set(full_range) - self._chosen_numbers else: output_range = full_range return",
"provide, most of all, a method of client instance, which will be used",
"raise StopReceivingInput if user_input in self.choose_all_commands: return 'all' single_choice = self.single_choice_regex.search(user_input) if single_choice:",
"a loop, until user quits or there are no queues left. In each",
"in chosen_queues.iteritems(): try: self._method_to_call(self._vhost, queue_name) except HTTPError as e: if e.status == 404:",
"no need to define every time options like API address or user credentials;",
"or other command line tools, provided with RabbitMQ. Concrete classes provide, most of",
"be parsed.') return None @staticmethod def _get_selected_mapping(mapping, parsed_input): if isinstance(parsed_input, Sequence): selected_mapping =",
"AMQP communication, parsing of user input and applying some action to chosen queues.",
"== 1 and queue_names[0] in self.choose_all_commands: chosen_queues = all_queues else: chosen_queues = queue_names",
"In each iteration of the loop, the list of available queues is shown,",
"class providing AMQP communication, parsing of user input and applying some action to",
"import Client from pyrabbit.http import HTTPError from rabbit_tools.config import ( Config, ConfigFileMissingException, )",
"successfully affected by an action; * no_queues_affected_msg (str) - message logged, when there",
"are two ways of using Rabbit Tools. The first is to pass a",
"AMQP queues, than GUI, API or other command line tools, provided with RabbitMQ.",
"argparse import logging import re import sys from collections import Sequence from pyrabbit",
"mode a tool runs in a loop, until user quits or there are",
"-h argument); * client_method_name (str) - name of a method of PyRabbit's client",
"of the loop, the list of available queues is shown, each queue has",
"space) / ' '\"all\" to choose all queues.', 'nargs': '*', }, } queue_not_affected_msg",
"self._vhost = self.config['vhost'] self.client = self._get_client(**self.config) self._method_to_call = getattr(self.client, self.client_method_name) self._chosen_numbers = set()",
"be bound to other names to avoid wrong selections (like in case of",
"bound to other names to avoid wrong selections (like in case of deleting",
"The other way is to run a tool with no arguments, so current",
"a number assigned, so user inputs proper number, not a whole name. Input",
"_get_selected_mapping(mapping, parsed_input): if isinstance(parsed_input, Sequence): selected_mapping = {nr: mapping[nr] for nr in parsed_input",
"shown inside of script's help (run with -h argument); * client_method_name (str) -",
"logger.error(\"Queue %r does not exist.\", queue_name) chosen_numbers.append(queue_number) else: logger.warning(\"%s: %r.\", self.queue_not_affected_msg, queue_name) else:",
"queues. Other attributes, that may be overridden in a subclass: * do_remove_chosen_numbers (bool)",
"successfully manipulated queues will disappear from the list, and numbers associated with them",
"If not overridden in a subclass, default messages will be logged. ** Usage",
"range. In the list of numbers, each number should be separated by space,",
"True: try: mapping = self._get_queue_mapping() user_input = self._get_user_input(mapping) parsed_input = self._parse_input(user_input) except StopReceivingInput:",
"from: * using the config file, so there is no need to define",
"in chosen_queues: try: self._method_to_call(self._vhost, queue) except HTTPError as e: if e.status == 404:",
"range_choice: return range(int(range_choice.group(1)), int(range_choice.group(2))+1) multi_choice = self.multi_choice_regex.search(user_input) if multi_choice: raw_numbers = multi_choice.group(0) return",
"if mapping: for nr, queue in mapping.iteritems(): print '[{}] {}'.format(nr, queue) user_input =",
"The range of numbers is presented as two numbers (beginning of the range",
"action to chosen queues. Tools implemented by concrete classes give user a faster",
"command' ' to generate it.') self._parsed_args = self._get_parsed_args() self._vhost = self.config['vhost'] self.client =",
"= self._get_api_url(host, port) cl = Client(api_url, user, password) return cl @staticmethod def _get_api_url(host,",
"raise StopReceivingInput def _parse_input(self, user_input): if user_input in self.quitting_commands: raise StopReceivingInput if user_input",
"the loop, the list of available queues is shown, each queue has a",
"'queue_name': { 'help': 'Name of one or more queues (seperated by space) /",
"', '.join(affected_queues)) else: logger.warning(self.no_queues_affected_msg) return chosen_numbers def run(self): queue_names = self._parsed_args.queue_name if queue_names:",
"queue_names: raise StopReceivingInput full_range = range(1, len(queue_names) + len(self._chosen_numbers) + 1) if self.do_remove_chosen_numbers:",
"classes give user a faster (and probably more convenient) way to manipulate AMQP",
"API address or user credentials; * ability to choose ranges of queue numbers.",
"(str) - name of a method of PyRabbit's client instance, which will be",
"_get_user_input(mapping): if mapping: for nr, queue in mapping.iteritems(): print '[{}] {}'.format(nr, queue) user_input",
"_yield_queue_list(self): return (x['name'] for x in self.client.get_queues(self._vhost)) def _get_queue_mapping(self): queue_names = list(self._yield_queue_list()) if",
"these numbers. Additional comfort of usage comes from: * using the config file,",
"in a subclass: * do_remove_chosen_numbers (bool) - set to True, if it is",
"whole name. Input can be a single number, list of numbers or range.",
"len(self._chosen_numbers) + 1) if self.do_remove_chosen_numbers: output_range = set(full_range) - self._chosen_numbers else: output_range =",
"queue_name in chosen_queues.iteritems(): try: self._method_to_call(self._vhost, queue_name) except HTTPError as e: if e.status ==",
"Sequence from pyrabbit import Client from pyrabbit.http import HTTPError from rabbit_tools.config import (",
"of dash can be separated by one or more spaces: 2 - 5",
"of numbers is presented as two numbers (beginning of the range and its",
"chosen queues; Note that some messages end with dot, other not, because they",
"separated by space, comma or space and comma (number of spaces does not",
"messages will be logged. ** Usage There are two ways of using Rabbit",
"to choose all queues.', 'nargs': '*', }, } queue_not_affected_msg = 'Queue not affected'",
"self.config['vhost'] self.client = self._get_client(**self.config) self._method_to_call = getattr(self.client, self.client_method_name) self._chosen_numbers = set() def _get_parsed_args(self):",
"in self.quitting_commands: raise StopReceivingInput if user_input in self.choose_all_commands: return 'all' single_choice = self.single_choice_regex.search(user_input)",
"5) IMPORTANT: list and range of numbers should not be mixed in one",
"Client from pyrabbit.http import HTTPError from rabbit_tools.config import ( Config, ConfigFileMissingException, ) logger",
"each iteration of the loop, the list of available queues is shown, each",
"typed a quitting command. \"\"\" class RabbitToolBase(object): \"\"\" Base class providing AMQP communication,",
"the associated number should not be shown anymore do_remove_chosen_numbers = False single_choice_regex =",
"with them should not be bound to other names to avoid wrong selections",
"self._method_to_call(self._vhost, queue) except HTTPError as e: if e.status == 404: logger.error(\"Queue %r does",
"_parse_input(self, user_input): if user_input in self.quitting_commands: raise StopReceivingInput if user_input in self.choose_all_commands: return",
"%r.\", self.queue_not_affected_msg, queue_name) else: affected_queues.append(queue_name) chosen_numbers.append(queue_number) if affected_queues: logger.info(\"%s: %s.\", self.queues_affected_msg, ', '.join(affected_queues))",
"HTTPError as e: if e.status == 404: logger.error(\"Queue %r does not exist.\", queue_name)",
"queues are deleted after an action, # and the associated number should not",
"else: output_range = full_range return dict(zip(output_range, queue_names)) @staticmethod def _get_user_input(mapping): if mapping: for",
"been found. Use the \"rabbit_tools_config\" command' ' to generate it.') self._parsed_args = self._get_parsed_args()",
"provided with RabbitMQ. Concrete classes provide, most of all, a method of client",
"comma): 1, 2 3 , 4 (will chose numbers: 1, 2, 3, 4)",
"an action; * no_queues_affected_msg (str) - message logged, when there was no success",
"if not selected_mapping: logger.error('No queues were selected.') return None return selected_mapping elif parsed_input",
"all_queues else: chosen_queues = queue_names affected_queues = [] for queue in chosen_queues: try:",
"if it is expected, that successfully manipulated queues will disappear from the list,",
"will be used to manipulate chosen queues. Subclasses of the class have to",
"input and applying some action to chosen queues. Tools implemented by concrete classes",
"a quitting command. \"\"\" class RabbitToolBase(object): \"\"\" Base class providing AMQP communication, parsing",
"from the list, and numbers associated with them should not be bound to",
"manipulate AMQP queues, than GUI, API or other command line tools, provided with",
"no_queues_affected_msg (str) - message logged, when there was no success with any of",
"queue numbers. ** Choosing queues in the interactive mode: In this mode a",
"description = NotImplemented args = { 'queue_name': { 'help': 'Name of one or",
"queues, than GUI, API or other command line tools, provided with RabbitMQ. Concrete",
"_get_client(self, host, port, user, password, **kwargs): api_url = self._get_api_url(host, port) cl = Client(api_url,",
"= re.compile(r'\\b(\\d+)\\b') def __init__(self): try: self.config = Config(self.config_section) except ConfigFileMissingException: sys.exit('Config file has",
"file has not been found. Use the \"rabbit_tools_config\" command' ' to generate it.')",
"else: logger.info(\"%s: %s\", self.queues_affected_msg, ', '.join(affected_queues)) def make_action(self, chosen_queues): affected_queues = [] chosen_numbers",
"else: chosen_queues = queue_names affected_queues = [] for queue in chosen_queues: try: self._method_to_call(self._vhost,",
"arg_name, arg_opts in self.args.iteritems(): parser.add_argument(arg_name, **arg_opts) return parser.parse_args() def _get_client(self, host, port, user,",
"may be overridden in a subclass: * do_remove_chosen_numbers (bool) - set to True,",
"not be shown anymore do_remove_chosen_numbers = False single_choice_regex = re.compile(r'^\\d+$') range_choice_regex = re.compile(r'^(\\d+)[",
"'all': return mapping return None def make_action_from_args(self, all_queues, queue_names): if len(queue_names) == 1",
"* client_method_name (str) - name of a method of PyRabbit's client instance, which",
"message to log, when an action was unsuccessful for a current queue; *",
"ability to choose ranges of queue numbers. ** Choosing queues in the interactive",
"if queues are deleted after an action, # and the associated number should",
"= self._yield_queue_list() self.make_action_from_args(all_queues, queue_names) else: while True: try: mapping = self._get_queue_mapping() user_input =",
"pyrabbit.http import HTTPError from rabbit_tools.config import ( Config, ConfigFileMissingException, ) logger = logging.getLogger(__name__)",
"of queues will be shown and it will wait for input from user.",
"chose numbers: 1, 2, 3, 4) The range of numbers is presented as",
"end) separated by dash (-). Numbers and the symbol of dash can be",
"mapping = self._get_queue_mapping() user_input = self._get_user_input(mapping) parsed_input = self._parse_input(user_input) except StopReceivingInput: print 'bye'",
"number should be separated by space, comma or space and comma (number of",
"%r.\", self.queue_not_affected_msg, queue) else: affected_queues.append(queue) else: logger.info(\"%s: %s\", self.queues_affected_msg, ', '.join(affected_queues)) def make_action(self,",
"the interactive mode: In this mode a tool runs in a loop, until",
"**arg_opts) return parser.parse_args() def _get_client(self, host, port, user, password, **kwargs): api_url = self._get_api_url(host,",
"queues using these numbers. Additional comfort of usage comes from: * using the",
"default messages will be logged. ** Usage There are two ways of using",
"= set(full_range) - self._chosen_numbers else: output_range = full_range return dict(zip(output_range, queue_names)) @staticmethod def",
"a number associated with it, so in this mode user should choose queues",
"= self._get_parsed_args() self._vhost = self.config['vhost'] self.client = self._get_client(**self.config) self._method_to_call = getattr(self.client, self.client_method_name) self._chosen_numbers",
"a single number, list of numbers or range. In the list of numbers,",
"return dict(zip(output_range, queue_names)) @staticmethod def _get_user_input(mapping): if mapping: for nr, queue in mapping.iteritems():",
"_get_api_url(host, port): return '{0}:{1}'.format(host, str(port)) def _yield_queue_list(self): return (x['name'] for x in self.client.get_queues(self._vhost))",
"or user credentials; * ability to choose ranges of queue numbers. ** Choosing",
"user_input = raw_input(\"Queue number ('all' to choose all / 'q' to quit'): \")",
"chosen_numbers.append(queue_number) if affected_queues: logger.info(\"%s: %s.\", self.queues_affected_msg, ', '.join(affected_queues)) else: logger.warning(self.no_queues_affected_msg) return chosen_numbers def",
"input from user. Each queue has a number associated with it, so in",
"disappear from the list, and numbers associated with them should not be bound",
"}, } queue_not_affected_msg = 'Queue not affected' queues_affected_msg = 'Queues affected' no_queues_affected_msg =",
"False single_choice_regex = re.compile(r'^\\d+$') range_choice_regex = re.compile(r'^(\\d+)[ ]*-[ ]*(\\d+)$') multi_choice_regex = re.compile(r'^((\\d+)*[ ]*,?[",
"message to log, to show, which queues were successfully affected by an action;",
"raw_numbers = multi_choice.group(0) return map(int, self.multi_choice_inner_regex.findall(raw_numbers)) logger.error('Input could not be parsed.') return None",
"re.compile(r'^\\d+$') range_choice_regex = re.compile(r'^(\\d+)[ ]*-[ ]*(\\d+)$') multi_choice_regex = re.compile(r'^((\\d+)*[ ]*,?[ ]*){2,}$') multi_choice_inner_regex =",
"\"\"\" class RabbitToolBase(object): \"\"\" Base class providing AMQP communication, parsing of user input",
"no success with any of chosen queues; Note that some messages end with",
"full_range return dict(zip(output_range, queue_names)) @staticmethod def _get_user_input(mapping): if mapping: for nr, queue in",
"a method of PyRabbit's client instance, which will be used to manipulate queues.",
"= ['a', 'all'] # set to True, if queues are deleted after an",
"overridden in a subclass, default messages will be logged. ** Usage There are",
"api_url = self._get_api_url(host, port) cl = Client(api_url, user, password) return cl @staticmethod def",
"/ ' '\"all\" to choose all queues.', 'nargs': '*', }, } queue_not_affected_msg =",
"= raw_input(\"Queue number ('all' to choose all / 'q' to quit'): \") user_input",
"many queue names, separated by space, or \"all\" string, to choose all queues.",
"parsed_input == 'all': return mapping return None def make_action_from_args(self, all_queues, queue_names): if len(queue_names)",
"2, 3, 4) The range of numbers is presented as two numbers (beginning",
"command. \"\"\" class RabbitToolBase(object): \"\"\" Base class providing AMQP communication, parsing of user",
"of deleting queues); * queue_not_affected_msg (str) - message to log, when an action",
"or more queues (seperated by space) / ' '\"all\" to choose all queues.',",
"[] chosen_numbers = [] for queue_number, queue_name in chosen_queues.iteritems(): try: self._method_to_call(self._vhost, queue_name) except",
"of usage comes from: * using the config file, so there is no",
"client_method_name = NotImplemented description = NotImplemented args = { 'queue_name': { 'help': 'Name",
"more convenient) way to manipulate AMQP queues, than GUI, API or other command",
"from collections import Sequence from pyrabbit import Client from pyrabbit.http import HTTPError from",
"by concrete classes give user a faster (and probably more convenient) way to",
"which will be shown inside of script's help (run with -h argument); *",
"pass a known queue name or many queue names, separated by space, or",
"try: self.config = Config(self.config_section) except ConfigFileMissingException: sys.exit('Config file has not been found. Use",
"return user_input else: logger.info('No more queues to choose.') raise StopReceivingInput def _parse_input(self, user_input):",
"= self.range_choice_regex.search(user_input) if range_choice: return range(int(range_choice.group(1)), int(range_choice.group(2))+1) multi_choice = self.multi_choice_regex.search(user_input) if multi_choice: raw_numbers",
"have been affected.' quitting_commands = ['q', 'quit', 'exit', 'e'] choose_all_commands = ['a', 'all']",
"x in self.client.get_queues(self._vhost)) def _get_queue_mapping(self): queue_names = list(self._yield_queue_list()) if not queue_names: raise StopReceivingInput",
"+ len(self._chosen_numbers) + 1) if self.do_remove_chosen_numbers: output_range = set(full_range) - self._chosen_numbers else: output_range",
"logging import re import sys from collections import Sequence from pyrabbit import Client",
"[] for queue_number, queue_name in chosen_queues.iteritems(): try: self._method_to_call(self._vhost, queue_name) except HTTPError as e:",
"to run a tool with no arguments, so current list of queues will",
"with dot, other not, because they are formatted differently. If not overridden in",
"or \"all\" string, to choose all queues. The other way is to run",
"choose all queues. The other way is to run a tool with no",
"numbers (beginning of the range and its end) separated by dash (-). Numbers",
"return '{0}:{1}'.format(host, str(port)) def _yield_queue_list(self): return (x['name'] for x in self.client.get_queues(self._vhost)) def _get_queue_mapping(self):",
"chosen_queues: try: self._method_to_call(self._vhost, queue) except HTTPError as e: if e.status == 404: logger.error(\"Queue",
"description (str) - description of the tool, which will be shown inside of",
"are no queues left. In each iteration of the loop, the list of",
"single number, list of numbers or range. In the list of numbers, each",
"= Client(api_url, user, password) return cl @staticmethod def _get_api_url(host, port): return '{0}:{1}'.format(host, str(port))",
"import logging import re import sys from collections import Sequence from pyrabbit import",
"logger.error('No queues were selected.') return None return selected_mapping elif parsed_input == 'all': return",
"nr in parsed_input if nr in mapping} if not selected_mapping: logger.error('No queues were",
"IMPORTANT: list and range of numbers should not be mixed in one input.",
"chosen_queues.iteritems(): try: self._method_to_call(self._vhost, queue_name) except HTTPError as e: if e.status == 404: logger.error(\"Queue",
"mapping} if not selected_mapping: logger.error('No queues were selected.') return None return selected_mapping elif",
"spaces: 2 - 5 (will chose: 2, 3, 4, 5) IMPORTANT: list and",
"parsed_input): if isinstance(parsed_input, Sequence): selected_mapping = {nr: mapping[nr] for nr in parsed_input if",
"Concrete classes provide, most of all, a method of client instance, which will",
"mapping return None def make_action_from_args(self, all_queues, queue_names): if len(queue_names) == 1 and queue_names[0]",
"as e: if e.status == 404: logger.error(\"Queue %r does not exist.\", queue_name) chosen_numbers.append(queue_number)",
"the list of numbers, each number should be separated by space, comma or",
"return None def make_action_from_args(self, all_queues, queue_names): if len(queue_names) == 1 and queue_names[0] in",
"by an action; * no_queues_affected_msg (str) - message logged, when there was no",
"queue_not_affected_msg = 'Queue not affected' queues_affected_msg = 'Queues affected' no_queues_affected_msg = 'No queues",
"credentials; * ability to choose ranges of queue numbers. ** Choosing queues in",
"(-). Numbers and the symbol of dash can be separated by one or",
"range_choice_regex = re.compile(r'^(\\d+)[ ]*-[ ]*(\\d+)$') multi_choice_regex = re.compile(r'^((\\d+)*[ ]*,?[ ]*){2,}$') multi_choice_inner_regex = re.compile(r'\\b(\\d+)\\b')",
"a subclass, default messages will be logged. ** Usage There are two ways",
"list of available queues is shown, each queue has a number assigned, so",
"Base class providing AMQP communication, parsing of user input and applying some action",
"if range_choice: return range(int(range_choice.group(1)), int(range_choice.group(2))+1) multi_choice = self.multi_choice_regex.search(user_input) if multi_choice: raw_numbers = multi_choice.group(0)",
"else: logger.warning(\"%s: %r.\", self.queue_not_affected_msg, queue) else: affected_queues.append(queue) else: logger.info(\"%s: %s\", self.queues_affected_msg, ', '.join(affected_queues))",
"import sys from collections import Sequence from pyrabbit import Client from pyrabbit.http import",
"no queues are left, or user typed a quitting command. \"\"\" class RabbitToolBase(object):",
"command line tools, provided with RabbitMQ. Concrete classes provide, most of all, a",
"= user_input.strip().lower() return user_input else: logger.info('No more queues to choose.') raise StopReceivingInput def",
"There are two ways of using Rabbit Tools. The first is to pass",
"%s.\", self.queues_affected_msg, ', '.join(affected_queues)) else: logger.warning(self.no_queues_affected_msg) return chosen_numbers def run(self): queue_names = self._parsed_args.queue_name",
"more than one, before and after the comma): 1, 2 3 , 4",
"queues is shown, each queue has a number assigned, so user inputs proper",
"not matter, there can be more than one, before and after the comma):",
"self.client_method_name) self._chosen_numbers = set() def _get_parsed_args(self): parser = argparse.ArgumentParser(description=self.description) for arg_name, arg_opts in",
"quit'): \") user_input = user_input.strip().lower() return user_input else: logger.info('No more queues to choose.')",
"numbers. Additional comfort of usage comes from: * using the config file, so",
"than GUI, API or other command line tools, provided with RabbitMQ. Concrete classes",
"queues will disappear from the list, and numbers associated with them should not",
"True, if it is expected, that successfully manipulated queues will disappear from the",
"in mapping} if not selected_mapping: logger.error('No queues were selected.') return None return selected_mapping",
"self.queues_affected_msg, ', '.join(affected_queues)) else: logger.warning(self.no_queues_affected_msg) return chosen_numbers def run(self): queue_names = self._parsed_args.queue_name if",
"to log, when an action was unsuccessful for a current queue; * queues_affected_msg",
"than one, before and after the comma): 1, 2 3 , 4 (will",
"dash can be separated by one or more spaces: 2 - 5 (will",
"queues_affected_msg = 'Queues affected' no_queues_affected_msg = 'No queues have been affected.' quitting_commands =",
"if e.status == 404: logger.error(\"Queue %r does not exist.\", queue_name) chosen_numbers.append(queue_number) else: logger.warning(\"%s:",
"faster (and probably more convenient) way to manipulate AMQP queues, than GUI, API",
"should not be shown anymore do_remove_chosen_numbers = False single_choice_regex = re.compile(r'^\\d+$') range_choice_regex =",
"def make_action_from_args(self, all_queues, queue_names): if len(queue_names) == 1 and queue_names[0] in self.choose_all_commands: chosen_queues",
"success with any of chosen queues; Note that some messages end with dot,",
"with it, so in this mode user should choose queues using these numbers.",
"parser = argparse.ArgumentParser(description=self.description) for arg_name, arg_opts in self.args.iteritems(): parser.add_argument(arg_name, **arg_opts) return parser.parse_args() def",
"single_choice_regex = re.compile(r'^\\d+$') range_choice_regex = re.compile(r'^(\\d+)[ ]*-[ ]*(\\d+)$') multi_choice_regex = re.compile(r'^((\\d+)*[ ]*,?[ ]*){2,}$')",
"3, 4, 5) IMPORTANT: list and range of numbers should not be mixed",
"cl = Client(api_url, user, password) return cl @staticmethod def _get_api_url(host, port): return '{0}:{1}'.format(host,",
"parsing of user input and applying some action to chosen queues. Tools implemented",
"self._parsed_args.queue_name if queue_names: all_queues = self._yield_queue_list() self.make_action_from_args(all_queues, queue_names) else: while True: try: mapping",
"separated by dash (-). Numbers and the symbol of dash can be separated",
"way is to run a tool with no arguments, so current list of",
"will wait for input from user. Each queue has a number associated with",
"5 (will chose: 2, 3, 4, 5) IMPORTANT: list and range of numbers",
"isinstance(parsed_input, Sequence): selected_mapping = {nr: mapping[nr] for nr in parsed_input if nr in",
"so current list of queues will be shown and it will wait for",
"because they are formatted differently. If not overridden in a subclass, default messages",
"implemented by concrete classes give user a faster (and probably more convenient) way",
"('all' to choose all / 'q' to quit'): \") user_input = user_input.strip().lower() return",
"do_remove_chosen_numbers = False single_choice_regex = re.compile(r'^\\d+$') range_choice_regex = re.compile(r'^(\\d+)[ ]*-[ ]*(\\d+)$') multi_choice_regex =",
"for input from user. Each queue has a number associated with it, so",
"and applying some action to chosen queues. Tools implemented by concrete classes give",
"string, to choose all queues. The other way is to run a tool",
"can be separated by one or more spaces: 2 - 5 (will chose:",
"'help': 'Name of one or more queues (seperated by space) / ' '\"all\"",
"} queue_not_affected_msg = 'Queue not affected' queues_affected_msg = 'Queues affected' no_queues_affected_msg = 'No",
"symbol of dash can be separated by one or more spaces: 2 -",
"__init__(self): try: self.config = Config(self.config_section) except ConfigFileMissingException: sys.exit('Config file has not been found.",
"will be logged. ** Usage There are two ways of using Rabbit Tools.",
"full_range = range(1, len(queue_names) + len(self._chosen_numbers) + 1) if self.do_remove_chosen_numbers: output_range = set(full_range)",
"name. Input can be a single number, list of numbers or range. In",
"logger.info('No more queues to choose.') raise StopReceivingInput def _parse_input(self, user_input): if user_input in",
"by space, comma or space and comma (number of spaces does not matter,",
"404: logger.error(\"Queue %r does not exist.\", queue) else: logger.warning(\"%s: %r.\", self.queue_not_affected_msg, queue) else:",
"(str) - message to log, when an action was unsuccessful for a current",
"try: mapping = self._get_queue_mapping() user_input = self._get_user_input(mapping) parsed_input = self._parse_input(user_input) except StopReceivingInput: print",
"generate it.') self._parsed_args = self._get_parsed_args() self._vhost = self.config['vhost'] self.client = self._get_client(**self.config) self._method_to_call =",
"queue_names = list(self._yield_queue_list()) if not queue_names: raise StopReceivingInput full_range = range(1, len(queue_names) +",
"multi_choice_regex = re.compile(r'^((\\d+)*[ ]*,?[ ]*){2,}$') multi_choice_inner_regex = re.compile(r'\\b(\\d+)\\b') def __init__(self): try: self.config =",
"queues were successfully affected by an action; * no_queues_affected_msg (str) - message logged,",
"so in this mode user should choose queues using these numbers. Additional comfort",
"from user. Each queue has a number associated with it, so in this",
"help (run with -h argument); * client_method_name (str) - name of a method",
"affected_queues.append(queue_name) chosen_numbers.append(queue_number) if affected_queues: logger.info(\"%s: %s.\", self.queues_affected_msg, ', '.join(affected_queues)) else: logger.warning(self.no_queues_affected_msg) return chosen_numbers",
"True, if queues are deleted after an action, # and the associated number",
"'.join(affected_queues)) else: logger.warning(self.no_queues_affected_msg) return chosen_numbers def run(self): queue_names = self._parsed_args.queue_name if queue_names: all_queues",
"be separated by one or more spaces: 2 - 5 (will chose: 2,",
"a current queue; * queues_affected_msg (str) - message to log, to show, which",
"'all'] # set to True, if queues are deleted after an action, #",
"a faster (and probably more convenient) way to manipulate AMQP queues, than GUI,",
"except StopReceivingInput: print 'bye' break if parsed_input: selected_mapping = self._get_selected_mapping(mapping, parsed_input) if selected_mapping:",
"if self.do_remove_chosen_numbers: output_range = set(full_range) - self._chosen_numbers else: output_range = full_range return dict(zip(output_range,",
"input. \"\"\" config_section = 'rabbit_tools' client_method_name = NotImplemented description = NotImplemented args =",
"by space) / ' '\"all\" to choose all queues.', 'nargs': '*', }, }",
"be logged. ** Usage There are two ways of using Rabbit Tools. The",
"import Sequence from pyrabbit import Client from pyrabbit.http import HTTPError from rabbit_tools.config import",
"to manipulate AMQP queues, than GUI, API or other command line tools, provided",
"Other attributes, that may be overridden in a subclass: * do_remove_chosen_numbers (bool) -",
"one or more queues (seperated by space) / ' '\"all\" to choose all",
"parsed_input if nr in mapping} if not selected_mapping: logger.error('No queues were selected.') return",
"GUI, API or other command line tools, provided with RabbitMQ. Concrete classes provide,",
"it will wait for input from user. Each queue has a number associated",
"else: logger.info('No more queues to choose.') raise StopReceivingInput def _parse_input(self, user_input): if user_input",
"list of numbers, each number should be separated by space, comma or space",
"= full_range return dict(zip(output_range, queue_names)) @staticmethod def _get_user_input(mapping): if mapping: for nr, queue",
"affected' no_queues_affected_msg = 'No queues have been affected.' quitting_commands = ['q', 'quit', 'exit',",
"'rabbit_tools' client_method_name = NotImplemented description = NotImplemented args = { 'queue_name': { 'help':",
"way to manipulate AMQP queues, than GUI, API or other command line tools,",
"messages end with dot, other not, because they are formatted differently. If not",
"\"all\" string, to choose all queues. The other way is to run a",
"ConfigFileMissingException: sys.exit('Config file has not been found. Use the \"rabbit_tools_config\" command' ' to",
"to log, to show, which queues were successfully affected by an action; *",
"queues; Note that some messages end with dot, other not, because they are",
"password, **kwargs): api_url = self._get_api_url(host, port) cl = Client(api_url, user, password) return cl",
"self.range_choice_regex.search(user_input) if range_choice: return range(int(range_choice.group(1)), int(range_choice.group(2))+1) multi_choice = self.multi_choice_regex.search(user_input) if multi_choice: raw_numbers =",
"** Choosing queues in the interactive mode: In this mode a tool runs",
") logger = logging.getLogger(__name__) class StopReceivingInput(Exception): \"\"\" Raised when no queues are left,",
"run a tool with no arguments, so current list of queues will be",
"4, 5) IMPORTANT: list and range of numbers should not be mixed in",
"chosen_numbers def run(self): queue_names = self._parsed_args.queue_name if queue_names: all_queues = self._yield_queue_list() self.make_action_from_args(all_queues, queue_names)",
"= argparse.ArgumentParser(description=self.description) for arg_name, arg_opts in self.args.iteritems(): parser.add_argument(arg_name, **arg_opts) return parser.parse_args() def _get_client(self,",
"import HTTPError from rabbit_tools.config import ( Config, ConfigFileMissingException, ) logger = logging.getLogger(__name__) class",
"= list(self._yield_queue_list()) if not queue_names: raise StopReceivingInput full_range = range(1, len(queue_names) + len(self._chosen_numbers)",
"def make_action(self, chosen_queues): affected_queues = [] chosen_numbers = [] for queue_number, queue_name in",
"it, so in this mode user should choose queues using these numbers. Additional",
"collections import Sequence from pyrabbit import Client from pyrabbit.http import HTTPError from rabbit_tools.config",
"'q' to quit'): \") user_input = user_input.strip().lower() return user_input else: logger.info('No more queues",
"None return selected_mapping elif parsed_input == 'all': return mapping return None def make_action_from_args(self,",
"dot, other not, because they are formatted differently. If not overridden in a",
"mode user should choose queues using these numbers. Additional comfort of usage comes",
"to manipulate chosen queues. Subclasses of the class have to implement attributes: *",
"Rabbit Tools. The first is to pass a known queue name or many",
"set() def _get_parsed_args(self): parser = argparse.ArgumentParser(description=self.description) for arg_name, arg_opts in self.args.iteritems(): parser.add_argument(arg_name, **arg_opts)",
"'Queues affected' no_queues_affected_msg = 'No queues have been affected.' quitting_commands = ['q', 'quit',",
"of the range and its end) separated by dash (-). Numbers and the",
"queues will be shown and it will wait for input from user. Each",
"in mapping.iteritems(): print '[{}] {}'.format(nr, queue) user_input = raw_input(\"Queue number ('all' to choose",
"so user inputs proper number, not a whole name. Input can be a",
"queue name or many queue names, separated by space, or \"all\" string, to",
"'[{}] {}'.format(nr, queue) user_input = raw_input(\"Queue number ('all' to choose all / 'q'",
"**kwargs): api_url = self._get_api_url(host, port) cl = Client(api_url, user, password) return cl @staticmethod",
"self.multi_choice_regex.search(user_input) if multi_choice: raw_numbers = multi_choice.group(0) return map(int, self.multi_choice_inner_regex.findall(raw_numbers)) logger.error('Input could not be",
"[] for queue in chosen_queues: try: self._method_to_call(self._vhost, queue) except HTTPError as e: if",
"raise StopReceivingInput full_range = range(1, len(queue_names) + len(self._chosen_numbers) + 1) if self.do_remove_chosen_numbers: output_range",
"tool runs in a loop, until user quits or there are no queues",
"that successfully manipulated queues will disappear from the list, and numbers associated with",
"@staticmethod def _get_selected_mapping(mapping, parsed_input): if isinstance(parsed_input, Sequence): selected_mapping = {nr: mapping[nr] for nr",
"self._chosen_numbers else: output_range = full_range return dict(zip(output_range, queue_names)) @staticmethod def _get_user_input(mapping): if mapping:",
"no queues left. In each iteration of the loop, the list of available",
"a method of client instance, which will be used to manipulate chosen queues.",
"multi_choice_inner_regex = re.compile(r'\\b(\\d+)\\b') def __init__(self): try: self.config = Config(self.config_section) except ConfigFileMissingException: sys.exit('Config file",
"* description (str) - description of the tool, which will be shown inside",
"len(queue_names) == 1 and queue_names[0] in self.choose_all_commands: chosen_queues = all_queues else: chosen_queues =",
"manipulate queues. Other attributes, that may be overridden in a subclass: * do_remove_chosen_numbers",
"in one input. \"\"\" config_section = 'rabbit_tools' client_method_name = NotImplemented description = NotImplemented",
"self.do_remove_chosen_numbers: output_range = set(full_range) - self._chosen_numbers else: output_range = full_range return dict(zip(output_range, queue_names))",
"(bool) - set to True, if it is expected, that successfully manipulated queues",
"used to manipulate chosen queues. Subclasses of the class have to implement attributes:",
"proper number, not a whole name. Input can be a single number, list",
"number, list of numbers or range. In the list of numbers, each number",
"the comma): 1, 2 3 , 4 (will chose numbers: 1, 2, 3,",
"of chosen queues; Note that some messages end with dot, other not, because",
"Sequence): selected_mapping = {nr: mapping[nr] for nr in parsed_input if nr in mapping}",
"StopReceivingInput def _parse_input(self, user_input): if user_input in self.quitting_commands: raise StopReceivingInput if user_input in",
"while True: try: mapping = self._get_queue_mapping() user_input = self._get_user_input(mapping) parsed_input = self._parse_input(user_input) except",
"'Queue not affected' queues_affected_msg = 'Queues affected' no_queues_affected_msg = 'No queues have been",
"not overridden in a subclass, default messages will be logged. ** Usage There",
"until user quits or there are no queues left. In each iteration of",
"user_input): if user_input in self.quitting_commands: raise StopReceivingInput if user_input in self.choose_all_commands: return 'all'",
"= self.multi_choice_regex.search(user_input) if multi_choice: raw_numbers = multi_choice.group(0) return map(int, self.multi_choice_inner_regex.findall(raw_numbers)) logger.error('Input could not",
"deleted after an action, # and the associated number should not be shown",
"available queues is shown, each queue has a number assigned, so user inputs",
"is shown, each queue has a number assigned, so user inputs proper number,",
"raw_input(\"Queue number ('all' to choose all / 'q' to quit'): \") user_input =",
"end with dot, other not, because they are formatted differently. If not overridden",
"queue_name) chosen_numbers.append(queue_number) else: logger.warning(\"%s: %r.\", self.queue_not_affected_msg, queue_name) else: affected_queues.append(queue_name) chosen_numbers.append(queue_number) if affected_queues: logger.info(\"%s:",
"do_remove_chosen_numbers (bool) - set to True, if it is expected, that successfully manipulated",
"usage comes from: * using the config file, so there is no need",
"to show, which queues were successfully affected by an action; * no_queues_affected_msg (str)",
"queue names, separated by space, or \"all\" string, to choose all queues. The",
"communication, parsing of user input and applying some action to chosen queues. Tools",
"numbers. ** Choosing queues in the interactive mode: In this mode a tool",
"dash (-). Numbers and the symbol of dash can be separated by one",
"queue_names = self._parsed_args.queue_name if queue_names: all_queues = self._yield_queue_list() self.make_action_from_args(all_queues, queue_names) else: while True:",
"== 404: logger.error(\"Queue %r does not exist.\", queue_name) chosen_numbers.append(queue_number) else: logger.warning(\"%s: %r.\", self.queue_not_affected_msg,",
"= self._get_client(**self.config) self._method_to_call = getattr(self.client, self.client_method_name) self._chosen_numbers = set() def _get_parsed_args(self): parser =",
"the range and its end) separated by dash (-). Numbers and the symbol",
"shown and it will wait for input from user. Each queue has a",
"there was no success with any of chosen queues; Note that some messages",
"def _get_selected_mapping(mapping, parsed_input): if isinstance(parsed_input, Sequence): selected_mapping = {nr: mapping[nr] for nr in",
"= self._parse_input(user_input) except StopReceivingInput: print 'bye' break if parsed_input: selected_mapping = self._get_selected_mapping(mapping, parsed_input)",
"subclass, default messages will be logged. ** Usage There are two ways of",
"left. In each iteration of the loop, the list of available queues is",
"no arguments, so current list of queues will be shown and it will",
"choose ranges of queue numbers. ** Choosing queues in the interactive mode: In",
"not be mixed in one input. \"\"\" config_section = 'rabbit_tools' client_method_name = NotImplemented",
"user typed a quitting command. \"\"\" class RabbitToolBase(object): \"\"\" Base class providing AMQP",
"known queue name or many queue names, separated by space, or \"all\" string,",
"mapping[nr] for nr in parsed_input if nr in mapping} if not selected_mapping: logger.error('No",
"in self.choose_all_commands: chosen_queues = all_queues else: chosen_queues = queue_names affected_queues = [] for",
"queues.', 'nargs': '*', }, } queue_not_affected_msg = 'Queue not affected' queues_affected_msg = 'Queues",
"for a current queue; * queues_affected_msg (str) - message to log, to show,",
"2, 3, 4, 5) IMPORTANT: list and range of numbers should not be",
"comes from: * using the config file, so there is no need to",
"has a number assigned, so user inputs proper number, not a whole name.",
"be used to manipulate chosen queues. Subclasses of the class have to implement",
"(str) - message to log, to show, which queues were successfully affected by",
"' '\"all\" to choose all queues.', 'nargs': '*', }, } queue_not_affected_msg = 'Queue",
"= range(1, len(queue_names) + len(self._chosen_numbers) + 1) if self.do_remove_chosen_numbers: output_range = set(full_range) -",
"queues are left, or user typed a quitting command. \"\"\" class RabbitToolBase(object): \"\"\"",
"of user input and applying some action to chosen queues. Tools implemented by",
"should choose queues using these numbers. Additional comfort of usage comes from: *",
"queue) user_input = raw_input(\"Queue number ('all' to choose all / 'q' to quit'):",
"have to implement attributes: * description (str) - description of the tool, which",
"space and comma (number of spaces does not matter, there can be more",
"loop, the list of available queues is shown, each queue has a number",
"be shown anymore do_remove_chosen_numbers = False single_choice_regex = re.compile(r'^\\d+$') range_choice_regex = re.compile(r'^(\\d+)[ ]*-[",
"to choose ranges of queue numbers. ** Choosing queues in the interactive mode:",
"was unsuccessful for a current queue; * queues_affected_msg (str) - message to log,",
"user_input.strip().lower() return user_input else: logger.info('No more queues to choose.') raise StopReceivingInput def _parse_input(self,",
"multi_choice = self.multi_choice_regex.search(user_input) if multi_choice: raw_numbers = multi_choice.group(0) return map(int, self.multi_choice_inner_regex.findall(raw_numbers)) logger.error('Input could",
"StopReceivingInput: print 'bye' break if parsed_input: selected_mapping = self._get_selected_mapping(mapping, parsed_input) if selected_mapping: self._chosen_numbers.update(self.make_action(selected_mapping))",
"in self.args.iteritems(): parser.add_argument(arg_name, **arg_opts) return parser.parse_args() def _get_client(self, host, port, user, password, **kwargs):",
"applying some action to chosen queues. Tools implemented by concrete classes give user",
"user should choose queues using these numbers. Additional comfort of usage comes from:",
"- name of a method of PyRabbit's client instance, which will be used",
"str(port)) def _yield_queue_list(self): return (x['name'] for x in self.client.get_queues(self._vhost)) def _get_queue_mapping(self): queue_names =",
"'{0}:{1}'.format(host, str(port)) def _yield_queue_list(self): return (x['name'] for x in self.client.get_queues(self._vhost)) def _get_queue_mapping(self): queue_names",
"user_input = user_input.strip().lower() return user_input else: logger.info('No more queues to choose.') raise StopReceivingInput",
"range and its end) separated by dash (-). Numbers and the symbol of",
"interactive mode: In this mode a tool runs in a loop, until user",
"+ 1) if self.do_remove_chosen_numbers: output_range = set(full_range) - self._chosen_numbers else: output_range = full_range",
"to chosen queues. Tools implemented by concrete classes give user a faster (and",
"a subclass: * do_remove_chosen_numbers (bool) - set to True, if it is expected,",
"runs in a loop, until user quits or there are no queues left.",
"self.make_action_from_args(all_queues, queue_names) else: while True: try: mapping = self._get_queue_mapping() user_input = self._get_user_input(mapping) parsed_input",
"or user typed a quitting command. \"\"\" class RabbitToolBase(object): \"\"\" Base class providing",
"and it will wait for input from user. Each queue has a number",
"each queue has a number assigned, so user inputs proper number, not a",
"return chosen_numbers def run(self): queue_names = self._parsed_args.queue_name if queue_names: all_queues = self._yield_queue_list() self.make_action_from_args(all_queues,",
"# and the associated number should not be shown anymore do_remove_chosen_numbers = False",
"logger.error(\"Queue %r does not exist.\", queue) else: logger.warning(\"%s: %r.\", self.queue_not_affected_msg, queue) else: affected_queues.append(queue)",
"choose queues using these numbers. Additional comfort of usage comes from: * using",
"a tool runs in a loop, until user quits or there are no",
"@staticmethod def _get_user_input(mapping): if mapping: for nr, queue in mapping.iteritems(): print '[{}] {}'.format(nr,",
"from pyrabbit.http import HTTPError from rabbit_tools.config import ( Config, ConfigFileMissingException, ) logger =",
"overridden in a subclass: * do_remove_chosen_numbers (bool) - set to True, if it",
"Usage There are two ways of using Rabbit Tools. The first is to",
"queues. Subclasses of the class have to implement attributes: * description (str) -",
"and the associated number should not be shown anymore do_remove_chosen_numbers = False single_choice_regex",
"'all' single_choice = self.single_choice_regex.search(user_input) if single_choice: return [int(single_choice.group(0))] range_choice = self.range_choice_regex.search(user_input) if range_choice:",
"line tools, provided with RabbitMQ. Concrete classes provide, most of all, a method",
"there can be more than one, before and after the comma): 1, 2",
"== 404: logger.error(\"Queue %r does not exist.\", queue) else: logger.warning(\"%s: %r.\", self.queue_not_affected_msg, queue)",
"not queue_names: raise StopReceivingInput full_range = range(1, len(queue_names) + len(self._chosen_numbers) + 1) if",
"StopReceivingInput if user_input in self.choose_all_commands: return 'all' single_choice = self.single_choice_regex.search(user_input) if single_choice: return",
"logger.info(\"%s: %s.\", self.queues_affected_msg, ', '.join(affected_queues)) else: logger.warning(self.no_queues_affected_msg) return chosen_numbers def run(self): queue_names =",
"of all, a method of client instance, which will be used to manipulate",
"numbers associated with them should not be bound to other names to avoid",
"logged. ** Usage There are two ways of using Rabbit Tools. The first",
"]*,?[ ]*){2,}$') multi_choice_inner_regex = re.compile(r'\\b(\\d+)\\b') def __init__(self): try: self.config = Config(self.config_section) except ConfigFileMissingException:",
"avoid wrong selections (like in case of deleting queues); * queue_not_affected_msg (str) -",
"return range(int(range_choice.group(1)), int(range_choice.group(2))+1) multi_choice = self.multi_choice_regex.search(user_input) if multi_choice: raw_numbers = multi_choice.group(0) return map(int,",
"API or other command line tools, provided with RabbitMQ. Concrete classes provide, most",
"of PyRabbit's client instance, which will be used to manipulate queues. Other attributes,",
"Each queue has a number associated with it, so in this mode user",
"as two numbers (beginning of the range and its end) separated by dash",
"queue) else: affected_queues.append(queue) else: logger.info(\"%s: %s\", self.queues_affected_msg, ', '.join(affected_queues)) def make_action(self, chosen_queues): affected_queues",
"queue_number, queue_name in chosen_queues.iteritems(): try: self._method_to_call(self._vhost, queue_name) except HTTPError as e: if e.status",
"The first is to pass a known queue name or many queue names,",
"no_queues_affected_msg = 'No queues have been affected.' quitting_commands = ['q', 'quit', 'exit', 'e']",
"selected_mapping: logger.error('No queues were selected.') return None return selected_mapping elif parsed_input == 'all':",
"= Config(self.config_section) except ConfigFileMissingException: sys.exit('Config file has not been found. Use the \"rabbit_tools_config\"",
"numbers: 1, 2, 3, 4) The range of numbers is presented as two",
"404: logger.error(\"Queue %r does not exist.\", queue_name) chosen_numbers.append(queue_number) else: logger.warning(\"%s: %r.\", self.queue_not_affected_msg, queue_name)",
"define every time options like API address or user credentials; * ability to",
"user_input = self._get_user_input(mapping) parsed_input = self._parse_input(user_input) except StopReceivingInput: print 'bye' break if parsed_input:",
"space, comma or space and comma (number of spaces does not matter, there",
"chosen_numbers.append(queue_number) else: logger.warning(\"%s: %r.\", self.queue_not_affected_msg, queue_name) else: affected_queues.append(queue_name) chosen_numbers.append(queue_number) if affected_queues: logger.info(\"%s: %s.\",",
"nr in mapping} if not selected_mapping: logger.error('No queues were selected.') return None return",
"multi_choice.group(0) return map(int, self.multi_choice_inner_regex.findall(raw_numbers)) logger.error('Input could not be parsed.') return None @staticmethod def",
"self._get_parsed_args() self._vhost = self.config['vhost'] self.client = self._get_client(**self.config) self._method_to_call = getattr(self.client, self.client_method_name) self._chosen_numbers =",
"iteration of the loop, the list of available queues is shown, each queue",
"else: affected_queues.append(queue) else: logger.info(\"%s: %s\", self.queues_affected_msg, ', '.join(affected_queues)) def make_action(self, chosen_queues): affected_queues =",
"client instance, which will be used to manipulate chosen queues. Subclasses of the",
"current list of queues will be shown and it will wait for input",
"_get_queue_mapping(self): queue_names = list(self._yield_queue_list()) if not queue_names: raise StopReceivingInput full_range = range(1, len(queue_names)",
"NotImplemented args = { 'queue_name': { 'help': 'Name of one or more queues",
"two numbers (beginning of the range and its end) separated by dash (-).",
"anymore do_remove_chosen_numbers = False single_choice_regex = re.compile(r'^\\d+$') range_choice_regex = re.compile(r'^(\\d+)[ ]*-[ ]*(\\d+)$') multi_choice_regex",
"affected by an action; * no_queues_affected_msg (str) - message logged, when there was",
"ways of using Rabbit Tools. The first is to pass a known queue",
"'No queues have been affected.' quitting_commands = ['q', 'quit', 'exit', 'e'] choose_all_commands =",
"', '.join(affected_queues)) def make_action(self, chosen_queues): affected_queues = [] chosen_numbers = [] for queue_number,",
"= False single_choice_regex = re.compile(r'^\\d+$') range_choice_regex = re.compile(r'^(\\d+)[ ]*-[ ]*(\\d+)$') multi_choice_regex = re.compile(r'^((\\d+)*[",
"e.status == 404: logger.error(\"Queue %r does not exist.\", queue_name) chosen_numbers.append(queue_number) else: logger.warning(\"%s: %r.\",",
"\") user_input = user_input.strip().lower() return user_input else: logger.info('No more queues to choose.') raise",
"re import sys from collections import Sequence from pyrabbit import Client from pyrabbit.http",
"sys.exit('Config file has not been found. Use the \"rabbit_tools_config\" command' ' to generate",
"be more than one, before and after the comma): 1, 2 3 ,",
"probably more convenient) way to manipulate AMQP queues, than GUI, API or other",
"action was unsuccessful for a current queue; * queues_affected_msg (str) - message to",
"chose: 2, 3, 4, 5) IMPORTANT: list and range of numbers should not",
"self._chosen_numbers = set() def _get_parsed_args(self): parser = argparse.ArgumentParser(description=self.description) for arg_name, arg_opts in self.args.iteritems():",
"user, password, **kwargs): api_url = self._get_api_url(host, port) cl = Client(api_url, user, password) return",
"return map(int, self.multi_choice_inner_regex.findall(raw_numbers)) logger.error('Input could not be parsed.') return None @staticmethod def _get_selected_mapping(mapping,",
"queues_affected_msg (str) - message to log, to show, which queues were successfully affected",
"arguments, so current list of queues will be shown and it will wait",
"to quit'): \") user_input = user_input.strip().lower() return user_input else: logger.info('No more queues to",
"In this mode a tool runs in a loop, until user quits or",
"logged, when there was no success with any of chosen queues; Note that",
"associated with it, so in this mode user should choose queues using these",
"= set() def _get_parsed_args(self): parser = argparse.ArgumentParser(description=self.description) for arg_name, arg_opts in self.args.iteritems(): parser.add_argument(arg_name,",
"HTTPError from rabbit_tools.config import ( Config, ConfigFileMissingException, ) logger = logging.getLogger(__name__) class StopReceivingInput(Exception):",
"attributes, that may be overridden in a subclass: * do_remove_chosen_numbers (bool) - set",
"StopReceivingInput full_range = range(1, len(queue_names) + len(self._chosen_numbers) + 1) if self.do_remove_chosen_numbers: output_range =",
"except HTTPError as e: if e.status == 404: logger.error(\"Queue %r does not exist.\",",
"all queues.', 'nargs': '*', }, } queue_not_affected_msg = 'Queue not affected' queues_affected_msg =",
"all, a method of client instance, which will be used to manipulate chosen",
"options like API address or user credentials; * ability to choose ranges of",
"using the config file, so there is no need to define every time",
"does not matter, there can be more than one, before and after the",
"** Usage There are two ways of using Rabbit Tools. The first is",
"None def make_action_from_args(self, all_queues, queue_names): if len(queue_names) == 1 and queue_names[0] in self.choose_all_commands:",
"are formatted differently. If not overridden in a subclass, default messages will be",
"1 and queue_names[0] in self.choose_all_commands: chosen_queues = all_queues else: chosen_queues = queue_names affected_queues",
"'e'] choose_all_commands = ['a', 'all'] # set to True, if queues are deleted",
"matter, there can be more than one, before and after the comma): 1,",
"elif parsed_input == 'all': return mapping return None def make_action_from_args(self, all_queues, queue_names): if",
"user a faster (and probably more convenient) way to manipulate AMQP queues, than",
"show, which queues were successfully affected by an action; * no_queues_affected_msg (str) -",
"more queues (seperated by space) / ' '\"all\" to choose all queues.', 'nargs':",
"or more spaces: 2 - 5 (will chose: 2, 3, 4, 5) IMPORTANT:",
"that may be overridden in a subclass: * do_remove_chosen_numbers (bool) - set to",
"number ('all' to choose all / 'q' to quit'): \") user_input = user_input.strip().lower()",
"= logging.getLogger(__name__) class StopReceivingInput(Exception): \"\"\" Raised when no queues are left, or user",
"import ( Config, ConfigFileMissingException, ) logger = logging.getLogger(__name__) class StopReceivingInput(Exception): \"\"\" Raised when",
"quitting command. \"\"\" class RabbitToolBase(object): \"\"\" Base class providing AMQP communication, parsing of",
"when an action was unsuccessful for a current queue; * queues_affected_msg (str) -",
"= 'No queues have been affected.' quitting_commands = ['q', 'quit', 'exit', 'e'] choose_all_commands",
"def _get_client(self, host, port, user, password, **kwargs): api_url = self._get_api_url(host, port) cl =",
"list of numbers or range. In the list of numbers, each number should",
"to choose all / 'q' to quit'): \") user_input = user_input.strip().lower() return user_input",
"queue_name) else: affected_queues.append(queue_name) chosen_numbers.append(queue_number) if affected_queues: logger.info(\"%s: %s.\", self.queues_affected_msg, ', '.join(affected_queues)) else: logger.warning(self.no_queues_affected_msg)",
"affected_queues: logger.info(\"%s: %s.\", self.queues_affected_msg, ', '.join(affected_queues)) else: logger.warning(self.no_queues_affected_msg) return chosen_numbers def run(self): queue_names",
"one input. \"\"\" config_section = 'rabbit_tools' client_method_name = NotImplemented description = NotImplemented args",
"args = { 'queue_name': { 'help': 'Name of one or more queues (seperated",
"of numbers, each number should be separated by space, comma or space and",
"2 3 , 4 (will chose numbers: 1, 2, 3, 4) The range",
"def _parse_input(self, user_input): if user_input in self.quitting_commands: raise StopReceivingInput if user_input in self.choose_all_commands:",
"logger.warning(\"%s: %r.\", self.queue_not_affected_msg, queue) else: affected_queues.append(queue) else: logger.info(\"%s: %s\", self.queues_affected_msg, ', '.join(affected_queues)) def",
"self.queues_affected_msg, ', '.join(affected_queues)) def make_action(self, chosen_queues): affected_queues = [] chosen_numbers = [] for",
"this mode user should choose queues using these numbers. Additional comfort of usage",
"Choosing queues in the interactive mode: In this mode a tool runs in",
"In the list of numbers, each number should be separated by space, comma",
"classes provide, most of all, a method of client instance, which will be",
"which will be used to manipulate queues. Other attributes, that may be overridden",
"(beginning of the range and its end) separated by dash (-). Numbers and",
"4) The range of numbers is presented as two numbers (beginning of the",
"with any of chosen queues; Note that some messages end with dot, other",
"chosen_numbers = [] for queue_number, queue_name in chosen_queues.iteritems(): try: self._method_to_call(self._vhost, queue_name) except HTTPError",
"were selected.') return None return selected_mapping elif parsed_input == 'all': return mapping return",
"self.args.iteritems(): parser.add_argument(arg_name, **arg_opts) return parser.parse_args() def _get_client(self, host, port, user, password, **kwargs): api_url",
"and numbers associated with them should not be bound to other names to",
"be mixed in one input. \"\"\" config_section = 'rabbit_tools' client_method_name = NotImplemented description",
"manipulate chosen queues. Subclasses of the class have to implement attributes: * description",
"queue in mapping.iteritems(): print '[{}] {}'.format(nr, queue) user_input = raw_input(\"Queue number ('all' to",
"exist.\", queue) else: logger.warning(\"%s: %r.\", self.queue_not_affected_msg, queue) else: affected_queues.append(queue) else: logger.info(\"%s: %s\", self.queues_affected_msg,",
"(run with -h argument); * client_method_name (str) - name of a method of",
"queue_names) else: while True: try: mapping = self._get_queue_mapping() user_input = self._get_user_input(mapping) parsed_input =",
"be used to manipulate queues. Other attributes, that may be overridden in a",
"to True, if it is expected, that successfully manipulated queues will disappear from",
"is to pass a known queue name or many queue names, separated by",
"like API address or user credentials; * ability to choose ranges of queue",
"instance, which will be used to manipulate chosen queues. Subclasses of the class",
"queues left. In each iteration of the loop, the list of available queues",
"Config(self.config_section) except ConfigFileMissingException: sys.exit('Config file has not been found. Use the \"rabbit_tools_config\" command'",
"tool with no arguments, so current list of queues will be shown and",
"numbers or range. In the list of numbers, each number should be separated",
"self.queue_not_affected_msg, queue_name) else: affected_queues.append(queue_name) chosen_numbers.append(queue_number) if affected_queues: logger.info(\"%s: %s.\", self.queues_affected_msg, ', '.join(affected_queues)) else:",
"queues); * queue_not_affected_msg (str) - message to log, when an action was unsuccessful",
"set to True, if queues are deleted after an action, # and the",
"if len(queue_names) == 1 and queue_names[0] in self.choose_all_commands: chosen_queues = all_queues else: chosen_queues",
"parser.add_argument(arg_name, **arg_opts) return parser.parse_args() def _get_client(self, host, port, user, password, **kwargs): api_url =",
"does not exist.\", queue_name) chosen_numbers.append(queue_number) else: logger.warning(\"%s: %r.\", self.queue_not_affected_msg, queue_name) else: affected_queues.append(queue_name) chosen_numbers.append(queue_number)",
"need to define every time options like API address or user credentials; *",
"from pyrabbit import Client from pyrabbit.http import HTTPError from rabbit_tools.config import ( Config,",
"logger.warning(\"%s: %r.\", self.queue_not_affected_msg, queue_name) else: affected_queues.append(queue_name) chosen_numbers.append(queue_number) if affected_queues: logger.info(\"%s: %s.\", self.queues_affected_msg, ',",
"def _get_queue_mapping(self): queue_names = list(self._yield_queue_list()) if not queue_names: raise StopReceivingInput full_range = range(1,",
"concrete classes give user a faster (and probably more convenient) way to manipulate",
"port, user, password, **kwargs): api_url = self._get_api_url(host, port) cl = Client(api_url, user, password)",
"if nr in mapping} if not selected_mapping: logger.error('No queues were selected.') return None",
"return [int(single_choice.group(0))] range_choice = self.range_choice_regex.search(user_input) if range_choice: return range(int(range_choice.group(1)), int(range_choice.group(2))+1) multi_choice = self.multi_choice_regex.search(user_input)",
"Client(api_url, user, password) return cl @staticmethod def _get_api_url(host, port): return '{0}:{1}'.format(host, str(port)) def",
"import argparse import logging import re import sys from collections import Sequence from",
"of using Rabbit Tools. The first is to pass a known queue name",
"of the tool, which will be shown inside of script's help (run with",
"'*', }, } queue_not_affected_msg = 'Queue not affected' queues_affected_msg = 'Queues affected' no_queues_affected_msg",
"user quits or there are no queues left. In each iteration of the",
"of the class have to implement attributes: * description (str) - description of",
"in case of deleting queues); * queue_not_affected_msg (str) - message to log, when",
"differently. If not overridden in a subclass, default messages will be logged. **",
"if isinstance(parsed_input, Sequence): selected_mapping = {nr: mapping[nr] for nr in parsed_input if nr",
"* do_remove_chosen_numbers (bool) - set to True, if it is expected, that successfully",
"method of PyRabbit's client instance, which will be used to manipulate queues. Other",
"choose.') raise StopReceivingInput def _parse_input(self, user_input): if user_input in self.quitting_commands: raise StopReceivingInput if",
"before and after the comma): 1, 2 3 , 4 (will chose numbers:",
"'nargs': '*', }, } queue_not_affected_msg = 'Queue not affected' queues_affected_msg = 'Queues affected'",
"else: while True: try: mapping = self._get_queue_mapping() user_input = self._get_user_input(mapping) parsed_input = self._parse_input(user_input)",
"]*(\\d+)$') multi_choice_regex = re.compile(r'^((\\d+)*[ ]*,?[ ]*){2,}$') multi_choice_inner_regex = re.compile(r'\\b(\\d+)\\b') def __init__(self): try: self.config",
"other names to avoid wrong selections (like in case of deleting queues); *",
"case of deleting queues); * queue_not_affected_msg (str) - message to log, when an",
"e: if e.status == 404: logger.error(\"Queue %r does not exist.\", queue) else: logger.warning(\"%s:",
"(str) - description of the tool, which will be shown inside of script's",
"of numbers or range. In the list of numbers, each number should be",
"- description of the tool, which will be shown inside of script's help",
"been affected.' quitting_commands = ['q', 'quit', 'exit', 'e'] choose_all_commands = ['a', 'all'] #",
"Input can be a single number, list of numbers or range. In the",
"= multi_choice.group(0) return map(int, self.multi_choice_inner_regex.findall(raw_numbers)) logger.error('Input could not be parsed.') return None @staticmethod",
"using Rabbit Tools. The first is to pass a known queue name or",
"- message to log, when an action was unsuccessful for a current queue;",
"= 'Queues affected' no_queues_affected_msg = 'No queues have been affected.' quitting_commands = ['q',",
"map(int, self.multi_choice_inner_regex.findall(raw_numbers)) logger.error('Input could not be parsed.') return None @staticmethod def _get_selected_mapping(mapping, parsed_input):",
"else: affected_queues.append(queue_name) chosen_numbers.append(queue_number) if affected_queues: logger.info(\"%s: %s.\", self.queues_affected_msg, ', '.join(affected_queues)) else: logger.warning(self.no_queues_affected_msg) return",
"PyRabbit's client instance, which will be used to manipulate queues. Other attributes, that",
"names to avoid wrong selections (like in case of deleting queues); * queue_not_affected_msg",
"there are no queues left. In each iteration of the loop, the list",
"cl @staticmethod def _get_api_url(host, port): return '{0}:{1}'.format(host, str(port)) def _yield_queue_list(self): return (x['name'] for",
"to manipulate queues. Other attributes, that may be overridden in a subclass: *",
"queues (seperated by space) / ' '\"all\" to choose all queues.', 'nargs': '*',",
"self._method_to_call = getattr(self.client, self.client_method_name) self._chosen_numbers = set() def _get_parsed_args(self): parser = argparse.ArgumentParser(description=self.description) for",
"re.compile(r'^(\\d+)[ ]*-[ ]*(\\d+)$') multi_choice_regex = re.compile(r'^((\\d+)*[ ]*,?[ ]*){2,}$') multi_choice_inner_regex = re.compile(r'\\b(\\d+)\\b') def __init__(self):",
"queue_names)) @staticmethod def _get_user_input(mapping): if mapping: for nr, queue in mapping.iteritems(): print '[{}]",
"class StopReceivingInput(Exception): \"\"\" Raised when no queues are left, or user typed a",
"that some messages end with dot, other not, because they are formatted differently.",
"rabbit_tools.config import ( Config, ConfigFileMissingException, ) logger = logging.getLogger(__name__) class StopReceivingInput(Exception): \"\"\" Raised",
"of client instance, which will be used to manipulate chosen queues. Subclasses of",
"try: self._method_to_call(self._vhost, queue_name) except HTTPError as e: if e.status == 404: logger.error(\"Queue %r",
"with RabbitMQ. Concrete classes provide, most of all, a method of client instance,",
"should not be bound to other names to avoid wrong selections (like in",
"the list of available queues is shown, each queue has a number assigned,",
"client instance, which will be used to manipulate queues. Other attributes, that may",
"e: if e.status == 404: logger.error(\"Queue %r does not exist.\", queue_name) chosen_numbers.append(queue_number) else:",
"in this mode user should choose queues using these numbers. Additional comfort of",
"self.multi_choice_inner_regex.findall(raw_numbers)) logger.error('Input could not be parsed.') return None @staticmethod def _get_selected_mapping(mapping, parsed_input): if",
"number should not be shown anymore do_remove_chosen_numbers = False single_choice_regex = re.compile(r'^\\d+$') range_choice_regex",
"quitting_commands = ['q', 'quit', 'exit', 'e'] choose_all_commands = ['a', 'all'] # set to",
"= self._parsed_args.queue_name if queue_names: all_queues = self._yield_queue_list() self.make_action_from_args(all_queues, queue_names) else: while True: try:",
"address or user credentials; * ability to choose ranges of queue numbers. **",
"RabbitToolBase(object): \"\"\" Base class providing AMQP communication, parsing of user input and applying",
"chosen_queues = queue_names affected_queues = [] for queue in chosen_queues: try: self._method_to_call(self._vhost, queue)",
"= queue_names affected_queues = [] for queue in chosen_queues: try: self._method_to_call(self._vhost, queue) except",
"used to manipulate queues. Other attributes, that may be overridden in a subclass:",
"NotImplemented description = NotImplemented args = { 'queue_name': { 'help': 'Name of one",
"if user_input in self.quitting_commands: raise StopReceivingInput if user_input in self.choose_all_commands: return 'all' single_choice",
"{}'.format(nr, queue) user_input = raw_input(\"Queue number ('all' to choose all / 'q' to",
"affected_queues.append(queue) else: logger.info(\"%s: %s\", self.queues_affected_msg, ', '.join(affected_queues)) def make_action(self, chosen_queues): affected_queues = []",
"multi_choice: raw_numbers = multi_choice.group(0) return map(int, self.multi_choice_inner_regex.findall(raw_numbers)) logger.error('Input could not be parsed.') return",
"for queue in chosen_queues: try: self._method_to_call(self._vhost, queue) except HTTPError as e: if e.status",
"getattr(self.client, self.client_method_name) self._chosen_numbers = set() def _get_parsed_args(self): parser = argparse.ArgumentParser(description=self.description) for arg_name, arg_opts",
"= 'Queue not affected' queues_affected_msg = 'Queues affected' no_queues_affected_msg = 'No queues have",
"= re.compile(r'^(\\d+)[ ]*-[ ]*(\\d+)$') multi_choice_regex = re.compile(r'^((\\d+)*[ ]*,?[ ]*){2,}$') multi_choice_inner_regex = re.compile(r'\\b(\\d+)\\b') def",
"/ 'q' to quit'): \") user_input = user_input.strip().lower() return user_input else: logger.info('No more",
"is presented as two numbers (beginning of the range and its end) separated",
"self.config = Config(self.config_section) except ConfigFileMissingException: sys.exit('Config file has not been found. Use the",
"sys from collections import Sequence from pyrabbit import Client from pyrabbit.http import HTTPError",
"range_choice = self.range_choice_regex.search(user_input) if range_choice: return range(int(range_choice.group(1)), int(range_choice.group(2))+1) multi_choice = self.multi_choice_regex.search(user_input) if multi_choice:",
"were successfully affected by an action; * no_queues_affected_msg (str) - message logged, when",
"Note that some messages end with dot, other not, because they are formatted",
"quits or there are no queues left. In each iteration of the loop,",
"= {nr: mapping[nr] for nr in parsed_input if nr in mapping} if not",
"'.join(affected_queues)) def make_action(self, chosen_queues): affected_queues = [] chosen_numbers = [] for queue_number, queue_name",
"Tools implemented by concrete classes give user a faster (and probably more convenient)",
"logger.warning(self.no_queues_affected_msg) return chosen_numbers def run(self): queue_names = self._parsed_args.queue_name if queue_names: all_queues = self._yield_queue_list()",
"def __init__(self): try: self.config = Config(self.config_section) except ConfigFileMissingException: sys.exit('Config file has not been",
"except ConfigFileMissingException: sys.exit('Config file has not been found. Use the \"rabbit_tools_config\" command' '",
"spaces does not matter, there can be more than one, before and after",
"ranges of queue numbers. ** Choosing queues in the interactive mode: In this",
"logging.getLogger(__name__) class StopReceivingInput(Exception): \"\"\" Raised when no queues are left, or user typed",
"of spaces does not matter, there can be more than one, before and",
"print '[{}] {}'.format(nr, queue) user_input = raw_input(\"Queue number ('all' to choose all /",
"for nr in parsed_input if nr in mapping} if not selected_mapping: logger.error('No queues",
"in self.client.get_queues(self._vhost)) def _get_queue_mapping(self): queue_names = list(self._yield_queue_list()) if not queue_names: raise StopReceivingInput full_range",
"self._parsed_args = self._get_parsed_args() self._vhost = self.config['vhost'] self.client = self._get_client(**self.config) self._method_to_call = getattr(self.client, self.client_method_name)",
"self.client.get_queues(self._vhost)) def _get_queue_mapping(self): queue_names = list(self._yield_queue_list()) if not queue_names: raise StopReceivingInput full_range =",
"- self._chosen_numbers else: output_range = full_range return dict(zip(output_range, queue_names)) @staticmethod def _get_user_input(mapping): if",
"of available queues is shown, each queue has a number assigned, so user",
"\"\"\" Base class providing AMQP communication, parsing of user input and applying some",
"for arg_name, arg_opts in self.args.iteritems(): parser.add_argument(arg_name, **arg_opts) return parser.parse_args() def _get_client(self, host, port,",
"self.single_choice_regex.search(user_input) if single_choice: return [int(single_choice.group(0))] range_choice = self.range_choice_regex.search(user_input) if range_choice: return range(int(range_choice.group(1)), int(range_choice.group(2))+1)",
"are left, or user typed a quitting command. \"\"\" class RabbitToolBase(object): \"\"\" Base",
"message logged, when there was no success with any of chosen queues; Note",
"with no arguments, so current list of queues will be shown and it",
"inputs proper number, not a whole name. Input can be a single number,",
"self._get_client(**self.config) self._method_to_call = getattr(self.client, self.client_method_name) self._chosen_numbers = set() def _get_parsed_args(self): parser = argparse.ArgumentParser(description=self.description)",
"user, password) return cl @staticmethod def _get_api_url(host, port): return '{0}:{1}'.format(host, str(port)) def _yield_queue_list(self):",
"make_action_from_args(self, all_queues, queue_names): if len(queue_names) == 1 and queue_names[0] in self.choose_all_commands: chosen_queues =",
"self._yield_queue_list() self.make_action_from_args(all_queues, queue_names) else: while True: try: mapping = self._get_queue_mapping() user_input = self._get_user_input(mapping)",
"give user a faster (and probably more convenient) way to manipulate AMQP queues,",
"the config file, so there is no need to define every time options",
"and queue_names[0] in self.choose_all_commands: chosen_queues = all_queues else: chosen_queues = queue_names affected_queues =",
"Additional comfort of usage comes from: * using the config file, so there",
"be separated by space, comma or space and comma (number of spaces does",
"its end) separated by dash (-). Numbers and the symbol of dash can",
"def run(self): queue_names = self._parsed_args.queue_name if queue_names: all_queues = self._yield_queue_list() self.make_action_from_args(all_queues, queue_names) else:",
"with -h argument); * client_method_name (str) - name of a method of PyRabbit's",
"will be shown and it will wait for input from user. Each queue",
"host, port, user, password, **kwargs): api_url = self._get_api_url(host, port) cl = Client(api_url, user,",
"range(int(range_choice.group(1)), int(range_choice.group(2))+1) multi_choice = self.multi_choice_regex.search(user_input) if multi_choice: raw_numbers = multi_choice.group(0) return map(int, self.multi_choice_inner_regex.findall(raw_numbers))",
"( Config, ConfigFileMissingException, ) logger = logging.getLogger(__name__) class StopReceivingInput(Exception): \"\"\" Raised when no",
"return None return selected_mapping elif parsed_input == 'all': return mapping return None def",
"action, # and the associated number should not be shown anymore do_remove_chosen_numbers =",
"does not exist.\", queue) else: logger.warning(\"%s: %r.\", self.queue_not_affected_msg, queue) else: affected_queues.append(queue) else: logger.info(\"%s:",
"%r does not exist.\", queue_name) chosen_numbers.append(queue_number) else: logger.warning(\"%s: %r.\", self.queue_not_affected_msg, queue_name) else: affected_queues.append(queue_name)",
"\"\"\" config_section = 'rabbit_tools' client_method_name = NotImplemented description = NotImplemented args = {",
"= { 'queue_name': { 'help': 'Name of one or more queues (seperated by",
"(like in case of deleting queues); * queue_not_affected_msg (str) - message to log,",
"]*-[ ]*(\\d+)$') multi_choice_regex = re.compile(r'^((\\d+)*[ ]*,?[ ]*){2,}$') multi_choice_inner_regex = re.compile(r'\\b(\\d+)\\b') def __init__(self): try:",
"* ability to choose ranges of queue numbers. ** Choosing queues in the",
"should not be mixed in one input. \"\"\" config_section = 'rabbit_tools' client_method_name =",
"affected.' quitting_commands = ['q', 'quit', 'exit', 'e'] choose_all_commands = ['a', 'all'] # set",
"some action to chosen queues. Tools implemented by concrete classes give user a",
"numbers, each number should be separated by space, comma or space and comma",
"self._get_api_url(host, port) cl = Client(api_url, user, password) return cl @staticmethod def _get_api_url(host, port):",
"if user_input in self.choose_all_commands: return 'all' single_choice = self.single_choice_regex.search(user_input) if single_choice: return [int(single_choice.group(0))]",
"3, 4) The range of numbers is presented as two numbers (beginning of",
"arg_opts in self.args.iteritems(): parser.add_argument(arg_name, **arg_opts) return parser.parse_args() def _get_client(self, host, port, user, password,",
"to other names to avoid wrong selections (like in case of deleting queues);",
"StopReceivingInput(Exception): \"\"\" Raised when no queues are left, or user typed a quitting",
"not a whole name. Input can be a single number, list of numbers",
"class have to implement attributes: * description (str) - description of the tool,",
"queue in chosen_queues: try: self._method_to_call(self._vhost, queue) except HTTPError as e: if e.status ==",
"queues. Tools implemented by concrete classes give user a faster (and probably more",
"return selected_mapping elif parsed_input == 'all': return mapping return None def make_action_from_args(self, all_queues,",
"queues have been affected.' quitting_commands = ['q', 'quit', 'exit', 'e'] choose_all_commands = ['a',",
"it is expected, that successfully manipulated queues will disappear from the list, and",
"queue; * queues_affected_msg (str) - message to log, to show, which queues were",
"comfort of usage comes from: * using the config file, so there is",
"number assigned, so user inputs proper number, not a whole name. Input can",
"1, 2 3 , 4 (will chose numbers: 1, 2, 3, 4) The",
"attributes: * description (str) - description of the tool, which will be shown",
"- message to log, to show, which queues were successfully affected by an",
"has a number associated with it, so in this mode user should choose",
"* using the config file, so there is no need to define every",
"queues in the interactive mode: In this mode a tool runs in a",
"numbers is presented as two numbers (beginning of the range and its end)",
"self._get_user_input(mapping) parsed_input = self._parse_input(user_input) except StopReceivingInput: print 'bye' break if parsed_input: selected_mapping =",
"parsed_input = self._parse_input(user_input) except StopReceivingInput: print 'bye' break if parsed_input: selected_mapping = self._get_selected_mapping(mapping,",
"['a', 'all'] # set to True, if queues are deleted after an action,",
"there is no need to define every time options like API address or",
"could not be parsed.') return None @staticmethod def _get_selected_mapping(mapping, parsed_input): if isinstance(parsed_input, Sequence):",
"separated by one or more spaces: 2 - 5 (will chose: 2, 3,",
"one or more spaces: 2 - 5 (will chose: 2, 3, 4, 5)",
"queues were selected.') return None return selected_mapping elif parsed_input == 'all': return mapping",
"(will chose numbers: 1, 2, 3, 4) The range of numbers is presented",
"Raised when no queues are left, or user typed a quitting command. \"\"\"",
"and its end) separated by dash (-). Numbers and the symbol of dash",
"* no_queues_affected_msg (str) - message logged, when there was no success with any",
"argument); * client_method_name (str) - name of a method of PyRabbit's client instance,",
"output_range = full_range return dict(zip(output_range, queue_names)) @staticmethod def _get_user_input(mapping): if mapping: for nr,",
"dict(zip(output_range, queue_names)) @staticmethod def _get_user_input(mapping): if mapping: for nr, queue in mapping.iteritems(): print",
"mode: In this mode a tool runs in a loop, until user quits",
"current queue; * queues_affected_msg (str) - message to log, to show, which queues",
"(and probably more convenient) way to manipulate AMQP queues, than GUI, API or",
"and the symbol of dash can be separated by one or more spaces:",
"]*){2,}$') multi_choice_inner_regex = re.compile(r'\\b(\\d+)\\b') def __init__(self): try: self.config = Config(self.config_section) except ConfigFileMissingException: sys.exit('Config",
"- set to True, if it is expected, that successfully manipulated queues will",
"Tools. The first is to pass a known queue name or many queue",
"found. Use the \"rabbit_tools_config\" command' ' to generate it.') self._parsed_args = self._get_parsed_args() self._vhost",
"ConfigFileMissingException, ) logger = logging.getLogger(__name__) class StopReceivingInput(Exception): \"\"\" Raised when no queues are",
"when no queues are left, or user typed a quitting command. \"\"\" class",
"mapping.iteritems(): print '[{}] {}'.format(nr, queue) user_input = raw_input(\"Queue number ('all' to choose all",
"int(range_choice.group(2))+1) multi_choice = self.multi_choice_regex.search(user_input) if multi_choice: raw_numbers = multi_choice.group(0) return map(int, self.multi_choice_inner_regex.findall(raw_numbers)) logger.error('Input",
"of a method of PyRabbit's client instance, which will be used to manipulate",
"if affected_queues: logger.info(\"%s: %s.\", self.queues_affected_msg, ', '.join(affected_queues)) else: logger.warning(self.no_queues_affected_msg) return chosen_numbers def run(self):",
"presented as two numbers (beginning of the range and its end) separated by",
"if e.status == 404: logger.error(\"Queue %r does not exist.\", queue) else: logger.warning(\"%s: %r.\",",
"affected_queues = [] for queue in chosen_queues: try: self._method_to_call(self._vhost, queue) except HTTPError as",
"not affected' queues_affected_msg = 'Queues affected' no_queues_affected_msg = 'No queues have been affected.'",
"= self._get_queue_mapping() user_input = self._get_user_input(mapping) parsed_input = self._parse_input(user_input) except StopReceivingInput: print 'bye' break",
"selected_mapping elif parsed_input == 'all': return mapping return None def make_action_from_args(self, all_queues, queue_names):",
"password) return cl @staticmethod def _get_api_url(host, port): return '{0}:{1}'.format(host, str(port)) def _yield_queue_list(self): return",
"this mode a tool runs in a loop, until user quits or there",
"user_input in self.choose_all_commands: return 'all' single_choice = self.single_choice_regex.search(user_input) if single_choice: return [int(single_choice.group(0))] range_choice",
"user input and applying some action to chosen queues. Tools implemented by concrete",
"['q', 'quit', 'exit', 'e'] choose_all_commands = ['a', 'all'] # set to True, if",
"chosen queues. Tools implemented by concrete classes give user a faster (and probably",
"def _get_api_url(host, port): return '{0}:{1}'.format(host, str(port)) def _yield_queue_list(self): return (x['name'] for x in",
"can be more than one, before and after the comma): 1, 2 3",
"single_choice: return [int(single_choice.group(0))] range_choice = self.range_choice_regex.search(user_input) if range_choice: return range(int(range_choice.group(1)), int(range_choice.group(2))+1) multi_choice =",
"logger.error('Input could not be parsed.') return None @staticmethod def _get_selected_mapping(mapping, parsed_input): if isinstance(parsed_input,",
"queue_not_affected_msg (str) - message to log, when an action was unsuccessful for a",
"not, because they are formatted differently. If not overridden in a subclass, default",
"a whole name. Input can be a single number, list of numbers or",
"affected_queues = [] chosen_numbers = [] for queue_number, queue_name in chosen_queues.iteritems(): try: self._method_to_call(self._vhost,",
"name or many queue names, separated by space, or \"all\" string, to choose",
"some messages end with dot, other not, because they are formatted differently. If",
"and after the comma): 1, 2 3 , 4 (will chose numbers: 1,",
"unsuccessful for a current queue; * queues_affected_msg (str) - message to log, to",
"implement attributes: * description (str) - description of the tool, which will be",
"convenient) way to manipulate AMQP queues, than GUI, API or other command line",
"an action, # and the associated number should not be shown anymore do_remove_chosen_numbers",
"self.queue_not_affected_msg, queue) else: affected_queues.append(queue) else: logger.info(\"%s: %s\", self.queues_affected_msg, ', '.join(affected_queues)) def make_action(self, chosen_queues):",
"file, so there is no need to define every time options like API",
"in the interactive mode: In this mode a tool runs in a loop,",
"will be shown inside of script's help (run with -h argument); * client_method_name",
"should be separated by space, comma or space and comma (number of spaces",
"every time options like API address or user credentials; * ability to choose",
"len(queue_names) + len(self._chosen_numbers) + 1) if self.do_remove_chosen_numbers: output_range = set(full_range) - self._chosen_numbers else:",
"user credentials; * ability to choose ranges of queue numbers. ** Choosing queues",
"= all_queues else: chosen_queues = queue_names affected_queues = [] for queue in chosen_queues:",
"choose all queues.', 'nargs': '*', }, } queue_not_affected_msg = 'Queue not affected' queues_affected_msg",
"- message logged, when there was no success with any of chosen queues;",
"to True, if queues are deleted after an action, # and the associated",
"return parser.parse_args() def _get_client(self, host, port, user, password, **kwargs): api_url = self._get_api_url(host, port)",
"the symbol of dash can be separated by one or more spaces: 2",
"range of numbers should not be mixed in one input. \"\"\" config_section =",
"to pass a known queue name or many queue names, separated by space,",
"'quit', 'exit', 'e'] choose_all_commands = ['a', 'all'] # set to True, if queues",
"or range. In the list of numbers, each number should be separated by",
"= NotImplemented description = NotImplemented args = { 'queue_name': { 'help': 'Name of",
"a tool with no arguments, so current list of queues will be shown",
"range of numbers is presented as two numbers (beginning of the range and",
"all_queues, queue_names): if len(queue_names) == 1 and queue_names[0] in self.choose_all_commands: chosen_queues = all_queues",
"will disappear from the list, and numbers associated with them should not be",
"by space, or \"all\" string, to choose all queues. The other way is",
"to choose.') raise StopReceivingInput def _parse_input(self, user_input): if user_input in self.quitting_commands: raise StopReceivingInput",
"list, and numbers associated with them should not be bound to other names",
"manipulated queues will disappear from the list, and numbers associated with them should",
", 4 (will chose numbers: 1, 2, 3, 4) The range of numbers",
"{nr: mapping[nr] for nr in parsed_input if nr in mapping} if not selected_mapping:",
"return cl @staticmethod def _get_api_url(host, port): return '{0}:{1}'.format(host, str(port)) def _yield_queue_list(self): return (x['name']",
"an action was unsuccessful for a current queue; * queues_affected_msg (str) - message",
"the \"rabbit_tools_config\" command' ' to generate it.') self._parsed_args = self._get_parsed_args() self._vhost = self.config['vhost']",
"self._method_to_call(self._vhost, queue_name) except HTTPError as e: if e.status == 404: logger.error(\"Queue %r does",
"{ 'queue_name': { 'help': 'Name of one or more queues (seperated by space)",
"the class have to implement attributes: * description (str) - description of the",
"output_range = set(full_range) - self._chosen_numbers else: output_range = full_range return dict(zip(output_range, queue_names)) @staticmethod",
"names, separated by space, or \"all\" string, to choose all queues. The other"
] |
[
"= [ ] operations = [ migrations.CreateModel( name='Portfolio', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"models.CharField(max_length=255, verbose_name='title')), ('slug', models.SlugField(help_text=\"Used to build the category's URL.\", max_length=255, unique=True, verbose_name='slug')), ('content',",
"Generated by Django 2.1.1 on 2018-09-13 18:15 from django.db import migrations, models import",
"showcase.models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [",
"('image', models.ImageField(blank=True, help_text='Used for illustration.', upload_to=showcase.models.image_upload_to_dispatcher, verbose_name='image')), ('image_caption', models.TextField(blank=True, help_text=\"Image's caption.\", verbose_name='caption')), ('creation_date',",
"dependencies = [ ] operations = [ migrations.CreateModel( name='Portfolio', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,",
"('title', models.CharField(max_length=255, verbose_name='title')), ('slug', models.SlugField(help_text=\"Used to build the category's URL.\", max_length=255, unique=True, verbose_name='slug')),",
"models.SlugField(help_text=\"Used to build the category's URL.\", max_length=255, unique=True, verbose_name='slug')), ('content', models.TextField(blank=True, verbose_name='content')), ('image',",
"# Generated by Django 2.1.1 on 2018-09-13 18:15 from django.db import migrations, models",
"import showcase.models class Migration(migrations.Migration): initial = True dependencies = [ ] operations =",
"18:15 from django.db import migrations, models import django.utils.timezone import showcase.models class Migration(migrations.Migration): initial",
"2018-09-13 18:15 from django.db import migrations, models import django.utils.timezone import showcase.models class Migration(migrations.Migration):",
"Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Portfolio',",
"name='Portfolio', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=255, verbose_name='title')), ('slug', models.SlugField(help_text=\"Used to",
"verbose_name='title')), ('slug', models.SlugField(help_text=\"Used to build the category's URL.\", max_length=255, unique=True, verbose_name='slug')), ('content', models.TextField(blank=True,",
"URL.\", max_length=255, unique=True, verbose_name='slug')), ('content', models.TextField(blank=True, verbose_name='content')), ('image', models.ImageField(blank=True, help_text='Used for illustration.', upload_to=showcase.models.image_upload_to_dispatcher,",
"Django 2.1.1 on 2018-09-13 18:15 from django.db import migrations, models import django.utils.timezone import",
"for illustration.', upload_to=showcase.models.image_upload_to_dispatcher, verbose_name='image')), ('image_caption', models.TextField(blank=True, help_text=\"Image's caption.\", verbose_name='caption')), ('creation_date', models.DateTimeField(default=django.utils.timezone.now, verbose_name='creation date')),",
"django.db import migrations, models import django.utils.timezone import showcase.models class Migration(migrations.Migration): initial = True",
"help_text='Used for illustration.', upload_to=showcase.models.image_upload_to_dispatcher, verbose_name='image')), ('image_caption', models.TextField(blank=True, help_text=\"Image's caption.\", verbose_name='caption')), ('creation_date', models.DateTimeField(default=django.utils.timezone.now, verbose_name='creation",
"True dependencies = [ ] operations = [ migrations.CreateModel( name='Portfolio', fields=[ ('id', models.AutoField(auto_created=True,",
"primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=255, verbose_name='title')), ('slug', models.SlugField(help_text=\"Used to build the category's URL.\",",
"models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=255, verbose_name='title')), ('slug', models.SlugField(help_text=\"Used to build the category's",
"from django.db import migrations, models import django.utils.timezone import showcase.models class Migration(migrations.Migration): initial =",
"models.TextField(blank=True, verbose_name='content')), ('image', models.ImageField(blank=True, help_text='Used for illustration.', upload_to=showcase.models.image_upload_to_dispatcher, verbose_name='image')), ('image_caption', models.TextField(blank=True, help_text=\"Image's caption.\",",
"build the category's URL.\", max_length=255, unique=True, verbose_name='slug')), ('content', models.TextField(blank=True, verbose_name='content')), ('image', models.ImageField(blank=True, help_text='Used",
"migrations, models import django.utils.timezone import showcase.models class Migration(migrations.Migration): initial = True dependencies =",
"initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Portfolio', fields=[",
"fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=255, verbose_name='title')), ('slug', models.SlugField(help_text=\"Used to build",
"by Django 2.1.1 on 2018-09-13 18:15 from django.db import migrations, models import django.utils.timezone",
"= True dependencies = [ ] operations = [ migrations.CreateModel( name='Portfolio', fields=[ ('id',",
"verbose_name='ID')), ('title', models.CharField(max_length=255, verbose_name='title')), ('slug', models.SlugField(help_text=\"Used to build the category's URL.\", max_length=255, unique=True,",
"verbose_name='content')), ('image', models.ImageField(blank=True, help_text='Used for illustration.', upload_to=showcase.models.image_upload_to_dispatcher, verbose_name='image')), ('image_caption', models.TextField(blank=True, help_text=\"Image's caption.\", verbose_name='caption')),",
"max_length=255, unique=True, verbose_name='slug')), ('content', models.TextField(blank=True, verbose_name='content')), ('image', models.ImageField(blank=True, help_text='Used for illustration.', upload_to=showcase.models.image_upload_to_dispatcher, verbose_name='image')),",
"verbose_name='image')), ('image_caption', models.TextField(blank=True, help_text=\"Image's caption.\", verbose_name='caption')), ('creation_date', models.DateTimeField(default=django.utils.timezone.now, verbose_name='creation date')), ], ), ]",
"migrations.CreateModel( name='Portfolio', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=255, verbose_name='title')), ('slug', models.SlugField(help_text=\"Used",
"unique=True, verbose_name='slug')), ('content', models.TextField(blank=True, verbose_name='content')), ('image', models.ImageField(blank=True, help_text='Used for illustration.', upload_to=showcase.models.image_upload_to_dispatcher, verbose_name='image')), ('image_caption',",
"on 2018-09-13 18:15 from django.db import migrations, models import django.utils.timezone import showcase.models class",
"class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel(",
"verbose_name='slug')), ('content', models.TextField(blank=True, verbose_name='content')), ('image', models.ImageField(blank=True, help_text='Used for illustration.', upload_to=showcase.models.image_upload_to_dispatcher, verbose_name='image')), ('image_caption', models.TextField(blank=True,",
"models.ImageField(blank=True, help_text='Used for illustration.', upload_to=showcase.models.image_upload_to_dispatcher, verbose_name='image')), ('image_caption', models.TextField(blank=True, help_text=\"Image's caption.\", verbose_name='caption')), ('creation_date', models.DateTimeField(default=django.utils.timezone.now,",
"serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=255, verbose_name='title')), ('slug', models.SlugField(help_text=\"Used to build the category's URL.\", max_length=255,",
"operations = [ migrations.CreateModel( name='Portfolio', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=255,",
"upload_to=showcase.models.image_upload_to_dispatcher, verbose_name='image')), ('image_caption', models.TextField(blank=True, help_text=\"Image's caption.\", verbose_name='caption')), ('creation_date', models.DateTimeField(default=django.utils.timezone.now, verbose_name='creation date')), ], ),",
"2.1.1 on 2018-09-13 18:15 from django.db import migrations, models import django.utils.timezone import showcase.models",
"('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=255, verbose_name='title')), ('slug', models.SlugField(help_text=\"Used to build the",
"= [ migrations.CreateModel( name='Portfolio', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=255, verbose_name='title')),",
"django.utils.timezone import showcase.models class Migration(migrations.Migration): initial = True dependencies = [ ] operations",
"[ ] operations = [ migrations.CreateModel( name='Portfolio', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"[ migrations.CreateModel( name='Portfolio', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=255, verbose_name='title')), ('slug',",
"to build the category's URL.\", max_length=255, unique=True, verbose_name='slug')), ('content', models.TextField(blank=True, verbose_name='content')), ('image', models.ImageField(blank=True,",
"category's URL.\", max_length=255, unique=True, verbose_name='slug')), ('content', models.TextField(blank=True, verbose_name='content')), ('image', models.ImageField(blank=True, help_text='Used for illustration.',",
"illustration.', upload_to=showcase.models.image_upload_to_dispatcher, verbose_name='image')), ('image_caption', models.TextField(blank=True, help_text=\"Image's caption.\", verbose_name='caption')), ('creation_date', models.DateTimeField(default=django.utils.timezone.now, verbose_name='creation date')), ],",
"import django.utils.timezone import showcase.models class Migration(migrations.Migration): initial = True dependencies = [ ]",
"('slug', models.SlugField(help_text=\"Used to build the category's URL.\", max_length=255, unique=True, verbose_name='slug')), ('content', models.TextField(blank=True, verbose_name='content')),",
"('content', models.TextField(blank=True, verbose_name='content')), ('image', models.ImageField(blank=True, help_text='Used for illustration.', upload_to=showcase.models.image_upload_to_dispatcher, verbose_name='image')), ('image_caption', models.TextField(blank=True, help_text=\"Image's",
"the category's URL.\", max_length=255, unique=True, verbose_name='slug')), ('content', models.TextField(blank=True, verbose_name='content')), ('image', models.ImageField(blank=True, help_text='Used for",
"models import django.utils.timezone import showcase.models class Migration(migrations.Migration): initial = True dependencies = [",
"] operations = [ migrations.CreateModel( name='Portfolio', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title',",
"import migrations, models import django.utils.timezone import showcase.models class Migration(migrations.Migration): initial = True dependencies"
] |
[
") # the furthest i can go with current i if ( i",
"limit if i < len(steps) - 1: step_num += 1 # each switch",
"values in this problem 1. current furthest distance 2. current index 3. current",
"i, means i can never reach i return None furthest = max( furthest,",
"> len(steps) - 1: return step_num for i in range(len(steps)): if furthest <",
"limit means one step further. cur_cover = ( furthest ) # the new",
"return True return False elif method == 3: step_num = 0 furthest =",
"2: cover = 0 i = 0 while i < cover: cover =",
"i = 0 while i < cover: cover = max(cover, i + steps[i])",
"cur_cover <= i: return False if cur_cover >= len(steps) - 1: return True",
"0 furthest = steps[0] cur_cover = steps[0] if cur_cover > len(steps) - 1:",
"- 1: return step_num else: return step_num \"\"\" there are three values in",
"3. current range that index can iterate to \"\"\" steps = [2, 2,",
"2. current index 3. current range that index can iterate to \"\"\" steps",
"i in range(len(steps)): if furthest < i: # if the furthest i can",
"- 1: return True return False elif method == 2: cover = 0",
"1 if cover >= len(steps) - 1: return True return False elif method",
"== 3: step_num = 0 furthest = steps[0] cur_cover = steps[0] if cur_cover",
"if ( i == cur_cover ): # if i reaches the previous limit,",
"steps[0] else: cur_cover = max(cur_cover, i + steps[i]) if cur_cover <= i: return",
"can go, if cur_cover > len(steps) - 1: return step_num else: return step_num",
"cover: cover = max(cover, i + steps[i]) i += 1 if cover >=",
"< i: # if the furthest i can go < i, means i",
"1 # each switch of limit means one step further. cur_cover = (",
"max(cur_cover, i + steps[i]) if cur_cover <= i: return False if cur_cover >=",
"to update the limit if i < len(steps) - 1: step_num += 1",
"1. current furthest distance 2. current index 3. current range that index can",
"can go < i, means i can never reach i return None furthest",
"return step_num \"\"\" there are three values in this problem 1. current furthest",
"further. cur_cover = ( furthest ) # the new limte is the furtheest",
"1: return True return False elif method == 3: step_num = 0 furthest",
"in range(len(steps)): if furthest < i: # if the furthest i can go",
"= steps[0] else: cur_cover = max(cur_cover, i + steps[i]) if cur_cover <= i:",
"len(steps) - 1: return step_num for i in range(len(steps)): if furthest < i:",
"- 1: step_num += 1 # each switch of limit means one step",
"= steps[0] cur_cover = steps[0] if cur_cover > len(steps) - 1: return step_num",
"if method == 1: if len(steps) <= 1: return True for i in",
"one step further. cur_cover = ( furthest ) # the new limte is",
"< len(steps) - 1: step_num += 1 # each switch of limit means",
"+ steps[i] ) # the furthest i can go with current i if",
"1: return True for i in range(len(steps)): if i == 0: cur_cover =",
"step_num for i in range(len(steps)): if furthest < i: # if the furthest",
"in this problem 1. current furthest distance 2. current index 3. current range",
"i can go < i, means i can never reach i return None",
"<= 1: return True for i in range(len(steps)): if i == 0: cur_cover",
"= max(cover, i + steps[i]) i += 1 if cover >= len(steps) -",
"if the furthest i can go < i, means i can never reach",
"): # if i reaches the previous limit, check to see if i",
"< cover: cover = max(cover, i + steps[i]) i += 1 if cover",
"( furthest ) # the new limte is the furtheest curret i can",
"i need to update the limit if i < len(steps) - 1: step_num",
">= len(steps) - 1: return True return False elif method == 3: step_num",
"method=1): if method == 1: if len(steps) <= 1: return True for i",
"steps[i]) i += 1 if cover >= len(steps) - 1: return True return",
"index 3. current range that index can iterate to \"\"\" steps = [2,",
"furthest = steps[0] cur_cover = steps[0] if cur_cover > len(steps) - 1: return",
"True for i in range(len(steps)): if i == 0: cur_cover = steps[0] else:",
"check to see if i need to update the limit if i <",
"= 0 i = 0 while i < cover: cover = max(cover, i",
"method == 3: step_num = 0 furthest = steps[0] cur_cover = steps[0] if",
"steps[i] ) # the furthest i can go with current i if (",
"if i < len(steps) - 1: step_num += 1 # each switch of",
"means one step further. cur_cover = ( furthest ) # the new limte",
"in range(len(steps)): if i == 0: cur_cover = steps[0] else: cur_cover = max(cur_cover,",
"len(steps) - 1: step_num += 1 # each switch of limit means one",
"i + steps[i] ) # the furthest i can go with current i",
"if cur_cover > len(steps) - 1: return step_num else: return step_num \"\"\" there",
") # the new limte is the furtheest curret i can go, if",
"cur_cover = steps[0] else: cur_cover = max(cur_cover, i + steps[i]) if cur_cover <=",
"i + steps[i]) i += 1 if cover >= len(steps) - 1: return",
"None furthest = max( furthest, i + steps[i] ) # the furthest i",
"furthest, i + steps[i] ) # the furthest i can go with current",
"3: step_num = 0 furthest = steps[0] cur_cover = steps[0] if cur_cover >",
"furthest distance 2. current index 3. current range that index can iterate to",
"cover = max(cover, i + steps[i]) i += 1 if cover >= len(steps)",
"0 while i < cover: cover = max(cover, i + steps[i]) i +=",
"return False elif method == 3: step_num = 0 furthest = steps[0] cur_cover",
"i += 1 if cover >= len(steps) - 1: return True return False",
"reaches the previous limit, check to see if i need to update the",
"return step_num for i in range(len(steps)): if furthest < i: # if the",
"step_num += 1 # each switch of limit means one step further. cur_cover",
"furthest ) # the new limte is the furtheest curret i can go,",
"= max( furthest, i + steps[i] ) # the furthest i can go",
"are three values in this problem 1. current furthest distance 2. current index",
"i can go, if cur_cover > len(steps) - 1: return step_num else: return",
"can never reach i return None furthest = max( furthest, i + steps[i]",
"- 1: return True return False elif method == 3: step_num = 0",
"<= i: return False if cur_cover >= len(steps) - 1: return True return",
"i == 0: cur_cover = steps[0] else: cur_cover = max(cur_cover, i + steps[i])",
"jump(steps, method=1): if method == 1: if len(steps) <= 1: return True for",
">= len(steps) - 1: return True return False elif method == 2: cover",
"if furthest < i: # if the furthest i can go < i,",
"len(steps) - 1: return step_num else: return step_num \"\"\" there are three values",
"i + steps[i]) if cur_cover <= i: return False if cur_cover >= len(steps)",
"cur_cover = steps[0] if cur_cover > len(steps) - 1: return step_num for i",
"cover >= len(steps) - 1: return True return False elif method == 3:",
"False elif method == 2: cover = 0 i = 0 while i",
"i < len(steps) - 1: step_num += 1 # each switch of limit",
"> len(steps) - 1: return step_num else: return step_num \"\"\" there are three",
"switch of limit means one step further. cur_cover = ( furthest ) #",
"return True for i in range(len(steps)): if i == 0: cur_cover = steps[0]",
"+ steps[i]) if cur_cover <= i: return False if cur_cover >= len(steps) -",
"furtheest curret i can go, if cur_cover > len(steps) - 1: return step_num",
"+= 1 if cover >= len(steps) - 1: return True return False elif",
"the furthest i can go with current i if ( i == cur_cover",
"new limte is the furtheest curret i can go, if cur_cover > len(steps)",
"limit, check to see if i need to update the limit if i",
"len(steps) - 1: return True return False elif method == 2: cover =",
"\"\"\" there are three values in this problem 1. current furthest distance 2.",
"i in range(len(steps)): if i == 0: cur_cover = steps[0] else: cur_cover =",
"range(len(steps)): if i == 0: cur_cover = steps[0] else: cur_cover = max(cur_cover, i",
"True return False elif method == 3: step_num = 0 furthest = steps[0]",
"< i, means i can never reach i return None furthest = max(",
"reach i return None furthest = max( furthest, i + steps[i] ) #",
"go < i, means i can never reach i return None furthest =",
"index can iterate to \"\"\" steps = [2, 2, 1, 0, 4] print(jump(steps,",
"step_num = 0 furthest = steps[0] cur_cover = steps[0] if cur_cover > len(steps)",
"to see if i need to update the limit if i < len(steps)",
"if cur_cover <= i: return False if cur_cover >= len(steps) - 1: return",
"previous limit, check to see if i need to update the limit if",
"method == 2: cover = 0 i = 0 while i < cover:",
"1: step_num += 1 # each switch of limit means one step further.",
"the previous limit, check to see if i need to update the limit",
"i return None furthest = max( furthest, i + steps[i] ) # the",
"if i need to update the limit if i < len(steps) - 1:",
"furthest i can go < i, means i can never reach i return",
"len(steps) - 1: return True return False elif method == 3: step_num =",
"if i == 0: cur_cover = steps[0] else: cur_cover = max(cur_cover, i +",
"step further. cur_cover = ( furthest ) # the new limte is the",
"cur_cover > len(steps) - 1: return step_num else: return step_num \"\"\" there are",
"i can go with current i if ( i == cur_cover ): #",
"0: cur_cover = steps[0] else: cur_cover = max(cur_cover, i + steps[i]) if cur_cover",
"False elif method == 3: step_num = 0 furthest = steps[0] cur_cover =",
"distance 2. current index 3. current range that index can iterate to \"\"\"",
"current range that index can iterate to \"\"\" steps = [2, 2, 1,",
"max(cover, i + steps[i]) i += 1 if cover >= len(steps) - 1:",
"# each switch of limit means one step further. cur_cover = ( furthest",
"cur_cover > len(steps) - 1: return step_num for i in range(len(steps)): if furthest",
"three values in this problem 1. current furthest distance 2. current index 3.",
"steps[0] cur_cover = steps[0] if cur_cover > len(steps) - 1: return step_num for",
"False if cur_cover >= len(steps) - 1: return True return False elif method",
"update the limit if i < len(steps) - 1: step_num += 1 #",
"cover = 0 i = 0 while i < cover: cover = max(cover,",
"i: return False if cur_cover >= len(steps) - 1: return True return False",
"go with current i if ( i == cur_cover ): # if i",
"if cover >= len(steps) - 1: return True return False elif method ==",
"cur_cover ): # if i reaches the previous limit, check to see if",
"step_num \"\"\" there are three values in this problem 1. current furthest distance",
"= 0 while i < cover: cover = max(cover, i + steps[i]) i",
"furthest = max( furthest, i + steps[i] ) # the furthest i can",
"return False elif method == 2: cover = 0 i = 0 while",
"else: cur_cover = max(cur_cover, i + steps[i]) if cur_cover <= i: return False",
"if len(steps) <= 1: return True for i in range(len(steps)): if i ==",
"each switch of limit means one step further. cur_cover = ( furthest )",
"for i in range(len(steps)): if i == 0: cur_cover = steps[0] else: cur_cover",
"1: return step_num for i in range(len(steps)): if furthest < i: # if",
"steps[0] if cur_cover > len(steps) - 1: return step_num for i in range(len(steps)):",
"is the furtheest curret i can go, if cur_cover > len(steps) - 1:",
"go, if cur_cover > len(steps) - 1: return step_num else: return step_num \"\"\"",
"range that index can iterate to \"\"\" steps = [2, 2, 1, 0,",
"== cur_cover ): # if i reaches the previous limit, check to see",
"need to update the limit if i < len(steps) - 1: step_num +=",
"1: if len(steps) <= 1: return True for i in range(len(steps)): if i",
"the limit if i < len(steps) - 1: step_num += 1 # each",
"max( furthest, i + steps[i] ) # the furthest i can go with",
"current index 3. current range that index can iterate to \"\"\" steps =",
"steps[i]) if cur_cover <= i: return False if cur_cover >= len(steps) - 1:",
"furthest i can go with current i if ( i == cur_cover ):",
"can go with current i if ( i == cur_cover ): # if",
"return True return False elif method == 2: cover = 0 i =",
"furthest < i: # if the furthest i can go < i, means",
"the new limte is the furtheest curret i can go, if cur_cover >",
"current i if ( i == cur_cover ): # if i reaches the",
"== 2: cover = 0 i = 0 while i < cover: cover",
"range(len(steps)): if furthest < i: # if the furthest i can go <",
"== 0: cur_cover = steps[0] else: cur_cover = max(cur_cover, i + steps[i]) if",
"the furthest i can go < i, means i can never reach i",
"of limit means one step further. cur_cover = ( furthest ) # the",
"for i in range(len(steps)): if furthest < i: # if the furthest i",
"cur_cover = max(cur_cover, i + steps[i]) if cur_cover <= i: return False if",
"elif method == 3: step_num = 0 furthest = steps[0] cur_cover = steps[0]",
"that index can iterate to \"\"\" steps = [2, 2, 1, 0, 4]",
"cur_cover >= len(steps) - 1: return True return False elif method == 2:",
"+ steps[i]) i += 1 if cover >= len(steps) - 1: return True",
"i reaches the previous limit, check to see if i need to update",
"this problem 1. current furthest distance 2. current index 3. current range that",
"step_num else: return step_num \"\"\" there are three values in this problem 1.",
"i can never reach i return None furthest = max( furthest, i +",
"if i reaches the previous limit, check to see if i need to",
"never reach i return None furthest = max( furthest, i + steps[i] )",
"with current i if ( i == cur_cover ): # if i reaches",
"# if i reaches the previous limit, check to see if i need",
"i == cur_cover ): # if i reaches the previous limit, check to",
"see if i need to update the limit if i < len(steps) -",
"- 1: return step_num for i in range(len(steps)): if furthest < i: #",
"elif method == 2: cover = 0 i = 0 while i <",
"limte is the furtheest curret i can go, if cur_cover > len(steps) -",
"means i can never reach i return None furthest = max( furthest, i",
"return None furthest = max( furthest, i + steps[i] ) # the furthest",
"= steps[0] if cur_cover > len(steps) - 1: return step_num for i in",
"return step_num else: return step_num \"\"\" there are three values in this problem",
"else: return step_num \"\"\" there are three values in this problem 1. current",
"there are three values in this problem 1. current furthest distance 2. current",
"the furtheest curret i can go, if cur_cover > len(steps) - 1: return",
"method == 1: if len(steps) <= 1: return True for i in range(len(steps)):",
"1: return step_num else: return step_num \"\"\" there are three values in this",
"if cur_cover >= len(steps) - 1: return True return False elif method ==",
"cur_cover = ( furthest ) # the new limte is the furtheest curret",
"while i < cover: cover = max(cover, i + steps[i]) i += 1",
"if cur_cover > len(steps) - 1: return step_num for i in range(len(steps)): if",
"curret i can go, if cur_cover > len(steps) - 1: return step_num else:",
"== 1: if len(steps) <= 1: return True for i in range(len(steps)): if",
"+= 1 # each switch of limit means one step further. cur_cover =",
"i if ( i == cur_cover ): # if i reaches the previous",
"can iterate to \"\"\" steps = [2, 2, 1, 0, 4] print(jump(steps, 3))",
"= max(cur_cover, i + steps[i]) if cur_cover <= i: return False if cur_cover",
"def jump(steps, method=1): if method == 1: if len(steps) <= 1: return True",
"= 0 furthest = steps[0] cur_cover = steps[0] if cur_cover > len(steps) -",
"( i == cur_cover ): # if i reaches the previous limit, check",
"# the furthest i can go with current i if ( i ==",
"0 i = 0 while i < cover: cover = max(cover, i +",
"len(steps) <= 1: return True for i in range(len(steps)): if i == 0:",
"i: # if the furthest i can go < i, means i can",
"= ( furthest ) # the new limte is the furtheest curret i",
"1: return True return False elif method == 2: cover = 0 i",
"i < cover: cover = max(cover, i + steps[i]) i += 1 if",
"# the new limte is the furtheest curret i can go, if cur_cover",
"current furthest distance 2. current index 3. current range that index can iterate",
"True return False elif method == 2: cover = 0 i = 0",
"return False if cur_cover >= len(steps) - 1: return True return False elif",
"# if the furthest i can go < i, means i can never",
"problem 1. current furthest distance 2. current index 3. current range that index"
] |
[
"list_of_squares(num): i = 1 squares = [] while i**2 <= num: squares.append(i**2) i",
"squares = [] while i**2 <= num: squares.append(i**2) i += 1 return squares",
"<= num: squares.append(i**2) i += 1 return squares if __name__ == '__main__': num",
"квадратов def list_of_squares(num): i = 1 squares = [] while i**2 <= num:",
"# Список квадратов def list_of_squares(num): i = 1 squares = [] while i**2",
"1 squares = [] while i**2 <= num: squares.append(i**2) i += 1 return",
"i = 1 squares = [] while i**2 <= num: squares.append(i**2) i +=",
"= 1 squares = [] while i**2 <= num: squares.append(i**2) i += 1",
"= [] while i**2 <= num: squares.append(i**2) i += 1 return squares if",
"[] while i**2 <= num: squares.append(i**2) i += 1 return squares if __name__",
"while i**2 <= num: squares.append(i**2) i += 1 return squares if __name__ ==",
"i**2 <= num: squares.append(i**2) i += 1 return squares if __name__ == '__main__':",
"Список квадратов def list_of_squares(num): i = 1 squares = [] while i**2 <=",
"def list_of_squares(num): i = 1 squares = [] while i**2 <= num: squares.append(i**2)",
"i += 1 return squares if __name__ == '__main__': num = int(input()) print(*list_of_squares(num))",
"squares.append(i**2) i += 1 return squares if __name__ == '__main__': num = int(input())",
"num: squares.append(i**2) i += 1 return squares if __name__ == '__main__': num ="
] |
[] |
[
": float recall : float \"\"\" if position == 0: precision = 1.0",
"fig, ax = plt.subplots(1, 1, figsize=(7, 4)) plot_axes(ax, p, r, legend_text='IAP', **kwargs) plt.show()",
"side-by-side for two different sets of scores, against the same true observations. Parameters",
"on a weighted sum of the data. Parameters ---------- n_dim : int n_samples",
"**kwargs): \"\"\" Plots a precision-recall graph from a series of operating points. Parameters",
"of operating points. Parameters ---------- p : list Precision. r : recall Recall.",
"negative_idx]) np.random.shuffle(indices_to_use) return X[indices_to_use], y[indices_to_use] def generate_continuous_data_and_targets( n_dim, n_samples, mixing_factor=0.025, frac_positive=0.1): \"\"\" Generates",
"to a positive and negative class, where the positive class comes first in",
"rows of the input X (i.e. n' <= n) y : np.array (n',",
"(n, ) frac_positive : float Returns ------- X : np.array (n', m) Some",
"p_long, alpha=0.2, label='{} = {:5.4f}'.format(legend_text, area)) leg = ax.legend() leg.get_frame().set_linewidth(0.0) else: print(\"Interpolation value",
"(i.e. n' <= n) \"\"\" positive_idx = np.arange(len(y))[y == 1] negative_idx = np.arange(len(y))[y",
"data and trains a logistic regression model. Parameters ---------- n_dim : int Number",
"from copy import copy from collections import OrderedDict import numpy as np import",
"precision_recall_curve( y_true, y_score, sample_weight=sample_weight) return auc_using_step(recall, precision) def generate_positive_semi_definite_matrix(n_dim): \"\"\" Creates a positive",
"p, r, threshold = precision_recall_curve(true, score) pr[name] = [p, r] compare_recall_precision_graph(pr, **kwargs) def",
"optional See plot_axes. \"\"\" p, r, thresholds = precision_recall_curve(true, scores) plot_recall_precision(p, r, **kwargs)",
"np.array (n, m) y : np.array (n, ) frac_positive : float Returns -------",
"Returns ------- y : np.array (n_test, ) True observed values in the test",
"import average_precision_score, auc, roc_auc_score from sklearn.metrics import precision_recall_curve from sklearn.linear_model import LogisticRegressionCV from",
"of binary observations. position : int Position to split the list into positive",
"sum of the data. Parameters ---------- n_dim : int n_samples : int mixing_factor",
"y_scores : np.array (n_test, ) Model predictions of the test samples. roc_auc :",
"are positive. Parameters ---------- X : np.array (n, m) y : np.array (n,",
": list Must be binary (i.e. 1s and 0s). scores : list Consisting",
"y : np.array (n, ) frac_positive : float Returns ------- X : np.array",
"to 0 make the task more challenging. Returns ------- y : np.array (n_test,",
"interpolation is not None: if interpolation == 'linear': ax.plot(x, y) area = auc(x,",
"and `pr` is a tuple of precision and recall values. title : string",
"trains a logistic regression model. Parameters ---------- n_dim : int Number of dimensions",
"labelled observations to a positive and negative class, where the positive class comes",
"is not None: ax.set_title(title, fontsize=20) if interpolation is not None: if interpolation ==",
"- (frac_positive * n)) 0s constant_predictions : list Same length as observations \"\"\"",
"ax.set_xlim((-0.05, 1.05)) ax.set_ylim((-0.08, 1.08)) ax.set_xlabel('Recall') ax.set_ylabel('Precision') if title is not None: ax.set_title(title, fontsize=20)",
"precision and recall values. title : string kwargs : optional See plot_axes. \"\"\"",
"return precision, recall def auc_using_step(recall, precision): return sum([(recall[i] - recall[i+1]) * precision[i] for",
"- 1)]) def roam_average_precision(y_true, y_score, sample_weight=None): precision, recall, thresholds = precision_recall_curve( y_true, y_score,",
"matplotlib axes y : list x : list interpolation : None (default) or",
"precision, recall, thresholds = precision_recall_curve( y_true, y_score, sample_weight=sample_weight) return auc_using_step(recall, precision) def generate_positive_semi_definite_matrix(n_dim):",
"\"\"\" Generates a multivariate Gaussian-distributed dataset and a response variable that is conditioned",
"sklearn.metrics import precision_recall_curve from sklearn.linear_model import LogisticRegressionCV from sklearn.cross_validation import StratifiedShuffleSplit import matplotlib.pyplot",
"y def sigmoid(x): \"\"\" Computes sigmoid(x) for some activation x. Parameters ---------- x",
"a tuple of precision and recall values. title : string kwargs : optional",
"precision = 1.0 recall = 0.0 else: ranking = np.array(ranking) precision = (ranking[:position]",
"position): \"\"\" Computes the precision and recall of a particular assignment of labelled",
"ax.fill_between(x, 0, y, alpha=0.2, label='{} = {:5.4f}'.format(legend_text, area)) leg = ax.legend() leg.get_frame().set_linewidth(0.0) elif",
"int n_samples : int mixing_factor : float 'Squashes' the weighted sum into the",
"n_positive = int(frac_positive * n) n_negative = n - n_positive observations = [1",
"np.array (n_test, ) Model predictions of the test samples. roc_auc : float ROC",
"def generate_data_and_constant_predictions(n, frac_positive): \"\"\" Generates data in a fixed positive:negative ratio, and returns",
"class, where the positive class comes first in the list, and the negative",
"of the input y (i.e. n' <= n) \"\"\" positive_idx = np.arange(len(y))[y ==",
"== 1).sum() / (ranking == 1).sum() return precision, recall def auc_using_step(recall, precision): return",
"y) ax.fill_between(r_long, 0, p_long, alpha=0.2, label='{} = {:5.4f}'.format(legend_text, area)) leg = ax.legend() leg.get_frame().set_linewidth(0.0)",
"and recall from an ordered list of observations. Parameters ---------- ranking : list",
": int Number of dimensions for the training data. n_samples : int Number",
"p=y_probs) X, y = subsample(X, y, frac_positive) return X, y def sigmoid(x): \"\"\"",
"import copy from collections import OrderedDict import numpy as np import pandas as",
"in range(n_positive)] + \\ [0 for _ in range(n_negative)] constant_predictions = [0.5 for",
"ranking : list Ordered list of binary observations. position : int Position to",
"list recall : list \"\"\" precision, recall = list(), list() for pos in",
"'Area') Text to include on the legend before showing the area. Only used",
"float Fraction of the examples that are positive Returns ------- observations : list",
"np.array(ranking) precision = (ranking[:position] == 1).sum() / position recall = (ranking[:position] == 1).sum()",
"= np.arange(len(y))[y == 1] negative_idx = np.arange(len(y))[y == 0] num_positive = int(frac_positive *",
"n_dim, n_samples, mixing_factor=0.025, frac_positive=0.1): \"\"\" Generates a multivariate Gaussian-distributed dataset and a response",
"score) pr[name] = [p, r] compare_recall_precision_graph(pr, **kwargs) def compare_recall_precision_graph(pr_dict, title=None, **kwargs): \"\"\" Parameters",
": list Entries should be binary (0 or 1) and in descending order",
"(n_dim, n_dim) \"\"\" cov = np.random.randn(n_dim, n_dim) return np.dot(cov, cov.T) def subsample(X, y,",
") frac_positive : float Returns ------- X : np.array (n', m) Some subset",
"1] negative_idx = np.arange(len(y))[y == 0] num_positive = int(frac_positive * len(negative_idx)) positive_idx =",
"generate_data_and_constant_predictions(n, frac_positive): \"\"\" Generates data in a fixed positive:negative ratio, and returns the",
"precision, recall def auc_using_step(recall, precision): return sum([(recall[i] - recall[i+1]) * precision[i] for i",
"y, marker='o', linewidths=0, s=marker_size, clip_on=False) # Show first and last points more visably",
"kwargs : optional See plot_axes. \"\"\" pr = OrderedDict() for name, score in",
"a string and `pr` is a tuple of precision and recall values. title",
"tuple of precision and recall values. title : string kwargs : optional See",
"ax.fill_between(r_long, 0, p_long, alpha=0.2, label='{} = {:5.4f}'.format(legend_text, area)) leg = ax.legend() leg.get_frame().set_linewidth(0.0) else:",
"and `scores` is a list of floats. kwargs : optional See plot_axes. \"\"\"",
"string kwargs : optional See plot_axes. \"\"\" fig, ax = plt.subplots(1, 2, figsize=(15,",
"optional See plot_axes. \"\"\" fig, ax = plt.subplots(1, 2, figsize=(15, 4)) for side,",
"See plot_axes. \"\"\" fig, ax = plt.subplots(1, 2, figsize=(15, 4)) for side, (name,",
"None: fig.suptitle(title, fontsize=20, y=1.05) plt.show() def operating_points(ranking): \"\"\" Computes lists of precision and",
"indices_to_use = np.concatenate([positive_idx, negative_idx]) np.random.shuffle(indices_to_use) return X[indices_to_use], y[indices_to_use] def generate_continuous_data_and_targets( n_dim, n_samples, mixing_factor=0.025,",
"the task more challenging. Returns ------- y : np.array (n_test, ) True observed",
"import precision_recall_curve from sklearn.linear_model import LogisticRegressionCV from sklearn.cross_validation import StratifiedShuffleSplit import matplotlib.pyplot as",
"np.array (n, ) frac_positive : float Returns ------- X : np.array (n', m)",
"activation x. Parameters ---------- x : float Returns ------- sigmoid(x) : float \"\"\"",
"list Entries should be binary (0 or 1) and in descending order (i.e.",
"a response variable that is conditioned on a weighted sum of the data.",
"where the positive class comes first in the list, and the negative class",
"0, p_long, alpha=0.2, label='{} = {:5.4f}'.format(legend_text, area)) leg = ax.legend() leg.get_frame().set_linewidth(0.0) else: print(\"Interpolation",
"scores, **kwargs): \"\"\" Computes precision and recall from some observations and scores assigned",
"the area. Only used if interpolation is not None. \"\"\" ax.scatter(x, y, marker='o',",
"Creates a positive semi-definite matrix. Parameters ---------- n_dim : int Returns ------- np.array",
"r_long = [v for v in x for _ in (0, 1)][1:] ax.plot(r_long,",
"if interpolation is not None. \"\"\" ax.scatter(x, y, marker='o', linewidths=0, s=marker_size, clip_on=False) #",
": float Returns ------- X : np.array (n', m) Some subset of the",
"leg.get_frame().set_linewidth(0.0) else: print(\"Interpolation value of '{}' not recognised. \" \"Choose from 'linear', 'quadrature'.\".format(interpolation))",
"plot_recall_precision(p, r, **kwargs) def plot_recall_precision(p, r, **kwargs): \"\"\" Plots a precision-recall graph from",
"`{name: pr}` where `name` is a string and `pr` is a tuple of",
"nearer to 0 make the task more challenging. Returns ------- y : np.array",
"+ n_negative)] return observations, constant_predictions def plot_recall_precision_from_predictions(true, scores, **kwargs): \"\"\" Computes precision and",
"in [0, -1]], marker='x', linewidths=2, s=100, clip_on=False) ax.set_xlim((-0.05, 1.05)) ax.set_ylim((-0.08, 1.08)) ax.set_xlabel('Recall') ax.set_ylabel('Precision')",
"leg = ax.legend() leg.get_frame().set_linewidth(0.0) else: print(\"Interpolation value of '{}' not recognised. \" \"Choose",
"i in range(len(recall) - 1)]) def roam_average_precision(y_true, y_score, sample_weight=None): precision, recall, thresholds =",
"**kwargs) def compare_recall_precision_graph(pr_dict, title=None, **kwargs): \"\"\" Parameters ---------- pr_dict : dict Consisting of",
"else: print(\"Interpolation value of '{}' not recognised. \" \"Choose from 'linear', 'quadrature'.\".format(interpolation)) def",
"dict Consisting of `{name: pr}` where `name` is a string and `pr` is",
"= np.arange(len(y))[y == 0] num_positive = int(frac_positive * len(negative_idx)) positive_idx = np.random.choice(positive_idx, size=num_positive,",
"marker='o', linewidths=0, s=marker_size, clip_on=False) # Show first and last points more visably ax.scatter([x[i]",
"= np.random.binomial(1, p=y_probs) X, y = subsample(X, y, frac_positive) return X, y def",
"subsample(X, y, frac_positive) return X, y def sigmoid(x): \"\"\" Computes sigmoid(x) for some",
"\"\"\" if position == 0: precision = 1.0 recall = 0.0 else: ranking",
"/ (1 + np.exp(-x)) def train_model_and_evaluate(n_dim=50, n_samples=10000, frac_positive=0.05, mixing_factor=0.025): \"\"\" Generates some data",
"from a series of operating points. Parameters ---------- p : list Precision. r",
"roc_auc : float ROC AUC score on the test data \"\"\" X, y",
"== 0] num_positive = int(frac_positive * len(negative_idx)) positive_idx = np.random.choice(positive_idx, size=num_positive, replace=False) indices_to_use",
"-1]], [y[i] for i in [0, -1]], marker='x', linewidths=2, s=100, clip_on=False) ax.set_xlim((-0.05, 1.05))",
"= [0.5 for _ in range(n_positive + n_negative)] return observations, constant_predictions def plot_recall_precision_from_predictions(true,",
"OrderedDict import numpy as np import pandas as pd from sklearn.metrics import average_precision_score,",
"np.random.choice(positive_idx, size=num_positive, replace=False) indices_to_use = np.concatenate([positive_idx, negative_idx]) np.random.shuffle(indices_to_use) return X[indices_to_use], y[indices_to_use] def generate_continuous_data_and_targets(",
"---------- n_dim : int Number of dimensions for the training data. n_samples :",
"copy import copy from collections import OrderedDict import numpy as np import pandas",
"examples. Parameters ---------- n : int Number of examples frac_positive : float Fraction",
": list Consisting of (frac_positive * n) 1s, and (n - (frac_positive *",
"+ \\ [0 for _ in range(n_negative)] constant_predictions = [0.5 for _ in",
"axes provided. Parameters ---------- ax : matplotlib axes y : list x :",
"4)) plot_axes(ax, p, r, legend_text='IAP', **kwargs) plt.show() def plot_axes( ax, y, x, interpolation=None,",
": np.array (n_samples, n_dim) y : np.array (n_samples, ) \"\"\" cov = generate_positive_semi_definite_matrix(n_dim)",
"as np import pandas as pd from sklearn.metrics import average_precision_score, auc, roc_auc_score from",
"data. Parameters ---------- n_dim : int n_samples : int mixing_factor : float 'Squashes'",
"examples that are positive Returns ------- observations : list Consisting of (frac_positive *",
"plot_recall_precision(p, r, **kwargs): \"\"\" Plots a precision-recall graph from a series of operating",
"Returns ------- X : np.array (n_samples, n_dim) y : np.array (n_samples, ) \"\"\"",
"a series of operating points. Parameters ---------- p : list Precision. r :",
"from a dummy model that predicts 0.5 for all examples. Parameters ---------- n",
": np.array (n, m) y : np.array (n, ) frac_positive : float Returns",
"sigmoid. Smaller numbers squash closer to 0.5. Returns ------- X : np.array (n_samples,",
"ax = plt.subplots(1, 2, figsize=(15, 4)) for side, (name, [p, r]) in enumerate(pr_dict.items()):",
"sum into the linear regime of a sigmoid. Smaller numbers squash closer to",
"\"Choose from 'linear', 'quadrature'.\".format(interpolation)) def compare_recall_precisions_from_predictions(true, score_dict, **kwargs): \"\"\" Show two graphs side-by-side",
"int Number of dimensions for the training data. n_samples : int Number of",
"\"\"\" Computes sigmoid(x) for some activation x. Parameters ---------- x : float Returns",
"kwargs : optional See plot_axes. Returns ------- \"\"\" fig, ax = plt.subplots(1, 1,",
"Returns ------- \"\"\" fig, ax = plt.subplots(1, 1, figsize=(7, 4)) plot_axes(ax, p, r,",
"recall = (ranking[:position] == 1).sum() / (ranking == 1).sum() return precision, recall def",
"x : float Returns ------- sigmoid(x) : float \"\"\" return 1 / (1",
"values in the test set. y_scores : np.array (n_test, ) Model predictions of",
"= np.random.randn(n_dim, n_dim) return np.dot(cov, cov.T) def subsample(X, y, frac_positive): \"\"\" Subsamples a",
"clip_on=False) ax.set_xlim((-0.05, 1.05)) ax.set_ylim((-0.08, 1.08)) ax.set_xlabel('Recall') ax.set_ylabel('Precision') if title is not None: ax.set_title(title,",
"a multivariate Gaussian-distributed dataset and a response variable that is conditioned on a",
"a particular assignment of labelled observations to a positive and negative class, where",
"{:5.4f}'.format(legend_text, area)) leg = ax.legend() leg.get_frame().set_linewidth(0.0) else: print(\"Interpolation value of '{}' not recognised.",
"of floats. kwargs : optional See plot_axes. \"\"\" pr = OrderedDict() for name,",
"4)) for side, (name, [p, r]) in enumerate(pr_dict.items()): plot_axes(ax[side], p, r, title=name, legend_text='IAP',",
"\"\"\" X, y = generate_continuous_data_and_targets( n_dim=n_dim, n_samples=n_samples, frac_positive=frac_positive, mixing_factor=mixing_factor) splits = StratifiedShuffleSplit(y, test_size=0.3,",
"matplotlib from IPython.display import display, HTML matplotlib.style.use('../../src/roam.mplstyle') def generate_data_and_constant_predictions(n, frac_positive): \"\"\" Generates data",
"range(len(ranking)): p, r = precision_recall_from_ranking(ranking, pos) precision.append(p) recall.append(r) return precision, recall def precision_recall_from_ranking(ranking,",
"= [v for v in x for _ in (0, 1)][1:] ax.plot(r_long, p_long)",
"thresholds = precision_recall_curve( y_true, y_score, sample_weight=sample_weight) return auc_using_step(recall, precision) def generate_positive_semi_definite_matrix(n_dim): \"\"\" Creates",
"to split the list into positive and negative. Returns ------- precision : float",
"float \"\"\" if position == 0: precision = 1.0 recall = 0.0 else:",
"-1]], marker='x', linewidths=2, s=100, clip_on=False) ax.set_xlim((-0.05, 1.05)) ax.set_ylim((-0.08, 1.08)) ax.set_xlabel('Recall') ax.set_ylabel('Precision') if title",
"Returns ------- precision : list recall : list \"\"\" precision, recall = list(),",
"of the examples that are positive Returns ------- observations : list Consisting of",
"in range(len(recall) - 1)]) def roam_average_precision(y_true, y_score, sample_weight=None): precision, recall, thresholds = precision_recall_curve(",
"**kwargs) plt.show() def plot_axes( ax, y, x, interpolation=None, marker_size=30, title=None, legend_text='Area'): \"\"\" Plots",
"string legend_text : string (default: 'Area') Text to include on the legend before",
"scores : list Consisting of floats. kwargs : optional See plot_axes. \"\"\" p,",
"Show two graphs side-by-side for two different sets of scores, against the same",
"def compare_recall_precision_graph(pr_dict, title=None, **kwargs): \"\"\" Parameters ---------- pr_dict : dict Consisting of `{name:",
"<= n) y : np.array (n', ) Some subset of the rows of",
"training data. n_samples : int Number of observations. frac_positive : float mixing_factor :",
"s=100, clip_on=False) ax.set_xlim((-0.05, 1.05)) ax.set_ylim((-0.08, 1.08)) ax.set_xlabel('Recall') ax.set_ylabel('Precision') if title is not None:",
"is first). Returns ------- precision : list recall : list \"\"\" precision, recall",
"= precision_recall_curve( y_true, y_score, sample_weight=sample_weight) return auc_using_step(recall, precision) def generate_positive_semi_definite_matrix(n_dim): \"\"\" Creates a",
"task more challenging. Returns ------- y : np.array (n_test, ) True observed values",
"int Position to split the list into positive and negative. Returns ------- precision",
"or string ['linear', 'step'] marker_size : float (default: 30) title : None or",
"the test data \"\"\" X, y = generate_continuous_data_and_targets( n_dim=n_dim, n_samples=n_samples, frac_positive=frac_positive, mixing_factor=mixing_factor) splits",
"m) Some subset of the rows of the input X (i.e. n' <=",
"logistic regression model. Parameters ---------- n_dim : int Number of dimensions for the",
"recall = list(), list() for pos in range(len(ranking)): p, r = precision_recall_from_ranking(ranking, pos)",
"(1 + np.exp(-x)) def train_model_and_evaluate(n_dim=50, n_samples=10000, frac_positive=0.05, mixing_factor=0.025): \"\"\" Generates some data and",
"Consisting of `{name: pr}` where `name` is a string and `pr` is a",
"plt import matplotlib from IPython.display import display, HTML matplotlib.style.use('../../src/roam.mplstyle') def generate_data_and_constant_predictions(n, frac_positive): \"\"\"",
"title : None or string legend_text : string (default: 'Area') Text to include",
"def generate_positive_semi_definite_matrix(n_dim): \"\"\" Creates a positive semi-definite matrix. Parameters ---------- n_dim : int",
"position recall = (ranking[:position] == 1).sum() / (ranking == 1).sum() return precision, recall",
"None or string legend_text : string (default: 'Area') Text to include on the",
"in score_dict.items(): p, r, threshold = precision_recall_curve(true, score) pr[name] = [p, r] compare_recall_precision_graph(pr,",
"list Must be binary (i.e. 1s and 0s). scores : list Consisting of",
"points more visably ax.scatter([x[i] for i in [0, -1]], [y[i] for i in",
"np.random.multivariate_normal( mean=np.zeros(n_dim), cov=cov, size=n_samples) weights = np.random.randn(n_dim) y_probs = sigmoid(mixing_factor * np.dot(X, weights))",
"in range(len(ranking)): p, r = precision_recall_from_ranking(ranking, pos) precision.append(p) recall.append(r) return precision, recall def",
"a sigmoid. Smaller numbers squash closer to 0.5. Returns ------- X : np.array",
"where `name` is a string and `pr` is a tuple of precision and",
"\"\"\" Plots a graph on axes provided. Parameters ---------- ax : matplotlib axes",
"predictions of the test samples. roc_auc : float ROC AUC score on the",
": list score_dict : dict Consisting of `{name: scores}` where `name` is a",
"np.random.binomial(1, p=y_probs) X, y = subsample(X, y, frac_positive) return X, y def sigmoid(x):",
"cov = np.random.randn(n_dim, n_dim) return np.dot(cov, cov.T) def subsample(X, y, frac_positive): \"\"\" Subsamples",
"ax, y, x, interpolation=None, marker_size=30, title=None, legend_text='Area'): \"\"\" Plots a graph on axes",
"score_dict.items(): p, r, threshold = precision_recall_curve(true, score) pr[name] = [p, r] compare_recall_precision_graph(pr, **kwargs)",
"Parameters ---------- ranking : list Entries should be binary (0 or 1) and",
"list x : list interpolation : None (default) or string ['linear', 'step'] marker_size",
"and recall of a particular assignment of labelled observations to a positive and",
"string and `scores` is a list of floats. kwargs : optional See plot_axes.",
"the split point is specified. Parameters ---------- ranking : list Ordered list of",
"= int(frac_positive * len(negative_idx)) positive_idx = np.random.choice(positive_idx, size=num_positive, replace=False) indices_to_use = np.concatenate([positive_idx, negative_idx])",
"float mixing_factor : float Numbers nearer to 0 make the task more challenging.",
"p, r, legend_text='IAP', **kwargs) plt.show() def plot_axes( ax, y, x, interpolation=None, marker_size=30, title=None,",
"that are positive Returns ------- observations : list Consisting of (frac_positive * n)",
"lr = LogisticRegressionCV() lr.fit(X[train_idx], y[train_idx]) y_scores = lr.predict_proba(X[test_idx])[:, 1] roc_auc = roc_auc_score(y[test_idx], y_scores)",
"positive class comes first in the list, and the negative class comes second,",
"from sklearn.metrics import average_precision_score, auc, roc_auc_score from sklearn.metrics import precision_recall_curve from sklearn.linear_model import",
"matplotlib.pyplot as plt import matplotlib from IPython.display import display, HTML matplotlib.style.use('../../src/roam.mplstyle') def generate_data_and_constant_predictions(n,",
"0 make the task more challenging. Returns ------- y : np.array (n_test, )",
"copy from collections import OrderedDict import numpy as np import pandas as pd",
": np.array (n_samples, ) \"\"\" cov = generate_positive_semi_definite_matrix(n_dim) X = np.random.multivariate_normal( mean=np.zeros(n_dim), cov=cov,",
"list Precision. r : recall Recall. kwargs : optional See plot_axes. Returns -------",
"regression model. Parameters ---------- n_dim : int Number of dimensions for the training",
"against the same true observations. Parameters ---------- true : list score_dict : dict",
"the test set. y_scores : np.array (n_test, ) Model predictions of the test",
"n_negative = n - n_positive observations = [1 for _ in range(n_positive)] +",
"model that predicts 0.5 for all examples. Parameters ---------- n : int Number",
"curve. Parameters ---------- true : list Must be binary (i.e. 1s and 0s).",
"import StratifiedShuffleSplit import matplotlib.pyplot as plt import matplotlib from IPython.display import display, HTML",
"n_samples=10000, frac_positive=0.05, mixing_factor=0.025): \"\"\" Generates some data and trains a logistic regression model.",
"examples frac_positive : float Fraction of the examples that are positive Returns -------",
"some observations and scores assigned to them, and plots a precision-recall curve. Parameters",
"from sklearn.metrics import precision_recall_curve from sklearn.linear_model import LogisticRegressionCV from sklearn.cross_validation import StratifiedShuffleSplit import",
"positive and negative. Returns ------- precision : float recall : float \"\"\" if",
"pr_dict : dict Consisting of `{name: pr}` where `name` is a string and",
"a positive and negative class, where the positive class comes first in the",
"set. y_scores : np.array (n_test, ) Model predictions of the test samples. roc_auc",
"interpolation=None, marker_size=30, title=None, legend_text='Area'): \"\"\" Plots a graph on axes provided. Parameters ----------",
"graph on axes provided. Parameters ---------- ax : matplotlib axes y : list",
"recall from an ordered list of observations. Parameters ---------- ranking : list Entries",
"r, threshold = precision_recall_curve(true, score) pr[name] = [p, r] compare_recall_precision_graph(pr, **kwargs) def compare_recall_precision_graph(pr_dict,",
"y, frac_positive): \"\"\" Subsamples a feature matrix and target vector to ensure that",
"the rows of the input y (i.e. n' <= n) \"\"\" positive_idx =",
"(frac_positive * n)) 0s constant_predictions : list Same length as observations \"\"\" n_positive",
"from sklearn.cross_validation import StratifiedShuffleSplit import matplotlib.pyplot as plt import matplotlib from IPython.display import",
"def subsample(X, y, frac_positive): \"\"\" Subsamples a feature matrix and target vector to",
"scores assigned to them, and plots a precision-recall curve. Parameters ---------- true :",
"ordered list of observations. Parameters ---------- ranking : list Entries should be binary",
"(i.e. top-ranked is first). Returns ------- precision : list recall : list \"\"\"",
"and the split point is specified. Parameters ---------- ranking : list Ordered list",
"m) y : np.array (n, ) frac_positive : float Returns ------- X :",
"**kwargs): \"\"\" Parameters ---------- pr_dict : dict Consisting of `{name: pr}` where `name`",
"input X (i.e. n' <= n) y : np.array (n', ) Some subset",
"input y (i.e. n' <= n) \"\"\" positive_idx = np.arange(len(y))[y == 1] negative_idx",
"values. title : string kwargs : optional See plot_axes. \"\"\" fig, ax =",
"Generates a multivariate Gaussian-distributed dataset and a response variable that is conditioned on",
"n_dim) y : np.array (n_samples, ) \"\"\" cov = generate_positive_semi_definite_matrix(n_dim) X = np.random.multivariate_normal(",
": np.array (n_test, ) Model predictions of the test samples. roc_auc : float",
"constant_predictions = [0.5 for _ in range(n_positive + n_negative)] return observations, constant_predictions def",
"title is not None: ax.set_title(title, fontsize=20) if interpolation is not None: if interpolation",
"response variable that is conditioned on a weighted sum of the data. Parameters",
"[0, -1]], [y[i] for i in [0, -1]], marker='x', linewidths=2, s=100, clip_on=False) ax.set_xlim((-0.05,",
"the precision and recall of a particular assignment of labelled observations to a",
"'{}' not recognised. \" \"Choose from 'linear', 'quadrature'.\".format(interpolation)) def compare_recall_precisions_from_predictions(true, score_dict, **kwargs): \"\"\"",
": np.array (n', ) Some subset of the rows of the input y",
"p, r, title=name, legend_text='IAP', **kwargs) if title is not None: fig.suptitle(title, fontsize=20, y=1.05)",
"= np.random.randn(n_dim) y_probs = sigmoid(mixing_factor * np.dot(X, weights)) y = np.random.binomial(1, p=y_probs) X,",
"1 / (1 + np.exp(-x)) def train_model_and_evaluate(n_dim=50, n_samples=10000, frac_positive=0.05, mixing_factor=0.025): \"\"\" Generates some",
"not None: ax.set_title(title, fontsize=20) if interpolation is not None: if interpolation == 'linear':",
"compare_recall_precision_graph(pr, **kwargs) def compare_recall_precision_graph(pr_dict, title=None, **kwargs): \"\"\" Parameters ---------- pr_dict : dict Consisting",
"where `name` is a string and `scores` is a list of floats. kwargs",
"sample_weight=sample_weight) return auc_using_step(recall, precision) def generate_positive_semi_definite_matrix(n_dim): \"\"\" Creates a positive semi-definite matrix. Parameters",
"Returns ------- sigmoid(x) : float \"\"\" return 1 / (1 + np.exp(-x)) def",
": optional See plot_axes. \"\"\" fig, ax = plt.subplots(1, 2, figsize=(15, 4)) for",
"num_positive = int(frac_positive * len(negative_idx)) positive_idx = np.random.choice(positive_idx, size=num_positive, replace=False) indices_to_use = np.concatenate([positive_idx,",
"(n_test, ) True observed values in the test set. y_scores : np.array (n_test,",
"[0 for _ in range(n_negative)] constant_predictions = [0.5 for _ in range(n_positive +",
"are positive Returns ------- observations : list Consisting of (frac_positive * n) 1s,",
"scores from a dummy model that predicts 0.5 for all examples. Parameters ----------",
"auc, roc_auc_score from sklearn.metrics import precision_recall_curve from sklearn.linear_model import LogisticRegressionCV from sklearn.cross_validation import",
": float Fraction of the examples that are positive Returns ------- observations :",
"to them, and plots a precision-recall curve. Parameters ---------- true : list Must",
"print(\"Interpolation value of '{}' not recognised. \" \"Choose from 'linear', 'quadrature'.\".format(interpolation)) def compare_recall_precisions_from_predictions(true,",
"Parameters ---------- pr_dict : dict Consisting of `{name: pr}` where `name` is a",
"that is conditioned on a weighted sum of the data. Parameters ---------- n_dim",
"more challenging. Returns ------- y : np.array (n_test, ) True observed values in",
"---------- true : list score_dict : dict Consisting of `{name: scores}` where `name`",
"y[train_idx]) y_scores = lr.predict_proba(X[test_idx])[:, 1] roc_auc = roc_auc_score(y[test_idx], y_scores) return y[test_idx], y_scores, roc_auc",
"return precision, recall def precision_recall_from_ranking(ranking, position): \"\"\" Computes the precision and recall of",
"0: precision = 1.0 recall = 0.0 else: ranking = np.array(ranking) precision =",
"== 1).sum() / position recall = (ranking[:position] == 1).sum() / (ranking == 1).sum()",
"all examples. Parameters ---------- n : int Number of examples frac_positive : float",
"recall.append(r) return precision, recall def precision_recall_from_ranking(ranking, position): \"\"\" Computes the precision and recall",
"= subsample(X, y, frac_positive) return X, y def sigmoid(x): \"\"\" Computes sigmoid(x) for",
"operating_points(ranking): \"\"\" Computes lists of precision and recall from an ordered list of",
"StratifiedShuffleSplit(y, test_size=0.3, random_state=42) train_idx, test_idx = list(splits)[0] lr = LogisticRegressionCV() lr.fit(X[train_idx], y[train_idx]) y_scores",
"def roam_average_precision(y_true, y_score, sample_weight=None): precision, recall, thresholds = precision_recall_curve( y_true, y_score, sample_weight=sample_weight) return",
"Entries should be binary (0 or 1) and in descending order (i.e. top-ranked",
"precision_recall_curve(true, score) pr[name] = [p, r] compare_recall_precision_graph(pr, **kwargs) def compare_recall_precision_graph(pr_dict, title=None, **kwargs): \"\"\"",
": int Number of observations. frac_positive : float mixing_factor : float Numbers nearer",
"from IPython.display import display, HTML matplotlib.style.use('../../src/roam.mplstyle') def generate_data_and_constant_predictions(n, frac_positive): \"\"\" Generates data in",
"of precision and recall values. title : string kwargs : optional See plot_axes.",
"kwargs : optional See plot_axes. \"\"\" fig, ax = plt.subplots(1, 2, figsize=(15, 4))",
"'quadrature'.\".format(interpolation)) def compare_recall_precisions_from_predictions(true, score_dict, **kwargs): \"\"\" Show two graphs side-by-side for two different",
"alpha=0.2, label='{} = {:5.4f}'.format(legend_text, area)) leg = ax.legend() leg.get_frame().set_linewidth(0.0) elif interpolation == 'step':",
"the data. Parameters ---------- n_dim : int n_samples : int mixing_factor : float",
"range(n_positive)] + \\ [0 for _ in range(n_negative)] constant_predictions = [0.5 for _",
": float 'Squashes' the weighted sum into the linear regime of a sigmoid.",
"to 0.5. Returns ------- X : np.array (n_samples, n_dim) y : np.array (n_samples,",
"area)) leg = ax.legend() leg.get_frame().set_linewidth(0.0) else: print(\"Interpolation value of '{}' not recognised. \"",
"0s constant_predictions : list Same length as observations \"\"\" n_positive = int(frac_positive *",
"None: if interpolation == 'linear': ax.plot(x, y) area = auc(x, y) ax.fill_between(x, 0,",
"figsize=(7, 4)) plot_axes(ax, p, r, legend_text='IAP', **kwargs) plt.show() def plot_axes( ax, y, x,",
"ax.plot(x, y) area = auc(x, y) ax.fill_between(x, 0, y, alpha=0.2, label='{} = {:5.4f}'.format(legend_text,",
"side, (name, [p, r]) in enumerate(pr_dict.items()): plot_axes(ax[side], p, r, title=name, legend_text='IAP', **kwargs) if",
"np.arange(len(y))[y == 0] num_positive = int(frac_positive * len(negative_idx)) positive_idx = np.random.choice(positive_idx, size=num_positive, replace=False)",
"* np.dot(X, weights)) y = np.random.binomial(1, p=y_probs) X, y = subsample(X, y, frac_positive)",
"sklearn.metrics import average_precision_score, auc, roc_auc_score from sklearn.metrics import precision_recall_curve from sklearn.linear_model import LogisticRegressionCV",
"a logistic regression model. Parameters ---------- n_dim : int Number of dimensions for",
"`{name: scores}` where `name` is a string and `scores` is a list of",
"in (0, 1)][:-1] r_long = [v for v in x for _ in",
"is not None. \"\"\" ax.scatter(x, y, marker='o', linewidths=0, s=marker_size, clip_on=False) # Show first",
"first and last points more visably ax.scatter([x[i] for i in [0, -1]], [y[i]",
"in x for _ in (0, 1)][1:] ax.plot(r_long, p_long) area = auc_using_step(x, y)",
"visably ax.scatter([x[i] for i in [0, -1]], [y[i] for i in [0, -1]],",
"mixing_factor : float Numbers nearer to 0 make the task more challenging. Returns",
"two graphs side-by-side for two different sets of scores, against the same true",
"n_samples=n_samples, frac_positive=frac_positive, mixing_factor=mixing_factor) splits = StratifiedShuffleSplit(y, test_size=0.3, random_state=42) train_idx, test_idx = list(splits)[0] lr",
"average_precision_score, auc, roc_auc_score from sklearn.metrics import precision_recall_curve from sklearn.linear_model import LogisticRegressionCV from sklearn.cross_validation",
"as observations \"\"\" n_positive = int(frac_positive * n) n_negative = n - n_positive",
"np.dot(X, weights)) y = np.random.binomial(1, p=y_probs) X, y = subsample(X, y, frac_positive) return",
"or 1) and in descending order (i.e. top-ranked is first). Returns ------- precision",
"precision = (ranking[:position] == 1).sum() / position recall = (ranking[:position] == 1).sum() /",
"mixing_factor : float 'Squashes' the weighted sum into the linear regime of a",
"sigmoid(mixing_factor * np.dot(X, weights)) y = np.random.binomial(1, p=y_probs) X, y = subsample(X, y,",
"* len(negative_idx)) positive_idx = np.random.choice(positive_idx, size=num_positive, replace=False) indices_to_use = np.concatenate([positive_idx, negative_idx]) np.random.shuffle(indices_to_use) return",
"test_idx = list(splits)[0] lr = LogisticRegressionCV() lr.fit(X[train_idx], y[train_idx]) y_scores = lr.predict_proba(X[test_idx])[:, 1] roc_auc",
"and (n - (frac_positive * n)) 0s constant_predictions : list Same length as",
"of precision and recall from an ordered list of observations. Parameters ---------- ranking",
"observations. Parameters ---------- ranking : list Entries should be binary (0 or 1)",
": float (default: 30) title : None or string legend_text : string (default:",
"Plots a graph on axes provided. Parameters ---------- ax : matplotlib axes y",
"Computes the precision and recall of a particular assignment of labelled observations to",
"legend_text='IAP', **kwargs) if title is not None: fig.suptitle(title, fontsize=20, y=1.05) plt.show() def operating_points(ranking):",
"precision-recall graph from a series of operating points. Parameters ---------- p : list",
"= {:5.4f}'.format(legend_text, area)) leg = ax.legend() leg.get_frame().set_linewidth(0.0) elif interpolation == 'step': p_long =",
"that predicts 0.5 for all examples. Parameters ---------- n : int Number of",
"Number of examples frac_positive : float Fraction of the examples that are positive",
"numpy as np import pandas as pd from sklearn.metrics import average_precision_score, auc, roc_auc_score",
"list Consisting of (frac_positive * n) 1s, and (n - (frac_positive * n))",
"interpolation == 'linear': ax.plot(x, y) area = auc(x, y) ax.fill_between(x, 0, y, alpha=0.2,",
"range(n_negative)] constant_predictions = [0.5 for _ in range(n_positive + n_negative)] return observations, constant_predictions",
"'step': p_long = [v for v in y for _ in (0, 1)][:-1]",
"= precision_recall_curve(true, scores) plot_recall_precision(p, r, **kwargs) def plot_recall_precision(p, r, **kwargs): \"\"\" Plots a",
"auc_using_step(x, y) ax.fill_between(r_long, 0, p_long, alpha=0.2, label='{} = {:5.4f}'.format(legend_text, area)) leg = ax.legend()",
"(ranking[:position] == 1).sum() / position recall = (ranking[:position] == 1).sum() / (ranking ==",
"== 1] negative_idx = np.arange(len(y))[y == 0] num_positive = int(frac_positive * len(negative_idx)) positive_idx",
"weighted sum into the linear regime of a sigmoid. Smaller numbers squash closer",
"Computes precision and recall from some observations and scores assigned to them, and",
"them, and plots a precision-recall curve. Parameters ---------- true : list Must be",
"for name, score in score_dict.items(): p, r, threshold = precision_recall_curve(true, score) pr[name] =",
"n)) 0s constant_predictions : list Same length as observations \"\"\" n_positive = int(frac_positive",
"import matplotlib.pyplot as plt import matplotlib from IPython.display import display, HTML matplotlib.style.use('../../src/roam.mplstyle') def",
"series of operating points. Parameters ---------- p : list Precision. r : recall",
"recall of a particular assignment of labelled observations to a positive and negative",
"list into positive and negative. Returns ------- precision : float recall : float",
"recall def auc_using_step(recall, precision): return sum([(recall[i] - recall[i+1]) * precision[i] for i in",
"X, y def sigmoid(x): \"\"\" Computes sigmoid(x) for some activation x. Parameters ----------",
"y, x, interpolation=None, marker_size=30, title=None, legend_text='Area'): \"\"\" Plots a graph on axes provided.",
"test set. y_scores : np.array (n_test, ) Model predictions of the test samples.",
"int(frac_positive * len(negative_idx)) positive_idx = np.random.choice(positive_idx, size=num_positive, replace=False) indices_to_use = np.concatenate([positive_idx, negative_idx]) np.random.shuffle(indices_to_use)",
"in (0, 1)][1:] ax.plot(r_long, p_long) area = auc_using_step(x, y) ax.fill_between(r_long, 0, p_long, alpha=0.2,",
"int mixing_factor : float 'Squashes' the weighted sum into the linear regime of",
"np.random.shuffle(indices_to_use) return X[indices_to_use], y[indices_to_use] def generate_continuous_data_and_targets( n_dim, n_samples, mixing_factor=0.025, frac_positive=0.1): \"\"\" Generates a",
"(name, [p, r]) in enumerate(pr_dict.items()): plot_axes(ax[side], p, r, title=name, legend_text='IAP', **kwargs) if title",
"is a string and `scores` is a list of floats. kwargs : optional",
"linewidths=0, s=marker_size, clip_on=False) # Show first and last points more visably ax.scatter([x[i] for",
"------- np.array : (n_dim, n_dim) \"\"\" cov = np.random.randn(n_dim, n_dim) return np.dot(cov, cov.T)",
"1)][1:] ax.plot(r_long, p_long) area = auc_using_step(x, y) ax.fill_between(r_long, 0, p_long, alpha=0.2, label='{} =",
"Parameters ---------- p : list Precision. r : recall Recall. kwargs : optional",
"a graph on axes provided. Parameters ---------- ax : matplotlib axes y :",
"\"\"\" pr = OrderedDict() for name, score in score_dict.items(): p, r, threshold =",
"1.08)) ax.set_xlabel('Recall') ax.set_ylabel('Precision') if title is not None: ax.set_title(title, fontsize=20) if interpolation is",
"before showing the area. Only used if interpolation is not None. \"\"\" ax.scatter(x,",
"linewidths=2, s=100, clip_on=False) ax.set_xlim((-0.05, 1.05)) ax.set_ylim((-0.08, 1.08)) ax.set_xlabel('Recall') ax.set_ylabel('Precision') if title is not",
"is a tuple of precision and recall values. title : string kwargs :",
"plt.subplots(1, 2, figsize=(15, 4)) for side, (name, [p, r]) in enumerate(pr_dict.items()): plot_axes(ax[side], p,",
"list \"\"\" precision, recall = list(), list() for pos in range(len(ranking)): p, r",
"list(), list() for pos in range(len(ranking)): p, r = precision_recall_from_ranking(ranking, pos) precision.append(p) recall.append(r)",
"of the input X (i.e. n' <= n) y : np.array (n', )",
"float Returns ------- sigmoid(x) : float \"\"\" return 1 / (1 + np.exp(-x))",
"def train_model_and_evaluate(n_dim=50, n_samples=10000, frac_positive=0.05, mixing_factor=0.025): \"\"\" Generates some data and trains a logistic",
"float Returns ------- X : np.array (n', m) Some subset of the rows",
"and a response variable that is conditioned on a weighted sum of the",
"plot_axes. Returns ------- \"\"\" fig, ax = plt.subplots(1, 1, figsize=(7, 4)) plot_axes(ax, p,",
"y) ax.fill_between(x, 0, y, alpha=0.2, label='{} = {:5.4f}'.format(legend_text, area)) leg = ax.legend() leg.get_frame().set_linewidth(0.0)",
"of a particular assignment of labelled observations to a positive and negative class,",
": np.array (n, ) frac_positive : float Returns ------- X : np.array (n',",
"return X[indices_to_use], y[indices_to_use] def generate_continuous_data_and_targets( n_dim, n_samples, mixing_factor=0.025, frac_positive=0.1): \"\"\" Generates a multivariate",
"cov=cov, size=n_samples) weights = np.random.randn(n_dim) y_probs = sigmoid(mixing_factor * np.dot(X, weights)) y =",
"= int(frac_positive * n) n_negative = n - n_positive observations = [1 for",
"true : list Must be binary (i.e. 1s and 0s). scores : list",
"a precision-recall curve. Parameters ---------- true : list Must be binary (i.e. 1s",
"of the target values are positive. Parameters ---------- X : np.array (n, m)",
"for two different sets of scores, against the same true observations. Parameters ----------",
"dataset and a response variable that is conditioned on a weighted sum of",
"sigmoid(x) : float \"\"\" return 1 / (1 + np.exp(-x)) def train_model_and_evaluate(n_dim=50, n_samples=10000,",
"dict Consisting of `{name: scores}` where `name` is a string and `scores` is",
"[v for v in y for _ in (0, 1)][:-1] r_long = [v",
"r, **kwargs): \"\"\" Plots a precision-recall graph from a series of operating points.",
"positive. Parameters ---------- X : np.array (n, m) y : np.array (n, )",
"/ position recall = (ranking[:position] == 1).sum() / (ranking == 1).sum() return precision,",
"Some subset of the rows of the input X (i.e. n' <= n)",
"Number of observations. frac_positive : float mixing_factor : float Numbers nearer to 0",
"lr.fit(X[train_idx], y[train_idx]) y_scores = lr.predict_proba(X[test_idx])[:, 1] roc_auc = roc_auc_score(y[test_idx], y_scores) return y[test_idx], y_scores,",
"include on the legend before showing the area. Only used if interpolation is",
"p, r = precision_recall_from_ranking(ranking, pos) precision.append(p) recall.append(r) return precision, recall def precision_recall_from_ranking(ranking, position):",
"\"\"\" fig, ax = plt.subplots(1, 1, figsize=(7, 4)) plot_axes(ax, p, r, legend_text='IAP', **kwargs)",
"_ in range(n_positive)] + \\ [0 for _ in range(n_negative)] constant_predictions = [0.5",
"== 'step': p_long = [v for v in y for _ in (0,",
"some data and trains a logistic regression model. Parameters ---------- n_dim : int",
"plt.subplots(1, 1, figsize=(7, 4)) plot_axes(ax, p, r, legend_text='IAP', **kwargs) plt.show() def plot_axes( ax,",
"the examples that are positive Returns ------- observations : list Consisting of (frac_positive",
"showing the area. Only used if interpolation is not None. \"\"\" ax.scatter(x, y,",
"precision-recall curve. Parameters ---------- true : list Must be binary (i.e. 1s and",
"if interpolation is not None: if interpolation == 'linear': ax.plot(x, y) area =",
"constant_predictions : list Same length as observations \"\"\" n_positive = int(frac_positive * n)",
"list of binary observations. position : int Position to split the list into",
"Computes sigmoid(x) for some activation x. Parameters ---------- x : float Returns -------",
"train_idx, test_idx = list(splits)[0] lr = LogisticRegressionCV() lr.fit(X[train_idx], y[train_idx]) y_scores = lr.predict_proba(X[test_idx])[:, 1]",
"precision, recall def precision_recall_from_ranking(ranking, position): \"\"\" Computes the precision and recall of a",
"precision_recall_curve(true, scores) plot_recall_precision(p, r, **kwargs) def plot_recall_precision(p, r, **kwargs): \"\"\" Plots a precision-recall",
"auc_using_step(recall, precision) def generate_positive_semi_definite_matrix(n_dim): \"\"\" Creates a positive semi-definite matrix. Parameters ---------- n_dim",
"[1 for _ in range(n_positive)] + \\ [0 for _ in range(n_negative)] constant_predictions",
"string (default: 'Area') Text to include on the legend before showing the area.",
"area)) leg = ax.legend() leg.get_frame().set_linewidth(0.0) elif interpolation == 'step': p_long = [v for",
"x : list interpolation : None (default) or string ['linear', 'step'] marker_size :",
"def plot_recall_precision(p, r, **kwargs): \"\"\" Plots a precision-recall graph from a series of",
"of floats. kwargs : optional See plot_axes. \"\"\" p, r, thresholds = precision_recall_curve(true,",
"returns the data and scores from a dummy model that predicts 0.5 for",
"StratifiedShuffleSplit import matplotlib.pyplot as plt import matplotlib from IPython.display import display, HTML matplotlib.style.use('../../src/roam.mplstyle')",
": list interpolation : None (default) or string ['linear', 'step'] marker_size : float",
"score_dict : dict Consisting of `{name: scores}` where `name` is a string and",
"used if interpolation is not None. \"\"\" ax.scatter(x, y, marker='o', linewidths=0, s=marker_size, clip_on=False)",
"feature matrix and target vector to ensure that a specified fraction of the",
"= generate_positive_semi_definite_matrix(n_dim) X = np.random.multivariate_normal( mean=np.zeros(n_dim), cov=cov, size=n_samples) weights = np.random.randn(n_dim) y_probs =",
"a feature matrix and target vector to ensure that a specified fraction of",
"is conditioned on a weighted sum of the data. Parameters ---------- n_dim :",
": optional See plot_axes. \"\"\" pr = OrderedDict() for name, score in score_dict.items():",
"if title is not None: ax.set_title(title, fontsize=20) if interpolation is not None: if",
"to ensure that a specified fraction of the target values are positive. Parameters",
"Parameters ---------- ax : matplotlib axes y : list x : list interpolation",
"or string legend_text : string (default: 'Area') Text to include on the legend",
"X, y = subsample(X, y, frac_positive) return X, y def sigmoid(x): \"\"\" Computes",
"ax.scatter(x, y, marker='o', linewidths=0, s=marker_size, clip_on=False) # Show first and last points more",
"------- precision : list recall : list \"\"\" precision, recall = list(), list()",
"the input y (i.e. n' <= n) \"\"\" positive_idx = np.arange(len(y))[y == 1]",
"from some observations and scores assigned to them, and plots a precision-recall curve.",
"_ in (0, 1)][:-1] r_long = [v for v in x for _",
"'Squashes' the weighted sum into the linear regime of a sigmoid. Smaller numbers",
"samples. roc_auc : float ROC AUC score on the test data \"\"\" X,",
"data in a fixed positive:negative ratio, and returns the data and scores from",
"frac_positive=0.1): \"\"\" Generates a multivariate Gaussian-distributed dataset and a response variable that is",
"= [1 for _ in range(n_positive)] + \\ [0 for _ in range(n_negative)]",
"the data and scores from a dummy model that predicts 0.5 for all",
"Same length as observations \"\"\" n_positive = int(frac_positive * n) n_negative = n",
"not None. \"\"\" ax.scatter(x, y, marker='o', linewidths=0, s=marker_size, clip_on=False) # Show first and",
"= [p, r] compare_recall_precision_graph(pr, **kwargs) def compare_recall_precision_graph(pr_dict, title=None, **kwargs): \"\"\" Parameters ---------- pr_dict",
"precision : float recall : float \"\"\" if position == 0: precision =",
"n_positive observations = [1 for _ in range(n_positive)] + \\ [0 for _",
"y : np.array (n_test, ) True observed values in the test set. y_scores",
"order (i.e. top-ranked is first). Returns ------- precision : list recall : list",
"= precision_recall_curve(true, score) pr[name] = [p, r] compare_recall_precision_graph(pr, **kwargs) def compare_recall_precision_graph(pr_dict, title=None, **kwargs):",
"Returns ------- observations : list Consisting of (frac_positive * n) 1s, and (n",
"See plot_axes. \"\"\" pr = OrderedDict() for name, score in score_dict.items(): p, r,",
"be binary (0 or 1) and in descending order (i.e. top-ranked is first).",
"1s, and (n - (frac_positive * n)) 0s constant_predictions : list Same length",
"precision[i] for i in range(len(recall) - 1)]) def roam_average_precision(y_true, y_score, sample_weight=None): precision, recall,",
"model. Parameters ---------- n_dim : int Number of dimensions for the training data.",
": float \"\"\" if position == 0: precision = 1.0 recall = 0.0",
"n) y : np.array (n', ) Some subset of the rows of the",
"---------- true : list Must be binary (i.e. 1s and 0s). scores :",
"None. \"\"\" ax.scatter(x, y, marker='o', linewidths=0, s=marker_size, clip_on=False) # Show first and last",
"1.05)) ax.set_ylim((-0.08, 1.08)) ax.set_xlabel('Recall') ax.set_ylabel('Precision') if title is not None: ax.set_title(title, fontsize=20) if",
"area = auc_using_step(x, y) ax.fill_between(r_long, 0, p_long, alpha=0.2, label='{} = {:5.4f}'.format(legend_text, area)) leg",
"Parameters ---------- true : list score_dict : dict Consisting of `{name: scores}` where",
"enumerate(pr_dict.items()): plot_axes(ax[side], p, r, title=name, legend_text='IAP', **kwargs) if title is not None: fig.suptitle(title,",
": dict Consisting of `{name: scores}` where `name` is a string and `scores`",
"\"\"\" Generates data in a fixed positive:negative ratio, and returns the data and",
"of scores, against the same true observations. Parameters ---------- true : list score_dict",
"Consisting of (frac_positive * n) 1s, and (n - (frac_positive * n)) 0s",
"ax.set_ylabel('Precision') if title is not None: ax.set_title(title, fontsize=20) if interpolation is not None:",
"interpolation == 'step': p_long = [v for v in y for _ in",
"collections import OrderedDict import numpy as np import pandas as pd from sklearn.metrics",
"of `{name: pr}` where `name` is a string and `pr` is a tuple",
"as plt import matplotlib from IPython.display import display, HTML matplotlib.style.use('../../src/roam.mplstyle') def generate_data_and_constant_predictions(n, frac_positive):",
"int(frac_positive * n) n_negative = n - n_positive observations = [1 for _",
"for i in [0, -1]], marker='x', linewidths=2, s=100, clip_on=False) ax.set_xlim((-0.05, 1.05)) ax.set_ylim((-0.08, 1.08))",
"is a string and `pr` is a tuple of precision and recall values.",
"compare_recall_precisions_from_predictions(true, score_dict, **kwargs): \"\"\" Show two graphs side-by-side for two different sets of",
"title=name, legend_text='IAP', **kwargs) if title is not None: fig.suptitle(title, fontsize=20, y=1.05) plt.show() def",
"Ordered list of binary observations. position : int Position to split the list",
"1)]) def roam_average_precision(y_true, y_score, sample_weight=None): precision, recall, thresholds = precision_recall_curve( y_true, y_score, sample_weight=sample_weight)",
"roam_average_precision(y_true, y_score, sample_weight=None): precision, recall, thresholds = precision_recall_curve( y_true, y_score, sample_weight=sample_weight) return auc_using_step(recall,",
"<= n) \"\"\" positive_idx = np.arange(len(y))[y == 1] negative_idx = np.arange(len(y))[y == 0]",
"True observed values in the test set. y_scores : np.array (n_test, ) Model",
"= plt.subplots(1, 2, figsize=(15, 4)) for side, (name, [p, r]) in enumerate(pr_dict.items()): plot_axes(ax[side],",
"a weighted sum of the data. Parameters ---------- n_dim : int n_samples :",
": dict Consisting of `{name: pr}` where `name` is a string and `pr`",
"None: ax.set_title(title, fontsize=20) if interpolation is not None: if interpolation == 'linear': ax.plot(x,",
"sample_weight=None): precision, recall, thresholds = precision_recall_curve( y_true, y_score, sample_weight=sample_weight) return auc_using_step(recall, precision) def",
"matplotlib.style.use('../../src/roam.mplstyle') def generate_data_and_constant_predictions(n, frac_positive): \"\"\" Generates data in a fixed positive:negative ratio, and",
"title=None, **kwargs): \"\"\" Parameters ---------- pr_dict : dict Consisting of `{name: pr}` where",
"else: ranking = np.array(ranking) precision = (ranking[:position] == 1).sum() / position recall =",
"recognised. \" \"Choose from 'linear', 'quadrature'.\".format(interpolation)) def compare_recall_precisions_from_predictions(true, score_dict, **kwargs): \"\"\" Show two",
"\"\"\" return 1 / (1 + np.exp(-x)) def train_model_and_evaluate(n_dim=50, n_samples=10000, frac_positive=0.05, mixing_factor=0.025): \"\"\"",
"a dummy model that predicts 0.5 for all examples. Parameters ---------- n :",
"title=None, legend_text='Area'): \"\"\" Plots a graph on axes provided. Parameters ---------- ax :",
"**kwargs) def plot_recall_precision(p, r, **kwargs): \"\"\" Plots a precision-recall graph from a series",
"recall[i+1]) * precision[i] for i in range(len(recall) - 1)]) def roam_average_precision(y_true, y_score, sample_weight=None):",
"\"\"\" positive_idx = np.arange(len(y))[y == 1] negative_idx = np.arange(len(y))[y == 0] num_positive =",
"from collections import OrderedDict import numpy as np import pandas as pd from",
"* n) 1s, and (n - (frac_positive * n)) 0s constant_predictions : list",
"return sum([(recall[i] - recall[i+1]) * precision[i] for i in range(len(recall) - 1)]) def",
"marker_size : float (default: 30) title : None or string legend_text : string",
"generate_continuous_data_and_targets( n_dim=n_dim, n_samples=n_samples, frac_positive=frac_positive, mixing_factor=mixing_factor) splits = StratifiedShuffleSplit(y, test_size=0.3, random_state=42) train_idx, test_idx =",
"range(n_positive + n_negative)] return observations, constant_predictions def plot_recall_precision_from_predictions(true, scores, **kwargs): \"\"\" Computes precision",
"sum([(recall[i] - recall[i+1]) * precision[i] for i in range(len(recall) - 1)]) def roam_average_precision(y_true,",
"ax.set_ylim((-0.08, 1.08)) ax.set_xlabel('Recall') ax.set_ylabel('Precision') if title is not None: ax.set_title(title, fontsize=20) if interpolation",
"= auc(x, y) ax.fill_between(x, 0, y, alpha=0.2, label='{} = {:5.4f}'.format(legend_text, area)) leg =",
"list Consisting of floats. kwargs : optional See plot_axes. \"\"\" p, r, thresholds",
"recall Recall. kwargs : optional See plot_axes. Returns ------- \"\"\" fig, ax =",
"binary observations. position : int Position to split the list into positive and",
"frac_positive : float Returns ------- X : np.array (n', m) Some subset of",
"and trains a logistic regression model. Parameters ---------- n_dim : int Number of",
"dimensions for the training data. n_samples : int Number of observations. frac_positive :",
"sklearn.linear_model import LogisticRegressionCV from sklearn.cross_validation import StratifiedShuffleSplit import matplotlib.pyplot as plt import matplotlib",
"kwargs : optional See plot_axes. \"\"\" p, r, thresholds = precision_recall_curve(true, scores) plot_recall_precision(p,",
"in enumerate(pr_dict.items()): plot_axes(ax[side], p, r, title=name, legend_text='IAP', **kwargs) if title is not None:",
"= plt.subplots(1, 1, figsize=(7, 4)) plot_axes(ax, p, r, legend_text='IAP', **kwargs) plt.show() def plot_axes(",
"X (i.e. n' <= n) y : np.array (n', ) Some subset of",
"plot_axes(ax[side], p, r, title=name, legend_text='IAP', **kwargs) if title is not None: fig.suptitle(title, fontsize=20,",
"plot_axes. \"\"\" fig, ax = plt.subplots(1, 2, figsize=(15, 4)) for side, (name, [p,",
": list recall : list \"\"\" precision, recall = list(), list() for pos",
"Position to split the list into positive and negative. Returns ------- precision :",
"and negative. Returns ------- precision : float recall : float \"\"\" if position",
"pr[name] = [p, r] compare_recall_precision_graph(pr, **kwargs) def compare_recall_precision_graph(pr_dict, title=None, **kwargs): \"\"\" Parameters ----------",
"dummy model that predicts 0.5 for all examples. Parameters ---------- n : int",
"class comes second, and the split point is specified. Parameters ---------- ranking :",
"n_dim) return np.dot(cov, cov.T) def subsample(X, y, frac_positive): \"\"\" Subsamples a feature matrix",
"positive_idx = np.arange(len(y))[y == 1] negative_idx = np.arange(len(y))[y == 0] num_positive = int(frac_positive",
"Number of dimensions for the training data. n_samples : int Number of observations.",
"30) title : None or string legend_text : string (default: 'Area') Text to",
"is a list of floats. kwargs : optional See plot_axes. \"\"\" pr =",
"= auc_using_step(x, y) ax.fill_between(r_long, 0, p_long, alpha=0.2, label='{} = {:5.4f}'.format(legend_text, area)) leg =",
"weighted sum of the data. Parameters ---------- n_dim : int n_samples : int",
"def plot_axes( ax, y, x, interpolation=None, marker_size=30, title=None, legend_text='Area'): \"\"\" Plots a graph",
"y : list x : list interpolation : None (default) or string ['linear',",
"list of floats. kwargs : optional See plot_axes. \"\"\" pr = OrderedDict() for",
"(frac_positive * n) 1s, and (n - (frac_positive * n)) 0s constant_predictions :",
"specified. Parameters ---------- ranking : list Ordered list of binary observations. position :",
"return np.dot(cov, cov.T) def subsample(X, y, frac_positive): \"\"\" Subsamples a feature matrix and",
"= ax.legend() leg.get_frame().set_linewidth(0.0) elif interpolation == 'step': p_long = [v for v in",
"for i in range(len(recall) - 1)]) def roam_average_precision(y_true, y_score, sample_weight=None): precision, recall, thresholds",
"X : np.array (n', m) Some subset of the rows of the input",
"---------- ax : matplotlib axes y : list x : list interpolation :",
"frac_positive) return X, y def sigmoid(x): \"\"\" Computes sigmoid(x) for some activation x.",
") True observed values in the test set. y_scores : np.array (n_test, )",
"recall def precision_recall_from_ranking(ranking, position): \"\"\" Computes the precision and recall of a particular",
"Parameters ---------- ranking : list Ordered list of binary observations. position : int",
"= OrderedDict() for name, score in score_dict.items(): p, r, threshold = precision_recall_curve(true, score)",
"y : np.array (n', ) Some subset of the rows of the input",
"subset of the rows of the input X (i.e. n' <= n) y",
"n_negative)] return observations, constant_predictions def plot_recall_precision_from_predictions(true, scores, **kwargs): \"\"\" Computes precision and recall",
"+ np.exp(-x)) def train_model_and_evaluate(n_dim=50, n_samples=10000, frac_positive=0.05, mixing_factor=0.025): \"\"\" Generates some data and trains",
"ax.legend() leg.get_frame().set_linewidth(0.0) elif interpolation == 'step': p_long = [v for v in y",
"binary (i.e. 1s and 0s). scores : list Consisting of floats. kwargs :",
"------- X : np.array (n', m) Some subset of the rows of the",
"X = np.random.multivariate_normal( mean=np.zeros(n_dim), cov=cov, size=n_samples) weights = np.random.randn(n_dim) y_probs = sigmoid(mixing_factor *",
"weights)) y = np.random.binomial(1, p=y_probs) X, y = subsample(X, y, frac_positive) return X,",
"cov = generate_positive_semi_definite_matrix(n_dim) X = np.random.multivariate_normal( mean=np.zeros(n_dim), cov=cov, size=n_samples) weights = np.random.randn(n_dim) y_probs",
": optional See plot_axes. Returns ------- \"\"\" fig, ax = plt.subplots(1, 1, figsize=(7,",
"* precision[i] for i in range(len(recall) - 1)]) def roam_average_precision(y_true, y_score, sample_weight=None): precision,",
"in range(n_negative)] constant_predictions = [0.5 for _ in range(n_positive + n_negative)] return observations,",
"n_dim : int Returns ------- np.array : (n_dim, n_dim) \"\"\" cov = np.random.randn(n_dim,",
"r = precision_recall_from_ranking(ranking, pos) precision.append(p) recall.append(r) return precision, recall def precision_recall_from_ranking(ranking, position): \"\"\"",
"challenging. Returns ------- y : np.array (n_test, ) True observed values in the",
"(ranking[:position] == 1).sum() / (ranking == 1).sum() return precision, recall def auc_using_step(recall, precision):",
"not recognised. \" \"Choose from 'linear', 'quadrature'.\".format(interpolation)) def compare_recall_precisions_from_predictions(true, score_dict, **kwargs): \"\"\" Show",
"linear regime of a sigmoid. Smaller numbers squash closer to 0.5. Returns -------",
"= {:5.4f}'.format(legend_text, area)) leg = ax.legend() leg.get_frame().set_linewidth(0.0) else: print(\"Interpolation value of '{}' not",
"ax.set_title(title, fontsize=20) if interpolation is not None: if interpolation == 'linear': ax.plot(x, y)",
"different sets of scores, against the same true observations. Parameters ---------- true :",
"data \"\"\" X, y = generate_continuous_data_and_targets( n_dim=n_dim, n_samples=n_samples, frac_positive=frac_positive, mixing_factor=mixing_factor) splits = StratifiedShuffleSplit(y,",
"Consisting of `{name: scores}` where `name` is a string and `scores` is a",
"in descending order (i.e. top-ranked is first). Returns ------- precision : list recall",
"assigned to them, and plots a precision-recall curve. Parameters ---------- true : list",
"(default: 'Area') Text to include on the legend before showing the area. Only",
"semi-definite matrix. Parameters ---------- n_dim : int Returns ------- np.array : (n_dim, n_dim)",
"(n, m) y : np.array (n, ) frac_positive : float Returns ------- X",
"v in y for _ in (0, 1)][:-1] r_long = [v for v",
"mixing_factor=0.025, frac_positive=0.1): \"\"\" Generates a multivariate Gaussian-distributed dataset and a response variable that",
"OrderedDict() for name, score in score_dict.items(): p, r, threshold = precision_recall_curve(true, score) pr[name]",
"\"\"\" Generates some data and trains a logistic regression model. Parameters ---------- n_dim",
"plot_axes(ax, p, r, legend_text='IAP', **kwargs) plt.show() def plot_axes( ax, y, x, interpolation=None, marker_size=30,",
"'linear': ax.plot(x, y) area = auc(x, y) ax.fill_between(x, 0, y, alpha=0.2, label='{} =",
"list of observations. Parameters ---------- ranking : list Entries should be binary (0",
"in the list, and the negative class comes second, and the split point",
"float \"\"\" return 1 / (1 + np.exp(-x)) def train_model_and_evaluate(n_dim=50, n_samples=10000, frac_positive=0.05, mixing_factor=0.025):",
"p : list Precision. r : recall Recall. kwargs : optional See plot_axes.",
"be binary (i.e. 1s and 0s). scores : list Consisting of floats. kwargs",
"v in x for _ in (0, 1)][1:] ax.plot(r_long, p_long) area = auc_using_step(x,",
"Parameters ---------- n_dim : int n_samples : int mixing_factor : float 'Squashes' the",
"split the list into positive and negative. Returns ------- precision : float recall",
"(0, 1)][:-1] r_long = [v for v in x for _ in (0,",
"if title is not None: fig.suptitle(title, fontsize=20, y=1.05) plt.show() def operating_points(ranking): \"\"\" Computes",
"test_size=0.3, random_state=42) train_idx, test_idx = list(splits)[0] lr = LogisticRegressionCV() lr.fit(X[train_idx], y[train_idx]) y_scores =",
"n_samples : int mixing_factor : float 'Squashes' the weighted sum into the linear",
"more visably ax.scatter([x[i] for i in [0, -1]], [y[i] for i in [0,",
"= sigmoid(mixing_factor * np.dot(X, weights)) y = np.random.binomial(1, p=y_probs) X, y = subsample(X,",
"roc_auc_score from sklearn.metrics import precision_recall_curve from sklearn.linear_model import LogisticRegressionCV from sklearn.cross_validation import StratifiedShuffleSplit",
": int Number of examples frac_positive : float Fraction of the examples that",
"ax.scatter([x[i] for i in [0, -1]], [y[i] for i in [0, -1]], marker='x',",
"of examples frac_positive : float Fraction of the examples that are positive Returns",
"split point is specified. Parameters ---------- ranking : list Ordered list of binary",
"data and scores from a dummy model that predicts 0.5 for all examples.",
"that a specified fraction of the target values are positive. Parameters ---------- X",
"from 'linear', 'quadrature'.\".format(interpolation)) def compare_recall_precisions_from_predictions(true, score_dict, **kwargs): \"\"\" Show two graphs side-by-side for",
"y_probs = sigmoid(mixing_factor * np.dot(X, weights)) y = np.random.binomial(1, p=y_probs) X, y =",
"graph from a series of operating points. Parameters ---------- p : list Precision.",
"X : np.array (n, m) y : np.array (n, ) frac_positive : float",
"ax = plt.subplots(1, 1, figsize=(7, 4)) plot_axes(ax, p, r, legend_text='IAP', **kwargs) plt.show() def",
": None or string legend_text : string (default: 'Area') Text to include on",
"ax.set_xlabel('Recall') ax.set_ylabel('Precision') if title is not None: ax.set_title(title, fontsize=20) if interpolation is not",
"---------- n_dim : int n_samples : int mixing_factor : float 'Squashes' the weighted",
"precision_recall_from_ranking(ranking, pos) precision.append(p) recall.append(r) return precision, recall def precision_recall_from_ranking(ranking, position): \"\"\" Computes the",
"is specified. Parameters ---------- ranking : list Ordered list of binary observations. position",
"area. Only used if interpolation is not None. \"\"\" ax.scatter(x, y, marker='o', linewidths=0,",
"auc(x, y) ax.fill_between(x, 0, y, alpha=0.2, label='{} = {:5.4f}'.format(legend_text, area)) leg = ax.legend()",
"in range(n_positive + n_negative)] return observations, constant_predictions def plot_recall_precision_from_predictions(true, scores, **kwargs): \"\"\" Computes",
": list Ordered list of binary observations. position : int Position to split",
"* n) n_negative = n - n_positive observations = [1 for _ in",
"pr = OrderedDict() for name, score in score_dict.items(): p, r, threshold = precision_recall_curve(true,",
"precision_recall_curve from sklearn.linear_model import LogisticRegressionCV from sklearn.cross_validation import StratifiedShuffleSplit import matplotlib.pyplot as plt",
"y, alpha=0.2, label='{} = {:5.4f}'.format(legend_text, area)) leg = ax.legend() leg.get_frame().set_linewidth(0.0) elif interpolation ==",
"precision, recall = list(), list() for pos in range(len(ranking)): p, r = precision_recall_from_ranking(ranking,",
"label='{} = {:5.4f}'.format(legend_text, area)) leg = ax.legend() leg.get_frame().set_linewidth(0.0) elif interpolation == 'step': p_long",
"1s and 0s). scores : list Consisting of floats. kwargs : optional See",
"from an ordered list of observations. Parameters ---------- ranking : list Entries should",
"observations, constant_predictions def plot_recall_precision_from_predictions(true, scores, **kwargs): \"\"\" Computes precision and recall from some",
"* n)) 0s constant_predictions : list Same length as observations \"\"\" n_positive =",
": string (default: 'Area') Text to include on the legend before showing the",
"Must be binary (i.e. 1s and 0s). scores : list Consisting of floats.",
"leg.get_frame().set_linewidth(0.0) elif interpolation == 'step': p_long = [v for v in y for",
"not None: fig.suptitle(title, fontsize=20, y=1.05) plt.show() def operating_points(ranking): \"\"\" Computes lists of precision",
"precision.append(p) recall.append(r) return precision, recall def precision_recall_from_ranking(ranking, position): \"\"\" Computes the precision and",
"recall = 0.0 else: ranking = np.array(ranking) precision = (ranking[:position] == 1).sum() /",
"Subsamples a feature matrix and target vector to ensure that a specified fraction",
"and in descending order (i.e. top-ranked is first). Returns ------- precision : list",
"list(splits)[0] lr = LogisticRegressionCV() lr.fit(X[train_idx], y[train_idx]) y_scores = lr.predict_proba(X[test_idx])[:, 1] roc_auc = roc_auc_score(y[test_idx],",
"Recall. kwargs : optional See plot_axes. Returns ------- \"\"\" fig, ax = plt.subplots(1,",
"score in score_dict.items(): p, r, threshold = precision_recall_curve(true, score) pr[name] = [p, r]",
"Parameters ---------- n_dim : int Returns ------- np.array : (n_dim, n_dim) \"\"\" cov",
"def sigmoid(x): \"\"\" Computes sigmoid(x) for some activation x. Parameters ---------- x :",
"\\ [0 for _ in range(n_negative)] constant_predictions = [0.5 for _ in range(n_positive",
"assignment of labelled observations to a positive and negative class, where the positive",
"\"\"\" Parameters ---------- pr_dict : dict Consisting of `{name: pr}` where `name` is",
"scores) plot_recall_precision(p, r, **kwargs) def plot_recall_precision(p, r, **kwargs): \"\"\" Plots a precision-recall graph",
"frac_positive : float mixing_factor : float Numbers nearer to 0 make the task",
"if interpolation == 'linear': ax.plot(x, y) area = auc(x, y) ax.fill_between(x, 0, y,",
"a precision-recall graph from a series of operating points. Parameters ---------- p :",
"\"\"\" Plots a precision-recall graph from a series of operating points. Parameters ----------",
"the negative class comes second, and the split point is specified. Parameters ----------",
"for _ in range(n_positive)] + \\ [0 for _ in range(n_negative)] constant_predictions =",
"a list of floats. kwargs : optional See plot_axes. \"\"\" pr = OrderedDict()",
"return X, y def sigmoid(x): \"\"\" Computes sigmoid(x) for some activation x. Parameters",
"int Number of examples frac_positive : float Fraction of the examples that are",
"---------- n : int Number of examples frac_positive : float Fraction of the",
"- recall[i+1]) * precision[i] for i in range(len(recall) - 1)]) def roam_average_precision(y_true, y_score,",
"conditioned on a weighted sum of the data. Parameters ---------- n_dim : int",
"n_dim : int n_samples : int mixing_factor : float 'Squashes' the weighted sum",
"threshold = precision_recall_curve(true, score) pr[name] = [p, r] compare_recall_precision_graph(pr, **kwargs) def compare_recall_precision_graph(pr_dict, title=None,",
"def generate_continuous_data_and_targets( n_dim, n_samples, mixing_factor=0.025, frac_positive=0.1): \"\"\" Generates a multivariate Gaussian-distributed dataset and",
"= np.array(ranking) precision = (ranking[:position] == 1).sum() / position recall = (ranking[:position] ==",
"0s). scores : list Consisting of floats. kwargs : optional See plot_axes. \"\"\"",
"for i in [0, -1]], [y[i] for i in [0, -1]], marker='x', linewidths=2,",
"x for _ in (0, 1)][1:] ax.plot(r_long, p_long) area = auc_using_step(x, y) ax.fill_between(r_long,",
"frac_positive): \"\"\" Generates data in a fixed positive:negative ratio, and returns the data",
"floats. kwargs : optional See plot_axes. \"\"\" p, r, thresholds = precision_recall_curve(true, scores)",
": matplotlib axes y : list x : list interpolation : None (default)",
"X : np.array (n_samples, n_dim) y : np.array (n_samples, ) \"\"\" cov =",
"= ax.legend() leg.get_frame().set_linewidth(0.0) else: print(\"Interpolation value of '{}' not recognised. \" \"Choose from",
"on the legend before showing the area. Only used if interpolation is not",
"(i.e. n' <= n) y : np.array (n', ) Some subset of the",
"n' <= n) \"\"\" positive_idx = np.arange(len(y))[y == 1] negative_idx = np.arange(len(y))[y ==",
"weights = np.random.randn(n_dim) y_probs = sigmoid(mixing_factor * np.dot(X, weights)) y = np.random.binomial(1, p=y_probs)",
"title is not None: fig.suptitle(title, fontsize=20, y=1.05) plt.show() def operating_points(ranking): \"\"\" Computes lists",
") Model predictions of the test samples. roc_auc : float ROC AUC score",
"of dimensions for the training data. n_samples : int Number of observations. frac_positive",
"plots a precision-recall curve. Parameters ---------- true : list Must be binary (i.e.",
"the weighted sum into the linear regime of a sigmoid. Smaller numbers squash",
"for side, (name, [p, r]) in enumerate(pr_dict.items()): plot_axes(ax[side], p, r, title=name, legend_text='IAP', **kwargs)",
"Some subset of the rows of the input y (i.e. n' <= n)",
"on the test data \"\"\" X, y = generate_continuous_data_and_targets( n_dim=n_dim, n_samples=n_samples, frac_positive=frac_positive, mixing_factor=mixing_factor)",
"positive Returns ------- observations : list Consisting of (frac_positive * n) 1s, and",
"`pr` is a tuple of precision and recall values. title : string kwargs",
"matrix and target vector to ensure that a specified fraction of the target",
"---------- p : list Precision. r : recall Recall. kwargs : optional See",
"Parameters ---------- true : list Must be binary (i.e. 1s and 0s). scores",
"observations \"\"\" n_positive = int(frac_positive * n) n_negative = n - n_positive observations",
"y_score, sample_weight=None): precision, recall, thresholds = precision_recall_curve( y_true, y_score, sample_weight=sample_weight) return auc_using_step(recall, precision)",
"Parameters ---------- n : int Number of examples frac_positive : float Fraction of",
"float (default: 30) title : None or string legend_text : string (default: 'Area')",
"second, and the split point is specified. Parameters ---------- ranking : list Ordered",
"y_true, y_score, sample_weight=sample_weight) return auc_using_step(recall, precision) def generate_positive_semi_definite_matrix(n_dim): \"\"\" Creates a positive semi-definite",
"\"\"\" Subsamples a feature matrix and target vector to ensure that a specified",
": (n_dim, n_dim) \"\"\" cov = np.random.randn(n_dim, n_dim) return np.dot(cov, cov.T) def subsample(X,",
"points. Parameters ---------- p : list Precision. r : recall Recall. kwargs :",
"return observations, constant_predictions def plot_recall_precision_from_predictions(true, scores, **kwargs): \"\"\" Computes precision and recall from",
"on axes provided. Parameters ---------- ax : matplotlib axes y : list x",
"the linear regime of a sigmoid. Smaller numbers squash closer to 0.5. Returns",
"constant_predictions def plot_recall_precision_from_predictions(true, scores, **kwargs): \"\"\" Computes precision and recall from some observations",
"p_long = [v for v in y for _ in (0, 1)][:-1] r_long",
"legend_text='IAP', **kwargs) plt.show() def plot_axes( ax, y, x, interpolation=None, marker_size=30, title=None, legend_text='Area'): \"\"\"",
"specified fraction of the target values are positive. Parameters ---------- X : np.array",
"return auc_using_step(recall, precision) def generate_positive_semi_definite_matrix(n_dim): \"\"\" Creates a positive semi-definite matrix. Parameters ----------",
"\"\"\" n_positive = int(frac_positive * n) n_negative = n - n_positive observations =",
"string ['linear', 'step'] marker_size : float (default: 30) title : None or string",
"**kwargs) if title is not None: fig.suptitle(title, fontsize=20, y=1.05) plt.show() def operating_points(ranking): \"\"\"",
"np.exp(-x)) def train_model_and_evaluate(n_dim=50, n_samples=10000, frac_positive=0.05, mixing_factor=0.025): \"\"\" Generates some data and trains a",
"Model predictions of the test samples. roc_auc : float ROC AUC score on",
"_ in range(n_negative)] constant_predictions = [0.5 for _ in range(n_positive + n_negative)] return",
"= np.random.choice(positive_idx, size=num_positive, replace=False) indices_to_use = np.concatenate([positive_idx, negative_idx]) np.random.shuffle(indices_to_use) return X[indices_to_use], y[indices_to_use] def",
"interpolation is not None. \"\"\" ax.scatter(x, y, marker='o', linewidths=0, s=marker_size, clip_on=False) # Show",
"the test samples. roc_auc : float ROC AUC score on the test data",
"[y[i] for i in [0, -1]], marker='x', linewidths=2, s=100, clip_on=False) ax.set_xlim((-0.05, 1.05)) ax.set_ylim((-0.08,",
"x. Parameters ---------- x : float Returns ------- sigmoid(x) : float \"\"\" return",
"last points more visably ax.scatter([x[i] for i in [0, -1]], [y[i] for i",
"int Returns ------- np.array : (n_dim, n_dim) \"\"\" cov = np.random.randn(n_dim, n_dim) return",
"IPython.display import display, HTML matplotlib.style.use('../../src/roam.mplstyle') def generate_data_and_constant_predictions(n, frac_positive): \"\"\" Generates data in a",
"the list into positive and negative. Returns ------- precision : float recall :",
"\"\"\" precision, recall = list(), list() for pos in range(len(ranking)): p, r =",
"Returns ------- precision : float recall : float \"\"\" if position == 0:",
"Fraction of the examples that are positive Returns ------- observations : list Consisting",
"not None: if interpolation == 'linear': ax.plot(x, y) area = auc(x, y) ax.fill_between(x,",
"optional See plot_axes. Returns ------- \"\"\" fig, ax = plt.subplots(1, 1, figsize=(7, 4))",
"observations. Parameters ---------- true : list score_dict : dict Consisting of `{name: scores}`",
"plt.show() def operating_points(ranking): \"\"\" Computes lists of precision and recall from an ordered",
"and the negative class comes second, and the split point is specified. Parameters",
"_ in (0, 1)][1:] ax.plot(r_long, p_long) area = auc_using_step(x, y) ax.fill_between(r_long, 0, p_long,",
"recall values. title : string kwargs : optional See plot_axes. \"\"\" fig, ax",
"def precision_recall_from_ranking(ranking, position): \"\"\" Computes the precision and recall of a particular assignment",
"interpolation : None (default) or string ['linear', 'step'] marker_size : float (default: 30)",
"value of '{}' not recognised. \" \"Choose from 'linear', 'quadrature'.\".format(interpolation)) def compare_recall_precisions_from_predictions(true, score_dict,",
"= list(splits)[0] lr = LogisticRegressionCV() lr.fit(X[train_idx], y[train_idx]) y_scores = lr.predict_proba(X[test_idx])[:, 1] roc_auc =",
"in [0, -1]], [y[i] for i in [0, -1]], marker='x', linewidths=2, s=100, clip_on=False)",
"[p, r]) in enumerate(pr_dict.items()): plot_axes(ax[side], p, r, title=name, legend_text='IAP', **kwargs) if title is",
"scores, against the same true observations. Parameters ---------- true : list score_dict :",
"def plot_recall_precision_from_predictions(true, scores, **kwargs): \"\"\" Computes precision and recall from some observations and",
"legend_text='Area'): \"\"\" Plots a graph on axes provided. Parameters ---------- ax : matplotlib",
"0.5 for all examples. Parameters ---------- n : int Number of examples frac_positive",
"1).sum() / position recall = (ranking[:position] == 1).sum() / (ranking == 1).sum() return",
"the input X (i.e. n' <= n) y : np.array (n', ) Some",
"int Number of observations. frac_positive : float mixing_factor : float Numbers nearer to",
"(n_samples, ) \"\"\" cov = generate_positive_semi_definite_matrix(n_dim) X = np.random.multivariate_normal( mean=np.zeros(n_dim), cov=cov, size=n_samples) weights",
"elif interpolation == 'step': p_long = [v for v in y for _",
"r, title=name, legend_text='IAP', **kwargs) if title is not None: fig.suptitle(title, fontsize=20, y=1.05) plt.show()",
"np.random.randn(n_dim, n_dim) return np.dot(cov, cov.T) def subsample(X, y, frac_positive): \"\"\" Subsamples a feature",
"fig, ax = plt.subplots(1, 2, figsize=(15, 4)) for side, (name, [p, r]) in",
"Generates some data and trains a logistic regression model. Parameters ---------- n_dim :",
"ratio, and returns the data and scores from a dummy model that predicts",
"p_long) area = auc_using_step(x, y) ax.fill_between(r_long, 0, p_long, alpha=0.2, label='{} = {:5.4f}'.format(legend_text, area))",
"y_score, sample_weight=sample_weight) return auc_using_step(recall, precision) def generate_positive_semi_definite_matrix(n_dim): \"\"\" Creates a positive semi-definite matrix.",
"from sklearn.linear_model import LogisticRegressionCV from sklearn.cross_validation import StratifiedShuffleSplit import matplotlib.pyplot as plt import",
"and returns the data and scores from a dummy model that predicts 0.5",
"for v in y for _ in (0, 1)][:-1] r_long = [v for",
"position == 0: precision = 1.0 recall = 0.0 else: ranking = np.array(ranking)",
"n) \"\"\" positive_idx = np.arange(len(y))[y == 1] negative_idx = np.arange(len(y))[y == 0] num_positive",
"is not None: if interpolation == 'linear': ax.plot(x, y) area = auc(x, y)",
"(n_samples, n_dim) y : np.array (n_samples, ) \"\"\" cov = generate_positive_semi_definite_matrix(n_dim) X =",
"------- \"\"\" fig, ax = plt.subplots(1, 1, figsize=(7, 4)) plot_axes(ax, p, r, legend_text='IAP',",
"{:5.4f}'.format(legend_text, area)) leg = ax.legend() leg.get_frame().set_linewidth(0.0) elif interpolation == 'step': p_long = [v",
"ranking : list Entries should be binary (0 or 1) and in descending",
"fontsize=20) if interpolation is not None: if interpolation == 'linear': ax.plot(x, y) area",
"= (ranking[:position] == 1).sum() / position recall = (ranking[:position] == 1).sum() / (ranking",
"fixed positive:negative ratio, and returns the data and scores from a dummy model",
": np.array (n', m) Some subset of the rows of the input X",
"= 0.0 else: ranking = np.array(ranking) precision = (ranking[:position] == 1).sum() / position",
"the training data. n_samples : int Number of observations. frac_positive : float mixing_factor",
"= LogisticRegressionCV() lr.fit(X[train_idx], y[train_idx]) y_scores = lr.predict_proba(X[test_idx])[:, 1] roc_auc = roc_auc_score(y[test_idx], y_scores) return",
": float ROC AUC score on the test data \"\"\" X, y =",
"LogisticRegressionCV() lr.fit(X[train_idx], y[train_idx]) y_scores = lr.predict_proba(X[test_idx])[:, 1] roc_auc = roc_auc_score(y[test_idx], y_scores) return y[test_idx],",
"r : recall Recall. kwargs : optional See plot_axes. Returns ------- \"\"\" fig,",
"to include on the legend before showing the area. Only used if interpolation",
"an ordered list of observations. Parameters ---------- ranking : list Entries should be",
": float \"\"\" return 1 / (1 + np.exp(-x)) def train_model_and_evaluate(n_dim=50, n_samples=10000, frac_positive=0.05,",
"graphs side-by-side for two different sets of scores, against the same true observations.",
"import numpy as np import pandas as pd from sklearn.metrics import average_precision_score, auc,",
"(i.e. 1s and 0s). scores : list Consisting of floats. kwargs : optional",
": float Returns ------- sigmoid(x) : float \"\"\" return 1 / (1 +",
"frac_positive=0.05, mixing_factor=0.025): \"\"\" Generates some data and trains a logistic regression model. Parameters",
"recall from some observations and scores assigned to them, and plots a precision-recall",
"0, y, alpha=0.2, label='{} = {:5.4f}'.format(legend_text, area)) leg = ax.legend() leg.get_frame().set_linewidth(0.0) elif interpolation",
"pos in range(len(ranking)): p, r = precision_recall_from_ranking(ranking, pos) precision.append(p) recall.append(r) return precision, recall",
"---------- n_dim : int Returns ------- np.array : (n_dim, n_dim) \"\"\" cov =",
"n_samples : int Number of observations. frac_positive : float mixing_factor : float Numbers",
"plot_axes( ax, y, x, interpolation=None, marker_size=30, title=None, legend_text='Area'): \"\"\" Plots a graph on",
"1, figsize=(7, 4)) plot_axes(ax, p, r, legend_text='IAP', **kwargs) plt.show() def plot_axes( ax, y,",
"and scores from a dummy model that predicts 0.5 for all examples. Parameters",
"Smaller numbers squash closer to 0.5. Returns ------- X : np.array (n_samples, n_dim)",
": None (default) or string ['linear', 'step'] marker_size : float (default: 30) title",
"y) area = auc(x, y) ax.fill_between(x, 0, y, alpha=0.2, label='{} = {:5.4f}'.format(legend_text, area))",
"for _ in (0, 1)][:-1] r_long = [v for v in x for",
"pr}` where `name` is a string and `pr` is a tuple of precision",
"as pd from sklearn.metrics import average_precision_score, auc, roc_auc_score from sklearn.metrics import precision_recall_curve from",
"same true observations. Parameters ---------- true : list score_dict : dict Consisting of",
"and recall values. title : string kwargs : optional See plot_axes. \"\"\" fig,",
"lists of precision and recall from an ordered list of observations. Parameters ----------",
"def operating_points(ranking): \"\"\" Computes lists of precision and recall from an ordered list",
"observations = [1 for _ in range(n_positive)] + \\ [0 for _ in",
"s=marker_size, clip_on=False) # Show first and last points more visably ax.scatter([x[i] for i",
"= precision_recall_from_ranking(ranking, pos) precision.append(p) recall.append(r) return precision, recall def precision_recall_from_ranking(ranking, position): \"\"\" Computes",
"1.0 recall = 0.0 else: ranking = np.array(ranking) precision = (ranking[:position] == 1).sum()",
"variable that is conditioned on a weighted sum of the data. Parameters ----------",
"mean=np.zeros(n_dim), cov=cov, size=n_samples) weights = np.random.randn(n_dim) y_probs = sigmoid(mixing_factor * np.dot(X, weights)) y",
"and recall from some observations and scores assigned to them, and plots a",
"range(len(recall) - 1)]) def roam_average_precision(y_true, y_score, sample_weight=None): precision, recall, thresholds = precision_recall_curve( y_true,",
": float mixing_factor : float Numbers nearer to 0 make the task more",
"pd from sklearn.metrics import average_precision_score, auc, roc_auc_score from sklearn.metrics import precision_recall_curve from sklearn.linear_model",
"None (default) or string ['linear', 'step'] marker_size : float (default: 30) title :",
"particular assignment of labelled observations to a positive and negative class, where the",
"Returns ------- np.array : (n_dim, n_dim) \"\"\" cov = np.random.randn(n_dim, n_dim) return np.dot(cov,",
"rows of the input y (i.e. n' <= n) \"\"\" positive_idx = np.arange(len(y))[y",
"for some activation x. Parameters ---------- x : float Returns ------- sigmoid(x) :",
"train_model_and_evaluate(n_dim=50, n_samples=10000, frac_positive=0.05, mixing_factor=0.025): \"\"\" Generates some data and trains a logistic regression",
"observations : list Consisting of (frac_positive * n) 1s, and (n - (frac_positive",
"[v for v in x for _ in (0, 1)][1:] ax.plot(r_long, p_long) area",
"generate_continuous_data_and_targets( n_dim, n_samples, mixing_factor=0.025, frac_positive=0.1): \"\"\" Generates a multivariate Gaussian-distributed dataset and a",
"def auc_using_step(recall, precision): return sum([(recall[i] - recall[i+1]) * precision[i] for i in range(len(recall)",
"n : int Number of examples frac_positive : float Fraction of the examples",
"n) n_negative = n - n_positive observations = [1 for _ in range(n_positive)]",
"pos) precision.append(p) recall.append(r) return precision, recall def precision_recall_from_ranking(ranking, position): \"\"\" Computes the precision",
"\"\"\" cov = np.random.randn(n_dim, n_dim) return np.dot(cov, cov.T) def subsample(X, y, frac_positive): \"\"\"",
"score_dict, **kwargs): \"\"\" Show two graphs side-by-side for two different sets of scores,",
"observations and scores assigned to them, and plots a precision-recall curve. Parameters ----------",
"fig.suptitle(title, fontsize=20, y=1.05) plt.show() def operating_points(ranking): \"\"\" Computes lists of precision and recall",
"Computes lists of precision and recall from an ordered list of observations. Parameters",
"should be binary (0 or 1) and in descending order (i.e. top-ranked is",
"sklearn.cross_validation import StratifiedShuffleSplit import matplotlib.pyplot as plt import matplotlib from IPython.display import display,",
"= (ranking[:position] == 1).sum() / (ranking == 1).sum() return precision, recall def auc_using_step(recall,",
"subsample(X, y, frac_positive): \"\"\" Subsamples a feature matrix and target vector to ensure",
"vector to ensure that a specified fraction of the target values are positive.",
"name, score in score_dict.items(): p, r, threshold = precision_recall_curve(true, score) pr[name] = [p,",
"marker='x', linewidths=2, s=100, clip_on=False) ax.set_xlim((-0.05, 1.05)) ax.set_ylim((-0.08, 1.08)) ax.set_xlabel('Recall') ax.set_ylabel('Precision') if title is",
"fontsize=20, y=1.05) plt.show() def operating_points(ranking): \"\"\" Computes lists of precision and recall from",
"\"\"\" cov = generate_positive_semi_definite_matrix(n_dim) X = np.random.multivariate_normal( mean=np.zeros(n_dim), cov=cov, size=n_samples) weights = np.random.randn(n_dim)",
"**kwargs): \"\"\" Show two graphs side-by-side for two different sets of scores, against",
"observations. position : int Position to split the list into positive and negative.",
"if position == 0: precision = 1.0 recall = 0.0 else: ranking =",
"float recall : float \"\"\" if position == 0: precision = 1.0 recall",
"i in [0, -1]], marker='x', linewidths=2, s=100, clip_on=False) ax.set_xlim((-0.05, 1.05)) ax.set_ylim((-0.08, 1.08)) ax.set_xlabel('Recall')",
") Some subset of the rows of the input y (i.e. n' <=",
"numbers squash closer to 0.5. Returns ------- X : np.array (n_samples, n_dim) y",
"positive semi-definite matrix. Parameters ---------- n_dim : int Returns ------- np.array : (n_dim,",
"(0, 1)][1:] ax.plot(r_long, p_long) area = auc_using_step(x, y) ax.fill_between(r_long, 0, p_long, alpha=0.2, label='{}",
"1)][:-1] r_long = [v for v in x for _ in (0, 1)][1:]",
"------- X : np.array (n_samples, n_dim) y : np.array (n_samples, ) \"\"\" cov",
"\"\"\" Computes precision and recall from some observations and scores assigned to them,",
"in the test set. y_scores : np.array (n_test, ) Model predictions of the",
"(n', m) Some subset of the rows of the input X (i.e. n'",
"Parameters ---------- x : float Returns ------- sigmoid(x) : float \"\"\" return 1",
"= 1.0 recall = 0.0 else: ranking = np.array(ranking) precision = (ranking[:position] ==",
"the positive class comes first in the list, and the negative class comes",
"of a sigmoid. Smaller numbers squash closer to 0.5. Returns ------- X :",
"= np.random.multivariate_normal( mean=np.zeros(n_dim), cov=cov, size=n_samples) weights = np.random.randn(n_dim) y_probs = sigmoid(mixing_factor * np.dot(X,",
"binary (0 or 1) and in descending order (i.e. top-ranked is first). Returns",
"precision and recall of a particular assignment of labelled observations to a positive",
"and plots a precision-recall curve. Parameters ---------- true : list Must be binary",
"[p, r] compare_recall_precision_graph(pr, **kwargs) def compare_recall_precision_graph(pr_dict, title=None, **kwargs): \"\"\" Parameters ---------- pr_dict :",
": int mixing_factor : float 'Squashes' the weighted sum into the linear regime",
": int Position to split the list into positive and negative. Returns -------",
"------- observations : list Consisting of (frac_positive * n) 1s, and (n -",
"sets of scores, against the same true observations. Parameters ---------- true : list",
"observations. frac_positive : float mixing_factor : float Numbers nearer to 0 make the",
"**kwargs): \"\"\" Computes precision and recall from some observations and scores assigned to",
"Text to include on the legend before showing the area. Only used if",
"`name` is a string and `scores` is a list of floats. kwargs :",
"float Numbers nearer to 0 make the task more challenging. Returns ------- y",
"replace=False) indices_to_use = np.concatenate([positive_idx, negative_idx]) np.random.shuffle(indices_to_use) return X[indices_to_use], y[indices_to_use] def generate_continuous_data_and_targets( n_dim, n_samples,",
"len(negative_idx)) positive_idx = np.random.choice(positive_idx, size=num_positive, replace=False) indices_to_use = np.concatenate([positive_idx, negative_idx]) np.random.shuffle(indices_to_use) return X[indices_to_use],",
"negative class, where the positive class comes first in the list, and the",
"Consisting of floats. kwargs : optional See plot_axes. \"\"\" p, r, thresholds =",
"---------- x : float Returns ------- sigmoid(x) : float \"\"\" return 1 /",
"list Same length as observations \"\"\" n_positive = int(frac_positive * n) n_negative =",
"2, figsize=(15, 4)) for side, (name, [p, r]) in enumerate(pr_dict.items()): plot_axes(ax[side], p, r,",
"Precision. r : recall Recall. kwargs : optional See plot_axes. Returns ------- \"\"\"",
"comes second, and the split point is specified. Parameters ---------- ranking : list",
"target values are positive. Parameters ---------- X : np.array (n, m) y :",
"of the test samples. roc_auc : float ROC AUC score on the test",
"HTML matplotlib.style.use('../../src/roam.mplstyle') def generate_data_and_constant_predictions(n, frac_positive): \"\"\" Generates data in a fixed positive:negative ratio,",
"(0 or 1) and in descending order (i.e. top-ranked is first). Returns -------",
"n_dim : int Number of dimensions for the training data. n_samples : int",
"Show first and last points more visably ax.scatter([x[i] for i in [0, -1]],",
": list \"\"\" precision, recall = list(), list() for pos in range(len(ranking)): p,",
"of (frac_positive * n) 1s, and (n - (frac_positive * n)) 0s constant_predictions",
"precision): return sum([(recall[i] - recall[i+1]) * precision[i] for i in range(len(recall) - 1)])",
"list Ordered list of binary observations. position : int Position to split the",
"n' <= n) y : np.array (n', ) Some subset of the rows",
"np.concatenate([positive_idx, negative_idx]) np.random.shuffle(indices_to_use) return X[indices_to_use], y[indices_to_use] def generate_continuous_data_and_targets( n_dim, n_samples, mixing_factor=0.025, frac_positive=0.1): \"\"\"",
"= [v for v in y for _ in (0, 1)][:-1] r_long =",
") \"\"\" cov = generate_positive_semi_definite_matrix(n_dim) X = np.random.multivariate_normal( mean=np.zeros(n_dim), cov=cov, size=n_samples) weights =",
"some activation x. Parameters ---------- x : float Returns ------- sigmoid(x) : float",
"figsize=(15, 4)) for side, (name, [p, r]) in enumerate(pr_dict.items()): plot_axes(ax[side], p, r, title=name,",
"generate_positive_semi_definite_matrix(n_dim): \"\"\" Creates a positive semi-definite matrix. Parameters ---------- n_dim : int Returns",
"np.array (n', ) Some subset of the rows of the input y (i.e.",
"is not None: fig.suptitle(title, fontsize=20, y=1.05) plt.show() def operating_points(ranking): \"\"\" Computes lists of",
"splits = StratifiedShuffleSplit(y, test_size=0.3, random_state=42) train_idx, test_idx = list(splits)[0] lr = LogisticRegressionCV() lr.fit(X[train_idx],",
"recall, thresholds = precision_recall_curve( y_true, y_score, sample_weight=sample_weight) return auc_using_step(recall, precision) def generate_positive_semi_definite_matrix(n_dim): \"\"\"",
"np.array : (n_dim, n_dim) \"\"\" cov = np.random.randn(n_dim, n_dim) return np.dot(cov, cov.T) def",
"target vector to ensure that a specified fraction of the target values are",
"return 1 / (1 + np.exp(-x)) def train_model_and_evaluate(n_dim=50, n_samples=10000, frac_positive=0.05, mixing_factor=0.025): \"\"\" Generates",
"make the task more challenging. Returns ------- y : np.array (n_test, ) True",
"precision_recall_from_ranking(ranking, position): \"\"\" Computes the precision and recall of a particular assignment of",
"into the linear regime of a sigmoid. Smaller numbers squash closer to 0.5.",
"list interpolation : None (default) or string ['linear', 'step'] marker_size : float (default:",
"list() for pos in range(len(ranking)): p, r = precision_recall_from_ranking(ranking, pos) precision.append(p) recall.append(r) return",
"np.random.randn(n_dim) y_probs = sigmoid(mixing_factor * np.dot(X, weights)) y = np.random.binomial(1, p=y_probs) X, y",
"y = subsample(X, y, frac_positive) return X, y def sigmoid(x): \"\"\" Computes sigmoid(x)",
"\"\"\" Computes the precision and recall of a particular assignment of labelled observations",
"score on the test data \"\"\" X, y = generate_continuous_data_and_targets( n_dim=n_dim, n_samples=n_samples, frac_positive=frac_positive,",
"\"\"\" p, r, thresholds = precision_recall_curve(true, scores) plot_recall_precision(p, r, **kwargs) def plot_recall_precision(p, r,",
"of observations. Parameters ---------- ranking : list Entries should be binary (0 or",
"(n_test, ) Model predictions of the test samples. roc_auc : float ROC AUC",
"into positive and negative. Returns ------- precision : float recall : float \"\"\"",
"'linear', 'quadrature'.\".format(interpolation)) def compare_recall_precisions_from_predictions(true, score_dict, **kwargs): \"\"\" Show two graphs side-by-side for two",
"/ (ranking == 1).sum() return precision, recall def auc_using_step(recall, precision): return sum([(recall[i] -",
"two different sets of scores, against the same true observations. Parameters ---------- true",
"n_samples, mixing_factor=0.025, frac_positive=0.1): \"\"\" Generates a multivariate Gaussian-distributed dataset and a response variable",
"1) and in descending order (i.e. top-ranked is first). Returns ------- precision :",
"sigmoid(x) for some activation x. Parameters ---------- x : float Returns ------- sigmoid(x)",
"precision : list recall : list \"\"\" precision, recall = list(), list() for",
"and target vector to ensure that a specified fraction of the target values",
"Parameters ---------- n_dim : int Number of dimensions for the training data. n_samples",
"y=1.05) plt.show() def operating_points(ranking): \"\"\" Computes lists of precision and recall from an",
"r, **kwargs) def plot_recall_precision(p, r, **kwargs): \"\"\" Plots a precision-recall graph from a",
"mixing_factor=mixing_factor) splits = StratifiedShuffleSplit(y, test_size=0.3, random_state=42) train_idx, test_idx = list(splits)[0] lr = LogisticRegressionCV()",
"title : string kwargs : optional See plot_axes. \"\"\" fig, ax = plt.subplots(1,",
"a fixed positive:negative ratio, and returns the data and scores from a dummy",
"def compare_recall_precisions_from_predictions(true, score_dict, **kwargs): \"\"\" Show two graphs side-by-side for two different sets",
"== 0: precision = 1.0 recall = 0.0 else: ranking = np.array(ranking) precision",
"plot_recall_precision_from_predictions(true, scores, **kwargs): \"\"\" Computes precision and recall from some observations and scores",
"`name` is a string and `pr` is a tuple of precision and recall",
"1).sum() / (ranking == 1).sum() return precision, recall def auc_using_step(recall, precision): return sum([(recall[i]",
"closer to 0.5. Returns ------- X : np.array (n_samples, n_dim) y : np.array",
"== 1).sum() return precision, recall def auc_using_step(recall, precision): return sum([(recall[i] - recall[i+1]) *",
"provided. Parameters ---------- ax : matplotlib axes y : list x : list",
"first in the list, and the negative class comes second, and the split",
"size=num_positive, replace=False) indices_to_use = np.concatenate([positive_idx, negative_idx]) np.random.shuffle(indices_to_use) return X[indices_to_use], y[indices_to_use] def generate_continuous_data_and_targets( n_dim,",
"== 'linear': ax.plot(x, y) area = auc(x, y) ax.fill_between(x, 0, y, alpha=0.2, label='{}",
"observed values in the test set. y_scores : np.array (n_test, ) Model predictions",
"[0, -1]], marker='x', linewidths=2, s=100, clip_on=False) ax.set_xlim((-0.05, 1.05)) ax.set_ylim((-0.08, 1.08)) ax.set_xlabel('Recall') ax.set_ylabel('Precision') if",
"0.0 else: ranking = np.array(ranking) precision = (ranking[:position] == 1).sum() / position recall",
"for all examples. Parameters ---------- n : int Number of examples frac_positive :",
"a string and `scores` is a list of floats. kwargs : optional See",
"of labelled observations to a positive and negative class, where the positive class",
"regime of a sigmoid. Smaller numbers squash closer to 0.5. Returns ------- X",
"in a fixed positive:negative ratio, and returns the data and scores from a",
"plot_axes. \"\"\" pr = OrderedDict() for name, score in score_dict.items(): p, r, threshold",
"------- y : np.array (n_test, ) True observed values in the test set.",
"predicts 0.5 for all examples. Parameters ---------- n : int Number of examples",
"ax.legend() leg.get_frame().set_linewidth(0.0) else: print(\"Interpolation value of '{}' not recognised. \" \"Choose from 'linear',",
"y = np.random.binomial(1, p=y_probs) X, y = subsample(X, y, frac_positive) return X, y",
"a positive semi-definite matrix. Parameters ---------- n_dim : int Returns ------- np.array :",
"LogisticRegressionCV from sklearn.cross_validation import StratifiedShuffleSplit import matplotlib.pyplot as plt import matplotlib from IPython.display",
"and scores assigned to them, and plots a precision-recall curve. Parameters ---------- true",
"[0.5 for _ in range(n_positive + n_negative)] return observations, constant_predictions def plot_recall_precision_from_predictions(true, scores,",
"point is specified. Parameters ---------- ranking : list Ordered list of binary observations.",
": int n_samples : int mixing_factor : float 'Squashes' the weighted sum into",
"test data \"\"\" X, y = generate_continuous_data_and_targets( n_dim=n_dim, n_samples=n_samples, frac_positive=frac_positive, mixing_factor=mixing_factor) splits =",
": list Precision. r : recall Recall. kwargs : optional See plot_axes. Returns",
"length as observations \"\"\" n_positive = int(frac_positive * n) n_negative = n -",
"of observations. frac_positive : float mixing_factor : float Numbers nearer to 0 make",
"thresholds = precision_recall_curve(true, scores) plot_recall_precision(p, r, **kwargs) def plot_recall_precision(p, r, **kwargs): \"\"\" Plots",
"precision) def generate_positive_semi_definite_matrix(n_dim): \"\"\" Creates a positive semi-definite matrix. Parameters ---------- n_dim :",
"the rows of the input X (i.e. n' <= n) y : np.array",
": int Returns ------- np.array : (n_dim, n_dim) \"\"\" cov = np.random.randn(n_dim, n_dim)",
"float 'Squashes' the weighted sum into the linear regime of a sigmoid. Smaller",
"x, interpolation=None, marker_size=30, title=None, legend_text='Area'): \"\"\" Plots a graph on axes provided. Parameters",
"`scores` is a list of floats. kwargs : optional See plot_axes. \"\"\" pr",
"\"\"\" fig, ax = plt.subplots(1, 2, figsize=(15, 4)) for side, (name, [p, r])",
"np.dot(cov, cov.T) def subsample(X, y, frac_positive): \"\"\" Subsamples a feature matrix and target",
"first). Returns ------- precision : list recall : list \"\"\" precision, recall =",
"values are positive. Parameters ---------- X : np.array (n, m) y : np.array",
"X[indices_to_use], y[indices_to_use] def generate_continuous_data_and_targets( n_dim, n_samples, mixing_factor=0.025, frac_positive=0.1): \"\"\" Generates a multivariate Gaussian-distributed",
"of the rows of the input X (i.e. n' <= n) y :",
"AUC score on the test data \"\"\" X, y = generate_continuous_data_and_targets( n_dim=n_dim, n_samples=n_samples,",
"- n_positive observations = [1 for _ in range(n_positive)] + \\ [0 for",
"optional See plot_axes. \"\"\" pr = OrderedDict() for name, score in score_dict.items(): p,",
"marker_size=30, title=None, legend_text='Area'): \"\"\" Plots a graph on axes provided. Parameters ---------- ax",
"frac_positive : float Fraction of the examples that are positive Returns ------- observations",
"mixing_factor=0.025): \"\"\" Generates some data and trains a logistic regression model. Parameters ----------",
": list Same length as observations \"\"\" n_positive = int(frac_positive * n) n_negative",
"import OrderedDict import numpy as np import pandas as pd from sklearn.metrics import",
"\"\"\" ax.scatter(x, y, marker='o', linewidths=0, s=marker_size, clip_on=False) # Show first and last points",
"---------- ranking : list Ordered list of binary observations. position : int Position",
"of '{}' not recognised. \" \"Choose from 'linear', 'quadrature'.\".format(interpolation)) def compare_recall_precisions_from_predictions(true, score_dict, **kwargs):",
"Parameters ---------- X : np.array (n, m) y : np.array (n, ) frac_positive",
"y, frac_positive) return X, y def sigmoid(x): \"\"\" Computes sigmoid(x) for some activation",
"\" \"Choose from 'linear', 'quadrature'.\".format(interpolation)) def compare_recall_precisions_from_predictions(true, score_dict, **kwargs): \"\"\" Show two graphs",
": optional See plot_axes. \"\"\" p, r, thresholds = precision_recall_curve(true, scores) plot_recall_precision(p, r,",
"(n', ) Some subset of the rows of the input y (i.e. n'",
"alpha=0.2, label='{} = {:5.4f}'.format(legend_text, area)) leg = ax.legend() leg.get_frame().set_linewidth(0.0) else: print(\"Interpolation value of",
"test samples. roc_auc : float ROC AUC score on the test data \"\"\"",
"= StratifiedShuffleSplit(y, test_size=0.3, random_state=42) train_idx, test_idx = list(splits)[0] lr = LogisticRegressionCV() lr.fit(X[train_idx], y[train_idx])",
"'step'] marker_size : float (default: 30) title : None or string legend_text :",
"legend before showing the area. Only used if interpolation is not None. \"\"\"",
"= generate_continuous_data_and_targets( n_dim=n_dim, n_samples=n_samples, frac_positive=frac_positive, mixing_factor=mixing_factor) splits = StratifiedShuffleSplit(y, test_size=0.3, random_state=42) train_idx, test_idx",
"ax.plot(r_long, p_long) area = auc_using_step(x, y) ax.fill_between(r_long, 0, p_long, alpha=0.2, label='{} = {:5.4f}'.format(legend_text,",
"import matplotlib from IPython.display import display, HTML matplotlib.style.use('../../src/roam.mplstyle') def generate_data_and_constant_predictions(n, frac_positive): \"\"\" Generates",
"ranking = np.array(ranking) precision = (ranking[:position] == 1).sum() / position recall = (ranking[:position]",
"size=n_samples) weights = np.random.randn(n_dim) y_probs = sigmoid(mixing_factor * np.dot(X, weights)) y = np.random.binomial(1,",
"in y for _ in (0, 1)][:-1] r_long = [v for v in",
"\"\"\" Creates a positive semi-definite matrix. Parameters ---------- n_dim : int Returns -------",
": list x : list interpolation : None (default) or string ['linear', 'step']",
"np.array (n_samples, ) \"\"\" cov = generate_positive_semi_definite_matrix(n_dim) X = np.random.multivariate_normal( mean=np.zeros(n_dim), cov=cov, size=n_samples)",
"import LogisticRegressionCV from sklearn.cross_validation import StratifiedShuffleSplit import matplotlib.pyplot as plt import matplotlib from",
"compare_recall_precision_graph(pr_dict, title=None, **kwargs): \"\"\" Parameters ---------- pr_dict : dict Consisting of `{name: pr}`",
"import display, HTML matplotlib.style.use('../../src/roam.mplstyle') def generate_data_and_constant_predictions(n, frac_positive): \"\"\" Generates data in a fixed",
"multivariate Gaussian-distributed dataset and a response variable that is conditioned on a weighted",
"leg = ax.legend() leg.get_frame().set_linewidth(0.0) elif interpolation == 'step': p_long = [v for v",
"for _ in range(n_positive + n_negative)] return observations, constant_predictions def plot_recall_precision_from_predictions(true, scores, **kwargs):",
"y (i.e. n' <= n) \"\"\" positive_idx = np.arange(len(y))[y == 1] negative_idx =",
"data. n_samples : int Number of observations. frac_positive : float mixing_factor : float",
"n_dim) \"\"\" cov = np.random.randn(n_dim, n_dim) return np.dot(cov, cov.T) def subsample(X, y, frac_positive):",
"['linear', 'step'] marker_size : float (default: 30) title : None or string legend_text",
"Numbers nearer to 0 make the task more challenging. Returns ------- y :",
"display, HTML matplotlib.style.use('../../src/roam.mplstyle') def generate_data_and_constant_predictions(n, frac_positive): \"\"\" Generates data in a fixed positive:negative",
"Generates data in a fixed positive:negative ratio, and returns the data and scores",
"1).sum() return precision, recall def auc_using_step(recall, precision): return sum([(recall[i] - recall[i+1]) * precision[i]",
"list score_dict : dict Consisting of `{name: scores}` where `name` is a string",
": string kwargs : optional See plot_axes. \"\"\" fig, ax = plt.subplots(1, 2,",
": list Consisting of floats. kwargs : optional See plot_axes. \"\"\" p, r,",
"\"\"\" Computes lists of precision and recall from an ordered list of observations.",
"observations to a positive and negative class, where the positive class comes first",
"Gaussian-distributed dataset and a response variable that is conditioned on a weighted sum",
"squash closer to 0.5. Returns ------- X : np.array (n_samples, n_dim) y :",
"and last points more visably ax.scatter([x[i] for i in [0, -1]], [y[i] for",
"a specified fraction of the target values are positive. Parameters ---------- X :",
"for the training data. n_samples : int Number of observations. frac_positive : float",
": np.array (n_test, ) True observed values in the test set. y_scores :",
"np.array (n_test, ) True observed values in the test set. y_scores : np.array",
"_ in range(n_positive + n_negative)] return observations, constant_predictions def plot_recall_precision_from_predictions(true, scores, **kwargs): \"\"\"",
"cov.T) def subsample(X, y, frac_positive): \"\"\" Subsamples a feature matrix and target vector",
"positive_idx = np.random.choice(positive_idx, size=num_positive, replace=False) indices_to_use = np.concatenate([positive_idx, negative_idx]) np.random.shuffle(indices_to_use) return X[indices_to_use], y[indices_to_use]",
"\"\"\" Show two graphs side-by-side for two different sets of scores, against the",
"y : np.array (n_samples, ) \"\"\" cov = generate_positive_semi_definite_matrix(n_dim) X = np.random.multivariate_normal( mean=np.zeros(n_dim),",
"r]) in enumerate(pr_dict.items()): plot_axes(ax[side], p, r, title=name, legend_text='IAP', **kwargs) if title is not",
"top-ranked is first). Returns ------- precision : list recall : list \"\"\" precision,",
"pandas as pd from sklearn.metrics import average_precision_score, auc, roc_auc_score from sklearn.metrics import precision_recall_curve",
"frac_positive): \"\"\" Subsamples a feature matrix and target vector to ensure that a",
"subset of the rows of the input y (i.e. n' <= n) \"\"\"",
"positive:negative ratio, and returns the data and scores from a dummy model that",
"np.arange(len(y))[y == 1] negative_idx = np.arange(len(y))[y == 0] num_positive = int(frac_positive * len(negative_idx))",
"float ROC AUC score on the test data \"\"\" X, y = generate_continuous_data_and_targets(",
"fraction of the target values are positive. Parameters ---------- X : np.array (n,",
"(default) or string ['linear', 'step'] marker_size : float (default: 30) title : None",
"= n - n_positive observations = [1 for _ in range(n_positive)] + \\",
"the same true observations. Parameters ---------- true : list score_dict : dict Consisting",
"negative class comes second, and the split point is specified. Parameters ---------- ranking",
"recall : list \"\"\" precision, recall = list(), list() for pos in range(len(ranking)):",
"(default: 30) title : None or string legend_text : string (default: 'Area') Text",
"np import pandas as pd from sklearn.metrics import average_precision_score, auc, roc_auc_score from sklearn.metrics",
"sigmoid(x): \"\"\" Computes sigmoid(x) for some activation x. Parameters ---------- x : float",
"precision and recall from some observations and scores assigned to them, and plots",
"of `{name: scores}` where `name` is a string and `scores` is a list",
"import pandas as pd from sklearn.metrics import average_precision_score, auc, roc_auc_score from sklearn.metrics import",
"random_state=42) train_idx, test_idx = list(splits)[0] lr = LogisticRegressionCV() lr.fit(X[train_idx], y[train_idx]) y_scores = lr.predict_proba(X[test_idx])[:,",
"plt.show() def plot_axes( ax, y, x, interpolation=None, marker_size=30, title=None, legend_text='Area'): \"\"\" Plots a",
"true observations. Parameters ---------- true : list score_dict : dict Consisting of `{name:",
"n - n_positive observations = [1 for _ in range(n_positive)] + \\ [0",
"the list, and the negative class comes second, and the split point is",
"n_dim=n_dim, n_samples=n_samples, frac_positive=frac_positive, mixing_factor=mixing_factor) splits = StratifiedShuffleSplit(y, test_size=0.3, random_state=42) train_idx, test_idx = list(splits)[0]",
"<gh_stars>100-1000 from copy import copy from collections import OrderedDict import numpy as np",
"y for _ in (0, 1)][:-1] r_long = [v for v in x",
"floats. kwargs : optional See plot_axes. \"\"\" pr = OrderedDict() for name, score",
": recall Recall. kwargs : optional See plot_axes. Returns ------- \"\"\" fig, ax",
"for pos in range(len(ranking)): p, r = precision_recall_from_ranking(ranking, pos) precision.append(p) recall.append(r) return precision,",
"frac_positive=frac_positive, mixing_factor=mixing_factor) splits = StratifiedShuffleSplit(y, test_size=0.3, random_state=42) train_idx, test_idx = list(splits)[0] lr =",
"precision and recall from an ordered list of observations. Parameters ---------- ranking :",
"(n - (frac_positive * n)) 0s constant_predictions : list Same length as observations",
"r] compare_recall_precision_graph(pr, **kwargs) def compare_recall_precision_graph(pr_dict, title=None, **kwargs): \"\"\" Parameters ---------- pr_dict : dict",
"------- sigmoid(x) : float \"\"\" return 1 / (1 + np.exp(-x)) def train_model_and_evaluate(n_dim=50,",
"scores}` where `name` is a string and `scores` is a list of floats.",
"recall : float \"\"\" if position == 0: precision = 1.0 recall =",
"for _ in range(n_negative)] constant_predictions = [0.5 for _ in range(n_positive + n_negative)]",
"auc_using_step(recall, precision): return sum([(recall[i] - recall[i+1]) * precision[i] for i in range(len(recall) -",
"area = auc(x, y) ax.fill_between(x, 0, y, alpha=0.2, label='{} = {:5.4f}'.format(legend_text, area)) leg",
"comes first in the list, and the negative class comes second, and the",
"negative_idx = np.arange(len(y))[y == 0] num_positive = int(frac_positive * len(negative_idx)) positive_idx = np.random.choice(positive_idx,",
"of the data. Parameters ---------- n_dim : int n_samples : int mixing_factor :",
"generate_positive_semi_definite_matrix(n_dim) X = np.random.multivariate_normal( mean=np.zeros(n_dim), cov=cov, size=n_samples) weights = np.random.randn(n_dim) y_probs = sigmoid(mixing_factor",
"See plot_axes. Returns ------- \"\"\" fig, ax = plt.subplots(1, 1, figsize=(7, 4)) plot_axes(ax,",
"0.5. Returns ------- X : np.array (n_samples, n_dim) y : np.array (n_samples, )",
"ax : matplotlib axes y : list x : list interpolation : None",
"and negative class, where the positive class comes first in the list, and",
"negative. Returns ------- precision : float recall : float \"\"\" if position ==",
"positive and negative class, where the positive class comes first in the list,",
"= list(), list() for pos in range(len(ranking)): p, r = precision_recall_from_ranking(ranking, pos) precision.append(p)",
"string and `pr` is a tuple of precision and recall values. title :",
"Plots a precision-recall graph from a series of operating points. Parameters ---------- p",
"p, r, thresholds = precision_recall_curve(true, scores) plot_recall_precision(p, r, **kwargs) def plot_recall_precision(p, r, **kwargs):",
"descending order (i.e. top-ranked is first). Returns ------- precision : list recall :",
"ROC AUC score on the test data \"\"\" X, y = generate_continuous_data_and_targets( n_dim=n_dim,",
"ensure that a specified fraction of the target values are positive. Parameters ----------",
"---------- ranking : list Entries should be binary (0 or 1) and in",
"0] num_positive = int(frac_positive * len(negative_idx)) positive_idx = np.random.choice(positive_idx, size=num_positive, replace=False) indices_to_use =",
"axes y : list x : list interpolation : None (default) or string",
"y[indices_to_use] def generate_continuous_data_and_targets( n_dim, n_samples, mixing_factor=0.025, frac_positive=0.1): \"\"\" Generates a multivariate Gaussian-distributed dataset",
"(ranking == 1).sum() return precision, recall def auc_using_step(recall, precision): return sum([(recall[i] - recall[i+1])",
"Only used if interpolation is not None. \"\"\" ax.scatter(x, y, marker='o', linewidths=0, s=marker_size,",
"list, and the negative class comes second, and the split point is specified.",
"y = generate_continuous_data_and_targets( n_dim=n_dim, n_samples=n_samples, frac_positive=frac_positive, mixing_factor=mixing_factor) splits = StratifiedShuffleSplit(y, test_size=0.3, random_state=42) train_idx,",
"for v in x for _ in (0, 1)][1:] ax.plot(r_long, p_long) area =",
"------- precision : float recall : float \"\"\" if position == 0: precision",
"the legend before showing the area. Only used if interpolation is not None.",
"and 0s). scores : list Consisting of floats. kwargs : optional See plot_axes.",
"i in [0, -1]], [y[i] for i in [0, -1]], marker='x', linewidths=2, s=100,",
"for _ in (0, 1)][1:] ax.plot(r_long, p_long) area = auc_using_step(x, y) ax.fill_between(r_long, 0,",
"class comes first in the list, and the negative class comes second, and",
": float Numbers nearer to 0 make the task more challenging. Returns -------",
"operating points. Parameters ---------- p : list Precision. r : recall Recall. kwargs",
"of the rows of the input y (i.e. n' <= n) \"\"\" positive_idx",
"true : list score_dict : dict Consisting of `{name: scores}` where `name` is",
"plot_axes. \"\"\" p, r, thresholds = precision_recall_curve(true, scores) plot_recall_precision(p, r, **kwargs) def plot_recall_precision(p,",
"clip_on=False) # Show first and last points more visably ax.scatter([x[i] for i in",
"Returns ------- X : np.array (n', m) Some subset of the rows of",
"label='{} = {:5.4f}'.format(legend_text, area)) leg = ax.legend() leg.get_frame().set_linewidth(0.0) else: print(\"Interpolation value of '{}'",
"matrix. Parameters ---------- n_dim : int Returns ------- np.array : (n_dim, n_dim) \"\"\"",
"---------- pr_dict : dict Consisting of `{name: pr}` where `name` is a string",
"position : int Position to split the list into positive and negative. Returns",
"See plot_axes. \"\"\" p, r, thresholds = precision_recall_curve(true, scores) plot_recall_precision(p, r, **kwargs) def",
"n) 1s, and (n - (frac_positive * n)) 0s constant_predictions : list Same",
"np.array (n', m) Some subset of the rows of the input X (i.e.",
"= np.concatenate([positive_idx, negative_idx]) np.random.shuffle(indices_to_use) return X[indices_to_use], y[indices_to_use] def generate_continuous_data_and_targets( n_dim, n_samples, mixing_factor=0.025, frac_positive=0.1):",
"# Show first and last points more visably ax.scatter([x[i] for i in [0,",
"r, legend_text='IAP', **kwargs) plt.show() def plot_axes( ax, y, x, interpolation=None, marker_size=30, title=None, legend_text='Area'):",
"the target values are positive. Parameters ---------- X : np.array (n, m) y",
"legend_text : string (default: 'Area') Text to include on the legend before showing",
"X, y = generate_continuous_data_and_targets( n_dim=n_dim, n_samples=n_samples, frac_positive=frac_positive, mixing_factor=mixing_factor) splits = StratifiedShuffleSplit(y, test_size=0.3, random_state=42)",
"np.array (n_samples, n_dim) y : np.array (n_samples, ) \"\"\" cov = generate_positive_semi_definite_matrix(n_dim) X",
"---------- X : np.array (n, m) y : np.array (n, ) frac_positive :",
"r, thresholds = precision_recall_curve(true, scores) plot_recall_precision(p, r, **kwargs) def plot_recall_precision(p, r, **kwargs): \"\"\""
] |
[
"(i + l < len(B)) and (j - l > 0) right =",
"i: B[k][down] -= 1 # diagonal downwards queen line of sight for l",
"args[1] n = 0 try: n = int(ns) except ValueError: print(usage) return #",
"True ns = args[1] n = 0 try: n = int(ns) except ValueError:",
"if not args[0] == \"-v\": print(usage) return v = True ns = args[1]",
"B[0][1] = 1 else: B[0][1] = 0 printBoard(B) if __name__ == \"__main__\": #",
"> n: if v: for e in range(len(B)): printer += str(B[e][0]) if e",
"+ l][left] += 1 def findSolutions(B, i, mode): n = len(B)-1 v =",
"def removeQueen(B, i, j): B[i][j] -= 1 B[i][0] = 0 down = j",
"= True printer = \"(\" if i > n: if v: for e",
"to text printer += \")\" print(printer) B[0][0] += 1 return 1 else: for",
"leftClear: B[i + l][left] += 1 def findSolutions(B, i, mode): n = len(B)-1",
"print(usage) return ns = \"\" # string that holds n v = None",
"B[i][0] = 0 down = j # vertical downwards queen line of sight",
"print all solutions\" if len(args) < 1: print(usage) return ns = \"\" #",
"0 printBoard(B) if __name__ == \"__main__\": # execute only if run as a",
"1, \"\") print(str((len(B) - 1)) + \"-Queens has \" + str(sol) + \"",
"l if rightClear: B[i + l][right] -= 1 if leftClear: B[i + l][left]",
"not args[0] == \"-v\": print(usage) return v = True ns = args[1] n",
"+= \", \" #if not at end, keep adding separators to text printer",
"B[i + l][right] += 1 if leftClear: B[i + l][left] += 1 def",
"j) findSolutions(B, i+1, mode) removeQueen(B, i, j) return B[0][0] def printBoard(B): sol =",
"= \"\" # string that holds n v = None if len(args) ==",
"range(n+1): B_mini = [] for n2 in range(n+1): B_mini.append(0) B.append(B_mini) # Put a",
"!= n: printer += \", \" #if not at end, keep adding separators",
"\"\") print(str((len(B) - 1)) + \"-Queens has \" + str(sol) + \" solutions\")",
"Parsing finished. # Create board & run other methods. B = [] for",
"printer += str(B[e][0]) if e != n: printer += \", \" #if not",
"text printer += \")\" print(printer) B[0][0] += 1 return 1 else: for j",
"i, mode): n = len(B)-1 v = False if mode == \"verbose\": v",
"for n1 in range(n+1): B_mini = [] for n2 in range(n+1): B_mini.append(0) B.append(B_mini)",
"l > 0) right = j + l left = j - l",
"== \"__main__\": # execute only if run as a script args = input(\"Queens",
"j # vertical downwards queen line of sight for k in range(len(B)): if",
"diagonal downwards queen line of sight for l in range(len(B)): rightClear = (i",
"v = True ns = args[1] n = 0 try: n = int(ns)",
"B[i + l][left] -= 1 def removeQueen(B, i, j): B[i][j] -= 1 B[i][0]",
"for l in range(len(B)): rightClear = (i + l < len(B)) and (j",
"return # Parsing finished. # Create board & run other methods. B =",
"= len(B)-1 v = False if mode == \"verbose\": v = True printer",
"+ l < len(B)) leftClear = (i + l < len(B)) and (j",
"+= 1 if leftClear: B[i + l][left] += 1 def findSolutions(B, i, mode):",
"j - l if rightClear: B[i + l][right] -= 1 if leftClear: B[i",
"for e in range(len(B)): printer += str(B[e][0]) if e != n: printer +=",
"v = False ns = args[0] else: if not args[0] == \"-v\": print(usage)",
"range(n+1): B_mini.append(0) B.append(B_mini) # Put a T/F (1/0) in B[0][1] to indicate mode",
"if e != n: printer += \", \" #if not at end, keep",
"1 else: for j in range(len(B)): if B[i][j] == 0: placeQueen(B, i, j)",
"int(ns) except ValueError: print(usage) return # Parsing finished. # Create board & run",
"\"__main__\": # execute only if run as a script args = input(\"Queens \").split(\"",
"if __name__ == \"__main__\": # execute only if run as a script args",
"= [] for n1 in range(n+1): B_mini = [] for n2 in range(n+1):",
"B[i + l][right] -= 1 if leftClear: B[i + l][left] -= 1 def",
"= (i + l < len(B)) and (j - l > 0) right",
"B[0][0] def printBoard(B): sol = None if B[0][1] == 1: sol = findSolutions(B,",
"len(B)) leftClear = (i + l < len(B)) and (j - l >",
"Put a T/F (1/0) in B[0][1] to indicate mode if v: B[0][1] =",
"#if not at end, keep adding separators to text printer += \")\" print(printer)",
"return v = True ns = args[1] n = 0 try: n =",
"-= 1 # diagonal downwards queen line of sight for l in range(len(B)):",
"(i + l < len(B)) and (j + l < len(B)) leftClear =",
"+= \")\" print(printer) B[0][0] += 1 return 1 else: for j in range(len(B)):",
"sol = None if B[0][1] == 1: sol = findSolutions(B, 1, \"verbose\") else:",
"in range(len(B)): if k != i: B[k][down] += 1 # diagonal downwards queen",
"and (j - l > 0) right = j + l left =",
"n2 in range(n+1): B_mini.append(0) B.append(B_mini) # Put a T/F (1/0) in B[0][1] to",
"= j down = j # vertical downwards queen line of sight for",
"B.append(B_mini) # Put a T/F (1/0) in B[0][1] to indicate mode if v:",
"(1/0) in B[0][1] to indicate mode if v: B[0][1] = 1 else: B[0][1]",
"leftClear = (i + l < len(B)) and (j - l > 0)",
"= [] for n2 in range(n+1): B_mini.append(0) B.append(B_mini) # Put a T/F (1/0)",
"B[i][0] = j down = j # vertical downwards queen line of sight",
"indicate mode if v: B[0][1] = 1 else: B[0][1] = 0 printBoard(B) if",
"for j in range(len(B)): if B[i][j] == 0: placeQueen(B, i, j) findSolutions(B, i+1,",
"len(B)-1 v = False if mode == \"verbose\": v = True printer =",
"solutions\") def main(args): usage = \"Usage: Queens [-v] number \\nOption: -v verbose output,",
"= (i + l < len(B)) and (j + l < len(B)) leftClear",
"range(len(B)): if B[i][j] == 0: placeQueen(B, i, j) findSolutions(B, i+1, mode) removeQueen(B, i,",
"== 1: sol = findSolutions(B, 1, \"verbose\") else: sol = findSolutions(B, 1, \"\")",
"range(len(B)): rightClear = (i + l < len(B)) and (j + l <",
"< len(B)) and (j - l > 0) right = j + l",
"mode): n = len(B)-1 v = False if mode == \"verbose\": v =",
"sight for k in range(len(B)): if k != i: B[k][down] += 1 #",
"0 down = j # vertical downwards queen line of sight for k",
"\" + str(sol) + \" solutions\") def main(args): usage = \"Usage: Queens [-v]",
"if k != i: B[k][down] -= 1 # diagonal downwards queen line of",
"solutions\" if len(args) < 1: print(usage) return ns = \"\" # string that",
"= \"(\" if i > n: if v: for e in range(len(B)): printer",
"range(len(B)): printer += str(B[e][0]) if e != n: printer += \", \" #if",
"return 1 else: for j in range(len(B)): if B[i][j] == 0: placeQueen(B, i,",
"printBoard(B): sol = None if B[0][1] == 1: sol = findSolutions(B, 1, \"verbose\")",
"= findSolutions(B, 1, \"verbose\") else: sol = findSolutions(B, 1, \"\") print(str((len(B) - 1))",
"B[0][1] to indicate mode if v: B[0][1] = 1 else: B[0][1] = 0",
"separators to text printer += \")\" print(printer) B[0][0] += 1 return 1 else:",
"\"(\" if i > n: if v: for e in range(len(B)): printer +=",
"-= 1 B[i][0] = 0 down = j # vertical downwards queen line",
"= None if len(args) == 1: v = False ns = args[0] else:",
"keep adding separators to text printer += \")\" print(printer) B[0][0] += 1 return",
"+= 1 B[i][0] = j down = j # vertical downwards queen line",
"print(printer) B[0][0] += 1 return 1 else: for j in range(len(B)): if B[i][j]",
"l in range(len(B)): rightClear = (i + l < len(B)) and (j +",
"(j - l > 0) right = j + l left = j",
"sol = findSolutions(B, 1, \"verbose\") else: sol = findSolutions(B, 1, \"\") print(str((len(B) -",
"if B[i][j] == 0: placeQueen(B, i, j) findSolutions(B, i+1, mode) removeQueen(B, i, j)",
"1: v = False ns = args[0] else: if not args[0] == \"-v\":",
"+ l][left] -= 1 def removeQueen(B, i, j): B[i][j] -= 1 B[i][0] =",
"if len(args) == 1: v = False ns = args[0] else: if not",
"\"\" # string that holds n v = None if len(args) == 1:",
"n v = None if len(args) == 1: v = False ns =",
"rightClear: B[i + l][right] -= 1 if leftClear: B[i + l][left] -= 1",
"= 0 down = j # vertical downwards queen line of sight for",
"== \"verbose\": v = True printer = \"(\" if i > n: if",
"= findSolutions(B, 1, \"\") print(str((len(B) - 1)) + \"-Queens has \" + str(sol)",
"of sight for l in range(len(B)): rightClear = (i + l < len(B))",
"in range(len(B)): printer += str(B[e][0]) if e != n: printer += \", \"",
"ns = \"\" # string that holds n v = None if len(args)",
"B[i][j] += 1 B[i][0] = j down = j # vertical downwards queen",
"< 1: print(usage) return ns = \"\" # string that holds n v",
"n = int(ns) except ValueError: print(usage) return # Parsing finished. # Create board",
"return ns = \"\" # string that holds n v = None if",
"0 try: n = int(ns) except ValueError: print(usage) return # Parsing finished. #",
"= False ns = args[0] else: if not args[0] == \"-v\": print(usage) return",
"string that holds n v = None if len(args) == 1: v =",
"else: for j in range(len(B)): if B[i][j] == 0: placeQueen(B, i, j) findSolutions(B,",
"n: if v: for e in range(len(B)): printer += str(B[e][0]) if e !=",
"[] for n1 in range(n+1): B_mini = [] for n2 in range(n+1): B_mini.append(0)",
"[-v] number \\nOption: -v verbose output, print all solutions\" if len(args) < 1:",
"False ns = args[0] else: if not args[0] == \"-v\": print(usage) return v",
"removeQueen(B, i, j) return B[0][0] def printBoard(B): sol = None if B[0][1] ==",
"& run other methods. B = [] for n1 in range(n+1): B_mini =",
"[] for n2 in range(n+1): B_mini.append(0) B.append(B_mini) # Put a T/F (1/0) in",
"l < len(B)) and (j + l < len(B)) leftClear = (i +",
"for k in range(len(B)): if k != i: B[k][down] -= 1 # diagonal",
"B[0][1] == 1: sol = findSolutions(B, 1, \"verbose\") else: sol = findSolutions(B, 1,",
"False if mode == \"verbose\": v = True printer = \"(\" if i",
"v = None if len(args) == 1: v = False ns = args[0]",
"other methods. B = [] for n1 in range(n+1): B_mini = [] for",
"1 if leftClear: B[i + l][left] += 1 def findSolutions(B, i, mode): n",
"all solutions\" if len(args) < 1: print(usage) return ns = \"\" # string",
"- l if rightClear: B[i + l][right] -= 1 if leftClear: B[i +",
"for n2 in range(n+1): B_mini.append(0) B.append(B_mini) # Put a T/F (1/0) in B[0][1]",
"holds n v = None if len(args) == 1: v = False ns",
"j) return B[0][0] def printBoard(B): sol = None if B[0][1] == 1: sol",
"in range(n+1): B_mini = [] for n2 in range(n+1): B_mini.append(0) B.append(B_mini) # Put",
"def printBoard(B): sol = None if B[0][1] == 1: sol = findSolutions(B, 1,",
"None if len(args) == 1: v = False ns = args[0] else: if",
"findSolutions(B, 1, \"verbose\") else: sol = findSolutions(B, 1, \"\") print(str((len(B) - 1)) +",
"# vertical downwards queen line of sight for k in range(len(B)): if k",
"= 1 else: B[0][1] = 0 printBoard(B) if __name__ == \"__main__\": # execute",
"\"-v\": print(usage) return v = True ns = args[1] n = 0 try:",
"ns = args[1] n = 0 try: n = int(ns) except ValueError: print(usage)",
"None if B[0][1] == 1: sol = findSolutions(B, 1, \"verbose\") else: sol =",
"= int(ns) except ValueError: print(usage) return # Parsing finished. # Create board &",
"+ l left = j - l if rightClear: B[i + l][right] +=",
"def findSolutions(B, i, mode): n = len(B)-1 v = False if mode ==",
"1 B[i][0] = 0 down = j # vertical downwards queen line of",
"args[0] == \"-v\": print(usage) return v = True ns = args[1] n =",
"else: sol = findSolutions(B, 1, \"\") print(str((len(B) - 1)) + \"-Queens has \"",
"print(str((len(B) - 1)) + \"-Queens has \" + str(sol) + \" solutions\") def",
"i, j): B[i][j] += 1 B[i][0] = j down = j # vertical",
"return B[0][0] def printBoard(B): sol = None if B[0][1] == 1: sol =",
"a T/F (1/0) in B[0][1] to indicate mode if v: B[0][1] = 1",
"printer += \", \" #if not at end, keep adding separators to text",
"\"-Queens has \" + str(sol) + \" solutions\") def main(args): usage = \"Usage:",
"l][right] -= 1 if leftClear: B[i + l][left] -= 1 def removeQueen(B, i,",
"in range(len(B)): if B[i][j] == 0: placeQueen(B, i, j) findSolutions(B, i+1, mode) removeQueen(B,",
"k != i: B[k][down] += 1 # diagonal downwards queen line of sight",
"usage = \"Usage: Queens [-v] number \\nOption: -v verbose output, print all solutions\"",
"execute only if run as a script args = input(\"Queens \").split(\" \") main(args)",
"len(args) == 1: v = False ns = args[0] else: if not args[0]",
"n: printer += \", \" #if not at end, keep adding separators to",
"left = j - l if rightClear: B[i + l][right] += 1 if",
"j - l if rightClear: B[i + l][right] += 1 if leftClear: B[i",
"n1 in range(n+1): B_mini = [] for n2 in range(n+1): B_mini.append(0) B.append(B_mini) #",
"B[i][j] -= 1 B[i][0] = 0 down = j # vertical downwards queen",
"line of sight for k in range(len(B)): if k != i: B[k][down] +=",
"B[0][1] = 0 printBoard(B) if __name__ == \"__main__\": # execute only if run",
"rightClear = (i + l < len(B)) and (j + l < len(B))",
"sight for l in range(len(B)): rightClear = (i + l < len(B)) and",
"queen line of sight for k in range(len(B)): if k != i: B[k][down]",
"in range(len(B)): rightClear = (i + l < len(B)) and (j + l",
"try: n = int(ns) except ValueError: print(usage) return # Parsing finished. # Create",
"if mode == \"verbose\": v = True printer = \"(\" if i >",
"True printer = \"(\" if i > n: if v: for e in",
"l left = j - l if rightClear: B[i + l][right] -= 1",
"== 0: placeQueen(B, i, j) findSolutions(B, i+1, mode) removeQueen(B, i, j) return B[0][0]",
"board & run other methods. B = [] for n1 in range(n+1): B_mini",
"i, j) findSolutions(B, i+1, mode) removeQueen(B, i, j) return B[0][0] def printBoard(B): sol",
"\", \" #if not at end, keep adding separators to text printer +=",
"+= 1 return 1 else: for j in range(len(B)): if B[i][j] == 0:",
"j in range(len(B)): if B[i][j] == 0: placeQueen(B, i, j) findSolutions(B, i+1, mode)",
"-= 1 if leftClear: B[i + l][left] -= 1 def removeQueen(B, i, j):",
"# Create board & run other methods. B = [] for n1 in",
"l < len(B)) and (j - l > 0) right = j +",
"+ \" solutions\") def main(args): usage = \"Usage: Queens [-v] number \\nOption: -v",
"number \\nOption: -v verbose output, print all solutions\" if len(args) < 1: print(usage)",
"len(args) < 1: print(usage) return ns = \"\" # string that holds n",
"i, j): B[i][j] -= 1 B[i][0] = 0 down = j # vertical",
"print(usage) return # Parsing finished. # Create board & run other methods. B",
"+ str(sol) + \" solutions\") def main(args): usage = \"Usage: Queens [-v] number",
"i > n: if v: for e in range(len(B)): printer += str(B[e][0]) if",
"run other methods. B = [] for n1 in range(n+1): B_mini = []",
"l < len(B)) leftClear = (i + l < len(B)) and (j -",
"if v: for e in range(len(B)): printer += str(B[e][0]) if e != n:",
"== 1: v = False ns = args[0] else: if not args[0] ==",
"removeQueen(B, i, j): B[i][j] -= 1 B[i][0] = 0 down = j #",
"j): B[i][j] -= 1 B[i][0] = 0 down = j # vertical downwards",
"v: for e in range(len(B)): printer += str(B[e][0]) if e != n: printer",
"1 return 1 else: for j in range(len(B)): if B[i][j] == 0: placeQueen(B,",
"output, print all solutions\" if len(args) < 1: print(usage) return ns = \"\"",
"main(args): usage = \"Usage: Queens [-v] number \\nOption: -v verbose output, print all",
"+= 1 def findSolutions(B, i, mode): n = len(B)-1 v = False if",
"!= i: B[k][down] -= 1 # diagonal downwards queen line of sight for",
"< len(B)) and (j + l < len(B)) leftClear = (i + l",
"for k in range(len(B)): if k != i: B[k][down] += 1 # diagonal",
"l][left] -= 1 def removeQueen(B, i, j): B[i][j] -= 1 B[i][0] = 0",
"if rightClear: B[i + l][right] -= 1 if leftClear: B[i + l][left] -=",
"to indicate mode if v: B[0][1] = 1 else: B[0][1] = 0 printBoard(B)",
"B[k][down] += 1 # diagonal downwards queen line of sight for l in",
"findSolutions(B, i+1, mode) removeQueen(B, i, j) return B[0][0] def printBoard(B): sol = None",
"B = [] for n1 in range(n+1): B_mini = [] for n2 in",
"= 0 printBoard(B) if __name__ == \"__main__\": # execute only if run as",
"= True ns = args[1] n = 0 try: n = int(ns) except",
"of sight for k in range(len(B)): if k != i: B[k][down] += 1",
"i: B[k][down] += 1 # diagonal downwards queen line of sight for l",
"if v: B[0][1] = 1 else: B[0][1] = 0 printBoard(B) if __name__ ==",
"\"verbose\": v = True printer = \"(\" if i > n: if v:",
"+ l][right] += 1 if leftClear: B[i + l][left] += 1 def findSolutions(B,",
"def main(args): usage = \"Usage: Queens [-v] number \\nOption: -v verbose output, print",
"if leftClear: B[i + l][left] += 1 def findSolutions(B, i, mode): n =",
"- l if rightClear: B[i + l][right] += 1 if leftClear: B[i +",
"j): B[i][j] += 1 B[i][0] = j down = j # vertical downwards",
"- l > 0) right = j + l left = j -",
"j down = j # vertical downwards queen line of sight for k",
"> 0) right = j + l left = j - l if",
"\"Usage: Queens [-v] number \\nOption: -v verbose output, print all solutions\" if len(args)",
"placeQueen(B, i, j) findSolutions(B, i+1, mode) removeQueen(B, i, j) return B[0][0] def printBoard(B):",
"k != i: B[k][down] -= 1 # diagonal downwards queen line of sight",
"n = 0 try: n = int(ns) except ValueError: print(usage) return # Parsing",
"that holds n v = None if len(args) == 1: v = False",
"1 if leftClear: B[i + l][left] -= 1 def removeQueen(B, i, j): B[i][j]",
"has \" + str(sol) + \" solutions\") def main(args): usage = \"Usage: Queens",
"printer = \"(\" if i > n: if v: for e in range(len(B)):",
"1: print(usage) return ns = \"\" # string that holds n v =",
"print(usage) return v = True ns = args[1] n = 0 try: n",
"in range(len(B)): if k != i: B[k][down] -= 1 # diagonal downwards queen",
"B[0][0] += 1 return 1 else: for j in range(len(B)): if B[i][j] ==",
"placeQueen(B, i, j): B[i][j] += 1 B[i][0] = j down = j #",
"mode == \"verbose\": v = True printer = \"(\" if i > n:",
"j + l left = j - l if rightClear: B[i + l][right]",
"sight for k in range(len(B)): if k != i: B[k][down] -= 1 #",
"else: if not args[0] == \"-v\": print(usage) return v = True ns =",
"# diagonal downwards queen line of sight for l in range(len(B)): rightClear =",
"if len(args) < 1: print(usage) return ns = \"\" # string that holds",
"findSolutions(B, i, mode): n = len(B)-1 v = False if mode == \"verbose\":",
"B_mini.append(0) B.append(B_mini) # Put a T/F (1/0) in B[0][1] to indicate mode if",
"1: sol = findSolutions(B, 1, \"verbose\") else: sol = findSolutions(B, 1, \"\") print(str((len(B)",
"l left = j - l if rightClear: B[i + l][right] += 1",
"1 else: B[0][1] = 0 printBoard(B) if __name__ == \"__main__\": # execute only",
"l if rightClear: B[i + l][right] += 1 if leftClear: B[i + l][left]",
"= args[0] else: if not args[0] == \"-v\": print(usage) return v = True",
"# execute only if run as a script args = input(\"Queens \").split(\" \")",
"mode) removeQueen(B, i, j) return B[0][0] def printBoard(B): sol = None if B[0][1]",
"n = len(B)-1 v = False if mode == \"verbose\": v = True",
"# string that holds n v = None if len(args) == 1: v",
"\"verbose\") else: sol = findSolutions(B, 1, \"\") print(str((len(B) - 1)) + \"-Queens has",
"+ l left = j - l if rightClear: B[i + l][right] -=",
"finished. # Create board & run other methods. B = [] for n1",
"rightClear: B[i + l][right] += 1 if leftClear: B[i + l][left] += 1",
"+ l < len(B)) and (j + l < len(B)) leftClear = (i",
"not at end, keep adding separators to text printer += \")\" print(printer) B[0][0]",
"B[k][down] -= 1 # diagonal downwards queen line of sight for l in",
"# Parsing finished. # Create board & run other methods. B = []",
"\" solutions\") def main(args): usage = \"Usage: Queens [-v] number \\nOption: -v verbose",
"leftClear: B[i + l][left] -= 1 def removeQueen(B, i, j): B[i][j] -= 1",
"+= 1 # diagonal downwards queen line of sight for l in range(len(B)):",
"+= str(B[e][0]) if e != n: printer += \", \" #if not at",
"= False if mode == \"verbose\": v = True printer = \"(\" if",
"Queens [-v] number \\nOption: -v verbose output, print all solutions\" if len(args) <",
"adding separators to text printer += \")\" print(printer) B[0][0] += 1 return 1",
"queen line of sight for l in range(len(B)): rightClear = (i + l",
"if leftClear: B[i + l][left] -= 1 def removeQueen(B, i, j): B[i][j] -=",
"of sight for k in range(len(B)): if k != i: B[k][down] -= 1",
"ns = args[0] else: if not args[0] == \"-v\": print(usage) return v =",
"(j + l < len(B)) leftClear = (i + l < len(B)) and",
"printer += \")\" print(printer) B[0][0] += 1 return 1 else: for j in",
"e != n: printer += \", \" #if not at end, keep adding",
"B[i][j] == 0: placeQueen(B, i, j) findSolutions(B, i+1, mode) removeQueen(B, i, j) return",
"i, j) return B[0][0] def printBoard(B): sol = None if B[0][1] == 1:",
"= j - l if rightClear: B[i + l][right] += 1 if leftClear:",
"e in range(len(B)): printer += str(B[e][0]) if e != n: printer += \",",
"range(len(B)): if k != i: B[k][down] += 1 # diagonal downwards queen line",
"in B[0][1] to indicate mode if v: B[0][1] = 1 else: B[0][1] =",
"str(B[e][0]) if e != n: printer += \", \" #if not at end,",
"= None if B[0][1] == 1: sol = findSolutions(B, 1, \"verbose\") else: sol",
"in range(n+1): B_mini.append(0) B.append(B_mini) # Put a T/F (1/0) in B[0][1] to indicate",
"except ValueError: print(usage) return # Parsing finished. # Create board & run other",
"+ l < len(B)) and (j - l > 0) right = j",
"downwards queen line of sight for k in range(len(B)): if k != i:",
"line of sight for k in range(len(B)): if k != i: B[k][down] -=",
"# Put a T/F (1/0) in B[0][1] to indicate mode if v: B[0][1]",
"mode if v: B[0][1] = 1 else: B[0][1] = 0 printBoard(B) if __name__",
"Create board & run other methods. B = [] for n1 in range(n+1):",
"methods. B = [] for n1 in range(n+1): B_mini = [] for n2",
"ValueError: print(usage) return # Parsing finished. # Create board & run other methods.",
"- 1)) + \"-Queens has \" + str(sol) + \" solutions\") def main(args):",
"verbose output, print all solutions\" if len(args) < 1: print(usage) return ns =",
"-v verbose output, print all solutions\" if len(args) < 1: print(usage) return ns",
"findSolutions(B, 1, \"\") print(str((len(B) - 1)) + \"-Queens has \" + str(sol) +",
"= j - l if rightClear: B[i + l][right] -= 1 if leftClear:",
"down = j # vertical downwards queen line of sight for k in",
"if k != i: B[k][down] += 1 # diagonal downwards queen line of",
"k in range(len(B)): if k != i: B[k][down] -= 1 # diagonal downwards",
"l][right] += 1 if leftClear: B[i + l][left] += 1 def findSolutions(B, i,",
"end, keep adding separators to text printer += \")\" print(printer) B[0][0] += 1",
"0: placeQueen(B, i, j) findSolutions(B, i+1, mode) removeQueen(B, i, j) return B[0][0] def",
"vertical downwards queen line of sight for k in range(len(B)): if k !=",
"+ l][right] -= 1 if leftClear: B[i + l][left] -= 1 def removeQueen(B,",
"sol = findSolutions(B, 1, \"\") print(str((len(B) - 1)) + \"-Queens has \" +",
"v: B[0][1] = 1 else: B[0][1] = 0 printBoard(B) if __name__ == \"__main__\":",
"\\nOption: -v verbose output, print all solutions\" if len(args) < 1: print(usage) return",
"at end, keep adding separators to text printer += \")\" print(printer) B[0][0] +=",
"\" #if not at end, keep adding separators to text printer += \")\"",
"= args[1] n = 0 try: n = int(ns) except ValueError: print(usage) return",
"T/F (1/0) in B[0][1] to indicate mode if v: B[0][1] = 1 else:",
"== \"-v\": print(usage) return v = True ns = args[1] n = 0",
"len(B)) and (j - l > 0) right = j + l left",
"0) right = j + l left = j - l if rightClear:",
"if B[0][1] == 1: sol = findSolutions(B, 1, \"verbose\") else: sol = findSolutions(B,",
"-= 1 def removeQueen(B, i, j): B[i][j] -= 1 B[i][0] = 0 down",
"1, \"verbose\") else: sol = findSolutions(B, 1, \"\") print(str((len(B) - 1)) + \"-Queens",
"else: B[0][1] = 0 printBoard(B) if __name__ == \"__main__\": # execute only if",
"line of sight for l in range(len(B)): rightClear = (i + l <",
"args[0] else: if not args[0] == \"-v\": print(usage) return v = True ns",
"= 0 try: n = int(ns) except ValueError: print(usage) return # Parsing finished.",
"printBoard(B) if __name__ == \"__main__\": # execute only if run as a script",
"v = False if mode == \"verbose\": v = True printer = \"(\"",
"!= i: B[k][down] += 1 # diagonal downwards queen line of sight for",
"downwards queen line of sight for l in range(len(B)): rightClear = (i +",
"left = j - l if rightClear: B[i + l][right] -= 1 if",
"v = True printer = \"(\" if i > n: if v: for",
"str(sol) + \" solutions\") def main(args): usage = \"Usage: Queens [-v] number \\nOption:",
"B[i + l][left] += 1 def findSolutions(B, i, mode): n = len(B)-1 v",
"and (j + l < len(B)) leftClear = (i + l < len(B))",
"+ \"-Queens has \" + str(sol) + \" solutions\") def main(args): usage =",
"1 def findSolutions(B, i, mode): n = len(B)-1 v = False if mode",
"range(len(B)): if k != i: B[k][down] -= 1 # diagonal downwards queen line",
"right = j + l left = j - l if rightClear: B[i",
"if i > n: if v: for e in range(len(B)): printer += str(B[e][0])",
"< len(B)) leftClear = (i + l < len(B)) and (j - l",
"__name__ == \"__main__\": # execute only if run as a script args =",
"= \"Usage: Queens [-v] number \\nOption: -v verbose output, print all solutions\" if",
"= j + l left = j - l if rightClear: B[i +",
"= j # vertical downwards queen line of sight for k in range(len(B)):",
"len(B)) and (j + l < len(B)) leftClear = (i + l <",
"def placeQueen(B, i, j): B[i][j] += 1 B[i][0] = j down = j",
"k in range(len(B)): if k != i: B[k][down] += 1 # diagonal downwards",
"if rightClear: B[i + l][right] += 1 if leftClear: B[i + l][left] +=",
"l][left] += 1 def findSolutions(B, i, mode): n = len(B)-1 v = False",
"\")\" print(printer) B[0][0] += 1 return 1 else: for j in range(len(B)): if",
"1 B[i][0] = j down = j # vertical downwards queen line of",
"1 def removeQueen(B, i, j): B[i][j] -= 1 B[i][0] = 0 down =",
"1)) + \"-Queens has \" + str(sol) + \" solutions\") def main(args): usage",
"B_mini = [] for n2 in range(n+1): B_mini.append(0) B.append(B_mini) # Put a T/F",
"1 # diagonal downwards queen line of sight for l in range(len(B)): rightClear",
"i+1, mode) removeQueen(B, i, j) return B[0][0] def printBoard(B): sol = None if"
] |
[
"models extendable at runtime.\"\"\" # shortcut to main used class from .main import",
"pydantic models extendable at runtime.\"\"\" # shortcut to main used class from .main",
"\"\"\"A lib to define pydantic models extendable at runtime.\"\"\" # shortcut to main",
"to define pydantic models extendable at runtime.\"\"\" # shortcut to main used class",
"at runtime.\"\"\" # shortcut to main used class from .main import ExtendableModelMeta from",
"extendable at runtime.\"\"\" # shortcut to main used class from .main import ExtendableModelMeta",
"<gh_stars>0 \"\"\"A lib to define pydantic models extendable at runtime.\"\"\" # shortcut to",
"define pydantic models extendable at runtime.\"\"\" # shortcut to main used class from",
"lib to define pydantic models extendable at runtime.\"\"\" # shortcut to main used",
"# shortcut to main used class from .main import ExtendableModelMeta from .version import",
"runtime.\"\"\" # shortcut to main used class from .main import ExtendableModelMeta from .version",
"shortcut to main used class from .main import ExtendableModelMeta from .version import __version__"
] |
[
"arg +'\" &') serial.write('n'.encode()) else: print('Unknown Command') class ScratchServer(socketserver.ThreadingTCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,",
"+'\" &') serial.write('n'.encode()) else: print('Unknown Command') class ScratchServer(socketserver.ThreadingTCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)",
"os.system('/home/pi/mugbot-talk-1.1.sh ' + arg + ' &') # for speak in English #",
"'face_y': arg = min(max(int(arg) + 95, 80), 110) serial.write((str(arg) + 'y').encode()) elif action",
"speak in English # os.system('espeak -ven+f3 -k5 -s150 ' + '\"' + arg",
"English # os.system('espeak -ven+f3 -k5 -s150 \"Scratch connection established\" &') def handle(self): while",
"established\" &') def handle(self): while True: self.data = self.request.recv(1024).strip() if len(self.data) == 0:",
"elif action == 'face_x': arg = min(max(int(arg) + 90, 5), 175) serial.write((str(arg) +",
"json.loads(self.data) action = json_obj['action'] arg = json_obj['arg'] if action == 'face_y': arg =",
"'\"' + arg +'\" &') serial.write('n'.encode()) else: print('Unknown Command') class ScratchServer(socketserver.ThreadingTCPServer): def server_bind(self):",
"175) serial.write((str(arg) + 'x').encode()) elif action == 'eye': arg = min(max(int(arg), 0), 255)",
"95, 80), 110) serial.write((str(arg) + 'y').encode()) elif action == 'face_x': arg = min(max(int(arg)",
"action == 'face_x': arg = min(max(int(arg) + 90, 5), 175) serial.write((str(arg) + 'x').encode())",
"-*- coding: utf-8 -*- try: import socketserver except: import SocketServer as socketserver import",
"'face_x': arg = min(max(int(arg) + 90, 5), 175) serial.write((str(arg) + 'x').encode()) elif action",
"os.system('/home/pi/mugbot-talk-1.1.sh ' + 'スクラッチとの接続を開始しました &') # for speak in English # os.system('espeak -ven+f3",
"= self.request.recv(1024).strip() if len(self.data) == 0: break json_obj = json.loads(self.data) action = json_obj['action']",
"arg = min(max(int(arg), 0), 255) serial.write((str(arg) + 'z').encode()) elif action == 'speech': serial.write('t'.encode())",
"serial.write((str(arg) + 'z').encode()) elif action == 'speech': serial.write('t'.encode()) if sys.version_info.major == 2: arg",
"ScratchHandler(socketserver.BaseRequestHandler): def setup(self): os.system('/home/pi/mugbot-talk-1.1.sh ' + 'スクラッチとの接続を開始しました &') # for speak in English",
"arg = json_obj['arg'] if action == 'face_y': arg = min(max(int(arg) + 95, 80),",
"action == 'speech': serial.write('t'.encode()) if sys.version_info.major == 2: arg = arg.encode('utf-8') os.system('/home/pi/mugbot-talk-1.1.sh '",
"' + '\"' + arg +'\" &') serial.write('n'.encode()) else: print('Unknown Command') class ScratchServer(socketserver.ThreadingTCPServer):",
"57600) class ScratchHandler(socketserver.BaseRequestHandler): def setup(self): os.system('/home/pi/mugbot-talk-1.1.sh ' + 'スクラッチとの接続を開始しました &') # for speak",
"speak in English # os.system('espeak -ven+f3 -k5 -s150 \"Scratch connection established\" &') def",
"&') # for speak in English # os.system('espeak -ven+f3 -k5 -s150 \"Scratch connection",
"len(self.data) == 0: break json_obj = json.loads(self.data) action = json_obj['action'] arg = json_obj['arg']",
"sys HOST, PORT = '0.0.0.0', 51234 serial = serial.Serial('/dev/ttyACM0', 57600) class ScratchHandler(socketserver.BaseRequestHandler): def",
"python # -*- coding: utf-8 -*- try: import socketserver except: import SocketServer as",
"= '0.0.0.0', 51234 serial = serial.Serial('/dev/ttyACM0', 57600) class ScratchHandler(socketserver.BaseRequestHandler): def setup(self): os.system('/home/pi/mugbot-talk-1.1.sh '",
"self.request.recv(1024).strip() if len(self.data) == 0: break json_obj = json.loads(self.data) action = json_obj['action'] arg",
"SocketServer as socketserver import signal import socket import serial import os import json",
"-s150 \"Scratch connection established\" &') def handle(self): while True: self.data = self.request.recv(1024).strip() if",
"= min(max(int(arg), 0), 255) serial.write((str(arg) + 'z').encode()) elif action == 'speech': serial.write('t'.encode()) if",
"coding: utf-8 -*- try: import socketserver except: import SocketServer as socketserver import signal",
"+ 90, 5), 175) serial.write((str(arg) + 'x').encode()) elif action == 'eye': arg =",
"try: import socketserver except: import SocketServer as socketserver import signal import socket import",
"json import sys HOST, PORT = '0.0.0.0', 51234 serial = serial.Serial('/dev/ttyACM0', 57600) class",
"import sys HOST, PORT = '0.0.0.0', 51234 serial = serial.Serial('/dev/ttyACM0', 57600) class ScratchHandler(socketserver.BaseRequestHandler):",
"255) serial.write((str(arg) + 'z').encode()) elif action == 'speech': serial.write('t'.encode()) if sys.version_info.major == 2:",
"5), 175) serial.write((str(arg) + 'x').encode()) elif action == 'eye': arg = min(max(int(arg), 0),",
"&') # for speak in English # os.system('espeak -ven+f3 -k5 -s150 ' +",
"for speak in English # os.system('espeak -ven+f3 -k5 -s150 ' + '\"' +",
"0: break json_obj = json.loads(self.data) action = json_obj['action'] arg = json_obj['arg'] if action",
"== 'face_x': arg = min(max(int(arg) + 90, 5), 175) serial.write((str(arg) + 'x').encode()) elif",
"#!/usr/bin/env python # -*- coding: utf-8 -*- try: import socketserver except: import SocketServer",
"= min(max(int(arg) + 95, 80), 110) serial.write((str(arg) + 'y').encode()) elif action == 'face_x':",
"== 'speech': serial.write('t'.encode()) if sys.version_info.major == 2: arg = arg.encode('utf-8') os.system('/home/pi/mugbot-talk-1.1.sh ' +",
"+ 95, 80), 110) serial.write((str(arg) + 'y').encode()) elif action == 'face_x': arg =",
"== 2: arg = arg.encode('utf-8') os.system('/home/pi/mugbot-talk-1.1.sh ' + arg + ' &') #",
"self.socket.bind(self.server_address) if __name__ == '__main__': signal.signal(signal.SIGINT, signal.SIG_DFL) server = ScratchServer((HOST, PORT), ScratchHandler) server.serve_forever()",
"except: import SocketServer as socketserver import signal import socket import serial import os",
"elif action == 'speech': serial.write('t'.encode()) if sys.version_info.major == 2: arg = arg.encode('utf-8') os.system('/home/pi/mugbot-talk-1.1.sh",
"= json_obj['action'] arg = json_obj['arg'] if action == 'face_y': arg = min(max(int(arg) +",
"min(max(int(arg) + 90, 5), 175) serial.write((str(arg) + 'x').encode()) elif action == 'eye': arg",
"self.data = self.request.recv(1024).strip() if len(self.data) == 0: break json_obj = json.loads(self.data) action =",
"ScratchServer(socketserver.ThreadingTCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) self.socket.bind(self.server_address) if __name__ == '__main__': signal.signal(signal.SIGINT, signal.SIG_DFL)",
"arg = min(max(int(arg) + 95, 80), 110) serial.write((str(arg) + 'y').encode()) elif action ==",
"== 'eye': arg = min(max(int(arg), 0), 255) serial.write((str(arg) + 'z').encode()) elif action ==",
"as socketserver import signal import socket import serial import os import json import",
"== 'face_y': arg = min(max(int(arg) + 95, 80), 110) serial.write((str(arg) + 'y').encode()) elif",
"arg.encode('utf-8') os.system('/home/pi/mugbot-talk-1.1.sh ' + arg + ' &') # for speak in English",
"110) serial.write((str(arg) + 'y').encode()) elif action == 'face_x': arg = min(max(int(arg) + 90,",
"min(max(int(arg) + 95, 80), 110) serial.write((str(arg) + 'y').encode()) elif action == 'face_x': arg",
"if len(self.data) == 0: break json_obj = json.loads(self.data) action = json_obj['action'] arg =",
"'スクラッチとの接続を開始しました &') # for speak in English # os.system('espeak -ven+f3 -k5 -s150 \"Scratch",
"+ 'x').encode()) elif action == 'eye': arg = min(max(int(arg), 0), 255) serial.write((str(arg) +",
"'y').encode()) elif action == 'face_x': arg = min(max(int(arg) + 90, 5), 175) serial.write((str(arg)",
"json_obj['arg'] if action == 'face_y': arg = min(max(int(arg) + 95, 80), 110) serial.write((str(arg)",
"signal import socket import serial import os import json import sys HOST, PORT",
"80), 110) serial.write((str(arg) + 'y').encode()) elif action == 'face_x': arg = min(max(int(arg) +",
"HOST, PORT = '0.0.0.0', 51234 serial = serial.Serial('/dev/ttyACM0', 57600) class ScratchHandler(socketserver.BaseRequestHandler): def setup(self):",
"' &') # for speak in English # os.system('espeak -ven+f3 -k5 -s150 '",
"socket import serial import os import json import sys HOST, PORT = '0.0.0.0',",
"import socket import serial import os import json import sys HOST, PORT =",
"-ven+f3 -k5 -s150 ' + '\"' + arg +'\" &') serial.write('n'.encode()) else: print('Unknown",
"2: arg = arg.encode('utf-8') os.system('/home/pi/mugbot-talk-1.1.sh ' + arg + ' &') # for",
"json_obj['action'] arg = json_obj['arg'] if action == 'face_y': arg = min(max(int(arg) + 95,",
"&') serial.write('n'.encode()) else: print('Unknown Command') class ScratchServer(socketserver.ThreadingTCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) self.socket.bind(self.server_address)",
"import socketserver except: import SocketServer as socketserver import signal import socket import serial",
"import serial import os import json import sys HOST, PORT = '0.0.0.0', 51234",
"\"Scratch connection established\" &') def handle(self): while True: self.data = self.request.recv(1024).strip() if len(self.data)",
"= json_obj['arg'] if action == 'face_y': arg = min(max(int(arg) + 95, 80), 110)",
"' + arg + ' &') # for speak in English # os.system('espeak",
"-k5 -s150 \"Scratch connection established\" &') def handle(self): while True: self.data = self.request.recv(1024).strip()",
"'eye': arg = min(max(int(arg), 0), 255) serial.write((str(arg) + 'z').encode()) elif action == 'speech':",
"elif action == 'eye': arg = min(max(int(arg), 0), 255) serial.write((str(arg) + 'z').encode()) elif",
"= serial.Serial('/dev/ttyACM0', 57600) class ScratchHandler(socketserver.BaseRequestHandler): def setup(self): os.system('/home/pi/mugbot-talk-1.1.sh ' + 'スクラッチとの接続を開始しました &') #",
"+ arg +'\" &') serial.write('n'.encode()) else: print('Unknown Command') class ScratchServer(socketserver.ThreadingTCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET,",
"if sys.version_info.major == 2: arg = arg.encode('utf-8') os.system('/home/pi/mugbot-talk-1.1.sh ' + arg + '",
"os import json import sys HOST, PORT = '0.0.0.0', 51234 serial = serial.Serial('/dev/ttyACM0',",
"serial import os import json import sys HOST, PORT = '0.0.0.0', 51234 serial",
"'z').encode()) elif action == 'speech': serial.write('t'.encode()) if sys.version_info.major == 2: arg = arg.encode('utf-8')",
"sys.version_info.major == 2: arg = arg.encode('utf-8') os.system('/home/pi/mugbot-talk-1.1.sh ' + arg + ' &')",
"arg + ' &') # for speak in English # os.system('espeak -ven+f3 -k5",
"# os.system('espeak -ven+f3 -k5 -s150 ' + '\"' + arg +'\" &') serial.write('n'.encode())",
"+ '\"' + arg +'\" &') serial.write('n'.encode()) else: print('Unknown Command') class ScratchServer(socketserver.ThreadingTCPServer): def",
"True) self.socket.bind(self.server_address) if __name__ == '__main__': signal.signal(signal.SIGINT, signal.SIG_DFL) server = ScratchServer((HOST, PORT), ScratchHandler)",
"English # os.system('espeak -ven+f3 -k5 -s150 ' + '\"' + arg +'\" &')",
"else: print('Unknown Command') class ScratchServer(socketserver.ThreadingTCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) self.socket.bind(self.server_address) if __name__",
"socket.SO_REUSEADDR, True) self.socket.bind(self.server_address) if __name__ == '__main__': signal.signal(signal.SIGINT, signal.SIG_DFL) server = ScratchServer((HOST, PORT),",
"in English # os.system('espeak -ven+f3 -k5 -s150 \"Scratch connection established\" &') def handle(self):",
"handle(self): while True: self.data = self.request.recv(1024).strip() if len(self.data) == 0: break json_obj =",
"serial.Serial('/dev/ttyACM0', 57600) class ScratchHandler(socketserver.BaseRequestHandler): def setup(self): os.system('/home/pi/mugbot-talk-1.1.sh ' + 'スクラッチとの接続を開始しました &') # for",
"90, 5), 175) serial.write((str(arg) + 'x').encode()) elif action == 'eye': arg = min(max(int(arg),",
"Command') class ScratchServer(socketserver.ThreadingTCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) self.socket.bind(self.server_address) if __name__ == '__main__':",
"def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) self.socket.bind(self.server_address) if __name__ == '__main__': signal.signal(signal.SIGINT, signal.SIG_DFL) server",
"socketserver import signal import socket import serial import os import json import sys",
"-s150 ' + '\"' + arg +'\" &') serial.write('n'.encode()) else: print('Unknown Command') class",
"connection established\" &') def handle(self): while True: self.data = self.request.recv(1024).strip() if len(self.data) ==",
"in English # os.system('espeak -ven+f3 -k5 -s150 ' + '\"' + arg +'\"",
"== 0: break json_obj = json.loads(self.data) action = json_obj['action'] arg = json_obj['arg'] if",
"-k5 -s150 ' + '\"' + arg +'\" &') serial.write('n'.encode()) else: print('Unknown Command')",
"class ScratchServer(socketserver.ThreadingTCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) self.socket.bind(self.server_address) if __name__ == '__main__': signal.signal(signal.SIGINT,",
"utf-8 -*- try: import socketserver except: import SocketServer as socketserver import signal import",
"serial.write('n'.encode()) else: print('Unknown Command') class ScratchServer(socketserver.ThreadingTCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) self.socket.bind(self.server_address) if",
"import signal import socket import serial import os import json import sys HOST,",
"+ 'z').encode()) elif action == 'speech': serial.write('t'.encode()) if sys.version_info.major == 2: arg =",
"action == 'eye': arg = min(max(int(arg), 0), 255) serial.write((str(arg) + 'z').encode()) elif action",
"socketserver except: import SocketServer as socketserver import signal import socket import serial import",
"self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) self.socket.bind(self.server_address) if __name__ == '__main__': signal.signal(signal.SIGINT, signal.SIG_DFL) server = ScratchServer((HOST,",
"0), 255) serial.write((str(arg) + 'z').encode()) elif action == 'speech': serial.write('t'.encode()) if sys.version_info.major ==",
"# for speak in English # os.system('espeak -ven+f3 -k5 -s150 \"Scratch connection established\"",
"serial.write((str(arg) + 'x').encode()) elif action == 'eye': arg = min(max(int(arg), 0), 255) serial.write((str(arg)",
"serial.write('t'.encode()) if sys.version_info.major == 2: arg = arg.encode('utf-8') os.system('/home/pi/mugbot-talk-1.1.sh ' + arg +",
"True: self.data = self.request.recv(1024).strip() if len(self.data) == 0: break json_obj = json.loads(self.data) action",
"action == 'face_y': arg = min(max(int(arg) + 95, 80), 110) serial.write((str(arg) + 'y').encode())",
"os.system('espeak -ven+f3 -k5 -s150 ' + '\"' + arg +'\" &') serial.write('n'.encode()) else:",
"server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) self.socket.bind(self.server_address) if __name__ == '__main__': signal.signal(signal.SIGINT, signal.SIG_DFL) server =",
"# for speak in English # os.system('espeak -ven+f3 -k5 -s150 ' + '\"'",
"print('Unknown Command') class ScratchServer(socketserver.ThreadingTCPServer): def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) self.socket.bind(self.server_address) if __name__ ==",
"def handle(self): while True: self.data = self.request.recv(1024).strip() if len(self.data) == 0: break json_obj",
"serial = serial.Serial('/dev/ttyACM0', 57600) class ScratchHandler(socketserver.BaseRequestHandler): def setup(self): os.system('/home/pi/mugbot-talk-1.1.sh ' + 'スクラッチとの接続を開始しました &')",
"'0.0.0.0', 51234 serial = serial.Serial('/dev/ttyACM0', 57600) class ScratchHandler(socketserver.BaseRequestHandler): def setup(self): os.system('/home/pi/mugbot-talk-1.1.sh ' +",
"serial.write((str(arg) + 'y').encode()) elif action == 'face_x': arg = min(max(int(arg) + 90, 5),",
"def setup(self): os.system('/home/pi/mugbot-talk-1.1.sh ' + 'スクラッチとの接続を開始しました &') # for speak in English #",
"= min(max(int(arg) + 90, 5), 175) serial.write((str(arg) + 'x').encode()) elif action == 'eye':",
"while True: self.data = self.request.recv(1024).strip() if len(self.data) == 0: break json_obj = json.loads(self.data)",
"import SocketServer as socketserver import signal import socket import serial import os import",
"for speak in English # os.system('espeak -ven+f3 -k5 -s150 \"Scratch connection established\" &')",
"min(max(int(arg), 0), 255) serial.write((str(arg) + 'z').encode()) elif action == 'speech': serial.write('t'.encode()) if sys.version_info.major",
"# os.system('espeak -ven+f3 -k5 -s150 \"Scratch connection established\" &') def handle(self): while True:",
"if action == 'face_y': arg = min(max(int(arg) + 95, 80), 110) serial.write((str(arg) +",
"arg = arg.encode('utf-8') os.system('/home/pi/mugbot-talk-1.1.sh ' + arg + ' &') # for speak",
"break json_obj = json.loads(self.data) action = json_obj['action'] arg = json_obj['arg'] if action ==",
"os.system('espeak -ven+f3 -k5 -s150 \"Scratch connection established\" &') def handle(self): while True: self.data",
"json_obj = json.loads(self.data) action = json_obj['action'] arg = json_obj['arg'] if action == 'face_y':",
"= json.loads(self.data) action = json_obj['action'] arg = json_obj['arg'] if action == 'face_y': arg",
"+ ' &') # for speak in English # os.system('espeak -ven+f3 -k5 -s150",
"import json import sys HOST, PORT = '0.0.0.0', 51234 serial = serial.Serial('/dev/ttyACM0', 57600)",
"= arg.encode('utf-8') os.system('/home/pi/mugbot-talk-1.1.sh ' + arg + ' &') # for speak in",
"setup(self): os.system('/home/pi/mugbot-talk-1.1.sh ' + 'スクラッチとの接続を開始しました &') # for speak in English # os.system('espeak",
"&') def handle(self): while True: self.data = self.request.recv(1024).strip() if len(self.data) == 0: break",
"import os import json import sys HOST, PORT = '0.0.0.0', 51234 serial =",
"# -*- coding: utf-8 -*- try: import socketserver except: import SocketServer as socketserver",
"+ arg + ' &') # for speak in English # os.system('espeak -ven+f3",
"'speech': serial.write('t'.encode()) if sys.version_info.major == 2: arg = arg.encode('utf-8') os.system('/home/pi/mugbot-talk-1.1.sh ' + arg",
"'x').encode()) elif action == 'eye': arg = min(max(int(arg), 0), 255) serial.write((str(arg) + 'z').encode())",
"51234 serial = serial.Serial('/dev/ttyACM0', 57600) class ScratchHandler(socketserver.BaseRequestHandler): def setup(self): os.system('/home/pi/mugbot-talk-1.1.sh ' + 'スクラッチとの接続を開始しました",
"class ScratchHandler(socketserver.BaseRequestHandler): def setup(self): os.system('/home/pi/mugbot-talk-1.1.sh ' + 'スクラッチとの接続を開始しました &') # for speak in",
"' + 'スクラッチとの接続を開始しました &') # for speak in English # os.system('espeak -ven+f3 -k5",
"action = json_obj['action'] arg = json_obj['arg'] if action == 'face_y': arg = min(max(int(arg)",
"arg = min(max(int(arg) + 90, 5), 175) serial.write((str(arg) + 'x').encode()) elif action ==",
"-*- try: import socketserver except: import SocketServer as socketserver import signal import socket",
"+ 'スクラッチとの接続を開始しました &') # for speak in English # os.system('espeak -ven+f3 -k5 -s150",
"PORT = '0.0.0.0', 51234 serial = serial.Serial('/dev/ttyACM0', 57600) class ScratchHandler(socketserver.BaseRequestHandler): def setup(self): os.system('/home/pi/mugbot-talk-1.1.sh",
"+ 'y').encode()) elif action == 'face_x': arg = min(max(int(arg) + 90, 5), 175)",
"-ven+f3 -k5 -s150 \"Scratch connection established\" &') def handle(self): while True: self.data ="
] |
[
"show, warn, error from basemessage import WireMessage from nullsink import NullSink class Sink:",
"len(msg) > _max: _max = len(msg) if not _min or _min > len(msg):",
"= average message size\" % int(s/n)) show(\"%d = minimum message size\" % _min)",
"WireMessage from nullsink import NullSink class Sink: def __init__(self,source): self.input_type = WireMessage self.iter",
"= source def run(self): trace(\"\") n = 0 s = 0 _max =",
"= WireMessage self.iter = source def run(self): trace(\"\") n = 0 s =",
"str(type(msg))) n += 1 s += len(msg) if len(msg) > _max: _max =",
"source def run(self): trace(\"\") n = 0 s = 0 _max = 0",
"in self.iter: if n == 0: info(\"message type = %s\" % str(type(msg))) n",
"len(msg) if len(msg) > _max: _max = len(msg) if not _min or _min",
"basemessage import WireMessage from nullsink import NullSink class Sink: def __init__(self,source): self.input_type =",
"import NullSink class Sink: def __init__(self,source): self.input_type = WireMessage self.iter = source def",
"+= len(msg) if len(msg) > _max: _max = len(msg) if not _min or",
"trace(\"\") n = 0 s = 0 _max = 0 _min = None",
"_min or _min > len(msg): _min = len(msg) show(\"%d messages read\" % n)",
"int(s/n)) show(\"%d = minimum message size\" % _min) show(\"%d = maximum message size\"",
"logger import trace, info, show, warn, error from basemessage import WireMessage from nullsink",
"or _min > len(msg): _min = len(msg) show(\"%d messages read\" % n) show(\"%d",
"_max = 0 _min = None for msg in self.iter: if n ==",
"_min = len(msg) show(\"%d messages read\" % n) show(\"%d bytes read\" % s)",
"error from basemessage import WireMessage from nullsink import NullSink class Sink: def __init__(self,source):",
"len(msg) if not _min or _min > len(msg): _min = len(msg) show(\"%d messages",
"not _min or _min > len(msg): _min = len(msg) show(\"%d messages read\" %",
"0 _min = None for msg in self.iter: if n == 0: info(\"message",
"def run(self): trace(\"\") n = 0 s = 0 _max = 0 _min",
"s) show(\"%d = average message size\" % int(s/n)) show(\"%d = minimum message size\"",
"n += 1 s += len(msg) if len(msg) > _max: _max = len(msg)",
"0 s = 0 _max = 0 _min = None for msg in",
"bytes read\" % s) show(\"%d = average message size\" % int(s/n)) show(\"%d =",
"show(\"%d = minimum message size\" % _min) show(\"%d = maximum message size\" %",
"import trace, info, show, warn, error from basemessage import WireMessage from nullsink import",
"if len(msg) > _max: _max = len(msg) if not _min or _min >",
"self.iter: if n == 0: info(\"message type = %s\" % str(type(msg))) n +=",
"% str(type(msg))) n += 1 s += len(msg) if len(msg) > _max: _max",
"> len(msg): _min = len(msg) show(\"%d messages read\" % n) show(\"%d bytes read\"",
"> _max: _max = len(msg) if not _min or _min > len(msg): _min",
"0 _max = 0 _min = None for msg in self.iter: if n",
"len(msg): _min = len(msg) show(\"%d messages read\" % n) show(\"%d bytes read\" %",
"message size\" % int(s/n)) show(\"%d = minimum message size\" % _min) show(\"%d =",
"average message size\" % int(s/n)) show(\"%d = minimum message size\" % _min) show(\"%d",
"msg in self.iter: if n == 0: info(\"message type = %s\" % str(type(msg)))",
"% s) show(\"%d = average message size\" % int(s/n)) show(\"%d = minimum message",
"if n == 0: info(\"message type = %s\" % str(type(msg))) n += 1",
"messages read\" % n) show(\"%d bytes read\" % s) show(\"%d = average message",
"= %s\" % str(type(msg))) n += 1 s += len(msg) if len(msg) >",
"type = %s\" % str(type(msg))) n += 1 s += len(msg) if len(msg)",
"size\" % int(s/n)) show(\"%d = minimum message size\" % _min) show(\"%d = maximum",
"_max = len(msg) if not _min or _min > len(msg): _min = len(msg)",
"% n) show(\"%d bytes read\" % s) show(\"%d = average message size\" %",
"def __init__(self,source): self.input_type = WireMessage self.iter = source def run(self): trace(\"\") n =",
"read\" % s) show(\"%d = average message size\" % int(s/n)) show(\"%d = minimum",
"# bytesink.py from logger import trace, info, show, warn, error from basemessage import",
"= 0 _min = None for msg in self.iter: if n == 0:",
"= 0 s = 0 _max = 0 _min = None for msg",
"WireMessage self.iter = source def run(self): trace(\"\") n = 0 s = 0",
"0: info(\"message type = %s\" % str(type(msg))) n += 1 s += len(msg)",
"from nullsink import NullSink class Sink: def __init__(self,source): self.input_type = WireMessage self.iter =",
"for msg in self.iter: if n == 0: info(\"message type = %s\" %",
"== 0: info(\"message type = %s\" % str(type(msg))) n += 1 s +=",
"_max: _max = len(msg) if not _min or _min > len(msg): _min =",
"None for msg in self.iter: if n == 0: info(\"message type = %s\"",
"len(msg) show(\"%d messages read\" % n) show(\"%d bytes read\" % s) show(\"%d =",
"trace, info, show, warn, error from basemessage import WireMessage from nullsink import NullSink",
"s += len(msg) if len(msg) > _max: _max = len(msg) if not _min",
"self.iter = source def run(self): trace(\"\") n = 0 s = 0 _max",
"= 0 _max = 0 _min = None for msg in self.iter: if",
"% int(s/n)) show(\"%d = minimum message size\" % _min) show(\"%d = maximum message",
"NullSink class Sink: def __init__(self,source): self.input_type = WireMessage self.iter = source def run(self):",
"1 s += len(msg) if len(msg) > _max: _max = len(msg) if not",
"__init__(self,source): self.input_type = WireMessage self.iter = source def run(self): trace(\"\") n = 0",
"from logger import trace, info, show, warn, error from basemessage import WireMessage from",
"nullsink import NullSink class Sink: def __init__(self,source): self.input_type = WireMessage self.iter = source",
"show(\"%d messages read\" % n) show(\"%d bytes read\" % s) show(\"%d = average",
"info(\"message type = %s\" % str(type(msg))) n += 1 s += len(msg) if",
"read\" % n) show(\"%d bytes read\" % s) show(\"%d = average message size\"",
"run(self): trace(\"\") n = 0 s = 0 _max = 0 _min =",
"Sink: def __init__(self,source): self.input_type = WireMessage self.iter = source def run(self): trace(\"\") n",
"import WireMessage from nullsink import NullSink class Sink: def __init__(self,source): self.input_type = WireMessage",
"%s\" % str(type(msg))) n += 1 s += len(msg) if len(msg) > _max:",
"if not _min or _min > len(msg): _min = len(msg) show(\"%d messages read\"",
"n) show(\"%d bytes read\" % s) show(\"%d = average message size\" % int(s/n))",
"warn, error from basemessage import WireMessage from nullsink import NullSink class Sink: def",
"show(\"%d = average message size\" % int(s/n)) show(\"%d = minimum message size\" %",
"s = 0 _max = 0 _min = None for msg in self.iter:",
"_min = None for msg in self.iter: if n == 0: info(\"message type",
"+= 1 s += len(msg) if len(msg) > _max: _max = len(msg) if",
"= len(msg) if not _min or _min > len(msg): _min = len(msg) show(\"%d",
"= None for msg in self.iter: if n == 0: info(\"message type =",
"_min > len(msg): _min = len(msg) show(\"%d messages read\" % n) show(\"%d bytes",
"n == 0: info(\"message type = %s\" % str(type(msg))) n += 1 s",
"= len(msg) show(\"%d messages read\" % n) show(\"%d bytes read\" % s) show(\"%d",
"n = 0 s = 0 _max = 0 _min = None for",
"= minimum message size\" % _min) show(\"%d = maximum message size\" % _max)",
"from basemessage import WireMessage from nullsink import NullSink class Sink: def __init__(self,source): self.input_type",
"show(\"%d bytes read\" % s) show(\"%d = average message size\" % int(s/n)) show(\"%d",
"self.input_type = WireMessage self.iter = source def run(self): trace(\"\") n = 0 s",
"bytesink.py from logger import trace, info, show, warn, error from basemessage import WireMessage",
"<gh_stars>0 # bytesink.py from logger import trace, info, show, warn, error from basemessage",
"info, show, warn, error from basemessage import WireMessage from nullsink import NullSink class",
"class Sink: def __init__(self,source): self.input_type = WireMessage self.iter = source def run(self): trace(\"\")"
] |
[
"connection=dynamodb_connection, global_indexes=[index_job_id]) etl_records = ETLRecords(persistence_object=table, avro_schema_object=avro_schema) for job in SAMPLE_RECORD_JOBS: assert etl_records.put(**job) yield",
"None, } class TestRunActions(object): @pytest.yield_fixture(scope='module') # noqa def etl_records(self, dynamodb_connection): avro_schema = get_avro_schema('mycroft/avro/etl_record.json')",
"# noqa def etl_records(self, dynamodb_connection): avro_schema = get_avro_schema('mycroft/avro/etl_record.json') index_job_id = GlobalAllIndex( ETLRecords.INDEX_JOB_ID_AND_DATA_DATE, parts=[HashKey('job_id'),",
"@pytest.mark.parametrize(\"job_id\", ['y', '..', '!', '', '_']) def test_list_runs_by_job_id_bad_job_id(self, job_id): with pytest.raises(ValueError) as e:",
"import list_runs_by_job_id from tests.models.test_abstract_records import dynamodb_connection # noqa from tests.models.test_abstract_records import NAME_TO_SCHEMA from",
"Table.create( 'ETLRecords', schema=NAME_TO_SCHEMA['etl_records'], connection=dynamodb_connection, global_indexes=[index_job_id]) etl_records = ETLRecords(persistence_object=table, avro_schema_object=avro_schema) for job in SAMPLE_RECORD_JOBS:",
"ETLRecords(persistence_object=table, avro_schema_object=avro_schema) for job in SAMPLE_RECORD_JOBS: assert etl_records.put(**job) yield etl_records assert table.delete() def",
"import GlobalAllIndex from boto.dynamodb2.table import Table from mycroft.models.aws_connections import get_avro_schema from mycroft.models.etl_records import",
"'run_by': None, 'job_id': None, 'etl_error': None, 'additional_arguments': None, } class TestRunActions(object): @pytest.yield_fixture(scope='module') #",
"SAMPLE_JOB_ID]) assert len(return_value['runs']) == expected_count @pytest.mark.parametrize(\"job_id\", ['y', '..', '!', '', '_']) def test_list_runs_by_job_id_bad_job_id(self,",
"{ 'hash_key': None, 'data_date': None, 'etl_status': None, 'et_runtime': None, 'et_starttime': None, 'load_runtime': None,",
"'additional_arguments': None, } class TestRunActions(object): @pytest.yield_fixture(scope='module') # noqa def etl_records(self, dynamodb_connection): avro_schema =",
"result = _parse_runs(empty_runs) assert result['runs'][0] == BASE_DICT def test_list_runs_by_job_id(self, etl_records): return_value = list_runs_by_job_id(SAMPLE_JOB_ID,",
"global_indexes=[index_job_id]) etl_records = ETLRecords(persistence_object=table, avro_schema_object=avro_schema) for job in SAMPLE_RECORD_JOBS: assert etl_records.put(**job) yield etl_records",
"import dynamodb_connection # noqa from tests.models.test_abstract_records import NAME_TO_SCHEMA from tests.models.test_etl_record import FakeETLRecord from",
"from tests.data.etl_record import SAMPLE_JOB_ID from tests.data.etl_record import SAMPLE_RECORD_JOBS BASE_DICT = { 'hash_key': None,",
"'hash_key': None, 'data_date': None, 'etl_status': None, 'et_runtime': None, 'et_starttime': None, 'load_runtime': None, 'load_starttime':",
"import Table from mycroft.models.aws_connections import get_avro_schema from mycroft.models.etl_records import ETLRecords from mycroft.logic.run_actions import",
"job['job_id'] == SAMPLE_JOB_ID]) assert len(return_value['runs']) == expected_count @pytest.mark.parametrize(\"job_id\", ['y', '..', '!', '', '_'])",
"boto.dynamodb2.fields import RangeKey from boto.dynamodb2.fields import GlobalAllIndex from boto.dynamodb2.table import Table from mycroft.models.aws_connections",
"mycroft.models.etl_records import ETLRecords from mycroft.logic.run_actions import _parse_runs from mycroft.logic.run_actions import list_runs_by_job_id from tests.models.test_abstract_records",
"table.delete() def test__parse_runs_empty_run(self): empty_runs = [FakeETLRecord(BASE_DICT)] result = _parse_runs(empty_runs) assert result['runs'][0] == BASE_DICT",
"None, 'job_id': None, 'etl_error': None, 'additional_arguments': None, } class TestRunActions(object): @pytest.yield_fixture(scope='module') # noqa",
"== SAMPLE_JOB_ID]) assert len(return_value['runs']) == expected_count @pytest.mark.parametrize(\"job_id\", ['y', '..', '!', '', '_']) def",
"class TestRunActions(object): @pytest.yield_fixture(scope='module') # noqa def etl_records(self, dynamodb_connection): avro_schema = get_avro_schema('mycroft/avro/etl_record.json') index_job_id =",
"None, 'data_date': None, 'etl_status': None, 'et_runtime': None, 'et_starttime': None, 'load_runtime': None, 'load_starttime': None,",
"'ETLRecords', schema=NAME_TO_SCHEMA['etl_records'], connection=dynamodb_connection, global_indexes=[index_job_id]) etl_records = ETLRecords(persistence_object=table, avro_schema_object=avro_schema) for job in SAMPLE_RECORD_JOBS: assert",
"FakeETLRecord from tests.data.etl_record import SAMPLE_JOB_ID from tests.data.etl_record import SAMPLE_RECORD_JOBS BASE_DICT = { 'hash_key':",
"avro_schema = get_avro_schema('mycroft/avro/etl_record.json') index_job_id = GlobalAllIndex( ETLRecords.INDEX_JOB_ID_AND_DATA_DATE, parts=[HashKey('job_id'), RangeKey('data_date')]) table = Table.create( 'ETLRecords',",
"tests.data.etl_record import SAMPLE_RECORD_JOBS BASE_DICT = { 'hash_key': None, 'data_date': None, 'etl_status': None, 'et_runtime':",
"NAME_TO_SCHEMA from tests.models.test_etl_record import FakeETLRecord from tests.data.etl_record import SAMPLE_JOB_ID from tests.data.etl_record import SAMPLE_RECORD_JOBS",
"expected_count = len([job for job in SAMPLE_RECORD_JOBS if job['job_id'] == SAMPLE_JOB_ID]) assert len(return_value['runs'])",
"tests.data.etl_record import SAMPLE_JOB_ID from tests.data.etl_record import SAMPLE_RECORD_JOBS BASE_DICT = { 'hash_key': None, 'data_date':",
"mycroft.logic.run_actions import _parse_runs from mycroft.logic.run_actions import list_runs_by_job_id from tests.models.test_abstract_records import dynamodb_connection # noqa",
"= ETLRecords(persistence_object=table, avro_schema_object=avro_schema) for job in SAMPLE_RECORD_JOBS: assert etl_records.put(**job) yield etl_records assert table.delete()",
"mycroft.logic.run_actions import list_runs_by_job_id from tests.models.test_abstract_records import dynamodb_connection # noqa from tests.models.test_abstract_records import NAME_TO_SCHEMA",
"list_runs_by_job_id(SAMPLE_JOB_ID, etl_records) expected_count = len([job for job in SAMPLE_RECORD_JOBS if job['job_id'] == SAMPLE_JOB_ID])",
"etl_records = ETLRecords(persistence_object=table, avro_schema_object=avro_schema) for job in SAMPLE_RECORD_JOBS: assert etl_records.put(**job) yield etl_records assert",
"job in SAMPLE_RECORD_JOBS if job['job_id'] == SAMPLE_JOB_ID]) assert len(return_value['runs']) == expected_count @pytest.mark.parametrize(\"job_id\", ['y',",
"from boto.dynamodb2.fields import RangeKey from boto.dynamodb2.fields import GlobalAllIndex from boto.dynamodb2.table import Table from",
"= get_avro_schema('mycroft/avro/etl_record.json') index_job_id = GlobalAllIndex( ETLRecords.INDEX_JOB_ID_AND_DATA_DATE, parts=[HashKey('job_id'), RangeKey('data_date')]) table = Table.create( 'ETLRecords', schema=NAME_TO_SCHEMA['etl_records'],",
"None, 'etl_status': None, 'et_runtime': None, 'et_starttime': None, 'load_runtime': None, 'load_starttime': None, 'redshift_id': None,",
"get_avro_schema('mycroft/avro/etl_record.json') index_job_id = GlobalAllIndex( ETLRecords.INDEX_JOB_ID_AND_DATA_DATE, parts=[HashKey('job_id'), RangeKey('data_date')]) table = Table.create( 'ETLRecords', schema=NAME_TO_SCHEMA['etl_records'], connection=dynamodb_connection,",
"tests.models.test_etl_record import FakeETLRecord from tests.data.etl_record import SAMPLE_JOB_ID from tests.data.etl_record import SAMPLE_RECORD_JOBS BASE_DICT =",
"etl_records.put(**job) yield etl_records assert table.delete() def test__parse_runs_empty_run(self): empty_runs = [FakeETLRecord(BASE_DICT)] result = _parse_runs(empty_runs)",
"from boto.dynamodb2.fields import HashKey from boto.dynamodb2.fields import RangeKey from boto.dynamodb2.fields import GlobalAllIndex from",
"RangeKey from boto.dynamodb2.fields import GlobalAllIndex from boto.dynamodb2.table import Table from mycroft.models.aws_connections import get_avro_schema",
"index_job_id = GlobalAllIndex( ETLRecords.INDEX_JOB_ID_AND_DATA_DATE, parts=[HashKey('job_id'), RangeKey('data_date')]) table = Table.create( 'ETLRecords', schema=NAME_TO_SCHEMA['etl_records'], connection=dynamodb_connection, global_indexes=[index_job_id])",
"etl_records): return_value = list_runs_by_job_id(SAMPLE_JOB_ID, etl_records) expected_count = len([job for job in SAMPLE_RECORD_JOBS if",
"in SAMPLE_RECORD_JOBS if job['job_id'] == SAMPLE_JOB_ID]) assert len(return_value['runs']) == expected_count @pytest.mark.parametrize(\"job_id\", ['y', '..',",
"noqa def etl_records(self, dynamodb_connection): avro_schema = get_avro_schema('mycroft/avro/etl_record.json') index_job_id = GlobalAllIndex( ETLRecords.INDEX_JOB_ID_AND_DATA_DATE, parts=[HashKey('job_id'), RangeKey('data_date')])",
"assert table.delete() def test__parse_runs_empty_run(self): empty_runs = [FakeETLRecord(BASE_DICT)] result = _parse_runs(empty_runs) assert result['runs'][0] ==",
"} class TestRunActions(object): @pytest.yield_fixture(scope='module') # noqa def etl_records(self, dynamodb_connection): avro_schema = get_avro_schema('mycroft/avro/etl_record.json') index_job_id",
"-*- import pytest from boto.dynamodb2.fields import HashKey from boto.dynamodb2.fields import RangeKey from boto.dynamodb2.fields",
"'data_date': None, 'etl_status': None, 'et_runtime': None, 'et_starttime': None, 'load_runtime': None, 'load_starttime': None, 'redshift_id':",
"RangeKey('data_date')]) table = Table.create( 'ETLRecords', schema=NAME_TO_SCHEMA['etl_records'], connection=dynamodb_connection, global_indexes=[index_job_id]) etl_records = ETLRecords(persistence_object=table, avro_schema_object=avro_schema) for",
"from tests.data.etl_record import SAMPLE_RECORD_JOBS BASE_DICT = { 'hash_key': None, 'data_date': None, 'etl_status': None,",
"from tests.models.test_etl_record import FakeETLRecord from tests.data.etl_record import SAMPLE_JOB_ID from tests.data.etl_record import SAMPLE_RECORD_JOBS BASE_DICT",
"ETLRecords.INDEX_JOB_ID_AND_DATA_DATE, parts=[HashKey('job_id'), RangeKey('data_date')]) table = Table.create( 'ETLRecords', schema=NAME_TO_SCHEMA['etl_records'], connection=dynamodb_connection, global_indexes=[index_job_id]) etl_records = ETLRecords(persistence_object=table,",
"expected_count @pytest.mark.parametrize(\"job_id\", ['y', '..', '!', '', '_']) def test_list_runs_by_job_id_bad_job_id(self, job_id): with pytest.raises(ValueError) as",
"SAMPLE_RECORD_JOBS BASE_DICT = { 'hash_key': None, 'data_date': None, 'etl_status': None, 'et_runtime': None, 'et_starttime':",
"from boto.dynamodb2.table import Table from mycroft.models.aws_connections import get_avro_schema from mycroft.models.etl_records import ETLRecords from",
"_parse_runs(empty_runs) assert result['runs'][0] == BASE_DICT def test_list_runs_by_job_id(self, etl_records): return_value = list_runs_by_job_id(SAMPLE_JOB_ID, etl_records) expected_count",
"boto.dynamodb2.table import Table from mycroft.models.aws_connections import get_avro_schema from mycroft.models.etl_records import ETLRecords from mycroft.logic.run_actions",
"test_list_runs_by_job_id(self, etl_records): return_value = list_runs_by_job_id(SAMPLE_JOB_ID, etl_records) expected_count = len([job for job in SAMPLE_RECORD_JOBS",
"test__parse_runs_empty_run(self): empty_runs = [FakeETLRecord(BASE_DICT)] result = _parse_runs(empty_runs) assert result['runs'][0] == BASE_DICT def test_list_runs_by_job_id(self,",
"Table from mycroft.models.aws_connections import get_avro_schema from mycroft.models.etl_records import ETLRecords from mycroft.logic.run_actions import _parse_runs",
"tests.models.test_abstract_records import dynamodb_connection # noqa from tests.models.test_abstract_records import NAME_TO_SCHEMA from tests.models.test_etl_record import FakeETLRecord",
"GlobalAllIndex( ETLRecords.INDEX_JOB_ID_AND_DATA_DATE, parts=[HashKey('job_id'), RangeKey('data_date')]) table = Table.create( 'ETLRecords', schema=NAME_TO_SCHEMA['etl_records'], connection=dynamodb_connection, global_indexes=[index_job_id]) etl_records =",
"'..', '!', '', '_']) def test_list_runs_by_job_id_bad_job_id(self, job_id): with pytest.raises(ValueError) as e: list_runs_by_job_id(job_id, None)",
"None, 's3_path': None, 'updated_at': None, 'run_by': None, 'job_id': None, 'etl_error': None, 'additional_arguments': None,",
"= _parse_runs(empty_runs) assert result['runs'][0] == BASE_DICT def test_list_runs_by_job_id(self, etl_records): return_value = list_runs_by_job_id(SAMPLE_JOB_ID, etl_records)",
"= list_runs_by_job_id(SAMPLE_JOB_ID, etl_records) expected_count = len([job for job in SAMPLE_RECORD_JOBS if job['job_id'] ==",
"'redshift_id': None, 's3_path': None, 'updated_at': None, 'run_by': None, 'job_id': None, 'etl_error': None, 'additional_arguments':",
"for job in SAMPLE_RECORD_JOBS: assert etl_records.put(**job) yield etl_records assert table.delete() def test__parse_runs_empty_run(self): empty_runs",
"def test__parse_runs_empty_run(self): empty_runs = [FakeETLRecord(BASE_DICT)] result = _parse_runs(empty_runs) assert result['runs'][0] == BASE_DICT def",
"'', '_']) def test_list_runs_by_job_id_bad_job_id(self, job_id): with pytest.raises(ValueError) as e: list_runs_by_job_id(job_id, None) assert e.exconly().startswith(\"ValueError:",
"ETLRecords from mycroft.logic.run_actions import _parse_runs from mycroft.logic.run_actions import list_runs_by_job_id from tests.models.test_abstract_records import dynamodb_connection",
"None, 'et_starttime': None, 'load_runtime': None, 'load_starttime': None, 'redshift_id': None, 's3_path': None, 'updated_at': None,",
"import get_avro_schema from mycroft.models.etl_records import ETLRecords from mycroft.logic.run_actions import _parse_runs from mycroft.logic.run_actions import",
"assert len(return_value['runs']) == expected_count @pytest.mark.parametrize(\"job_id\", ['y', '..', '!', '', '_']) def test_list_runs_by_job_id_bad_job_id(self, job_id):",
"tests.models.test_abstract_records import NAME_TO_SCHEMA from tests.models.test_etl_record import FakeETLRecord from tests.data.etl_record import SAMPLE_JOB_ID from tests.data.etl_record",
"dynamodb_connection # noqa from tests.models.test_abstract_records import NAME_TO_SCHEMA from tests.models.test_etl_record import FakeETLRecord from tests.data.etl_record",
"get_avro_schema from mycroft.models.etl_records import ETLRecords from mycroft.logic.run_actions import _parse_runs from mycroft.logic.run_actions import list_runs_by_job_id",
"dynamodb_connection): avro_schema = get_avro_schema('mycroft/avro/etl_record.json') index_job_id = GlobalAllIndex( ETLRecords.INDEX_JOB_ID_AND_DATA_DATE, parts=[HashKey('job_id'), RangeKey('data_date')]) table = Table.create(",
"import FakeETLRecord from tests.data.etl_record import SAMPLE_JOB_ID from tests.data.etl_record import SAMPLE_RECORD_JOBS BASE_DICT = {",
"mycroft.models.aws_connections import get_avro_schema from mycroft.models.etl_records import ETLRecords from mycroft.logic.run_actions import _parse_runs from mycroft.logic.run_actions",
"GlobalAllIndex from boto.dynamodb2.table import Table from mycroft.models.aws_connections import get_avro_schema from mycroft.models.etl_records import ETLRecords",
"None, 'redshift_id': None, 's3_path': None, 'updated_at': None, 'run_by': None, 'job_id': None, 'etl_error': None,",
"list_runs_by_job_id from tests.models.test_abstract_records import dynamodb_connection # noqa from tests.models.test_abstract_records import NAME_TO_SCHEMA from tests.models.test_etl_record",
"result['runs'][0] == BASE_DICT def test_list_runs_by_job_id(self, etl_records): return_value = list_runs_by_job_id(SAMPLE_JOB_ID, etl_records) expected_count = len([job",
"= Table.create( 'ETLRecords', schema=NAME_TO_SCHEMA['etl_records'], connection=dynamodb_connection, global_indexes=[index_job_id]) etl_records = ETLRecords(persistence_object=table, avro_schema_object=avro_schema) for job in",
"None, 'load_starttime': None, 'redshift_id': None, 's3_path': None, 'updated_at': None, 'run_by': None, 'job_id': None,",
"BASE_DICT def test_list_runs_by_job_id(self, etl_records): return_value = list_runs_by_job_id(SAMPLE_JOB_ID, etl_records) expected_count = len([job for job",
"for job in SAMPLE_RECORD_JOBS if job['job_id'] == SAMPLE_JOB_ID]) assert len(return_value['runs']) == expected_count @pytest.mark.parametrize(\"job_id\",",
"from tests.models.test_abstract_records import dynamodb_connection # noqa from tests.models.test_abstract_records import NAME_TO_SCHEMA from tests.models.test_etl_record import",
"from mycroft.logic.run_actions import list_runs_by_job_id from tests.models.test_abstract_records import dynamodb_connection # noqa from tests.models.test_abstract_records import",
"etl_records assert table.delete() def test__parse_runs_empty_run(self): empty_runs = [FakeETLRecord(BASE_DICT)] result = _parse_runs(empty_runs) assert result['runs'][0]",
"SAMPLE_RECORD_JOBS: assert etl_records.put(**job) yield etl_records assert table.delete() def test__parse_runs_empty_run(self): empty_runs = [FakeETLRecord(BASE_DICT)] result",
"'!', '', '_']) def test_list_runs_by_job_id_bad_job_id(self, job_id): with pytest.raises(ValueError) as e: list_runs_by_job_id(job_id, None) assert",
"table = Table.create( 'ETLRecords', schema=NAME_TO_SCHEMA['etl_records'], connection=dynamodb_connection, global_indexes=[index_job_id]) etl_records = ETLRecords(persistence_object=table, avro_schema_object=avro_schema) for job",
"HashKey from boto.dynamodb2.fields import RangeKey from boto.dynamodb2.fields import GlobalAllIndex from boto.dynamodb2.table import Table",
"from mycroft.models.etl_records import ETLRecords from mycroft.logic.run_actions import _parse_runs from mycroft.logic.run_actions import list_runs_by_job_id from",
"'et_starttime': None, 'load_runtime': None, 'load_starttime': None, 'redshift_id': None, 's3_path': None, 'updated_at': None, 'run_by':",
"= len([job for job in SAMPLE_RECORD_JOBS if job['job_id'] == SAMPLE_JOB_ID]) assert len(return_value['runs']) ==",
"in SAMPLE_RECORD_JOBS: assert etl_records.put(**job) yield etl_records assert table.delete() def test__parse_runs_empty_run(self): empty_runs = [FakeETLRecord(BASE_DICT)]",
"None, 'run_by': None, 'job_id': None, 'etl_error': None, 'additional_arguments': None, } class TestRunActions(object): @pytest.yield_fixture(scope='module')",
"boto.dynamodb2.fields import GlobalAllIndex from boto.dynamodb2.table import Table from mycroft.models.aws_connections import get_avro_schema from mycroft.models.etl_records",
"import SAMPLE_JOB_ID from tests.data.etl_record import SAMPLE_RECORD_JOBS BASE_DICT = { 'hash_key': None, 'data_date': None,",
"from mycroft.models.aws_connections import get_avro_schema from mycroft.models.etl_records import ETLRecords from mycroft.logic.run_actions import _parse_runs from",
"['y', '..', '!', '', '_']) def test_list_runs_by_job_id_bad_job_id(self, job_id): with pytest.raises(ValueError) as e: list_runs_by_job_id(job_id,",
"etl_records) expected_count = len([job for job in SAMPLE_RECORD_JOBS if job['job_id'] == SAMPLE_JOB_ID]) assert",
"'s3_path': None, 'updated_at': None, 'run_by': None, 'job_id': None, 'etl_error': None, 'additional_arguments': None, }",
"'etl_error': None, 'additional_arguments': None, } class TestRunActions(object): @pytest.yield_fixture(scope='module') # noqa def etl_records(self, dynamodb_connection):",
"import HashKey from boto.dynamodb2.fields import RangeKey from boto.dynamodb2.fields import GlobalAllIndex from boto.dynamodb2.table import",
"'updated_at': None, 'run_by': None, 'job_id': None, 'etl_error': None, 'additional_arguments': None, } class TestRunActions(object):",
"avro_schema_object=avro_schema) for job in SAMPLE_RECORD_JOBS: assert etl_records.put(**job) yield etl_records assert table.delete() def test__parse_runs_empty_run(self):",
"'et_runtime': None, 'et_starttime': None, 'load_runtime': None, 'load_starttime': None, 'redshift_id': None, 's3_path': None, 'updated_at':",
"SAMPLE_RECORD_JOBS if job['job_id'] == SAMPLE_JOB_ID]) assert len(return_value['runs']) == expected_count @pytest.mark.parametrize(\"job_id\", ['y', '..', '!',",
"parts=[HashKey('job_id'), RangeKey('data_date')]) table = Table.create( 'ETLRecords', schema=NAME_TO_SCHEMA['etl_records'], connection=dynamodb_connection, global_indexes=[index_job_id]) etl_records = ETLRecords(persistence_object=table, avro_schema_object=avro_schema)",
"# -*- coding: utf-8 -*- import pytest from boto.dynamodb2.fields import HashKey from boto.dynamodb2.fields",
"from mycroft.logic.run_actions import _parse_runs from mycroft.logic.run_actions import list_runs_by_job_id from tests.models.test_abstract_records import dynamodb_connection #",
"== expected_count @pytest.mark.parametrize(\"job_id\", ['y', '..', '!', '', '_']) def test_list_runs_by_job_id_bad_job_id(self, job_id): with pytest.raises(ValueError)",
"= { 'hash_key': None, 'data_date': None, 'etl_status': None, 'et_runtime': None, 'et_starttime': None, 'load_runtime':",
"_parse_runs from mycroft.logic.run_actions import list_runs_by_job_id from tests.models.test_abstract_records import dynamodb_connection # noqa from tests.models.test_abstract_records",
"etl_records(self, dynamodb_connection): avro_schema = get_avro_schema('mycroft/avro/etl_record.json') index_job_id = GlobalAllIndex( ETLRecords.INDEX_JOB_ID_AND_DATA_DATE, parts=[HashKey('job_id'), RangeKey('data_date')]) table =",
"len([job for job in SAMPLE_RECORD_JOBS if job['job_id'] == SAMPLE_JOB_ID]) assert len(return_value['runs']) == expected_count",
"TestRunActions(object): @pytest.yield_fixture(scope='module') # noqa def etl_records(self, dynamodb_connection): avro_schema = get_avro_schema('mycroft/avro/etl_record.json') index_job_id = GlobalAllIndex(",
"len(return_value['runs']) == expected_count @pytest.mark.parametrize(\"job_id\", ['y', '..', '!', '', '_']) def test_list_runs_by_job_id_bad_job_id(self, job_id): with",
"def etl_records(self, dynamodb_connection): avro_schema = get_avro_schema('mycroft/avro/etl_record.json') index_job_id = GlobalAllIndex( ETLRecords.INDEX_JOB_ID_AND_DATA_DATE, parts=[HashKey('job_id'), RangeKey('data_date')]) table",
"noqa from tests.models.test_abstract_records import NAME_TO_SCHEMA from tests.models.test_etl_record import FakeETLRecord from tests.data.etl_record import SAMPLE_JOB_ID",
"None, 'updated_at': None, 'run_by': None, 'job_id': None, 'etl_error': None, 'additional_arguments': None, } class",
"'load_runtime': None, 'load_starttime': None, 'redshift_id': None, 's3_path': None, 'updated_at': None, 'run_by': None, 'job_id':",
"== BASE_DICT def test_list_runs_by_job_id(self, etl_records): return_value = list_runs_by_job_id(SAMPLE_JOB_ID, etl_records) expected_count = len([job for",
"import RangeKey from boto.dynamodb2.fields import GlobalAllIndex from boto.dynamodb2.table import Table from mycroft.models.aws_connections import",
"None, 'etl_error': None, 'additional_arguments': None, } class TestRunActions(object): @pytest.yield_fixture(scope='module') # noqa def etl_records(self,",
"from tests.models.test_abstract_records import NAME_TO_SCHEMA from tests.models.test_etl_record import FakeETLRecord from tests.data.etl_record import SAMPLE_JOB_ID from",
"'etl_status': None, 'et_runtime': None, 'et_starttime': None, 'load_runtime': None, 'load_starttime': None, 'redshift_id': None, 's3_path':",
"= GlobalAllIndex( ETLRecords.INDEX_JOB_ID_AND_DATA_DATE, parts=[HashKey('job_id'), RangeKey('data_date')]) table = Table.create( 'ETLRecords', schema=NAME_TO_SCHEMA['etl_records'], connection=dynamodb_connection, global_indexes=[index_job_id]) etl_records",
"return_value = list_runs_by_job_id(SAMPLE_JOB_ID, etl_records) expected_count = len([job for job in SAMPLE_RECORD_JOBS if job['job_id']",
"coding: utf-8 -*- import pytest from boto.dynamodb2.fields import HashKey from boto.dynamodb2.fields import RangeKey",
"utf-8 -*- import pytest from boto.dynamodb2.fields import HashKey from boto.dynamodb2.fields import RangeKey from",
"assert etl_records.put(**job) yield etl_records assert table.delete() def test__parse_runs_empty_run(self): empty_runs = [FakeETLRecord(BASE_DICT)] result =",
"empty_runs = [FakeETLRecord(BASE_DICT)] result = _parse_runs(empty_runs) assert result['runs'][0] == BASE_DICT def test_list_runs_by_job_id(self, etl_records):",
"BASE_DICT = { 'hash_key': None, 'data_date': None, 'etl_status': None, 'et_runtime': None, 'et_starttime': None,",
"= [FakeETLRecord(BASE_DICT)] result = _parse_runs(empty_runs) assert result['runs'][0] == BASE_DICT def test_list_runs_by_job_id(self, etl_records): return_value",
"None, 'additional_arguments': None, } class TestRunActions(object): @pytest.yield_fixture(scope='module') # noqa def etl_records(self, dynamodb_connection): avro_schema",
"None, 'et_runtime': None, 'et_starttime': None, 'load_runtime': None, 'load_starttime': None, 'redshift_id': None, 's3_path': None,",
"job in SAMPLE_RECORD_JOBS: assert etl_records.put(**job) yield etl_records assert table.delete() def test__parse_runs_empty_run(self): empty_runs =",
"'_']) def test_list_runs_by_job_id_bad_job_id(self, job_id): with pytest.raises(ValueError) as e: list_runs_by_job_id(job_id, None) assert e.exconly().startswith(\"ValueError: invalid",
"'job_id': None, 'etl_error': None, 'additional_arguments': None, } class TestRunActions(object): @pytest.yield_fixture(scope='module') # noqa def",
"'load_starttime': None, 'redshift_id': None, 's3_path': None, 'updated_at': None, 'run_by': None, 'job_id': None, 'etl_error':",
"if job['job_id'] == SAMPLE_JOB_ID]) assert len(return_value['runs']) == expected_count @pytest.mark.parametrize(\"job_id\", ['y', '..', '!', '',",
"[FakeETLRecord(BASE_DICT)] result = _parse_runs(empty_runs) assert result['runs'][0] == BASE_DICT def test_list_runs_by_job_id(self, etl_records): return_value =",
"boto.dynamodb2.fields import HashKey from boto.dynamodb2.fields import RangeKey from boto.dynamodb2.fields import GlobalAllIndex from boto.dynamodb2.table",
"# noqa from tests.models.test_abstract_records import NAME_TO_SCHEMA from tests.models.test_etl_record import FakeETLRecord from tests.data.etl_record import",
"-*- coding: utf-8 -*- import pytest from boto.dynamodb2.fields import HashKey from boto.dynamodb2.fields import",
"import NAME_TO_SCHEMA from tests.models.test_etl_record import FakeETLRecord from tests.data.etl_record import SAMPLE_JOB_ID from tests.data.etl_record import",
"from boto.dynamodb2.fields import GlobalAllIndex from boto.dynamodb2.table import Table from mycroft.models.aws_connections import get_avro_schema from",
"def test_list_runs_by_job_id(self, etl_records): return_value = list_runs_by_job_id(SAMPLE_JOB_ID, etl_records) expected_count = len([job for job in",
"import pytest from boto.dynamodb2.fields import HashKey from boto.dynamodb2.fields import RangeKey from boto.dynamodb2.fields import",
"assert result['runs'][0] == BASE_DICT def test_list_runs_by_job_id(self, etl_records): return_value = list_runs_by_job_id(SAMPLE_JOB_ID, etl_records) expected_count =",
"yield etl_records assert table.delete() def test__parse_runs_empty_run(self): empty_runs = [FakeETLRecord(BASE_DICT)] result = _parse_runs(empty_runs) assert",
"None, 'load_runtime': None, 'load_starttime': None, 'redshift_id': None, 's3_path': None, 'updated_at': None, 'run_by': None,",
"import SAMPLE_RECORD_JOBS BASE_DICT = { 'hash_key': None, 'data_date': None, 'etl_status': None, 'et_runtime': None,",
"@pytest.yield_fixture(scope='module') # noqa def etl_records(self, dynamodb_connection): avro_schema = get_avro_schema('mycroft/avro/etl_record.json') index_job_id = GlobalAllIndex( ETLRecords.INDEX_JOB_ID_AND_DATA_DATE,",
"def test_list_runs_by_job_id_bad_job_id(self, job_id): with pytest.raises(ValueError) as e: list_runs_by_job_id(job_id, None) assert e.exconly().startswith(\"ValueError: invalid job_id\")",
"schema=NAME_TO_SCHEMA['etl_records'], connection=dynamodb_connection, global_indexes=[index_job_id]) etl_records = ETLRecords(persistence_object=table, avro_schema_object=avro_schema) for job in SAMPLE_RECORD_JOBS: assert etl_records.put(**job)",
"pytest from boto.dynamodb2.fields import HashKey from boto.dynamodb2.fields import RangeKey from boto.dynamodb2.fields import GlobalAllIndex",
"SAMPLE_JOB_ID from tests.data.etl_record import SAMPLE_RECORD_JOBS BASE_DICT = { 'hash_key': None, 'data_date': None, 'etl_status':",
"import ETLRecords from mycroft.logic.run_actions import _parse_runs from mycroft.logic.run_actions import list_runs_by_job_id from tests.models.test_abstract_records import",
"import _parse_runs from mycroft.logic.run_actions import list_runs_by_job_id from tests.models.test_abstract_records import dynamodb_connection # noqa from"
] |
[
"= forms.CharField( label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ('email',",
"form for creating new users. Includes all the required fields, plus a repeated",
"plus a repeated password.\"\"\" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField( label='Password confirmation',",
"django.core.exceptions import ValidationError from django.contrib.auth import authenticate from .models import User, Profile from",
"a repeated password.\"\"\" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField( label='Password confirmation', widget=forms.PasswordInput)",
"PhoneNumberPrefixWidget from django.core.validators import RegexValidator class UserAdminCreationForm(forms.ModelForm): \"\"\"A form for creating new users.",
"fields = ('email', 'username') def clean_username(self): username = self.cleaned_data.get('username').lower() try: User.objects.get(username__exact=username) except User.DoesNotExist:",
"Meta: model = User fields = ('email', 'username') def clean_username(self): username = self.cleaned_data.get('username').lower()",
"email raise forms.ValidationError(f\"Email {email} is already in use.\") def save(self, commit=True): # Save",
"'Male'), ('Female', 'Female'), ('Other', 'Other'), ) gender = forms.ChoiceField( label='Gender', choices=GENDER, widget=forms.RadioSelect, required=False)",
"choices=GENDER, widget=forms.RadioSelect, required=False) date_of_birth = forms.DateField(widget=forms.DateInput( attrs={'type': 'date'}), required=False) phonenumber = PhoneNumberField( widget",
"import PhoneNumberPrefixWidget from django.core.validators import RegexValidator class UserAdminCreationForm(forms.ModelForm): \"\"\"A form for creating new",
"live'}), 'pincode': forms.TextInput(attrs={'placeholder': 'pincode'}), 'language': forms.TextInput(attrs={'placeholder': 'language'}), 'location': forms.TextInput(attrs={'placeholder': 'location'}), 'bio': forms.TextInput(attrs={'placeholder': 'about",
"field with admin's password hash display field. \"\"\" password = ReadOnlyPasswordHashField() class Meta:",
"password2 and password1 != password2: raise ValidationError(\"Passwords don't match\") return password2 def clean_email(self):",
"class Meta: model = Profile fields = ['first_name', 'last_name', 'phonenumber', 'country', 'avatar', 'address',",
"in use.\") def save(self, commit=True): # Save the provided password in hashed format",
"forms.TextInput(attrs={'placeholder': 'your first name'}), 'last_name': forms.TextInput(attrs={'placeholder': 'your last name'}), 'email': forms.EmailInput(attrs={'placeholder': 'you <EMAIL>'}),",
"= PhoneNumberField( widget = PhoneNumberPrefixWidget(initial='IN') ) class Meta: model = Profile fields =",
"def clean_email(self): email = self.cleaned_data['email'].lower() try: account = User.objects.get(email=email) except User.DoesNotExist: return email",
"model = Profile fields = ['first_name', 'last_name', 'phonenumber', 'country', 'avatar', 'address', 'gender', 'date_of_birth',",
"'date'}), required=False) phonenumber = PhoneNumberField( widget = PhoneNumberPrefixWidget(initial='IN') ) class Meta: model =",
"= ( ('Male', 'Male'), ('Female', 'Female'), ('Other', 'Other'), ) gender = forms.ChoiceField( label='Gender',",
"fields = ('__all__') def clean_password(self): # Regardless of what the user provides, return",
"the two password entries match password1 = self.cleaned_data.get(\"password1\") password2 = self.cleaned_data.get(\"password2\") if password1",
"clean_email(self): email = self.cleaned_data['email'].lower() try: account = User.objects.get(email=email) except User.DoesNotExist: return email raise",
"label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ('email', 'username') def",
"'country', 'avatar', 'address', 'gender', 'date_of_birth', 'pincode', 'language', 'location', 'website', 'bio'] widgets = {",
"\"\"\"A form for creating new users. Includes all the required fields, plus a",
"from phonenumber_field.formfields import PhoneNumberField from phonenumber_field.widgets import PhoneNumberPrefixWidget from django.core.validators import RegexValidator class",
"except User.DoesNotExist: return email raise forms.ValidationError(f\"Email {email} is already in use.\") def save(self,",
"return user class UserAdminChangeForm(forms.ModelForm): \"\"\"A form for updating users. Includes all the fields",
"replaces the password field with admin's password hash display field. \"\"\" password =",
"= super().save(commit=False) user.set_password(self.cleaned_data[\"password2\"]) if commit: user.save() return user class UserAdminChangeForm(forms.ModelForm): \"\"\"A form for",
"forms.CharField( label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ('email', 'username')",
"the fields on the user, but replaces the password field with admin's password",
"= ('email', 'username') def clean_username(self): username = self.cleaned_data.get('username').lower() try: User.objects.get(username__exact=username) except User.DoesNotExist: return",
"widget=forms.PasswordInput) class Meta: model = User fields = ('email', 'username') def clean_username(self): username",
"['first_name', 'last_name', 'phonenumber', 'country', 'avatar', 'address', 'gender', 'date_of_birth', 'pincode', 'language', 'location', 'website', 'bio']",
"'date_of_birth', 'pincode', 'language', 'location', 'website', 'bio'] widgets = { 'first_name': forms.TextInput(attrs={'placeholder': 'your first",
"here, rather than on the field, because the # field does not have",
"return self.initial[\"password\"] class UserProfileForm(forms.ModelForm): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ('Other', 'Other'),",
"where you live'}), 'address': forms.TextInput(attrs={'placeholder': 'your address where you live'}), 'pincode': forms.TextInput(attrs={'placeholder': 'pincode'}),",
"and password1 != password2: raise ValidationError(\"Passwords don't match\") return password2 def clean_email(self): email",
"= forms.DateField(widget=forms.DateInput( attrs={'type': 'date'}), required=False) phonenumber = PhoneNumberField( widget = PhoneNumberPrefixWidget(initial='IN') ) class",
"required=False) date_of_birth = forms.DateField(widget=forms.DateInput( attrs={'type': 'date'}), required=False) phonenumber = PhoneNumberField( widget = PhoneNumberPrefixWidget(initial='IN')",
"in hashed format user = super().save(commit=False) user.set_password(self.cleaned_data[\"password2\"]) if commit: user.save() return user class",
"def clean_password(self): # Regardless of what the user provides, return the initial value.",
"django.contrib.auth.forms import ReadOnlyPasswordHashField from django.core.exceptions import ValidationError from django.contrib.auth import authenticate from .models",
"'your last name'}), 'email': forms.EmailInput(attrs={'placeholder': 'you <EMAIL>'}), 'country': forms.TextInput(attrs={'placeholder': 'country you where you",
"value. # This is done here, rather than on the field, because the",
"password1 and password2 and password1 != password2: raise ValidationError(\"Passwords don't match\") return password2",
"have access to the initial value return self.initial[\"password\"] class UserProfileForm(forms.ModelForm): GENDER = (",
"raise forms.ValidationError(f\"Email {email} is already in use.\") def save(self, commit=True): # Save the",
"'avatar', 'address', 'gender', 'date_of_birth', 'pincode', 'language', 'location', 'website', 'bio'] widgets = { 'first_name':",
"forms.ValidationError(f\"Email {email} is already in use.\") def save(self, commit=True): # Save the provided",
"django.contrib import messages from phonenumber_field.formfields import PhoneNumberField from phonenumber_field.widgets import PhoneNumberPrefixWidget from django.core.validators",
"Meta: model = Profile fields = ['first_name', 'last_name', 'phonenumber', 'country', 'avatar', 'address', 'gender',",
"User.objects.get(email=email) except User.DoesNotExist: return email raise forms.ValidationError(f\"Email {email} is already in use.\") def",
"provided password in hashed format user = super().save(commit=False) user.set_password(self.cleaned_data[\"password2\"]) if commit: user.save() return",
"hashed format user = super().save(commit=False) user.set_password(self.cleaned_data[\"password2\"]) if commit: user.save() return user class UserAdminChangeForm(forms.ModelForm):",
"confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ('email', 'username') def clean_username(self):",
"already taken.\") def clean_password2(self): # Check that the two password entries match password1",
"use.\") def save(self, commit=True): # Save the provided password in hashed format user",
"the required fields, plus a repeated password.\"\"\" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 =",
"forms.TextInput(attrs={'placeholder': 'your last name'}), 'email': forms.EmailInput(attrs={'placeholder': 'you <EMAIL>'}), 'country': forms.TextInput(attrs={'placeholder': 'country you where",
"repeated password.\"\"\" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField( label='Password confirmation', widget=forms.PasswordInput) class",
"the user provides, return the initial value. # This is done here, rather",
"the password field with admin's password hash display field. \"\"\" password = ReadOnlyPasswordHashField()",
"'gender', 'date_of_birth', 'pincode', 'language', 'location', 'website', 'bio'] widgets = { 'first_name': forms.TextInput(attrs={'placeholder': 'your",
"PhoneNumberPrefixWidget(initial='IN') ) class Meta: model = Profile fields = ['first_name', 'last_name', 'phonenumber', 'country',",
"widget=forms.PasswordInput) password2 = forms.CharField( label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User fields",
"from django.contrib import messages from phonenumber_field.formfields import PhoneNumberField from phonenumber_field.widgets import PhoneNumberPrefixWidget from",
"django.contrib.auth.models import Group from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.core.exceptions import ValidationError from django.contrib.auth",
"form for updating users. Includes all the fields on the user, but replaces",
"ValidationError(\"Passwords don't match\") return password2 def clean_email(self): email = self.cleaned_data['email'].lower() try: account =",
"save(self, commit=True): # Save the provided password in hashed format user = super().save(commit=False)",
"'pincode'}), 'language': forms.TextInput(attrs={'placeholder': 'language'}), 'location': forms.TextInput(attrs={'placeholder': 'location'}), 'bio': forms.TextInput(attrs={'placeholder': 'about you'}), 'website': forms.TextInput(attrs={'placeholder':",
"initial value return self.initial[\"password\"] class UserProfileForm(forms.ModelForm): GENDER = ( ('Male', 'Male'), ('Female', 'Female'),",
"class UserProfileForm(forms.ModelForm): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ('Other', 'Other'), ) gender",
".models import User, Profile from django.contrib import messages from phonenumber_field.formfields import PhoneNumberField from",
"because the # field does not have access to the initial value return",
"label='Gender', choices=GENDER, widget=forms.RadioSelect, required=False) date_of_birth = forms.DateField(widget=forms.DateInput( attrs={'type': 'date'}), required=False) phonenumber = PhoneNumberField(",
"widget=forms.RadioSelect, required=False) date_of_birth = forms.DateField(widget=forms.DateInput( attrs={'type': 'date'}), required=False) phonenumber = PhoneNumberField( widget =",
"of what the user provides, return the initial value. # This is done",
"with admin's password hash display field. \"\"\" password = ReadOnlyPasswordHashField() class Meta: model",
"widget = PhoneNumberPrefixWidget(initial='IN') ) class Meta: model = Profile fields = ['first_name', 'last_name',",
") class Meta: model = Profile fields = ['first_name', 'last_name', 'phonenumber', 'country', 'avatar',",
"forms from django.contrib.auth.models import Group from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.core.exceptions import ValidationError",
"if commit: user.save() return user class UserAdminChangeForm(forms.ModelForm): \"\"\"A form for updating users. Includes",
"ReadOnlyPasswordHashField() class Meta: model = User fields = ('__all__') def clean_password(self): # Regardless",
"for creating new users. Includes all the required fields, plus a repeated password.\"\"\"",
"class Meta: model = User fields = ('email', 'username') def clean_username(self): username =",
"required fields, plus a repeated password.\"\"\" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(",
"last name'}), 'email': forms.EmailInput(attrs={'placeholder': 'you <EMAIL>'}), 'country': forms.TextInput(attrs={'placeholder': 'country you where you live'}),",
"password field with admin's password hash display field. \"\"\" password = ReadOnlyPasswordHashField() class",
"widgets = { 'first_name': forms.TextInput(attrs={'placeholder': 'your first name'}), 'last_name': forms.TextInput(attrs={'placeholder': 'your last name'}),",
"messages from phonenumber_field.formfields import PhoneNumberField from phonenumber_field.widgets import PhoneNumberPrefixWidget from django.core.validators import RegexValidator",
"if password1 and password2 and password1 != password2: raise ValidationError(\"Passwords don't match\") return",
"'your address where you live'}), 'pincode': forms.TextInput(attrs={'placeholder': 'pincode'}), 'language': forms.TextInput(attrs={'placeholder': 'language'}), 'location': forms.TextInput(attrs={'placeholder':",
"# Save the provided password in hashed format user = super().save(commit=False) user.set_password(self.cleaned_data[\"password2\"]) if",
"phonenumber = PhoneNumberField( widget = PhoneNumberPrefixWidget(initial='IN') ) class Meta: model = Profile fields",
"Meta: model = User fields = ('__all__') def clean_password(self): # Regardless of what",
"import Group from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.core.exceptions import ValidationError from django.contrib.auth import",
"that the two password entries match password1 = self.cleaned_data.get(\"password1\") password2 = self.cleaned_data.get(\"password2\") if",
"you live'}), 'pincode': forms.TextInput(attrs={'placeholder': 'pincode'}), 'language': forms.TextInput(attrs={'placeholder': 'language'}), 'location': forms.TextInput(attrs={'placeholder': 'location'}), 'bio': forms.TextInput(attrs={'placeholder':",
"'address': forms.TextInput(attrs={'placeholder': 'your address where you live'}), 'pincode': forms.TextInput(attrs={'placeholder': 'pincode'}), 'language': forms.TextInput(attrs={'placeholder': 'language'}),",
"live'}), 'address': forms.TextInput(attrs={'placeholder': 'your address where you live'}), 'pincode': forms.TextInput(attrs={'placeholder': 'pincode'}), 'language': forms.TextInput(attrs={'placeholder':",
"from django.core.exceptions import ValidationError from django.contrib.auth import authenticate from .models import User, Profile",
"('__all__') def clean_password(self): # Regardless of what the user provides, return the initial",
"'username') def clean_username(self): username = self.cleaned_data.get('username').lower() try: User.objects.get(username__exact=username) except User.DoesNotExist: return username raise",
"from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.core.exceptions import ValidationError from django.contrib.auth import authenticate from",
"forms.EmailInput(attrs={'placeholder': 'you <EMAIL>'}), 'country': forms.TextInput(attrs={'placeholder': 'country you where you live'}), 'address': forms.TextInput(attrs={'placeholder': 'your",
"UserAdminChangeForm(forms.ModelForm): \"\"\"A form for updating users. Includes all the fields on the user,",
"on the field, because the # field does not have access to the",
"('Female', 'Female'), ('Other', 'Other'), ) gender = forms.ChoiceField( label='Gender', choices=GENDER, widget=forms.RadioSelect, required=False) date_of_birth",
"= self.cleaned_data.get('username').lower() try: User.objects.get(username__exact=username) except User.DoesNotExist: return username raise forms.ValidationError(\"This username is already",
"'first_name': forms.TextInput(attrs={'placeholder': 'your first name'}), 'last_name': forms.TextInput(attrs={'placeholder': 'your last name'}), 'email': forms.EmailInput(attrs={'placeholder': 'you",
"GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ('Other', 'Other'), ) gender = forms.ChoiceField(",
"commit: user.save() return user class UserAdminChangeForm(forms.ModelForm): \"\"\"A form for updating users. Includes all",
"but replaces the password field with admin's password hash display field. \"\"\" password",
"# Regardless of what the user provides, return the initial value. # This",
"return password2 def clean_email(self): email = self.cleaned_data['email'].lower() try: account = User.objects.get(email=email) except User.DoesNotExist:",
"forms.ChoiceField( label='Gender', choices=GENDER, widget=forms.RadioSelect, required=False) date_of_birth = forms.DateField(widget=forms.DateInput( attrs={'type': 'date'}), required=False) phonenumber =",
"match\") return password2 def clean_email(self): email = self.cleaned_data['email'].lower() try: account = User.objects.get(email=email) except",
"= { 'first_name': forms.TextInput(attrs={'placeholder': 'your first name'}), 'last_name': forms.TextInput(attrs={'placeholder': 'your last name'}), 'email':",
"{email} is already in use.\") def save(self, commit=True): # Save the provided password",
"Save the provided password in hashed format user = super().save(commit=False) user.set_password(self.cleaned_data[\"password2\"]) if commit:",
"fields, plus a repeated password.\"\"\" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField( label='Password",
"from django.core.validators import RegexValidator class UserAdminCreationForm(forms.ModelForm): \"\"\"A form for creating new users. Includes",
"return email raise forms.ValidationError(f\"Email {email} is already in use.\") def save(self, commit=True): #",
"forms.TextInput(attrs={'placeholder': 'country you where you live'}), 'address': forms.TextInput(attrs={'placeholder': 'your address where you live'}),",
"first name'}), 'last_name': forms.TextInput(attrs={'placeholder': 'your last name'}), 'email': forms.EmailInput(attrs={'placeholder': 'you <EMAIL>'}), 'country': forms.TextInput(attrs={'placeholder':",
"display field. \"\"\" password = ReadOnlyPasswordHashField() class Meta: model = User fields =",
"user = super().save(commit=False) user.set_password(self.cleaned_data[\"password2\"]) if commit: user.save() return user class UserAdminChangeForm(forms.ModelForm): \"\"\"A form",
"field. \"\"\" password = ReadOnlyPasswordHashField() class Meta: model = User fields = ('__all__')",
"provides, return the initial value. # This is done here, rather than on",
"to the initial value return self.initial[\"password\"] class UserProfileForm(forms.ModelForm): GENDER = ( ('Male', 'Male'),",
") gender = forms.ChoiceField( label='Gender', choices=GENDER, widget=forms.RadioSelect, required=False) date_of_birth = forms.DateField(widget=forms.DateInput( attrs={'type': 'date'}),",
"user class UserAdminChangeForm(forms.ModelForm): \"\"\"A form for updating users. Includes all the fields on",
"all the required fields, plus a repeated password.\"\"\" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2",
"self.cleaned_data.get('username').lower() try: User.objects.get(username__exact=username) except User.DoesNotExist: return username raise forms.ValidationError(\"This username is already taken.\")",
"raise ValidationError(\"Passwords don't match\") return password2 def clean_email(self): email = self.cleaned_data['email'].lower() try: account",
"Includes all the required fields, plus a repeated password.\"\"\" password1 = forms.CharField(label='Password', widget=forms.PasswordInput)",
"authenticate from .models import User, Profile from django.contrib import messages from phonenumber_field.formfields import",
"password1 = self.cleaned_data.get(\"password1\") password2 = self.cleaned_data.get(\"password2\") if password1 and password2 and password1 !=",
"( ('Male', 'Male'), ('Female', 'Female'), ('Other', 'Other'), ) gender = forms.ChoiceField( label='Gender', choices=GENDER,",
"'location'}), 'bio': forms.TextInput(attrs={'placeholder': 'about you'}), 'website': forms.TextInput(attrs={'placeholder': 'your website url e.g. https://your_website.com'}), }",
"= ['first_name', 'last_name', 'phonenumber', 'country', 'avatar', 'address', 'gender', 'date_of_birth', 'pincode', 'language', 'location', 'website',",
"fields on the user, but replaces the password field with admin's password hash",
"User.objects.get(username__exact=username) except User.DoesNotExist: return username raise forms.ValidationError(\"This username is already taken.\") def clean_password2(self):",
"class UserAdminCreationForm(forms.ModelForm): \"\"\"A form for creating new users. Includes all the required fields,",
"\"\"\" password = ReadOnlyPasswordHashField() class Meta: model = User fields = ('__all__') def",
"two password entries match password1 = self.cleaned_data.get(\"password1\") password2 = self.cleaned_data.get(\"password2\") if password1 and",
"'language'}), 'location': forms.TextInput(attrs={'placeholder': 'location'}), 'bio': forms.TextInput(attrs={'placeholder': 'about you'}), 'website': forms.TextInput(attrs={'placeholder': 'your website url",
"import PhoneNumberField from phonenumber_field.widgets import PhoneNumberPrefixWidget from django.core.validators import RegexValidator class UserAdminCreationForm(forms.ModelForm): \"\"\"A",
"raise forms.ValidationError(\"This username is already taken.\") def clean_password2(self): # Check that the two",
"admin's password hash display field. \"\"\" password = ReadOnlyPasswordHashField() class Meta: model =",
"format user = super().save(commit=False) user.set_password(self.cleaned_data[\"password2\"]) if commit: user.save() return user class UserAdminChangeForm(forms.ModelForm): \"\"\"A",
"= self.cleaned_data['email'].lower() try: account = User.objects.get(email=email) except User.DoesNotExist: return email raise forms.ValidationError(f\"Email {email}",
"import RegexValidator class UserAdminCreationForm(forms.ModelForm): \"\"\"A form for creating new users. Includes all the",
"user.set_password(self.cleaned_data[\"password2\"]) if commit: user.save() return user class UserAdminChangeForm(forms.ModelForm): \"\"\"A form for updating users.",
"ValidationError from django.contrib.auth import authenticate from .models import User, Profile from django.contrib import",
"'your first name'}), 'last_name': forms.TextInput(attrs={'placeholder': 'your last name'}), 'email': forms.EmailInput(attrs={'placeholder': 'you <EMAIL>'}), 'country':",
"password.\"\"\" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField( label='Password confirmation', widget=forms.PasswordInput) class Meta:",
"forms.DateField(widget=forms.DateInput( attrs={'type': 'date'}), required=False) phonenumber = PhoneNumberField( widget = PhoneNumberPrefixWidget(initial='IN') ) class Meta:",
"Group from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.core.exceptions import ValidationError from django.contrib.auth import authenticate",
"forms.TextInput(attrs={'placeholder': 'pincode'}), 'language': forms.TextInput(attrs={'placeholder': 'language'}), 'location': forms.TextInput(attrs={'placeholder': 'location'}), 'bio': forms.TextInput(attrs={'placeholder': 'about you'}), 'website':",
"Includes all the fields on the user, but replaces the password field with",
"self.cleaned_data['email'].lower() try: account = User.objects.get(email=email) except User.DoesNotExist: return email raise forms.ValidationError(f\"Email {email} is",
"Profile from django.contrib import messages from phonenumber_field.formfields import PhoneNumberField from phonenumber_field.widgets import PhoneNumberPrefixWidget",
"don't match\") return password2 def clean_email(self): email = self.cleaned_data['email'].lower() try: account = User.objects.get(email=email)",
"!= password2: raise ValidationError(\"Passwords don't match\") return password2 def clean_email(self): email = self.cleaned_data['email'].lower()",
"= User fields = ('__all__') def clean_password(self): # Regardless of what the user",
"'last_name': forms.TextInput(attrs={'placeholder': 'your last name'}), 'email': forms.EmailInput(attrs={'placeholder': 'you <EMAIL>'}), 'country': forms.TextInput(attrs={'placeholder': 'country you",
"from django.contrib.auth.models import Group from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.core.exceptions import ValidationError from",
"'website', 'bio'] widgets = { 'first_name': forms.TextInput(attrs={'placeholder': 'your first name'}), 'last_name': forms.TextInput(attrs={'placeholder': 'your",
"than on the field, because the # field does not have access to",
"entries match password1 = self.cleaned_data.get(\"password1\") password2 = self.cleaned_data.get(\"password2\") if password1 and password2 and",
"fields = ['first_name', 'last_name', 'phonenumber', 'country', 'avatar', 'address', 'gender', 'date_of_birth', 'pincode', 'language', 'location',",
"account = User.objects.get(email=email) except User.DoesNotExist: return email raise forms.ValidationError(f\"Email {email} is already in",
"try: User.objects.get(username__exact=username) except User.DoesNotExist: return username raise forms.ValidationError(\"This username is already taken.\") def",
"= PhoneNumberPrefixWidget(initial='IN') ) class Meta: model = Profile fields = ['first_name', 'last_name', 'phonenumber',",
"= self.cleaned_data.get(\"password1\") password2 = self.cleaned_data.get(\"password2\") if password1 and password2 and password1 != password2:",
"= Profile fields = ['first_name', 'last_name', 'phonenumber', 'country', 'avatar', 'address', 'gender', 'date_of_birth', 'pincode',",
"= ('__all__') def clean_password(self): # Regardless of what the user provides, return the",
"creating new users. Includes all the required fields, plus a repeated password.\"\"\" password1",
"= User fields = ('email', 'username') def clean_username(self): username = self.cleaned_data.get('username').lower() try: User.objects.get(username__exact=username)",
"from django.contrib.auth import authenticate from .models import User, Profile from django.contrib import messages",
"# field does not have access to the initial value return self.initial[\"password\"] class",
"model = User fields = ('__all__') def clean_password(self): # Regardless of what the",
"Regardless of what the user provides, return the initial value. # This is",
"import forms from django.contrib.auth.models import Group from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.core.exceptions import",
"= User.objects.get(email=email) except User.DoesNotExist: return email raise forms.ValidationError(f\"Email {email} is already in use.\")",
"users. Includes all the fields on the user, but replaces the password field",
"UserAdminCreationForm(forms.ModelForm): \"\"\"A form for creating new users. Includes all the required fields, plus",
"ReadOnlyPasswordHashField from django.core.exceptions import ValidationError from django.contrib.auth import authenticate from .models import User,",
"= self.cleaned_data.get(\"password2\") if password1 and password2 and password1 != password2: raise ValidationError(\"Passwords don't",
"you where you live'}), 'address': forms.TextInput(attrs={'placeholder': 'your address where you live'}), 'pincode': forms.TextInput(attrs={'placeholder':",
"= forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField( label='Password confirmation', widget=forms.PasswordInput) class Meta: model =",
"RegexValidator class UserAdminCreationForm(forms.ModelForm): \"\"\"A form for creating new users. Includes all the required",
"model = User fields = ('email', 'username') def clean_username(self): username = self.cleaned_data.get('username').lower() try:",
"not have access to the initial value return self.initial[\"password\"] class UserProfileForm(forms.ModelForm): GENDER =",
"User, Profile from django.contrib import messages from phonenumber_field.formfields import PhoneNumberField from phonenumber_field.widgets import",
"'country you where you live'}), 'address': forms.TextInput(attrs={'placeholder': 'your address where you live'}), 'pincode':",
"'address', 'gender', 'date_of_birth', 'pincode', 'language', 'location', 'website', 'bio'] widgets = { 'first_name': forms.TextInput(attrs={'placeholder':",
"is done here, rather than on the field, because the # field does",
"User fields = ('email', 'username') def clean_username(self): username = self.cleaned_data.get('username').lower() try: User.objects.get(username__exact=username) except",
"import User, Profile from django.contrib import messages from phonenumber_field.formfields import PhoneNumberField from phonenumber_field.widgets",
"from django import forms from django.contrib.auth.models import Group from django.contrib.auth.forms import ReadOnlyPasswordHashField from",
"date_of_birth = forms.DateField(widget=forms.DateInput( attrs={'type': 'date'}), required=False) phonenumber = PhoneNumberField( widget = PhoneNumberPrefixWidget(initial='IN') )",
"= forms.ChoiceField( label='Gender', choices=GENDER, widget=forms.RadioSelect, required=False) date_of_birth = forms.DateField(widget=forms.DateInput( attrs={'type': 'date'}), required=False) phonenumber",
"the initial value return self.initial[\"password\"] class UserProfileForm(forms.ModelForm): GENDER = ( ('Male', 'Male'), ('Female',",
"already in use.\") def save(self, commit=True): # Save the provided password in hashed",
"password2: raise ValidationError(\"Passwords don't match\") return password2 def clean_email(self): email = self.cleaned_data['email'].lower() try:",
"the user, but replaces the password field with admin's password hash display field.",
"gender = forms.ChoiceField( label='Gender', choices=GENDER, widget=forms.RadioSelect, required=False) date_of_birth = forms.DateField(widget=forms.DateInput( attrs={'type': 'date'}), required=False)",
"import ReadOnlyPasswordHashField from django.core.exceptions import ValidationError from django.contrib.auth import authenticate from .models import",
"user, but replaces the password field with admin's password hash display field. \"\"\"",
"# This is done here, rather than on the field, because the #",
"'last_name', 'phonenumber', 'country', 'avatar', 'address', 'gender', 'date_of_birth', 'pincode', 'language', 'location', 'website', 'bio'] widgets",
"username is already taken.\") def clean_password2(self): # Check that the two password entries",
"name'}), 'last_name': forms.TextInput(attrs={'placeholder': 'your last name'}), 'email': forms.EmailInput(attrs={'placeholder': 'you <EMAIL>'}), 'country': forms.TextInput(attrs={'placeholder': 'country",
"match password1 = self.cleaned_data.get(\"password1\") password2 = self.cleaned_data.get(\"password2\") if password1 and password2 and password1",
"import ValidationError from django.contrib.auth import authenticate from .models import User, Profile from django.contrib",
"forms.TextInput(attrs={'placeholder': 'language'}), 'location': forms.TextInput(attrs={'placeholder': 'location'}), 'bio': forms.TextInput(attrs={'placeholder': 'about you'}), 'website': forms.TextInput(attrs={'placeholder': 'your website",
"'you <EMAIL>'}), 'country': forms.TextInput(attrs={'placeholder': 'country you where you live'}), 'address': forms.TextInput(attrs={'placeholder': 'your address",
"where you live'}), 'pincode': forms.TextInput(attrs={'placeholder': 'pincode'}), 'language': forms.TextInput(attrs={'placeholder': 'language'}), 'location': forms.TextInput(attrs={'placeholder': 'location'}), 'bio':",
"is already taken.\") def clean_password2(self): # Check that the two password entries match",
"does not have access to the initial value return self.initial[\"password\"] class UserProfileForm(forms.ModelForm): GENDER",
"email = self.cleaned_data['email'].lower() try: account = User.objects.get(email=email) except User.DoesNotExist: return email raise forms.ValidationError(f\"Email",
"def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get(\"password1\")",
"self.cleaned_data.get(\"password1\") password2 = self.cleaned_data.get(\"password2\") if password1 and password2 and password1 != password2: raise",
"is already in use.\") def save(self, commit=True): # Save the provided password in",
"forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField( label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User",
"super().save(commit=False) user.set_password(self.cleaned_data[\"password2\"]) if commit: user.save() return user class UserAdminChangeForm(forms.ModelForm): \"\"\"A form for updating",
"def save(self, commit=True): # Save the provided password in hashed format user =",
"'Female'), ('Other', 'Other'), ) gender = forms.ChoiceField( label='Gender', choices=GENDER, widget=forms.RadioSelect, required=False) date_of_birth =",
"user provides, return the initial value. # This is done here, rather than",
"This is done here, rather than on the field, because the # field",
"and password2 and password1 != password2: raise ValidationError(\"Passwords don't match\") return password2 def",
"'language': forms.TextInput(attrs={'placeholder': 'language'}), 'location': forms.TextInput(attrs={'placeholder': 'location'}), 'bio': forms.TextInput(attrs={'placeholder': 'about you'}), 'website': forms.TextInput(attrs={'placeholder': 'your",
"# Check that the two password entries match password1 = self.cleaned_data.get(\"password1\") password2 =",
"User fields = ('__all__') def clean_password(self): # Regardless of what the user provides,",
"field does not have access to the initial value return self.initial[\"password\"] class UserProfileForm(forms.ModelForm):",
"django import forms from django.contrib.auth.models import Group from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.core.exceptions",
"password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField( label='Password confirmation', widget=forms.PasswordInput) class Meta: model",
"('Other', 'Other'), ) gender = forms.ChoiceField( label='Gender', choices=GENDER, widget=forms.RadioSelect, required=False) date_of_birth = forms.DateField(widget=forms.DateInput(",
"'email': forms.EmailInput(attrs={'placeholder': 'you <EMAIL>'}), 'country': forms.TextInput(attrs={'placeholder': 'country you where you live'}), 'address': forms.TextInput(attrs={'placeholder':",
"from phonenumber_field.widgets import PhoneNumberPrefixWidget from django.core.validators import RegexValidator class UserAdminCreationForm(forms.ModelForm): \"\"\"A form for",
"clean_password(self): # Regardless of what the user provides, return the initial value. #",
"taken.\") def clean_password2(self): # Check that the two password entries match password1 =",
"'language', 'location', 'website', 'bio'] widgets = { 'first_name': forms.TextInput(attrs={'placeholder': 'your first name'}), 'last_name':",
"all the fields on the user, but replaces the password field with admin's",
"self.cleaned_data.get(\"password2\") if password1 and password2 and password1 != password2: raise ValidationError(\"Passwords don't match\")",
"address where you live'}), 'pincode': forms.TextInput(attrs={'placeholder': 'pincode'}), 'language': forms.TextInput(attrs={'placeholder': 'language'}), 'location': forms.TextInput(attrs={'placeholder': 'location'}),",
"'pincode': forms.TextInput(attrs={'placeholder': 'pincode'}), 'language': forms.TextInput(attrs={'placeholder': 'language'}), 'location': forms.TextInput(attrs={'placeholder': 'location'}), 'bio': forms.TextInput(attrs={'placeholder': 'about you'}),",
"you live'}), 'address': forms.TextInput(attrs={'placeholder': 'your address where you live'}), 'pincode': forms.TextInput(attrs={'placeholder': 'pincode'}), 'language':",
"User.DoesNotExist: return username raise forms.ValidationError(\"This username is already taken.\") def clean_password2(self): # Check",
"password in hashed format user = super().save(commit=False) user.set_password(self.cleaned_data[\"password2\"]) if commit: user.save() return user",
"value return self.initial[\"password\"] class UserProfileForm(forms.ModelForm): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ('Other',",
"{ 'first_name': forms.TextInput(attrs={'placeholder': 'your first name'}), 'last_name': forms.TextInput(attrs={'placeholder': 'your last name'}), 'email': forms.EmailInput(attrs={'placeholder':",
"'location', 'website', 'bio'] widgets = { 'first_name': forms.TextInput(attrs={'placeholder': 'your first name'}), 'last_name': forms.TextInput(attrs={'placeholder':",
"import messages from phonenumber_field.formfields import PhoneNumberField from phonenumber_field.widgets import PhoneNumberPrefixWidget from django.core.validators import",
"'bio'] widgets = { 'first_name': forms.TextInput(attrs={'placeholder': 'your first name'}), 'last_name': forms.TextInput(attrs={'placeholder': 'your last",
"forms.ValidationError(\"This username is already taken.\") def clean_password2(self): # Check that the two password",
"'country': forms.TextInput(attrs={'placeholder': 'country you where you live'}), 'address': forms.TextInput(attrs={'placeholder': 'your address where you",
"password entries match password1 = self.cleaned_data.get(\"password1\") password2 = self.cleaned_data.get(\"password2\") if password1 and password2",
"forms.TextInput(attrs={'placeholder': 'your address where you live'}), 'pincode': forms.TextInput(attrs={'placeholder': 'pincode'}), 'language': forms.TextInput(attrs={'placeholder': 'language'}), 'location':",
"Profile fields = ['first_name', 'last_name', 'phonenumber', 'country', 'avatar', 'address', 'gender', 'date_of_birth', 'pincode', 'language',",
"import authenticate from .models import User, Profile from django.contrib import messages from phonenumber_field.formfields",
"return the initial value. # This is done here, rather than on the",
"('Male', 'Male'), ('Female', 'Female'), ('Other', 'Other'), ) gender = forms.ChoiceField( label='Gender', choices=GENDER, widget=forms.RadioSelect,",
"name'}), 'email': forms.EmailInput(attrs={'placeholder': 'you <EMAIL>'}), 'country': forms.TextInput(attrs={'placeholder': 'country you where you live'}), 'address':",
"updating users. Includes all the fields on the user, but replaces the password",
"attrs={'type': 'date'}), required=False) phonenumber = PhoneNumberField( widget = PhoneNumberPrefixWidget(initial='IN') ) class Meta: model",
"try: account = User.objects.get(email=email) except User.DoesNotExist: return email raise forms.ValidationError(f\"Email {email} is already",
"'location': forms.TextInput(attrs={'placeholder': 'location'}), 'bio': forms.TextInput(attrs={'placeholder': 'about you'}), 'website': forms.TextInput(attrs={'placeholder': 'your website url e.g.",
"return username raise forms.ValidationError(\"This username is already taken.\") def clean_password2(self): # Check that",
"username = self.cleaned_data.get('username').lower() try: User.objects.get(username__exact=username) except User.DoesNotExist: return username raise forms.ValidationError(\"This username is",
"required=False) phonenumber = PhoneNumberField( widget = PhoneNumberPrefixWidget(initial='IN') ) class Meta: model = Profile",
"users. Includes all the required fields, plus a repeated password.\"\"\" password1 = forms.CharField(label='Password',",
"except User.DoesNotExist: return username raise forms.ValidationError(\"This username is already taken.\") def clean_password2(self): #",
"password = ReadOnlyPasswordHashField() class Meta: model = User fields = ('__all__') def clean_password(self):",
"forms.TextInput(attrs={'placeholder': 'location'}), 'bio': forms.TextInput(attrs={'placeholder': 'about you'}), 'website': forms.TextInput(attrs={'placeholder': 'your website url e.g. https://your_website.com'}),",
"'phonenumber', 'country', 'avatar', 'address', 'gender', 'date_of_birth', 'pincode', 'language', 'location', 'website', 'bio'] widgets =",
"the # field does not have access to the initial value return self.initial[\"password\"]",
"self.initial[\"password\"] class UserProfileForm(forms.ModelForm): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ('Other', 'Other'), )",
"django.contrib.auth import authenticate from .models import User, Profile from django.contrib import messages from",
"django.core.validators import RegexValidator class UserAdminCreationForm(forms.ModelForm): \"\"\"A form for creating new users. Includes all",
"Check that the two password entries match password1 = self.cleaned_data.get(\"password1\") password2 = self.cleaned_data.get(\"password2\")",
"('email', 'username') def clean_username(self): username = self.cleaned_data.get('username').lower() try: User.objects.get(username__exact=username) except User.DoesNotExist: return username",
"field, because the # field does not have access to the initial value",
"User.DoesNotExist: return email raise forms.ValidationError(f\"Email {email} is already in use.\") def save(self, commit=True):",
"<EMAIL>'}), 'country': forms.TextInput(attrs={'placeholder': 'country you where you live'}), 'address': forms.TextInput(attrs={'placeholder': 'your address where",
"user.save() return user class UserAdminChangeForm(forms.ModelForm): \"\"\"A form for updating users. Includes all the",
"the initial value. # This is done here, rather than on the field,",
"phonenumber_field.formfields import PhoneNumberField from phonenumber_field.widgets import PhoneNumberPrefixWidget from django.core.validators import RegexValidator class UserAdminCreationForm(forms.ModelForm):",
"def clean_username(self): username = self.cleaned_data.get('username').lower() try: User.objects.get(username__exact=username) except User.DoesNotExist: return username raise forms.ValidationError(\"This",
"password2 = self.cleaned_data.get(\"password2\") if password1 and password2 and password1 != password2: raise ValidationError(\"Passwords",
"access to the initial value return self.initial[\"password\"] class UserProfileForm(forms.ModelForm): GENDER = ( ('Male',",
"password2 def clean_email(self): email = self.cleaned_data['email'].lower() try: account = User.objects.get(email=email) except User.DoesNotExist: return",
"password1 != password2: raise ValidationError(\"Passwords don't match\") return password2 def clean_email(self): email =",
"PhoneNumberField from phonenumber_field.widgets import PhoneNumberPrefixWidget from django.core.validators import RegexValidator class UserAdminCreationForm(forms.ModelForm): \"\"\"A form",
"hash display field. \"\"\" password = ReadOnlyPasswordHashField() class Meta: model = User fields",
"done here, rather than on the field, because the # field does not",
"PhoneNumberField( widget = PhoneNumberPrefixWidget(initial='IN') ) class Meta: model = Profile fields = ['first_name',",
"phonenumber_field.widgets import PhoneNumberPrefixWidget from django.core.validators import RegexValidator class UserAdminCreationForm(forms.ModelForm): \"\"\"A form for creating",
"password hash display field. \"\"\" password = ReadOnlyPasswordHashField() class Meta: model = User",
"\"\"\"A form for updating users. Includes all the fields on the user, but",
"new users. Includes all the required fields, plus a repeated password.\"\"\" password1 =",
"password2 = forms.CharField( label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User fields =",
"the provided password in hashed format user = super().save(commit=False) user.set_password(self.cleaned_data[\"password2\"]) if commit: user.save()",
"what the user provides, return the initial value. # This is done here,",
"class Meta: model = User fields = ('__all__') def clean_password(self): # Regardless of",
"the field, because the # field does not have access to the initial",
"initial value. # This is done here, rather than on the field, because",
"= ReadOnlyPasswordHashField() class Meta: model = User fields = ('__all__') def clean_password(self): #",
"clean_username(self): username = self.cleaned_data.get('username').lower() try: User.objects.get(username__exact=username) except User.DoesNotExist: return username raise forms.ValidationError(\"This username",
"username raise forms.ValidationError(\"This username is already taken.\") def clean_password2(self): # Check that the",
"clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get(\"password1\") password2",
"from .models import User, Profile from django.contrib import messages from phonenumber_field.formfields import PhoneNumberField",
"for updating users. Includes all the fields on the user, but replaces the",
"on the user, but replaces the password field with admin's password hash display",
"UserProfileForm(forms.ModelForm): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ('Other', 'Other'), ) gender =",
"commit=True): # Save the provided password in hashed format user = super().save(commit=False) user.set_password(self.cleaned_data[\"password2\"])",
"'pincode', 'language', 'location', 'website', 'bio'] widgets = { 'first_name': forms.TextInput(attrs={'placeholder': 'your first name'}),",
"rather than on the field, because the # field does not have access",
"class UserAdminChangeForm(forms.ModelForm): \"\"\"A form for updating users. Includes all the fields on the",
"'Other'), ) gender = forms.ChoiceField( label='Gender', choices=GENDER, widget=forms.RadioSelect, required=False) date_of_birth = forms.DateField(widget=forms.DateInput( attrs={'type':"
] |
[
"thermostat_devices(self): \"\"\" :return: Thermostat devices associated to the Raspberry Pi. \"\"\" residence =",
"= ('datetime',) def get_recursive_pks(self): pks = self.thermostat.get_recursive_pks() assert (self.pk == self.datetime) pks.append(self.datetime.isoformat()) return",
"future work. \"\"\" class Meta: unique_together = ('day', 'time', 'user') ordering = ('day',",
"= models.CharField(max_length=100, blank=False) class Meta: ordering = ('rfid',) def get_recursive_pks(self): pks = self.room.get_recursive_pks()",
"return pks class Temperature(Model): \"\"\" Represents a temperature. \"\"\" datetime = models.DateTimeField(primary_key=True) value",
"(0 <= len(residences) <= 1) if len(residences) > 0: return residences[0] else: return",
"Meta: ordering = ('datetime',) def get_recursive_pks(self): pks = self.thermostat.get_recursive_pks() assert (self.pk == self.datetime)",
"the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in",
"class Meta: ordering = ('rfid',) def get_recursive_pks(self): pks = self.room.get_recursive_pks() pks.append(self.pk) return pks",
"recursive parents. Used to determine the URL of an object. \"\"\" pass class",
"the URL of an object. \"\"\" pass class Residence(Model): \"\"\" Represents a residence.",
"<= len(thermostats) <= 1) if len(thermostats) > 0: return thermostats[0] else: return None",
"= models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) mac = models.CharField(max_length=17, unique=True) class Meta: abstract = True",
"return residences[0] else: return None @property def thermostat_devices(self): \"\"\" :return: Thermostat devices associated",
"of all recursive parents. Used to determine the URL of an object. \"\"\"",
"'user') ordering = ('day', 'time') user = models.ForeignKey(User) def get_recursive_pks(self): pks = self.user.get_recursive_pks()",
"class RaspberryDevice(Device): \"\"\" Represents a physical Raspberry Pi device. \"\"\" @property def residence(self):",
"datetime = models.DateTimeField(primary_key=True) value = models.FloatField() thermostat = models.ForeignKey('Thermostat', related_name='temperatures') class Meta: ordering",
"def get_recursive_pks(self): pks = self.residence.get_recursive_pks() pks.append(self.pk) return pks class Room(Model): \"\"\" Represents a",
"unique_together = ('day', 'time', 'user') ordering = ('day', 'time') user = models.ForeignKey(User) def",
"is a stub and is intended to be used in future work. \"\"\"",
"(field.name, getattr(self, field.name)) for field in self._meta.fields]) return '<%s(%s)>' % (self.__class__._meta.object_name, fields_string) def",
"None rooms = Room.objects.filter(residence=residence) room_pks = [room.pk for room in rooms] thermostats =",
"return thermostats[0] else: return None class TimetableEntry(Model): \"\"\" Base class for a weekly",
"and MAC address. \"\"\" __metaclass__ = ABCMeta rfid = models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) mac",
"return [self.pk] class RaspberryDevice(Device): \"\"\" Represents a physical Raspberry Pi device. \"\"\" @property",
"Returns a list of primary keys of all recursive parents. Used to determine",
"for thermostat in thermostats] thermostat_devices = ThermostatDevice.objects.filter(rfid__in=thermostat_rfids) return thermostat_devices class ThermostatDevice(Device): \"\"\" Represents",
"class for all models. \"\"\" __metaclass__ = ABCMeta class Meta: abstract = True",
"timetable entry. \"\"\" __metaclass__ = ABCMeta MONDAY = 0 TUESDAY = 1 WEDNESDAY",
"License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required",
"= 4 SATURDAY = 5 SUNDAY = 6 DAY_IN_WEEK_CHOICES = [ (MONDAY, 'Monday'),",
"is automatically generated if no other primary_key is defined name = models.CharField(max_length=100) residence",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the",
"class HeatingTableEntry(TimetableEntry): \"\"\" Represents an entry of a heating schedule. \"\"\" class Meta:",
"a weekly timetable entry. \"\"\" __metaclass__ = ABCMeta MONDAY = 0 TUESDAY =",
"\"\"\" Represents an user occupancy prediction entry. This is a stub and is",
"residence. \"\"\" rfid = models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) class Meta: ordering = ('rfid',) def",
"= 6 DAY_IN_WEEK_CHOICES = [ (MONDAY, 'Monday'), (TUESDAY, 'Tuesday'), (WEDNESDAY, 'Wednesday'), (THURSDAY, 'Thursday'),",
"max_length=100, validators=[alpha_numeric_validator]) name = models.CharField(max_length=100) residence = models.ForeignKey('Residence', related_name='users') class Meta: ordering =",
"Thermostat.objects.filter(room__in=room_pks) thermostat_rfids = [thermostat.rfid for thermostat in thermostats] thermostat_devices = ThermostatDevice.objects.filter(rfid__in=thermostat_rfids) return thermostat_devices",
"validators=[alpha_numeric_validator]) name = models.CharField(max_length=100) residence = models.ForeignKey('Residence', related_name='users') class Meta: ordering = ('imei',)",
"= self.thermostat.get_recursive_pks() pks.append(self.pk) return pks class OccupancyPredictionEntry(TimetableEntry): \"\"\" Represents an user occupancy prediction",
"ordering = ('rfid',) def get_recursive_pks(self): pks = [self.pk] return pks class User(Model): \"\"\"",
"work. \"\"\" class Meta: unique_together = ('day', 'time', 'user') ordering = ('day', 'time')",
"rfid = models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) mac = models.CharField(max_length=17, unique=True) class Meta: abstract =",
"= models.FloatField() thermostat = models.ForeignKey('Thermostat', related_name='temperatures') class Meta: ordering = ('datetime',) def get_recursive_pks(self):",
"def __str__(self): return str(self.pk) @abstractmethod def get_recursive_pks(self): \"\"\" Returns a list of primary",
"return pks class User(Model): \"\"\" Represents a user. \"\"\" imei = models.CharField(primary_key=True, max_length=100,",
"the License for the specific language governing permissions and limitations under the License.",
"class Meta: ordering = ('rfid',) def get_recursive_pks(self): pks = [self.pk] return pks class",
"= models.ForeignKey('Thermostat', related_name='temperatures') class Meta: ordering = ('datetime',) def get_recursive_pks(self): pks = self.thermostat.get_recursive_pks()",
"= ('day', 'time') user = models.ForeignKey(User) def get_recursive_pks(self): pks = self.user.get_recursive_pks() pks.append(self.pk) return",
"get_recursive_pks(self): \"\"\" Returns a list of primary keys of all recursive parents. Used",
"2 THURSDAY = 3 FRIDAY = 4 SATURDAY = 5 SUNDAY = 6",
"(THURSDAY, 'Thursday'), (FRIDAY, 'Friday'), (SATURDAY, 'Saturday'), (SUNDAY, 'Sunday'), ] day = models.CharField(max_length=3, choices=DAY_IN_WEEK_CHOICES)",
"License for the specific language governing permissions and limitations under the License. \"\"\"",
"= [room.pk for room in rooms] thermostats = Thermostat.objects.filter(room__in=room_pks) thermostat_rfids = [thermostat.rfid for",
"Unless required by applicable law or agreed to in writing, software distributed under",
"Represents a thermostat. \"\"\" rfid = models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) room = models.ForeignKey('Room', related_name='thermostats')",
"= ABCMeta rfid = models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) mac = models.CharField(max_length=17, unique=True) class Meta:",
"a thermistat meta entry containing signal strength, uptime and battery level. \"\"\" id",
"an RFID number and MAC address. \"\"\" __metaclass__ = ABCMeta rfid = models.CharField(primary_key=True,",
"rfid_validator = alpha_numeric_validator class Model(models.Model): \"\"\" Base class for all models. \"\"\" __metaclass__",
"max_length=100, validators=[rfid_validator]) room = models.ForeignKey('Room', related_name='thermostats') name = models.CharField(max_length=100, blank=False) class Meta: ordering",
"heating schedule. \"\"\" class Meta: unique_together = ('day', 'time', 'thermostat') ordering = ('day',",
"= models.ForeignKey(Thermostat, related_name='heating_table_entries') def get_recursive_pks(self): pks = self.thermostat.get_recursive_pks() pks.append(self.pk) return pks class OccupancyPredictionEntry(TimetableEntry):",
"for a physical device with an RFID number and MAC address. \"\"\" __metaclass__",
"__str__(self): return str(self.pk) @abstractmethod def get_recursive_pks(self): \"\"\" Returns a list of primary keys",
"rooms = Room.objects.filter(residence=residence) room_pks = [room.pk for room in rooms] thermostats = Thermostat.objects.filter(room__in=room_pks)",
"= self.residence.get_recursive_pks() pks.append(self.pk) return pks class Room(Model): \"\"\" Represents a room. \"\"\" #",
"assert (0 <= len(thermostats) <= 1) if len(thermostats) > 0: return thermostats[0] else:",
"<= 1) if len(thermostats) > 0: return thermostats[0] else: return None class TimetableEntry(Model):",
"models.IntegerField(null=True) uptime = models.IntegerField(null=True) battery = models.IntegerField(null=True) thermostat = models.ForeignKey('Thermostat', related_name='meta_entries') class Meta:",
"Represents a temperature. \"\"\" datetime = models.DateTimeField(primary_key=True) value = models.FloatField() thermostat = models.ForeignKey('Thermostat',",
"Raspberry Pi device. \"\"\" @property def residence(self): residences = Residence.objects.filter(rfid=self.rfid) assert (0 <=",
"= models.IntegerField(null=True) battery = models.IntegerField(null=True) thermostat = models.ForeignKey('Thermostat', related_name='meta_entries') class Meta: unique_together =",
"the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS",
"User(Model): \"\"\" Represents a user. \"\"\" imei = models.CharField(primary_key=True, max_length=100, validators=[alpha_numeric_validator]) name =",
"unique_together = ('day', 'time', 'thermostat') ordering = ('day', 'time') temperature = models.FloatField(validators=[validators.MinValueValidator(5), validators.MaxValueValidator(30)])",
"License, Version 2.0 (the \"License\"); you may not use this file except in",
"choices=DAY_IN_WEEK_CHOICES) time = models.TimeField() class Meta: abstract = True class HeatingTableEntry(TimetableEntry): \"\"\" Represents",
"entry containing signal strength, uptime and battery level. \"\"\" id = models.AutoField(primary_key=True) datetime",
":return: Thermostat devices associated to the Raspberry Pi. \"\"\" residence = self.residence if",
"= [self.pk] return pks class User(Model): \"\"\" Represents a user. \"\"\" imei =",
"an object. \"\"\" pass class Residence(Model): \"\"\" Represents a residence. \"\"\" rfid =",
"class Meta: unique_together = ('day', 'time', 'user') ordering = ('day', 'time') user =",
"return pks class Device(Model): \"\"\" Base class for a physical device with an",
"get_recursive_pks(self): pks = self.thermostat.get_recursive_pks() pks.append(self.pk) return pks class OccupancyPredictionEntry(TimetableEntry): \"\"\" Represents an user",
"ABCMeta, abstractmethod from django.core import validators from django.db import models alpha_numeric_validator = validators.RegexValidator(r'^[0-9a-zA-Z]+$',",
"id is automatically generated if no other primary_key is defined name = models.CharField(max_length=100)",
"entry of a heating schedule. \"\"\" class Meta: unique_together = ('day', 'time', 'thermostat')",
"class User(Model): \"\"\" Represents a user. \"\"\" imei = models.CharField(primary_key=True, max_length=100, validators=[alpha_numeric_validator]) name",
"@abstractmethod def get_recursive_pks(self): \"\"\" Returns a list of primary keys of all recursive",
"SUNDAY = 6 DAY_IN_WEEK_CHOICES = [ (MONDAY, 'Monday'), (TUESDAY, 'Tuesday'), (WEDNESDAY, 'Wednesday'), (THURSDAY,",
"abc import ABCMeta, abstractmethod from django.core import validators from django.db import models alpha_numeric_validator",
"Thermostat devices associated to the Raspberry Pi. \"\"\" residence = self.residence if residence",
"'time', 'thermostat') ordering = ('day', 'time') temperature = models.FloatField(validators=[validators.MinValueValidator(5), validators.MaxValueValidator(30)]) thermostat = models.ForeignKey(Thermostat,",
"MONDAY = 0 TUESDAY = 1 WEDNESDAY = 2 THURSDAY = 3 FRIDAY",
"if len(thermostats) > 0: return thermostats[0] else: return None class TimetableEntry(Model): \"\"\" Base",
"WEDNESDAY = 2 THURSDAY = 3 FRIDAY = 4 SATURDAY = 5 SUNDAY",
"= alpha_numeric_validator class Model(models.Model): \"\"\" Base class for all models. \"\"\" __metaclass__ =",
"thermostat_devices class ThermostatDevice(Device): \"\"\" Represents a physical thermostat device. \"\"\" @property def thermostat(self):",
"= ABCMeta MONDAY = 0 TUESDAY = 1 WEDNESDAY = 2 THURSDAY =",
"ABCMeta class Meta: abstract = True def __repr__(self): fields_string = ', '.join(['%s:\"%s\"' %",
"name = models.CharField(max_length=100) residence = models.ForeignKey('Residence', related_name='rooms') class Meta: ordering = ('name',) def",
"thermostat = models.ForeignKey('Thermostat', related_name='temperatures') class Meta: ordering = ('datetime',) def get_recursive_pks(self): pks =",
"FRIDAY = 4 SATURDAY = 5 SUNDAY = 6 DAY_IN_WEEK_CHOICES = [ (MONDAY,",
"software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT",
"by applicable law or agreed to in writing, software distributed under the License",
"models.CharField(max_length=17, unique=True) class Meta: abstract = True def get_recursive_pks(self): return [self.pk] class RaspberryDevice(Device):",
"Represents a physical Raspberry Pi device. \"\"\" @property def residence(self): residences = Residence.objects.filter(rfid=self.rfid)",
"@property def residence(self): residences = Residence.objects.filter(rfid=self.rfid) assert (0 <= len(residences) <= 1) if",
"('datetime',) def get_recursive_pks(self): pks = self.thermostat.get_recursive_pks() pks.append(self.pk) return pks class Device(Model): \"\"\" Base",
"of a heating schedule. \"\"\" class Meta: unique_together = ('day', 'time', 'thermostat') ordering",
"= True def __repr__(self): fields_string = ', '.join(['%s:\"%s\"' % (field.name, getattr(self, field.name)) for",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License",
"None @property def thermostat_devices(self): \"\"\" :return: Thermostat devices associated to the Raspberry Pi.",
"(SATURDAY, 'Saturday'), (SUNDAY, 'Sunday'), ] day = models.CharField(max_length=3, choices=DAY_IN_WEEK_CHOICES) time = models.TimeField() class",
"models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) class Meta: ordering = ('rfid',) def get_recursive_pks(self): pks = [self.pk]",
"rfid = models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) class Meta: ordering = ('rfid',) def get_recursive_pks(self): pks",
"temperature. \"\"\" datetime = models.DateTimeField(primary_key=True) value = models.FloatField() thermostat = models.ForeignKey('Thermostat', related_name='temperatures') class",
"self.residence.get_recursive_pks() pks.append(self.pk) return pks class Thermostat(Model): \"\"\" Represents a thermostat. \"\"\" rfid =",
"return pks class Room(Model): \"\"\" Represents a room. \"\"\" # id is automatically",
"= validators.RegexValidator(r'^[0-9a-zA-Z]+$', 'Only alphanumeric characters are allowed.') rfid_validator = alpha_numeric_validator class Model(models.Model): \"\"\"",
"a stub and is intended to be used in future work. \"\"\" class",
"a temperature. \"\"\" datetime = models.DateTimeField(primary_key=True) value = models.FloatField() thermostat = models.ForeignKey('Thermostat', related_name='temperatures')",
"weekly timetable entry. \"\"\" __metaclass__ = ABCMeta MONDAY = 0 TUESDAY = 1",
"= models.ForeignKey('Thermostat', related_name='meta_entries') class Meta: unique_together = ('thermostat', 'datetime') ordering = ('datetime',) def",
"'<%s(%s)>' % (self.__class__._meta.object_name, fields_string) def __str__(self): return str(self.pk) @abstractmethod def get_recursive_pks(self): \"\"\" Returns",
"('name',) def get_recursive_pks(self): pks = self.residence.get_recursive_pks() pks.append(self.pk) return pks class Thermostat(Model): \"\"\" Represents",
"4 SATURDAY = 5 SUNDAY = 6 DAY_IN_WEEK_CHOICES = [ (MONDAY, 'Monday'), (TUESDAY,",
"IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"alphanumeric characters are allowed.') rfid_validator = alpha_numeric_validator class Model(models.Model): \"\"\" Base class for",
"thermostats] thermostat_devices = ThermostatDevice.objects.filter(rfid__in=thermostat_rfids) return thermostat_devices class ThermostatDevice(Device): \"\"\" Represents a physical thermostat",
"Represents a residence. \"\"\" rfid = models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) class Meta: ordering =",
"language governing permissions and limitations under the License. \"\"\" from abc import ABCMeta,",
"Pi. \"\"\" residence = self.residence if residence is None: return None rooms =",
"residence = models.ForeignKey('Residence', related_name='rooms') class Meta: ordering = ('name',) def get_recursive_pks(self): pks =",
"in compliance with the License. You may obtain a copy of the License",
"class Meta: abstract = True class HeatingTableEntry(TimetableEntry): \"\"\" Represents an entry of a",
"License. \"\"\" from abc import ABCMeta, abstractmethod from django.core import validators from django.db",
"Meta: ordering = ('rfid',) def get_recursive_pks(self): pks = [self.pk] return pks class User(Model):",
"KIND, either express or implied. See the License for the specific language governing",
"validators=[rfid_validator]) mac = models.CharField(max_length=17, unique=True) class Meta: abstract = True def get_recursive_pks(self): return",
"return None class TimetableEntry(Model): \"\"\" Base class for a weekly timetable entry. \"\"\"",
"(TUESDAY, 'Tuesday'), (WEDNESDAY, 'Wednesday'), (THURSDAY, 'Thursday'), (FRIDAY, 'Friday'), (SATURDAY, 'Saturday'), (SUNDAY, 'Sunday'), ]",
"\"\"\" Base class for all models. \"\"\" __metaclass__ = ABCMeta class Meta: abstract",
"in writing, software distributed under the License is distributed on an \"AS IS\"",
"models.IntegerField(null=True) battery = models.IntegerField(null=True) thermostat = models.ForeignKey('Thermostat', related_name='meta_entries') class Meta: unique_together = ('thermostat',",
"writing, software distributed under the License is distributed on an \"AS IS\" BASIS,",
"pks = self.residence.get_recursive_pks() pks.append(self.pk) return pks class Room(Model): \"\"\" Represents a room. \"\"\"",
"device with an RFID number and MAC address. \"\"\" __metaclass__ = ABCMeta rfid",
"ordering = ('datetime',) def get_recursive_pks(self): pks = self.thermostat.get_recursive_pks() pks.append(self.pk) return pks class Device(Model):",
"models alpha_numeric_validator = validators.RegexValidator(r'^[0-9a-zA-Z]+$', 'Only alphanumeric characters are allowed.') rfid_validator = alpha_numeric_validator class",
"class for a physical device with an RFID number and MAC address. \"\"\"",
"def residence(self): residences = Residence.objects.filter(rfid=self.rfid) assert (0 <= len(residences) <= 1) if len(residences)",
"and is intended to be used in future work. \"\"\" class Meta: unique_together",
"permissions and limitations under the License. \"\"\" from abc import ABCMeta, abstractmethod from",
"or agreed to in writing, software distributed under the License is distributed on",
"('imei',) def get_recursive_pks(self): pks = self.residence.get_recursive_pks() pks.append(self.pk) return pks class Room(Model): \"\"\" Represents",
"\"\"\" rfid = models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) class Meta: ordering = ('rfid',) def get_recursive_pks(self):",
"Thermostat(Model): \"\"\" Represents a thermostat. \"\"\" rfid = models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) room =",
"an entry of a heating schedule. \"\"\" class Meta: unique_together = ('day', 'time',",
"Thermostat.objects.filter(rfid=self.rfid) assert (0 <= len(thermostats) <= 1) if len(thermostats) > 0: return thermostats[0]",
"= models.TimeField() class Meta: abstract = True class HeatingTableEntry(TimetableEntry): \"\"\" Represents an entry",
"an user occupancy prediction entry. This is a stub and is intended to",
"physical thermostat device. \"\"\" @property def thermostat(self): thermostats = Thermostat.objects.filter(rfid=self.rfid) assert (0 <=",
"if residence is None: return None rooms = Room.objects.filter(residence=residence) room_pks = [room.pk for",
"\"\"\" class Meta: unique_together = ('day', 'time', 'thermostat') ordering = ('day', 'time') temperature",
"DAY_IN_WEEK_CHOICES = [ (MONDAY, 'Monday'), (TUESDAY, 'Tuesday'), (WEDNESDAY, 'Wednesday'), (THURSDAY, 'Thursday'), (FRIDAY, 'Friday'),",
"MAC address. \"\"\" __metaclass__ = ABCMeta rfid = models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) mac =",
"thermostats = Thermostat.objects.filter(room__in=room_pks) thermostat_rfids = [thermostat.rfid for thermostat in thermostats] thermostat_devices = ThermostatDevice.objects.filter(rfid__in=thermostat_rfids)",
"entry. \"\"\" __metaclass__ = ABCMeta MONDAY = 0 TUESDAY = 1 WEDNESDAY =",
"\"\"\" # id is automatically generated if no other primary_key is defined name",
"validators from django.db import models alpha_numeric_validator = validators.RegexValidator(r'^[0-9a-zA-Z]+$', 'Only alphanumeric characters are allowed.')",
"This is a stub and is intended to be used in future work.",
"meta entry containing signal strength, uptime and battery level. \"\"\" id = models.AutoField(primary_key=True)",
"(self.pk == self.datetime) pks.append(self.datetime.isoformat()) return pks class ThermostatMetaEntry(Model): \"\"\" Represents a thermistat meta",
"the Raspberry Pi. \"\"\" residence = self.residence if residence is None: return None",
"0: return residences[0] else: return None @property def thermostat_devices(self): \"\"\" :return: Thermostat devices",
"alpha_numeric_validator class Model(models.Model): \"\"\" Base class for all models. \"\"\" __metaclass__ = ABCMeta",
"with an RFID number and MAC address. \"\"\" __metaclass__ = ABCMeta rfid =",
"battery = models.IntegerField(null=True) thermostat = models.ForeignKey('Thermostat', related_name='meta_entries') class Meta: unique_together = ('thermostat', 'datetime')",
"thermostat device. \"\"\" @property def thermostat(self): thermostats = Thermostat.objects.filter(rfid=self.rfid) assert (0 <= len(thermostats)",
"class Meta: ordering = ('name',) def get_recursive_pks(self): pks = self.residence.get_recursive_pks() pks.append(self.pk) return pks",
"django.core import validators from django.db import models alpha_numeric_validator = validators.RegexValidator(r'^[0-9a-zA-Z]+$', 'Only alphanumeric characters",
"class Residence(Model): \"\"\" Represents a residence. \"\"\" rfid = models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) class",
"Residence.objects.filter(rfid=self.rfid) assert (0 <= len(residences) <= 1) if len(residences) > 0: return residences[0]",
"get_recursive_pks(self): pks = self.room.get_recursive_pks() pks.append(self.pk) return pks class Temperature(Model): \"\"\" Represents a temperature.",
"\"\"\" @property def residence(self): residences = Residence.objects.filter(rfid=self.rfid) assert (0 <= len(residences) <= 1)",
"'Sunday'), ] day = models.CharField(max_length=3, choices=DAY_IN_WEEK_CHOICES) time = models.TimeField() class Meta: abstract =",
"be used in future work. \"\"\" class Meta: unique_together = ('day', 'time', 'user')",
"= ', '.join(['%s:\"%s\"' % (field.name, getattr(self, field.name)) for field in self._meta.fields]) return '<%s(%s)>'",
"of an object. \"\"\" pass class Residence(Model): \"\"\" Represents a residence. \"\"\" rfid",
"= 0 TUESDAY = 1 WEDNESDAY = 2 THURSDAY = 3 FRIDAY =",
"class Thermostat(Model): \"\"\" Represents a thermostat. \"\"\" rfid = models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) room",
"'Tuesday'), (WEDNESDAY, 'Wednesday'), (THURSDAY, 'Thursday'), (FRIDAY, 'Friday'), (SATURDAY, 'Saturday'), (SUNDAY, 'Sunday'), ] day",
"OR CONDITIONS OF ANY KIND, either express or implied. See the License for",
"class for a weekly timetable entry. \"\"\" __metaclass__ = ABCMeta MONDAY = 0",
"OF ANY KIND, either express or implied. See the License for the specific",
"residence = models.ForeignKey('Residence', related_name='users') class Meta: ordering = ('imei',) def get_recursive_pks(self): pks =",
"1 WEDNESDAY = 2 THURSDAY = 3 FRIDAY = 4 SATURDAY = 5",
"> 0: return thermostats[0] else: return None class TimetableEntry(Model): \"\"\" Base class for",
"ABCMeta rfid = models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) mac = models.CharField(max_length=17, unique=True) class Meta: abstract",
"'time') temperature = models.FloatField(validators=[validators.MinValueValidator(5), validators.MaxValueValidator(30)]) thermostat = models.ForeignKey(Thermostat, related_name='heating_table_entries') def get_recursive_pks(self): pks =",
"models.ForeignKey('Thermostat', related_name='meta_entries') class Meta: unique_together = ('thermostat', 'datetime') ordering = ('datetime',) def get_recursive_pks(self):",
"= models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) class Meta: ordering = ('rfid',) def get_recursive_pks(self): pks =",
"('day', 'time') user = models.ForeignKey(User) def get_recursive_pks(self): pks = self.user.get_recursive_pks() pks.append(self.pk) return pks",
"\"\"\" Represents an entry of a heating schedule. \"\"\" class Meta: unique_together =",
"\"\"\" __metaclass__ = ABCMeta class Meta: abstract = True def __repr__(self): fields_string =",
"Represents an entry of a heating schedule. \"\"\" class Meta: unique_together = ('day',",
"% (field.name, getattr(self, field.name)) for field in self._meta.fields]) return '<%s(%s)>' % (self.__class__._meta.object_name, fields_string)",
"# id is automatically generated if no other primary_key is defined name =",
"('day', 'time', 'thermostat') ordering = ('day', 'time') temperature = models.FloatField(validators=[validators.MinValueValidator(5), validators.MaxValueValidator(30)]) thermostat =",
"fields_string = ', '.join(['%s:\"%s\"' % (field.name, getattr(self, field.name)) for field in self._meta.fields]) return",
"may not use this file except in compliance with the License. You may",
"Meta: unique_together = ('day', 'time', 'thermostat') ordering = ('day', 'time') temperature = models.FloatField(validators=[validators.MinValueValidator(5),",
"a physical Raspberry Pi device. \"\"\" @property def residence(self): residences = Residence.objects.filter(rfid=self.rfid) assert",
"('rfid',) def get_recursive_pks(self): pks = [self.pk] return pks class User(Model): \"\"\" Represents a",
"under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR",
"a physical thermostat device. \"\"\" @property def thermostat(self): thermostats = Thermostat.objects.filter(rfid=self.rfid) assert (0",
"import models alpha_numeric_validator = validators.RegexValidator(r'^[0-9a-zA-Z]+$', 'Only alphanumeric characters are allowed.') rfid_validator = alpha_numeric_validator",
"get_recursive_pks(self): pks = self.thermostat.get_recursive_pks() assert (self.pk == self.datetime) pks.append(self.datetime.isoformat()) return pks class ThermostatMetaEntry(Model):",
"Meta: ordering = ('name',) def get_recursive_pks(self): pks = self.residence.get_recursive_pks() pks.append(self.pk) return pks class",
"related_name='heating_table_entries') def get_recursive_pks(self): pks = self.thermostat.get_recursive_pks() pks.append(self.pk) return pks class OccupancyPredictionEntry(TimetableEntry): \"\"\" Represents",
"validators.RegexValidator(r'^[0-9a-zA-Z]+$', 'Only alphanumeric characters are allowed.') rfid_validator = alpha_numeric_validator class Model(models.Model): \"\"\" Base",
"on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"to determine the URL of an object. \"\"\" pass class Residence(Model): \"\"\" Represents",
"Meta: abstract = True def get_recursive_pks(self): return [self.pk] class RaspberryDevice(Device): \"\"\" Represents a",
"\"\"\" datetime = models.DateTimeField(primary_key=True) value = models.FloatField() thermostat = models.ForeignKey('Thermostat', related_name='temperatures') class Meta:",
"Residence(Model): \"\"\" Represents a residence. \"\"\" rfid = models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) class Meta:",
"field in self._meta.fields]) return '<%s(%s)>' % (self.__class__._meta.object_name, fields_string) def __str__(self): return str(self.pk) @abstractmethod",
"return None rooms = Room.objects.filter(residence=residence) room_pks = [room.pk for room in rooms] thermostats",
"list of primary keys of all recursive parents. Used to determine the URL",
"\"\"\" Represents a thermostat. \"\"\" rfid = models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) room = models.ForeignKey('Room',",
"TimetableEntry(Model): \"\"\" Base class for a weekly timetable entry. \"\"\" __metaclass__ = ABCMeta",
"models.IntegerField(null=True) thermostat = models.ForeignKey('Thermostat', related_name='meta_entries') class Meta: unique_together = ('thermostat', 'datetime') ordering =",
"= self.thermostat.get_recursive_pks() pks.append(self.pk) return pks class Device(Model): \"\"\" Base class for a physical",
"\"\"\" Base class for a weekly timetable entry. \"\"\" __metaclass__ = ABCMeta MONDAY",
"for field in self._meta.fields]) return '<%s(%s)>' % (self.__class__._meta.object_name, fields_string) def __str__(self): return str(self.pk)",
"\"\"\" __metaclass__ = ABCMeta MONDAY = 0 TUESDAY = 1 WEDNESDAY = 2",
"return thermostat_devices class ThermostatDevice(Device): \"\"\" Represents a physical thermostat device. \"\"\" @property def",
"a thermostat. \"\"\" rfid = models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) room = models.ForeignKey('Room', related_name='thermostats') name",
"in thermostats] thermostat_devices = ThermostatDevice.objects.filter(rfid__in=thermostat_rfids) return thermostat_devices class ThermostatDevice(Device): \"\"\" Represents a physical",
"models.DateTimeField(primary_key=True) value = models.FloatField() thermostat = models.ForeignKey('Thermostat', related_name='temperatures') class Meta: ordering = ('datetime',)",
"residences[0] else: return None @property def thermostat_devices(self): \"\"\" :return: Thermostat devices associated to",
"'Thursday'), (FRIDAY, 'Friday'), (SATURDAY, 'Saturday'), (SUNDAY, 'Sunday'), ] day = models.CharField(max_length=3, choices=DAY_IN_WEEK_CHOICES) time",
"('rfid',) def get_recursive_pks(self): pks = self.room.get_recursive_pks() pks.append(self.pk) return pks class Temperature(Model): \"\"\" Represents",
"class Room(Model): \"\"\" Represents a room. \"\"\" # id is automatically generated if",
"(self.__class__._meta.object_name, fields_string) def __str__(self): return str(self.pk) @abstractmethod def get_recursive_pks(self): \"\"\" Returns a list",
"related_name='temperatures') class Meta: ordering = ('datetime',) def get_recursive_pks(self): pks = self.thermostat.get_recursive_pks() assert (self.pk",
"generated if no other primary_key is defined name = models.CharField(max_length=100) residence = models.ForeignKey('Residence',",
"OccupancyPredictionEntry(TimetableEntry): \"\"\" Represents an user occupancy prediction entry. This is a stub and",
"the License. \"\"\" from abc import ABCMeta, abstractmethod from django.core import validators from",
"See the License for the specific language governing permissions and limitations under the",
"user occupancy prediction entry. This is a stub and is intended to be",
"else: return None class TimetableEntry(Model): \"\"\" Base class for a weekly timetable entry.",
"governing permissions and limitations under the License. \"\"\" from abc import ABCMeta, abstractmethod",
"= models.FloatField(validators=[validators.MinValueValidator(5), validators.MaxValueValidator(30)]) thermostat = models.ForeignKey(Thermostat, related_name='heating_table_entries') def get_recursive_pks(self): pks = self.thermostat.get_recursive_pks() pks.append(self.pk)",
"pks = self.residence.get_recursive_pks() pks.append(self.pk) return pks class Thermostat(Model): \"\"\" Represents a thermostat. \"\"\"",
"\"\"\" Represents a room. \"\"\" # id is automatically generated if no other",
"occupancy prediction entry. This is a stub and is intended to be used",
"uptime = models.IntegerField(null=True) battery = models.IntegerField(null=True) thermostat = models.ForeignKey('Thermostat', related_name='meta_entries') class Meta: unique_together",
"under the License. \"\"\" from abc import ABCMeta, abstractmethod from django.core import validators",
"Represents a room. \"\"\" # id is automatically generated if no other primary_key",
"validators=[rfid_validator]) room = models.ForeignKey('Room', related_name='thermostats') name = models.CharField(max_length=100, blank=False) class Meta: ordering =",
"\"\"\" Base class for a physical device with an RFID number and MAC",
"a residence. \"\"\" rfid = models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) class Meta: ordering = ('rfid',)",
"name = models.CharField(max_length=100) residence = models.ForeignKey('Residence', related_name='users') class Meta: ordering = ('imei',) def",
"thermostat = models.ForeignKey(Thermostat, related_name='heating_table_entries') def get_recursive_pks(self): pks = self.thermostat.get_recursive_pks() pks.append(self.pk) return pks class",
"room in rooms] thermostats = Thermostat.objects.filter(room__in=room_pks) thermostat_rfids = [thermostat.rfid for thermostat in thermostats]",
"this file except in compliance with the License. You may obtain a copy",
"\"\"\" from abc import ABCMeta, abstractmethod from django.core import validators from django.db import",
"from django.core import validators from django.db import models alpha_numeric_validator = validators.RegexValidator(r'^[0-9a-zA-Z]+$', 'Only alphanumeric",
"\"License\"); you may not use this file except in compliance with the License.",
"def get_recursive_pks(self): pks = self.residence.get_recursive_pks() pks.append(self.pk) return pks class Thermostat(Model): \"\"\" Represents a",
"class ThermostatMetaEntry(Model): \"\"\" Represents a thermistat meta entry containing signal strength, uptime and",
"is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"ordering = ('day', 'time') user = models.ForeignKey(User) def get_recursive_pks(self): pks = self.user.get_recursive_pks() pks.append(self.pk)",
"you may not use this file except in compliance with the License. You",
"thermostat. \"\"\" rfid = models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) room = models.ForeignKey('Room', related_name='thermostats') name =",
"[ (MONDAY, 'Monday'), (TUESDAY, 'Tuesday'), (WEDNESDAY, 'Wednesday'), (THURSDAY, 'Thursday'), (FRIDAY, 'Friday'), (SATURDAY, 'Saturday'),",
"__metaclass__ = ABCMeta class Meta: abstract = True def __repr__(self): fields_string = ',",
"residences = Residence.objects.filter(rfid=self.rfid) assert (0 <= len(residences) <= 1) if len(residences) > 0:",
"agreed to in writing, software distributed under the License is distributed on an",
"= 1 WEDNESDAY = 2 THURSDAY = 3 FRIDAY = 4 SATURDAY =",
"determine the URL of an object. \"\"\" pass class Residence(Model): \"\"\" Represents a",
"('datetime',) def get_recursive_pks(self): pks = self.thermostat.get_recursive_pks() assert (self.pk == self.datetime) pks.append(self.datetime.isoformat()) return pks",
"'.join(['%s:\"%s\"' % (field.name, getattr(self, field.name)) for field in self._meta.fields]) return '<%s(%s)>' % (self.__class__._meta.object_name,",
"Represents a physical thermostat device. \"\"\" @property def thermostat(self): thermostats = Thermostat.objects.filter(rfid=self.rfid) assert",
"'Only alphanumeric characters are allowed.') rfid_validator = alpha_numeric_validator class Model(models.Model): \"\"\" Base class",
"distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES",
"and battery level. \"\"\" id = models.AutoField(primary_key=True) datetime = models.DateTimeField() rssi = models.IntegerField(null=True)",
"= models.IntegerField(null=True) thermostat = models.ForeignKey('Thermostat', related_name='meta_entries') class Meta: unique_together = ('thermostat', 'datetime') ordering",
"class Model(models.Model): \"\"\" Base class for all models. \"\"\" __metaclass__ = ABCMeta class",
"pks.append(self.pk) return pks class OccupancyPredictionEntry(TimetableEntry): \"\"\" Represents an user occupancy prediction entry. This",
"may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable",
"ABCMeta MONDAY = 0 TUESDAY = 1 WEDNESDAY = 2 THURSDAY = 3",
"Base class for all models. \"\"\" __metaclass__ = ABCMeta class Meta: abstract =",
"implied. See the License for the specific language governing permissions and limitations under",
"Copyright 2016 <NAME>, <NAME> Licensed under the Apache License, Version 2.0 (the \"License\");",
"rssi = models.IntegerField(null=True) uptime = models.IntegerField(null=True) battery = models.IntegerField(null=True) thermostat = models.ForeignKey('Thermostat', related_name='meta_entries')",
"thermostat in thermostats] thermostat_devices = ThermostatDevice.objects.filter(rfid__in=thermostat_rfids) return thermostat_devices class ThermostatDevice(Device): \"\"\" Represents a",
"device. \"\"\" @property def thermostat(self): thermostats = Thermostat.objects.filter(rfid=self.rfid) assert (0 <= len(thermostats) <=",
"\"\"\" Represents a physical thermostat device. \"\"\" @property def thermostat(self): thermostats = Thermostat.objects.filter(rfid=self.rfid)",
"= ('day', 'time', 'user') ordering = ('day', 'time') user = models.ForeignKey(User) def get_recursive_pks(self):",
"get_recursive_pks(self): pks = self.residence.get_recursive_pks() pks.append(self.pk) return pks class Room(Model): \"\"\" Represents a room.",
"(WEDNESDAY, 'Wednesday'), (THURSDAY, 'Thursday'), (FRIDAY, 'Friday'), (SATURDAY, 'Saturday'), (SUNDAY, 'Sunday'), ] day =",
"related_name='users') class Meta: ordering = ('imei',) def get_recursive_pks(self): pks = self.residence.get_recursive_pks() pks.append(self.pk) return",
"models.FloatField() thermostat = models.ForeignKey('Thermostat', related_name='temperatures') class Meta: ordering = ('datetime',) def get_recursive_pks(self): pks",
"self.room.get_recursive_pks() pks.append(self.pk) return pks class Temperature(Model): \"\"\" Represents a temperature. \"\"\" datetime =",
"True class HeatingTableEntry(TimetableEntry): \"\"\" Represents an entry of a heating schedule. \"\"\" class",
"Meta: abstract = True class HeatingTableEntry(TimetableEntry): \"\"\" Represents an entry of a heating",
"= 3 FRIDAY = 4 SATURDAY = 5 SUNDAY = 6 DAY_IN_WEEK_CHOICES =",
"Represents a user. \"\"\" imei = models.CharField(primary_key=True, max_length=100, validators=[alpha_numeric_validator]) name = models.CharField(max_length=100) residence",
"unique_together = ('thermostat', 'datetime') ordering = ('datetime',) def get_recursive_pks(self): pks = self.thermostat.get_recursive_pks() pks.append(self.pk)",
"a heating schedule. \"\"\" class Meta: unique_together = ('day', 'time', 'thermostat') ordering =",
"abstract = True def __repr__(self): fields_string = ', '.join(['%s:\"%s\"' % (field.name, getattr(self, field.name))",
"models.ForeignKey('Room', related_name='thermostats') name = models.CharField(max_length=100, blank=False) class Meta: ordering = ('rfid',) def get_recursive_pks(self):",
"= Thermostat.objects.filter(rfid=self.rfid) assert (0 <= len(thermostats) <= 1) if len(thermostats) > 0: return",
"'Wednesday'), (THURSDAY, 'Thursday'), (FRIDAY, 'Friday'), (SATURDAY, 'Saturday'), (SUNDAY, 'Sunday'), ] day = models.CharField(max_length=3,",
"'Saturday'), (SUNDAY, 'Sunday'), ] day = models.CharField(max_length=3, choices=DAY_IN_WEEK_CHOICES) time = models.TimeField() class Meta:",
"def thermostat(self): thermostats = Thermostat.objects.filter(rfid=self.rfid) assert (0 <= len(thermostats) <= 1) if len(thermostats)",
"self.thermostat.get_recursive_pks() pks.append(self.pk) return pks class OccupancyPredictionEntry(TimetableEntry): \"\"\" Represents an user occupancy prediction entry.",
"def __repr__(self): fields_string = ', '.join(['%s:\"%s\"' % (field.name, getattr(self, field.name)) for field in",
"6 DAY_IN_WEEK_CHOICES = [ (MONDAY, 'Monday'), (TUESDAY, 'Tuesday'), (WEDNESDAY, 'Wednesday'), (THURSDAY, 'Thursday'), (FRIDAY,",
"is None: return None rooms = Room.objects.filter(residence=residence) room_pks = [room.pk for room in",
"models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) mac = models.CharField(max_length=17, unique=True) class Meta: abstract = True def",
"automatically generated if no other primary_key is defined name = models.CharField(max_length=100) residence =",
"use this file except in compliance with the License. You may obtain a",
"rooms] thermostats = Thermostat.objects.filter(room__in=room_pks) thermostat_rfids = [thermostat.rfid for thermostat in thermostats] thermostat_devices =",
"of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to",
"and limitations under the License. \"\"\" from abc import ABCMeta, abstractmethod from django.core",
"Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use",
"parents. Used to determine the URL of an object. \"\"\" pass class Residence(Model):",
"def get_recursive_pks(self): \"\"\" Returns a list of primary keys of all recursive parents.",
"imei = models.CharField(primary_key=True, max_length=100, validators=[alpha_numeric_validator]) name = models.CharField(max_length=100) residence = models.ForeignKey('Residence', related_name='users') class",
"= 5 SUNDAY = 6 DAY_IN_WEEK_CHOICES = [ (MONDAY, 'Monday'), (TUESDAY, 'Tuesday'), (WEDNESDAY,",
"a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or",
"\"\"\" rfid = models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) room = models.ForeignKey('Room', related_name='thermostats') name = models.CharField(max_length=100,",
"'datetime') ordering = ('datetime',) def get_recursive_pks(self): pks = self.thermostat.get_recursive_pks() pks.append(self.pk) return pks class",
"models.FloatField(validators=[validators.MinValueValidator(5), validators.MaxValueValidator(30)]) thermostat = models.ForeignKey(Thermostat, related_name='heating_table_entries') def get_recursive_pks(self): pks = self.thermostat.get_recursive_pks() pks.append(self.pk) return",
"uptime and battery level. \"\"\" id = models.AutoField(primary_key=True) datetime = models.DateTimeField() rssi =",
"get_recursive_pks(self): pks = self.residence.get_recursive_pks() pks.append(self.pk) return pks class Thermostat(Model): \"\"\" Represents a thermostat.",
"def get_recursive_pks(self): pks = self.room.get_recursive_pks() pks.append(self.pk) return pks class Temperature(Model): \"\"\" Represents a",
"Raspberry Pi. \"\"\" residence = self.residence if residence is None: return None rooms",
"abstractmethod from django.core import validators from django.db import models alpha_numeric_validator = validators.RegexValidator(r'^[0-9a-zA-Z]+$', 'Only",
"models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) room = models.ForeignKey('Room', related_name='thermostats') name = models.CharField(max_length=100, blank=False) class Meta:",
"required by applicable law or agreed to in writing, software distributed under the",
"self.residence.get_recursive_pks() pks.append(self.pk) return pks class Room(Model): \"\"\" Represents a room. \"\"\" # id",
"models.CharField(max_length=100) residence = models.ForeignKey('Residence', related_name='rooms') class Meta: ordering = ('name',) def get_recursive_pks(self): pks",
"Base class for a physical device with an RFID number and MAC address.",
"'Monday'), (TUESDAY, 'Tuesday'), (WEDNESDAY, 'Wednesday'), (THURSDAY, 'Thursday'), (FRIDAY, 'Friday'), (SATURDAY, 'Saturday'), (SUNDAY, 'Sunday'),",
"= ('imei',) def get_recursive_pks(self): pks = self.residence.get_recursive_pks() pks.append(self.pk) return pks class Room(Model): \"\"\"",
"<= len(residences) <= 1) if len(residences) > 0: return residences[0] else: return None",
"def get_recursive_pks(self): pks = [self.pk] return pks class User(Model): \"\"\" Represents a user.",
"name = models.CharField(max_length=100, blank=False) class Meta: ordering = ('rfid',) def get_recursive_pks(self): pks =",
"\"\"\" class Meta: unique_together = ('day', 'time', 'user') ordering = ('day', 'time') user",
"= ('rfid',) def get_recursive_pks(self): pks = self.room.get_recursive_pks() pks.append(self.pk) return pks class Temperature(Model): \"\"\"",
"temperature = models.FloatField(validators=[validators.MinValueValidator(5), validators.MaxValueValidator(30)]) thermostat = models.ForeignKey(Thermostat, related_name='heating_table_entries') def get_recursive_pks(self): pks = self.thermostat.get_recursive_pks()",
"pass class Residence(Model): \"\"\" Represents a residence. \"\"\" rfid = models.CharField(primary_key=True, max_length=100, validators=[rfid_validator])",
"unique=True) class Meta: abstract = True def get_recursive_pks(self): return [self.pk] class RaspberryDevice(Device): \"\"\"",
"= self.thermostat.get_recursive_pks() assert (self.pk == self.datetime) pks.append(self.datetime.isoformat()) return pks class ThermostatMetaEntry(Model): \"\"\" Represents",
"SATURDAY = 5 SUNDAY = 6 DAY_IN_WEEK_CHOICES = [ (MONDAY, 'Monday'), (TUESDAY, 'Tuesday'),",
"ordering = ('datetime',) def get_recursive_pks(self): pks = self.thermostat.get_recursive_pks() assert (self.pk == self.datetime) pks.append(self.datetime.isoformat())",
"= Room.objects.filter(residence=residence) room_pks = [room.pk for room in rooms] thermostats = Thermostat.objects.filter(room__in=room_pks) thermostat_rfids",
"thermostat = models.ForeignKey('Thermostat', related_name='meta_entries') class Meta: unique_together = ('thermostat', 'datetime') ordering = ('datetime',)",
"self.residence if residence is None: return None rooms = Room.objects.filter(residence=residence) room_pks = [room.pk",
"allowed.') rfid_validator = alpha_numeric_validator class Model(models.Model): \"\"\" Base class for all models. \"\"\"",
"distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"for a weekly timetable entry. \"\"\" __metaclass__ = ABCMeta MONDAY = 0 TUESDAY",
"not use this file except in compliance with the License. You may obtain",
"\"\"\" Copyright 2016 <NAME>, <NAME> Licensed under the Apache License, Version 2.0 (the",
"validators.MaxValueValidator(30)]) thermostat = models.ForeignKey(Thermostat, related_name='heating_table_entries') def get_recursive_pks(self): pks = self.thermostat.get_recursive_pks() pks.append(self.pk) return pks",
"models.DateTimeField() rssi = models.IntegerField(null=True) uptime = models.IntegerField(null=True) battery = models.IntegerField(null=True) thermostat = models.ForeignKey('Thermostat',",
"models.ForeignKey('Residence', related_name='users') class Meta: ordering = ('imei',) def get_recursive_pks(self): pks = self.residence.get_recursive_pks() pks.append(self.pk)",
"models.ForeignKey('Thermostat', related_name='temperatures') class Meta: ordering = ('datetime',) def get_recursive_pks(self): pks = self.thermostat.get_recursive_pks() assert",
"1) if len(residences) > 0: return residences[0] else: return None @property def thermostat_devices(self):",
"\"\"\" Represents a user. \"\"\" imei = models.CharField(primary_key=True, max_length=100, validators=[alpha_numeric_validator]) name = models.CharField(max_length=100)",
"= ('rfid',) def get_recursive_pks(self): pks = [self.pk] return pks class User(Model): \"\"\" Represents",
"day = models.CharField(max_length=3, choices=DAY_IN_WEEK_CHOICES) time = models.TimeField() class Meta: abstract = True class",
"(FRIDAY, 'Friday'), (SATURDAY, 'Saturday'), (SUNDAY, 'Sunday'), ] day = models.CharField(max_length=3, choices=DAY_IN_WEEK_CHOICES) time =",
"id = models.AutoField(primary_key=True) datetime = models.DateTimeField() rssi = models.IntegerField(null=True) uptime = models.IntegerField(null=True) battery",
"models.CharField(max_length=3, choices=DAY_IN_WEEK_CHOICES) time = models.TimeField() class Meta: abstract = True class HeatingTableEntry(TimetableEntry): \"\"\"",
"thermostats[0] else: return None class TimetableEntry(Model): \"\"\" Base class for a weekly timetable",
"for room in rooms] thermostats = Thermostat.objects.filter(room__in=room_pks) thermostat_rfids = [thermostat.rfid for thermostat in",
"ordering = ('rfid',) def get_recursive_pks(self): pks = self.room.get_recursive_pks() pks.append(self.pk) return pks class Temperature(Model):",
"ANY KIND, either express or implied. See the License for the specific language",
"file except in compliance with the License. You may obtain a copy of",
"Room(Model): \"\"\" Represents a room. \"\"\" # id is automatically generated if no",
"Meta: abstract = True def __repr__(self): fields_string = ', '.join(['%s:\"%s\"' % (field.name, getattr(self,",
"class Meta: ordering = ('datetime',) def get_recursive_pks(self): pks = self.thermostat.get_recursive_pks() assert (self.pk ==",
"= models.DateTimeField() rssi = models.IntegerField(null=True) uptime = models.IntegerField(null=True) battery = models.IntegerField(null=True) thermostat =",
"Used to determine the URL of an object. \"\"\" pass class Residence(Model): \"\"\"",
"2.0 (the \"License\"); you may not use this file except in compliance with",
"device. \"\"\" @property def residence(self): residences = Residence.objects.filter(rfid=self.rfid) assert (0 <= len(residences) <=",
"return None @property def thermostat_devices(self): \"\"\" :return: Thermostat devices associated to the Raspberry",
"intended to be used in future work. \"\"\" class Meta: unique_together = ('day',",
"copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed",
"models.AutoField(primary_key=True) datetime = models.DateTimeField() rssi = models.IntegerField(null=True) uptime = models.IntegerField(null=True) battery = models.IntegerField(null=True)",
"return pks class OccupancyPredictionEntry(TimetableEntry): \"\"\" Represents an user occupancy prediction entry. This is",
"= models.ForeignKey('Residence', related_name='users') class Meta: ordering = ('imei',) def get_recursive_pks(self): pks = self.residence.get_recursive_pks()",
"alpha_numeric_validator = validators.RegexValidator(r'^[0-9a-zA-Z]+$', 'Only alphanumeric characters are allowed.') rfid_validator = alpha_numeric_validator class Model(models.Model):",
"if no other primary_key is defined name = models.CharField(max_length=100) residence = models.ForeignKey('Residence', related_name='rooms')",
"the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless",
"def thermostat_devices(self): \"\"\" :return: Thermostat devices associated to the Raspberry Pi. \"\"\" residence",
"pks class Room(Model): \"\"\" Represents a room. \"\"\" # id is automatically generated",
"related_name='thermostats') name = models.CharField(max_length=100, blank=False) class Meta: ordering = ('rfid',) def get_recursive_pks(self): pks",
"class Temperature(Model): \"\"\" Represents a temperature. \"\"\" datetime = models.DateTimeField(primary_key=True) value = models.FloatField()",
"physical device with an RFID number and MAC address. \"\"\" __metaclass__ = ABCMeta",
"(the \"License\"); you may not use this file except in compliance with the",
"models.CharField(max_length=100, blank=False) class Meta: ordering = ('rfid',) def get_recursive_pks(self): pks = self.room.get_recursive_pks() pks.append(self.pk)",
"limitations under the License. \"\"\" from abc import ABCMeta, abstractmethod from django.core import",
"len(residences) <= 1) if len(residences) > 0: return residences[0] else: return None @property",
"level. \"\"\" id = models.AutoField(primary_key=True) datetime = models.DateTimeField() rssi = models.IntegerField(null=True) uptime =",
"= ('datetime',) def get_recursive_pks(self): pks = self.thermostat.get_recursive_pks() pks.append(self.pk) return pks class Device(Model): \"\"\"",
"characters are allowed.') rfid_validator = alpha_numeric_validator class Model(models.Model): \"\"\" Base class for all",
"import ABCMeta, abstractmethod from django.core import validators from django.db import models alpha_numeric_validator =",
"pks = self.thermostat.get_recursive_pks() pks.append(self.pk) return pks class OccupancyPredictionEntry(TimetableEntry): \"\"\" Represents an user occupancy",
"pks class Device(Model): \"\"\" Base class for a physical device with an RFID",
"\"\"\" Represents a physical Raspberry Pi device. \"\"\" @property def residence(self): residences =",
"None: return None rooms = Room.objects.filter(residence=residence) room_pks = [room.pk for room in rooms]",
"battery level. \"\"\" id = models.AutoField(primary_key=True) datetime = models.DateTimeField() rssi = models.IntegerField(null=True) uptime",
"max_length=100, validators=[rfid_validator]) class Meta: ordering = ('rfid',) def get_recursive_pks(self): pks = [self.pk] return",
"Pi device. \"\"\" @property def residence(self): residences = Residence.objects.filter(rfid=self.rfid) assert (0 <= len(residences)",
"= ('day', 'time', 'thermostat') ordering = ('day', 'time') temperature = models.FloatField(validators=[validators.MinValueValidator(5), validators.MaxValueValidator(30)]) thermostat",
"pks.append(self.pk) return pks class Room(Model): \"\"\" Represents a room. \"\"\" # id is",
"\"\"\" residence = self.residence if residence is None: return None rooms = Room.objects.filter(residence=residence)",
"no other primary_key is defined name = models.CharField(max_length=100) residence = models.ForeignKey('Residence', related_name='rooms') class",
"if len(residences) > 0: return residences[0] else: return None @property def thermostat_devices(self): \"\"\"",
"ordering = ('name',) def get_recursive_pks(self): pks = self.residence.get_recursive_pks() pks.append(self.pk) return pks class Thermostat(Model):",
"= True def get_recursive_pks(self): return [self.pk] class RaspberryDevice(Device): \"\"\" Represents a physical Raspberry",
"= [thermostat.rfid for thermostat in thermostats] thermostat_devices = ThermostatDevice.objects.filter(rfid__in=thermostat_rfids) return thermostat_devices class ThermostatDevice(Device):",
"= Thermostat.objects.filter(room__in=room_pks) thermostat_rfids = [thermostat.rfid for thermostat in thermostats] thermostat_devices = ThermostatDevice.objects.filter(rfid__in=thermostat_rfids) return",
"devices associated to the Raspberry Pi. \"\"\" residence = self.residence if residence is",
"3 FRIDAY = 4 SATURDAY = 5 SUNDAY = 6 DAY_IN_WEEK_CHOICES = [",
"[self.pk] return pks class User(Model): \"\"\" Represents a user. \"\"\" imei = models.CharField(primary_key=True,",
"physical Raspberry Pi device. \"\"\" @property def residence(self): residences = Residence.objects.filter(rfid=self.rfid) assert (0",
"True def __repr__(self): fields_string = ', '.join(['%s:\"%s\"' % (field.name, getattr(self, field.name)) for field",
"to the Raspberry Pi. \"\"\" residence = self.residence if residence is None: return",
"Meta: unique_together = ('thermostat', 'datetime') ordering = ('datetime',) def get_recursive_pks(self): pks = self.thermostat.get_recursive_pks()",
"http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed",
"a room. \"\"\" # id is automatically generated if no other primary_key is",
"assert (0 <= len(residences) <= 1) if len(residences) > 0: return residences[0] else:",
"('thermostat', 'datetime') ordering = ('datetime',) def get_recursive_pks(self): pks = self.thermostat.get_recursive_pks() pks.append(self.pk) return pks",
"(MONDAY, 'Monday'), (TUESDAY, 'Tuesday'), (WEDNESDAY, 'Wednesday'), (THURSDAY, 'Thursday'), (FRIDAY, 'Friday'), (SATURDAY, 'Saturday'), (SUNDAY,",
"Temperature(Model): \"\"\" Represents a temperature. \"\"\" datetime = models.DateTimeField(primary_key=True) value = models.FloatField() thermostat",
"rfid = models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) room = models.ForeignKey('Room', related_name='thermostats') name = models.CharField(max_length=100, blank=False)",
"License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF",
"HeatingTableEntry(TimetableEntry): \"\"\" Represents an entry of a heating schedule. \"\"\" class Meta: unique_together",
"<NAME> Licensed under the Apache License, Version 2.0 (the \"License\"); you may not",
"\"\"\" Returns a list of primary keys of all recursive parents. Used to",
"pks class Thermostat(Model): \"\"\" Represents a thermostat. \"\"\" rfid = models.CharField(primary_key=True, max_length=100, validators=[rfid_validator])",
"ThermostatDevice.objects.filter(rfid__in=thermostat_rfids) return thermostat_devices class ThermostatDevice(Device): \"\"\" Represents a physical thermostat device. \"\"\" @property",
"= models.ForeignKey('Room', related_name='thermostats') name = models.CharField(max_length=100, blank=False) class Meta: ordering = ('rfid',) def",
"> 0: return residences[0] else: return None @property def thermostat_devices(self): \"\"\" :return: Thermostat",
"are allowed.') rfid_validator = alpha_numeric_validator class Model(models.Model): \"\"\" Base class for all models.",
"= self.residence.get_recursive_pks() pks.append(self.pk) return pks class Thermostat(Model): \"\"\" Represents a thermostat. \"\"\" rfid",
"related_name='meta_entries') class Meta: unique_together = ('thermostat', 'datetime') ordering = ('datetime',) def get_recursive_pks(self): pks",
"thermostat_rfids = [thermostat.rfid for thermostat in thermostats] thermostat_devices = ThermostatDevice.objects.filter(rfid__in=thermostat_rfids) return thermostat_devices class",
"law or agreed to in writing, software distributed under the License is distributed",
"stub and is intended to be used in future work. \"\"\" class Meta:",
"\"\"\" :return: Thermostat devices associated to the Raspberry Pi. \"\"\" residence = self.residence",
"Version 2.0 (the \"License\"); you may not use this file except in compliance",
"= [ (MONDAY, 'Monday'), (TUESDAY, 'Tuesday'), (WEDNESDAY, 'Wednesday'), (THURSDAY, 'Thursday'), (FRIDAY, 'Friday'), (SATURDAY,",
"used in future work. \"\"\" class Meta: unique_together = ('day', 'time', 'user') ordering",
"the Apache License, Version 2.0 (the \"License\"); you may not use this file",
"all recursive parents. Used to determine the URL of an object. \"\"\" pass",
"\"\"\" id = models.AutoField(primary_key=True) datetime = models.DateTimeField() rssi = models.IntegerField(null=True) uptime = models.IntegerField(null=True)",
"related_name='rooms') class Meta: ordering = ('name',) def get_recursive_pks(self): pks = self.residence.get_recursive_pks() pks.append(self.pk) return",
"thermostats = Thermostat.objects.filter(rfid=self.rfid) assert (0 <= len(thermostats) <= 1) if len(thermostats) > 0:",
"pks class Temperature(Model): \"\"\" Represents a temperature. \"\"\" datetime = models.DateTimeField(primary_key=True) value =",
"Base class for a weekly timetable entry. \"\"\" __metaclass__ = ABCMeta MONDAY =",
"class OccupancyPredictionEntry(TimetableEntry): \"\"\" Represents an user occupancy prediction entry. This is a stub",
"None class TimetableEntry(Model): \"\"\" Base class for a weekly timetable entry. \"\"\" __metaclass__",
"\"\"\" @property def thermostat(self): thermostats = Thermostat.objects.filter(rfid=self.rfid) assert (0 <= len(thermostats) <= 1)",
"under the Apache License, Version 2.0 (the \"License\"); you may not use this",
"class Device(Model): \"\"\" Base class for a physical device with an RFID number",
"for the specific language governing permissions and limitations under the License. \"\"\" from",
"assert (self.pk == self.datetime) pks.append(self.datetime.isoformat()) return pks class ThermostatMetaEntry(Model): \"\"\" Represents a thermistat",
"Represents a thermistat meta entry containing signal strength, uptime and battery level. \"\"\"",
"pks class User(Model): \"\"\" Represents a user. \"\"\" imei = models.CharField(primary_key=True, max_length=100, validators=[alpha_numeric_validator])",
"room. \"\"\" # id is automatically generated if no other primary_key is defined",
"either express or implied. See the License for the specific language governing permissions",
"all models. \"\"\" __metaclass__ = ABCMeta class Meta: abstract = True def __repr__(self):",
"thermistat meta entry containing signal strength, uptime and battery level. \"\"\" id =",
"signal strength, uptime and battery level. \"\"\" id = models.AutoField(primary_key=True) datetime = models.DateTimeField()",
"= models.AutoField(primary_key=True) datetime = models.DateTimeField() rssi = models.IntegerField(null=True) uptime = models.IntegerField(null=True) battery =",
"is intended to be used in future work. \"\"\" class Meta: unique_together =",
"Represents an user occupancy prediction entry. This is a stub and is intended",
"class ThermostatDevice(Device): \"\"\" Represents a physical thermostat device. \"\"\" @property def thermostat(self): thermostats",
"len(thermostats) <= 1) if len(thermostats) > 0: return thermostats[0] else: return None class",
"__repr__(self): fields_string = ', '.join(['%s:\"%s\"' % (field.name, getattr(self, field.name)) for field in self._meta.fields])",
"Apache License, Version 2.0 (the \"License\"); you may not use this file except",
"or implied. See the License for the specific language governing permissions and limitations",
"= ('day', 'time') temperature = models.FloatField(validators=[validators.MinValueValidator(5), validators.MaxValueValidator(30)]) thermostat = models.ForeignKey(Thermostat, related_name='heating_table_entries') def get_recursive_pks(self):",
"field.name)) for field in self._meta.fields]) return '<%s(%s)>' % (self.__class__._meta.object_name, fields_string) def __str__(self): return",
"abstract = True def get_recursive_pks(self): return [self.pk] class RaspberryDevice(Device): \"\"\" Represents a physical",
"@property def thermostat_devices(self): \"\"\" :return: Thermostat devices associated to the Raspberry Pi. \"\"\"",
"pks class ThermostatMetaEntry(Model): \"\"\" Represents a thermistat meta entry containing signal strength, uptime",
"def get_recursive_pks(self): pks = self.thermostat.get_recursive_pks() pks.append(self.pk) return pks class Device(Model): \"\"\" Base class",
"schedule. \"\"\" class Meta: unique_together = ('day', 'time', 'thermostat') ordering = ('day', 'time')",
"number and MAC address. \"\"\" __metaclass__ = ABCMeta rfid = models.CharField(primary_key=True, max_length=100, validators=[rfid_validator])",
"max_length=100, validators=[rfid_validator]) mac = models.CharField(max_length=17, unique=True) class Meta: abstract = True def get_recursive_pks(self):",
"return '<%s(%s)>' % (self.__class__._meta.object_name, fields_string) def __str__(self): return str(self.pk) @abstractmethod def get_recursive_pks(self): \"\"\"",
"__metaclass__ = ABCMeta rfid = models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) mac = models.CharField(max_length=17, unique=True) class",
"] day = models.CharField(max_length=3, choices=DAY_IN_WEEK_CHOICES) time = models.TimeField() class Meta: abstract = True",
"self._meta.fields]) return '<%s(%s)>' % (self.__class__._meta.object_name, fields_string) def __str__(self): return str(self.pk) @abstractmethod def get_recursive_pks(self):",
"blank=False) class Meta: ordering = ('rfid',) def get_recursive_pks(self): pks = self.room.get_recursive_pks() pks.append(self.pk) return",
"models.CharField(max_length=100) residence = models.ForeignKey('Residence', related_name='users') class Meta: ordering = ('imei',) def get_recursive_pks(self): pks",
"RaspberryDevice(Device): \"\"\" Represents a physical Raspberry Pi device. \"\"\" @property def residence(self): residences",
"models.CharField(primary_key=True, max_length=100, validators=[alpha_numeric_validator]) name = models.CharField(max_length=100) residence = models.ForeignKey('Residence', related_name='users') class Meta: ordering",
"= models.CharField(primary_key=True, max_length=100, validators=[alpha_numeric_validator]) name = models.CharField(max_length=100) residence = models.ForeignKey('Residence', related_name='users') class Meta:",
"URL of an object. \"\"\" pass class Residence(Model): \"\"\" Represents a residence. \"\"\"",
"len(thermostats) > 0: return thermostats[0] else: return None class TimetableEntry(Model): \"\"\" Base class",
"CONDITIONS OF ANY KIND, either express or implied. See the License for the",
"keys of all recursive parents. Used to determine the URL of an object.",
"pks class OccupancyPredictionEntry(TimetableEntry): \"\"\" Represents an user occupancy prediction entry. This is a",
"to in writing, software distributed under the License is distributed on an \"AS",
"models.TimeField() class Meta: abstract = True class HeatingTableEntry(TimetableEntry): \"\"\" Represents an entry of",
"residence = self.residence if residence is None: return None rooms = Room.objects.filter(residence=residence) room_pks",
"str(self.pk) @abstractmethod def get_recursive_pks(self): \"\"\" Returns a list of primary keys of all",
"def get_recursive_pks(self): pks = self.thermostat.get_recursive_pks() pks.append(self.pk) return pks class OccupancyPredictionEntry(TimetableEntry): \"\"\" Represents an",
"from abc import ABCMeta, abstractmethod from django.core import validators from django.db import models",
"pks.append(self.pk) return pks class Thermostat(Model): \"\"\" Represents a thermostat. \"\"\" rfid = models.CharField(primary_key=True,",
"except in compliance with the License. You may obtain a copy of the",
"room = models.ForeignKey('Room', related_name='thermostats') name = models.CharField(max_length=100, blank=False) class Meta: ordering = ('rfid',)",
"= 2 THURSDAY = 3 FRIDAY = 4 SATURDAY = 5 SUNDAY =",
"= models.CharField(max_length=3, choices=DAY_IN_WEEK_CHOICES) time = models.TimeField() class Meta: abstract = True class HeatingTableEntry(TimetableEntry):",
"django.db import models alpha_numeric_validator = validators.RegexValidator(r'^[0-9a-zA-Z]+$', 'Only alphanumeric characters are allowed.') rfid_validator =",
"\"\"\" Represents a residence. \"\"\" rfid = models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) class Meta: ordering",
"get_recursive_pks(self): return [self.pk] class RaspberryDevice(Device): \"\"\" Represents a physical Raspberry Pi device. \"\"\"",
"= models.ForeignKey('Residence', related_name='rooms') class Meta: ordering = ('name',) def get_recursive_pks(self): pks = self.residence.get_recursive_pks()",
"True def get_recursive_pks(self): return [self.pk] class RaspberryDevice(Device): \"\"\" Represents a physical Raspberry Pi",
"\"\"\" Represents a thermistat meta entry containing signal strength, uptime and battery level.",
"@property def thermostat(self): thermostats = Thermostat.objects.filter(rfid=self.rfid) assert (0 <= len(thermostats) <= 1) if",
"class Meta: unique_together = ('day', 'time', 'thermostat') ordering = ('day', 'time') temperature =",
"an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"return str(self.pk) @abstractmethod def get_recursive_pks(self): \"\"\" Returns a list of primary keys of",
"in rooms] thermostats = Thermostat.objects.filter(room__in=room_pks) thermostat_rfids = [thermostat.rfid for thermostat in thermostats] thermostat_devices",
"[room.pk for room in rooms] thermostats = Thermostat.objects.filter(room__in=room_pks) thermostat_rfids = [thermostat.rfid for thermostat",
"2016 <NAME>, <NAME> Licensed under the Apache License, Version 2.0 (the \"License\"); you",
"abstract = True class HeatingTableEntry(TimetableEntry): \"\"\" Represents an entry of a heating schedule.",
"residence(self): residences = Residence.objects.filter(rfid=self.rfid) assert (0 <= len(residences) <= 1) if len(residences) >",
"pks = self.room.get_recursive_pks() pks.append(self.pk) return pks class Temperature(Model): \"\"\" Represents a temperature. \"\"\"",
"fields_string) def __str__(self): return str(self.pk) @abstractmethod def get_recursive_pks(self): \"\"\" Returns a list of",
"= self.room.get_recursive_pks() pks.append(self.pk) return pks class Temperature(Model): \"\"\" Represents a temperature. \"\"\" datetime",
"to be used in future work. \"\"\" class Meta: unique_together = ('day', 'time',",
"obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law",
"0 TUESDAY = 1 WEDNESDAY = 2 THURSDAY = 3 FRIDAY = 4",
"= models.CharField(max_length=100) residence = models.ForeignKey('Residence', related_name='users') class Meta: ordering = ('imei',) def get_recursive_pks(self):",
"= ('name',) def get_recursive_pks(self): pks = self.residence.get_recursive_pks() pks.append(self.pk) return pks class Thermostat(Model): \"\"\"",
"class TimetableEntry(Model): \"\"\" Base class for a weekly timetable entry. \"\"\" __metaclass__ =",
"return pks class Thermostat(Model): \"\"\" Represents a thermostat. \"\"\" rfid = models.CharField(primary_key=True, max_length=100,",
"pks.append(self.pk) return pks class Device(Model): \"\"\" Base class for a physical device with",
"Device(Model): \"\"\" Base class for a physical device with an RFID number and",
"<= 1) if len(residences) > 0: return residences[0] else: return None @property def",
"('day', 'time') temperature = models.FloatField(validators=[validators.MinValueValidator(5), validators.MaxValueValidator(30)]) thermostat = models.ForeignKey(Thermostat, related_name='heating_table_entries') def get_recursive_pks(self): pks",
"def get_recursive_pks(self): pks = self.thermostat.get_recursive_pks() assert (self.pk == self.datetime) pks.append(self.datetime.isoformat()) return pks class",
"pks = [self.pk] return pks class User(Model): \"\"\" Represents a user. \"\"\" imei",
"License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing,",
"(SUNDAY, 'Sunday'), ] day = models.CharField(max_length=3, choices=DAY_IN_WEEK_CHOICES) time = models.TimeField() class Meta: abstract",
"class Meta: ordering = ('imei',) def get_recursive_pks(self): pks = self.residence.get_recursive_pks() pks.append(self.pk) return pks",
"\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"value = models.FloatField() thermostat = models.ForeignKey('Thermostat', related_name='temperatures') class Meta: ordering = ('datetime',) def",
"\"\"\" __metaclass__ = ABCMeta rfid = models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) mac = models.CharField(max_length=17, unique=True)",
"primary keys of all recursive parents. Used to determine the URL of an",
"= ABCMeta class Meta: abstract = True def __repr__(self): fields_string = ', '.join(['%s:\"%s\"'",
"defined name = models.CharField(max_length=100) residence = models.ForeignKey('Residence', related_name='rooms') class Meta: ordering = ('name',)",
"a physical device with an RFID number and MAC address. \"\"\" __metaclass__ =",
"validators=[rfid_validator]) class Meta: ordering = ('rfid',) def get_recursive_pks(self): pks = [self.pk] return pks",
"'thermostat') ordering = ('day', 'time') temperature = models.FloatField(validators=[validators.MinValueValidator(5), validators.MaxValueValidator(30)]) thermostat = models.ForeignKey(Thermostat, related_name='heating_table_entries')",
"self.datetime) pks.append(self.datetime.isoformat()) return pks class ThermostatMetaEntry(Model): \"\"\" Represents a thermistat meta entry containing",
"\"\"\" imei = models.CharField(primary_key=True, max_length=100, validators=[alpha_numeric_validator]) name = models.CharField(max_length=100) residence = models.ForeignKey('Residence', related_name='users')",
"compliance with the License. You may obtain a copy of the License at",
"return pks class ThermostatMetaEntry(Model): \"\"\" Represents a thermistat meta entry containing signal strength,",
"models.ForeignKey('Residence', related_name='rooms') class Meta: ordering = ('name',) def get_recursive_pks(self): pks = self.residence.get_recursive_pks() pks.append(self.pk)",
"('day', 'time', 'user') ordering = ('day', 'time') user = models.ForeignKey(User) def get_recursive_pks(self): pks",
"Model(models.Model): \"\"\" Base class for all models. \"\"\" __metaclass__ = ABCMeta class Meta:",
"for all models. \"\"\" __metaclass__ = ABCMeta class Meta: abstract = True def",
"class Meta: abstract = True def __repr__(self): fields_string = ', '.join(['%s:\"%s\"' % (field.name,",
"express or implied. See the License for the specific language governing permissions and",
"'time', 'user') ordering = ('day', 'time') user = models.ForeignKey(User) def get_recursive_pks(self): pks =",
"% (self.__class__._meta.object_name, fields_string) def __str__(self): return str(self.pk) @abstractmethod def get_recursive_pks(self): \"\"\" Returns a",
"RFID number and MAC address. \"\"\" __metaclass__ = ABCMeta rfid = models.CharField(primary_key=True, max_length=100,",
"of primary keys of all recursive parents. Used to determine the URL of",
"= models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) room = models.ForeignKey('Room', related_name='thermostats') name = models.CharField(max_length=100, blank=False) class",
"(0 <= len(thermostats) <= 1) if len(thermostats) > 0: return thermostats[0] else: return",
"class Meta: unique_together = ('thermostat', 'datetime') ordering = ('datetime',) def get_recursive_pks(self): pks =",
"ordering = ('day', 'time') temperature = models.FloatField(validators=[validators.MinValueValidator(5), validators.MaxValueValidator(30)]) thermostat = models.ForeignKey(Thermostat, related_name='heating_table_entries') def",
"import validators from django.db import models alpha_numeric_validator = validators.RegexValidator(r'^[0-9a-zA-Z]+$', 'Only alphanumeric characters are",
"thermostat(self): thermostats = Thermostat.objects.filter(rfid=self.rfid) assert (0 <= len(thermostats) <= 1) if len(thermostats) >",
"entry. This is a stub and is intended to be used in future",
"Meta: ordering = ('imei',) def get_recursive_pks(self): pks = self.residence.get_recursive_pks() pks.append(self.pk) return pks class",
"mac = models.CharField(max_length=17, unique=True) class Meta: abstract = True def get_recursive_pks(self): return [self.pk]",
"You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by",
"len(residences) > 0: return residences[0] else: return None @property def thermostat_devices(self): \"\"\" :return:",
"5 SUNDAY = 6 DAY_IN_WEEK_CHOICES = [ (MONDAY, 'Monday'), (TUESDAY, 'Tuesday'), (WEDNESDAY, 'Wednesday'),",
"TUESDAY = 1 WEDNESDAY = 2 THURSDAY = 3 FRIDAY = 4 SATURDAY",
"= ThermostatDevice.objects.filter(rfid__in=thermostat_rfids) return thermostat_devices class ThermostatDevice(Device): \"\"\" Represents a physical thermostat device. \"\"\"",
"= models.CharField(max_length=100) residence = models.ForeignKey('Residence', related_name='rooms') class Meta: ordering = ('name',) def get_recursive_pks(self):",
"in future work. \"\"\" class Meta: unique_together = ('day', 'time', 'user') ordering =",
"= models.IntegerField(null=True) uptime = models.IntegerField(null=True) battery = models.IntegerField(null=True) thermostat = models.ForeignKey('Thermostat', related_name='meta_entries') class",
"pks = self.thermostat.get_recursive_pks() pks.append(self.pk) return pks class Device(Model): \"\"\" Base class for a",
"containing signal strength, uptime and battery level. \"\"\" id = models.AutoField(primary_key=True) datetime =",
"0: return thermostats[0] else: return None class TimetableEntry(Model): \"\"\" Base class for a",
"applicable law or agreed to in writing, software distributed under the License is",
"= True class HeatingTableEntry(TimetableEntry): \"\"\" Represents an entry of a heating schedule. \"\"\"",
"models. \"\"\" __metaclass__ = ABCMeta class Meta: abstract = True def __repr__(self): fields_string",
"= Residence.objects.filter(rfid=self.rfid) assert (0 <= len(residences) <= 1) if len(residences) > 0: return",
"def get_recursive_pks(self): return [self.pk] class RaspberryDevice(Device): \"\"\" Represents a physical Raspberry Pi device.",
"[thermostat.rfid for thermostat in thermostats] thermostat_devices = ThermostatDevice.objects.filter(rfid__in=thermostat_rfids) return thermostat_devices class ThermostatDevice(Device): \"\"\"",
"= self.residence if residence is None: return None rooms = Room.objects.filter(residence=residence) room_pks =",
"class Meta: abstract = True def get_recursive_pks(self): return [self.pk] class RaspberryDevice(Device): \"\"\" Represents",
"in self._meta.fields]) return '<%s(%s)>' % (self.__class__._meta.object_name, fields_string) def __str__(self): return str(self.pk) @abstractmethod def",
"<NAME>, <NAME> Licensed under the Apache License, Version 2.0 (the \"License\"); you may",
"self.thermostat.get_recursive_pks() pks.append(self.pk) return pks class Device(Model): \"\"\" Base class for a physical device",
"[self.pk] class RaspberryDevice(Device): \"\"\" Represents a physical Raspberry Pi device. \"\"\" @property def",
"THURSDAY = 3 FRIDAY = 4 SATURDAY = 5 SUNDAY = 6 DAY_IN_WEEK_CHOICES",
"from django.db import models alpha_numeric_validator = validators.RegexValidator(r'^[0-9a-zA-Z]+$', 'Only alphanumeric characters are allowed.') rfid_validator",
"self.thermostat.get_recursive_pks() assert (self.pk == self.datetime) pks.append(self.datetime.isoformat()) return pks class ThermostatMetaEntry(Model): \"\"\" Represents a",
"is defined name = models.CharField(max_length=100) residence = models.ForeignKey('Residence', related_name='rooms') class Meta: ordering =",
"'Friday'), (SATURDAY, 'Saturday'), (SUNDAY, 'Sunday'), ] day = models.CharField(max_length=3, choices=DAY_IN_WEEK_CHOICES) time = models.TimeField()",
"ThermostatMetaEntry(Model): \"\"\" Represents a thermistat meta entry containing signal strength, uptime and battery",
"1) if len(thermostats) > 0: return thermostats[0] else: return None class TimetableEntry(Model): \"\"\"",
"specific language governing permissions and limitations under the License. \"\"\" from abc import",
"a list of primary keys of all recursive parents. Used to determine the",
"= models.DateTimeField(primary_key=True) value = models.FloatField() thermostat = models.ForeignKey('Thermostat', related_name='temperatures') class Meta: ordering =",
"ThermostatDevice(Device): \"\"\" Represents a physical thermostat device. \"\"\" @property def thermostat(self): thermostats =",
"pks = self.thermostat.get_recursive_pks() assert (self.pk == self.datetime) pks.append(self.datetime.isoformat()) return pks class ThermostatMetaEntry(Model): \"\"\"",
"BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See",
"= ('thermostat', 'datetime') ordering = ('datetime',) def get_recursive_pks(self): pks = self.thermostat.get_recursive_pks() pks.append(self.pk) return",
"thermostat_devices = ThermostatDevice.objects.filter(rfid__in=thermostat_rfids) return thermostat_devices class ThermostatDevice(Device): \"\"\" Represents a physical thermostat device.",
"\"\"\" Represents a temperature. \"\"\" datetime = models.DateTimeField(primary_key=True) value = models.FloatField() thermostat =",
"a user. \"\"\" imei = models.CharField(primary_key=True, max_length=100, validators=[alpha_numeric_validator]) name = models.CharField(max_length=100) residence =",
"Room.objects.filter(residence=residence) room_pks = [room.pk for room in rooms] thermostats = Thermostat.objects.filter(room__in=room_pks) thermostat_rfids =",
"associated to the Raspberry Pi. \"\"\" residence = self.residence if residence is None:",
"datetime = models.DateTimeField() rssi = models.IntegerField(null=True) uptime = models.IntegerField(null=True) battery = models.IntegerField(null=True) thermostat",
"__metaclass__ = ABCMeta MONDAY = 0 TUESDAY = 1 WEDNESDAY = 2 THURSDAY",
"room_pks = [room.pk for room in rooms] thermostats = Thermostat.objects.filter(room__in=room_pks) thermostat_rfids = [thermostat.rfid",
"residence is None: return None rooms = Room.objects.filter(residence=residence) room_pks = [room.pk for room",
"else: return None @property def thermostat_devices(self): \"\"\" :return: Thermostat devices associated to the",
"time = models.TimeField() class Meta: abstract = True class HeatingTableEntry(TimetableEntry): \"\"\" Represents an",
"primary_key is defined name = models.CharField(max_length=100) residence = models.ForeignKey('Residence', related_name='rooms') class Meta: ordering",
"get_recursive_pks(self): pks = self.thermostat.get_recursive_pks() pks.append(self.pk) return pks class Device(Model): \"\"\" Base class for",
"the specific language governing permissions and limitations under the License. \"\"\" from abc",
"\"\"\" pass class Residence(Model): \"\"\" Represents a residence. \"\"\" rfid = models.CharField(primary_key=True, max_length=100,",
"strength, uptime and battery level. \"\"\" id = models.AutoField(primary_key=True) datetime = models.DateTimeField() rssi",
"Meta: ordering = ('rfid',) def get_recursive_pks(self): pks = self.room.get_recursive_pks() pks.append(self.pk) return pks class",
"', '.join(['%s:\"%s\"' % (field.name, getattr(self, field.name)) for field in self._meta.fields]) return '<%s(%s)>' %",
"pks.append(self.pk) return pks class Temperature(Model): \"\"\" Represents a temperature. \"\"\" datetime = models.DateTimeField(primary_key=True)",
"get_recursive_pks(self): pks = [self.pk] return pks class User(Model): \"\"\" Represents a user. \"\"\"",
"getattr(self, field.name)) for field in self._meta.fields]) return '<%s(%s)>' % (self.__class__._meta.object_name, fields_string) def __str__(self):",
"user. \"\"\" imei = models.CharField(primary_key=True, max_length=100, validators=[alpha_numeric_validator]) name = models.CharField(max_length=100) residence = models.ForeignKey('Residence',",
"= models.CharField(max_length=17, unique=True) class Meta: abstract = True def get_recursive_pks(self): return [self.pk] class",
"object. \"\"\" pass class Residence(Model): \"\"\" Represents a residence. \"\"\" rfid = models.CharField(primary_key=True,",
"== self.datetime) pks.append(self.datetime.isoformat()) return pks class ThermostatMetaEntry(Model): \"\"\" Represents a thermistat meta entry",
"pks.append(self.datetime.isoformat()) return pks class ThermostatMetaEntry(Model): \"\"\" Represents a thermistat meta entry containing signal",
"address. \"\"\" __metaclass__ = ABCMeta rfid = models.CharField(primary_key=True, max_length=100, validators=[rfid_validator]) mac = models.CharField(max_length=17,",
"prediction entry. This is a stub and is intended to be used in",
"ordering = ('imei',) def get_recursive_pks(self): pks = self.residence.get_recursive_pks() pks.append(self.pk) return pks class Room(Model):",
"with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0",
"at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software",
"other primary_key is defined name = models.CharField(max_length=100) residence = models.ForeignKey('Residence', related_name='rooms') class Meta:",
"Meta: unique_together = ('day', 'time', 'user') ordering = ('day', 'time') user = models.ForeignKey(User)",
"models.ForeignKey(Thermostat, related_name='heating_table_entries') def get_recursive_pks(self): pks = self.thermostat.get_recursive_pks() pks.append(self.pk) return pks class OccupancyPredictionEntry(TimetableEntry): \"\"\""
] |
[
"to manage a frozen lake from gym lib and make an agent play.",
"game_setting : Dict() Dictionnary of all game setting ai_setting : Dict() Dictionnary of",
"is_done, _ = self.env.step(action) reward = 0 is_win = new_state == self.cell_count -",
": Env() Object that store all the gym environment Methods ------- reset(): Reset",
"will learn and update his q-table \"\"\" while True: action = self.agent.next_step() new_state,",
"agent : Agent() Agent object that will play and learn env : Env()",
"play for specific amount of round \"\"\" wins_rate = [0] rounds = [0]",
"agent will learn and update his q-table \"\"\" while True: action = self.agent.next_step()",
"Attributes ---------- setting : Dict() Dict of all game setting agent : Agent()",
"that will play and learn env : Env() Object that store all the",
"end of the game Parameters ---------- is_training : boolean true if the agent",
"the gym environment Methods ------- reset(): Reset gym environment play(is_training=True): Make agent play",
"store all the gym environment Methods ------- reset(): Reset gym environment play(is_training=True): Make",
"\"\"\" win_amount = 0 for _ in progressbar(range(1000),\"Test\",33): self.reset() is_win = self.play(False) if",
"self.cell_count = 16 if game_setting[\"lake_size\"] == \"4x4\" else 64 ai_setting[\"state_count\"] = self.cell_count if(ai_setting[\"q_learning_type\"]",
"= AgentDoubleQLearn(ai_setting) self.setting = game_setting self.setting[\"lake_type\"] = \"FrozenLake-v1\" if game_setting[\"lake_size\"] == \"4x4\" else",
"if game_setting[\"lake_size\"] == \"4x4\" else \"FrozenLake8x8-v1\" self.env = gym.make(self.setting[\"lake_type\"]) self.reset() def reset(self): \"\"\"",
"game Parameters ---------- is_training : boolean true if the agent will learn and",
"Make agent play during 1000 game to make statistics \"\"\" win_amount = 0",
"Env() Object that store all the gym environment Methods ------- reset(): Reset gym",
"= 0 for _ in progressbar(range(1000),\"Test\",33): self.reset() is_win = self.play(False) if is_win: win_amount",
"1 def train(self): \"\"\" Make agent play for specific amount of round \"\"\"",
"ai_setting and set gym environment up Parameters ---------- game_setting : Dict() Dictionnary of",
"ai_setting : Dict() Dictionnary of all agent setting \"\"\" game_setting[\"lake_type\"] = \"FrozenLake-v1\" if",
"end of the game train(): Make agent play for specific amount of round",
"all game setting agent : Agent() Agent object that will play and learn",
"if game_setting[\"lake_size\"] == \"4x4\" else 64 ai_setting[\"state_count\"] = self.cell_count if(ai_setting[\"q_learning_type\"] == \"simple\"): self.agent",
"game_setting self.setting[\"lake_type\"] = \"FrozenLake-v1\" if game_setting[\"lake_size\"] == \"4x4\" else \"FrozenLake8x8-v1\" self.env = gym.make(self.setting[\"lake_type\"])",
"\"\"\" A class to manage a frozen lake from gym lib and make",
"Make agent play during 1000 game to make statistics \"\"\" def __init__(self, game_setting,",
"from matplotlib.pyplot import * class Frozenlake(): \"\"\" A class to manage a frozen",
"is_win = new_state == self.cell_count - 1 if is_done: reward = self.setting[\"reward\"] if",
"\"4x4\" else \"FrozenLake8x8-v1\" self.cell_count = 16 if game_setting[\"lake_size\"] == \"4x4\" else 64 ai_setting[\"state_count\"]",
"gym from agent import * from progressBar import * from matplotlib.pyplot import *",
"manage a frozen lake from gym lib and make an agent play. ...",
"def __init__(self, game_setting, ai_setting): \"\"\" Create agent object using ai_setting and set gym",
"until end of the game train(): Make agent play for specific amount of",
"import * from progressBar import * from matplotlib.pyplot import * class Frozenlake(): \"\"\"",
"and set gym environment up Parameters ---------- game_setting : Dict() Dictionnary of all",
": Agent() Agent object that will play and learn env : Env() Object",
"reset(): Reset gym environment play(is_training=True): Make agent play until end of the game",
"game_setting[\"lake_size\"] == \"4x4\" else \"FrozenLake8x8-v1\" self.env = gym.make(self.setting[\"lake_type\"]) self.reset() def reset(self): \"\"\" Reset",
"self.agent.next_step() new_state, _, is_done, _ = self.env.step(action) reward = 0 is_win = new_state",
"to make statistics \"\"\" win_amount = 0 for _ in progressbar(range(1000),\"Test\",33): self.reset() is_win",
"game train(): Make agent play for specific amount of round test(): Make agent",
"\"\"\" while True: action = self.agent.next_step() new_state, _, is_done, _ = self.env.step(action) reward",
"learn and update his q-table \"\"\" while True: action = self.agent.next_step() new_state, _,",
"= gym.make(self.setting[\"lake_type\"]) self.reset() def reset(self): \"\"\" Reset gym environment \"\"\" self.env.reset() def play(self,",
"test(): Make agent play during 1000 game to make statistics \"\"\" def __init__(self,",
"and update his q-table \"\"\" while True: action = self.agent.next_step() new_state, _, is_done,",
"matplotlib.pyplot import * class Frozenlake(): \"\"\" A class to manage a frozen lake",
"play during 1000 game to make statistics \"\"\" def __init__(self, game_setting, ai_setting): \"\"\"",
"self.setting[\"reward\"] if is_win else self.setting[\"punish\"] self.agent.update_table(new_state,reward,is_training) if is_done: return new_state == self.cell_count -",
"play until end of the game train(): Make agent play for specific amount",
"if is_win: win_amount += 1 if (count+1) % int(self.setting[\"round_to_train\"] / 100) == 0:",
"train(self): \"\"\" Make agent play for specific amount of round \"\"\" wins_rate =",
"and make an agent play. ... Attributes ---------- setting : Dict() Dict of",
"self.setting = game_setting self.setting[\"lake_type\"] = \"FrozenLake-v1\" if game_setting[\"lake_size\"] == \"4x4\" else \"FrozenLake8x8-v1\" self.env",
"agent import * from progressBar import * from matplotlib.pyplot import * class Frozenlake():",
"def reset(self): \"\"\" Reset gym environment \"\"\" self.env.reset() def play(self, is_training=True): \"\"\" Make",
"__init__(self, game_setting, ai_setting): \"\"\" Create agent object using ai_setting and set gym environment",
"self.agent.update_table(new_state,reward,is_training) if is_done: return new_state == self.cell_count - 1 def train(self): \"\"\" Make",
"= self.env.step(action) reward = 0 is_win = new_state == self.cell_count - 1 if",
"\"FrozenLake8x8-v1\" self.cell_count = 16 if game_setting[\"lake_size\"] == \"4x4\" else 64 ai_setting[\"state_count\"] = self.cell_count",
"setting \"\"\" game_setting[\"lake_type\"] = \"FrozenLake-v1\" if game_setting[\"lake_size\"] == \"4x4\" else \"FrozenLake8x8-v1\" self.cell_count =",
"agent object using ai_setting and set gym environment up Parameters ---------- game_setting :",
"1000 game to make statistics \"\"\" def __init__(self, game_setting, ai_setting): \"\"\" Create agent",
"A class to manage a frozen lake from gym lib and make an",
"game to make statistics \"\"\" win_amount = 0 for _ in progressbar(range(1000),\"Test\",33): self.reset()",
"\"FrozenLake8x8-v1\" self.env = gym.make(self.setting[\"lake_type\"]) self.reset() def reset(self): \"\"\" Reset gym environment \"\"\" self.env.reset()",
"for specific amount of round \"\"\" wins_rate = [0] rounds = [0] win_amount",
"= \"FrozenLake-v1\" if game_setting[\"lake_size\"] == \"4x4\" else \"FrozenLake8x8-v1\" self.env = gym.make(self.setting[\"lake_type\"]) self.reset() def",
"------- reset(): Reset gym environment play(is_training=True): Make agent play until end of the",
"self.reset() is_win = self.play() if is_win: win_amount += 1 if (count+1) % int(self.setting[\"round_to_train\"]",
"Dict of all game setting agent : Agent() Agent object that will play",
"the agent will learn and update his q-table \"\"\" while True: action =",
"import * from matplotlib.pyplot import * class Frozenlake(): \"\"\" A class to manage",
"round test(): Make agent play during 1000 game to make statistics \"\"\" def",
"class to manage a frozen lake from gym lib and make an agent",
"for count in progressbar(range(self.setting[\"round_to_train\"]),\"Entrainement\",33): self.reset() is_win = self.play() if is_win: win_amount += 1",
"until end of the game Parameters ---------- is_training : boolean true if the",
"of all agent setting \"\"\" game_setting[\"lake_type\"] = \"FrozenLake-v1\" if game_setting[\"lake_size\"] == \"4x4\" else",
"_ in progressbar(range(1000),\"Test\",33): self.reset() is_win = self.play(False) if is_win: win_amount += 1 return",
"Object that store all the gym environment Methods ------- reset(): Reset gym environment",
"def train(self): \"\"\" Make agent play for specific amount of round \"\"\" wins_rate",
"environment play(is_training=True): Make agent play until end of the game train(): Make agent",
"q-table \"\"\" while True: action = self.agent.next_step() new_state, _, is_done, _ = self.env.step(action)",
"Make agent play for specific amount of round test(): Make agent play during",
"gym environment Methods ------- reset(): Reset gym environment play(is_training=True): Make agent play until",
"that store all the gym environment Methods ------- reset(): Reset gym environment play(is_training=True):",
"* from progressBar import * from matplotlib.pyplot import * class Frozenlake(): \"\"\" A",
"else \"FrozenLake8x8-v1\" self.env = gym.make(self.setting[\"lake_type\"]) self.reset() def reset(self): \"\"\" Reset gym environment \"\"\"",
"for specific amount of round test(): Make agent play during 1000 game to",
"new_state, _, is_done, _ = self.env.step(action) reward = 0 is_win = new_state ==",
"* from matplotlib.pyplot import * class Frozenlake(): \"\"\" A class to manage a",
"up Parameters ---------- game_setting : Dict() Dictionnary of all game setting ai_setting :",
"== \"4x4\" else \"FrozenLake8x8-v1\" self.cell_count = 16 if game_setting[\"lake_size\"] == \"4x4\" else 64",
"make an agent play. ... Attributes ---------- setting : Dict() Dict of all",
"and learn env : Env() Object that store all the gym environment Methods",
"game setting ai_setting : Dict() Dictionnary of all agent setting \"\"\" game_setting[\"lake_type\"] =",
"for _ in progressbar(range(1000),\"Test\",33): self.reset() is_win = self.play(False) if is_win: win_amount += 1",
"self.reset() def reset(self): \"\"\" Reset gym environment \"\"\" self.env.reset() def play(self, is_training=True): \"\"\"",
"play(self, is_training=True): \"\"\" Make agent play until end of the game Parameters ----------",
"of all game setting agent : Agent() Agent object that will play and",
"self.env.step(action) reward = 0 is_win = new_state == self.cell_count - 1 if is_done:",
"= 16 if game_setting[\"lake_size\"] == \"4x4\" else 64 ai_setting[\"state_count\"] = self.cell_count if(ai_setting[\"q_learning_type\"] ==",
"is_done: return new_state == self.cell_count - 1 def train(self): \"\"\" Make agent play",
"1 if (count+1) % int(self.setting[\"round_to_train\"] / 100) == 0: wins_rate.append(win_amount*100/count) rounds.append(count) figure() plot(rounds,wins_rate)",
"play and learn env : Env() Object that store all the gym environment",
"play. ... Attributes ---------- setting : Dict() Dict of all game setting agent",
"self.play() if is_win: win_amount += 1 if (count+1) % int(self.setting[\"round_to_train\"] / 100) ==",
"def test(self): \"\"\" Make agent play during 1000 game to make statistics \"\"\"",
"new_state == self.cell_count - 1 def train(self): \"\"\" Make agent play for specific",
"a frozen lake from gym lib and make an agent play. ... Attributes",
"training time\") ylim(0,100) xlim(0,self.setting[\"round_to_train\"]) draw() def test(self): \"\"\" Make agent play during 1000",
"from agent import * from progressBar import * from matplotlib.pyplot import * class",
"action = self.agent.next_step() new_state, _, is_done, _ = self.env.step(action) reward = 0 is_win",
"0 for _ in progressbar(range(1000),\"Test\",33): self.reset() is_win = self.play(False) if is_win: win_amount +=",
"== \"simple\"): self.agent = AgentSimpleQLearn(ai_setting) else: self.agent = AgentDoubleQLearn(ai_setting) self.setting = game_setting self.setting[\"lake_type\"]",
"game_setting[\"lake_size\"] == \"4x4\" else 64 ai_setting[\"state_count\"] = self.cell_count if(ai_setting[\"q_learning_type\"] == \"simple\"): self.agent =",
": Dict() Dict of all game setting agent : Agent() Agent object that",
"test(self): \"\"\" Make agent play during 1000 game to make statistics \"\"\" win_amount",
"100) == 0: wins_rate.append(win_amount*100/count) rounds.append(count) figure() plot(rounds,wins_rate) title(\"Win rate over training time\") ylim(0,100)",
"true if the agent will learn and update his q-table \"\"\" while True:",
"= \"FrozenLake-v1\" if game_setting[\"lake_size\"] == \"4x4\" else \"FrozenLake8x8-v1\" self.cell_count = 16 if game_setting[\"lake_size\"]",
"agent play until end of the game train(): Make agent play for specific",
"gym.make(self.setting[\"lake_type\"]) self.reset() def reset(self): \"\"\" Reset gym environment \"\"\" self.env.reset() def play(self, is_training=True):",
"env : Env() Object that store all the gym environment Methods ------- reset():",
"lib and make an agent play. ... Attributes ---------- setting : Dict() Dict",
"self.env = gym.make(self.setting[\"lake_type\"]) self.reset() def reset(self): \"\"\" Reset gym environment \"\"\" self.env.reset() def",
"Methods ------- reset(): Reset gym environment play(is_training=True): Make agent play until end of",
"0 for count in progressbar(range(self.setting[\"round_to_train\"]),\"Entrainement\",33): self.reset() is_win = self.play() if is_win: win_amount +=",
"of the game train(): Make agent play for specific amount of round test():",
"object that will play and learn env : Env() Object that store all",
"---------- game_setting : Dict() Dictionnary of all game setting ai_setting : Dict() Dictionnary",
"of round \"\"\" wins_rate = [0] rounds = [0] win_amount = 0 for",
"self.agent = AgentDoubleQLearn(ai_setting) self.setting = game_setting self.setting[\"lake_type\"] = \"FrozenLake-v1\" if game_setting[\"lake_size\"] == \"4x4\"",
"game to make statistics \"\"\" def __init__(self, game_setting, ai_setting): \"\"\" Create agent object",
"while True: action = self.agent.next_step() new_state, _, is_done, _ = self.env.step(action) reward =",
"else self.setting[\"punish\"] self.agent.update_table(new_state,reward,is_training) if is_done: return new_state == self.cell_count - 1 def train(self):",
"rounds.append(count) figure() plot(rounds,wins_rate) title(\"Win rate over training time\") ylim(0,100) xlim(0,self.setting[\"round_to_train\"]) draw() def test(self):",
"all the gym environment Methods ------- reset(): Reset gym environment play(is_training=True): Make agent",
"is_done: reward = self.setting[\"reward\"] if is_win else self.setting[\"punish\"] self.agent.update_table(new_state,reward,is_training) if is_done: return new_state",
"\"\"\" self.env.reset() def play(self, is_training=True): \"\"\" Make agent play until end of the",
"Parameters ---------- is_training : boolean true if the agent will learn and update",
"amount of round \"\"\" wins_rate = [0] rounds = [0] win_amount = 0",
"if(ai_setting[\"q_learning_type\"] == \"simple\"): self.agent = AgentSimpleQLearn(ai_setting) else: self.agent = AgentDoubleQLearn(ai_setting) self.setting = game_setting",
"self.cell_count - 1 def train(self): \"\"\" Make agent play for specific amount of",
"is_training=True): \"\"\" Make agent play until end of the game Parameters ---------- is_training",
"rate over training time\") ylim(0,100) xlim(0,self.setting[\"round_to_train\"]) draw() def test(self): \"\"\" Make agent play",
"play(is_training=True): Make agent play until end of the game train(): Make agent play",
"if game_setting[\"lake_size\"] == \"4x4\" else \"FrozenLake8x8-v1\" self.cell_count = 16 if game_setting[\"lake_size\"] == \"4x4\"",
"update his q-table \"\"\" while True: action = self.agent.next_step() new_state, _, is_done, _",
"else 64 ai_setting[\"state_count\"] = self.cell_count if(ai_setting[\"q_learning_type\"] == \"simple\"): self.agent = AgentSimpleQLearn(ai_setting) else: self.agent",
"(count+1) % int(self.setting[\"round_to_train\"] / 100) == 0: wins_rate.append(win_amount*100/count) rounds.append(count) figure() plot(rounds,wins_rate) title(\"Win rate",
"Reset gym environment \"\"\" self.env.reset() def play(self, is_training=True): \"\"\" Make agent play until",
"agent play for specific amount of round test(): Make agent play during 1000",
"is_win else self.setting[\"punish\"] self.agent.update_table(new_state,reward,is_training) if is_done: return new_state == self.cell_count - 1 def",
"agent play during 1000 game to make statistics \"\"\" win_amount = 0 for",
"train(): Make agent play for specific amount of round test(): Make agent play",
"if the agent will learn and update his q-table \"\"\" while True: action",
"to make statistics \"\"\" def __init__(self, game_setting, ai_setting): \"\"\" Create agent object using",
"object using ai_setting and set gym environment up Parameters ---------- game_setting : Dict()",
"play for specific amount of round test(): Make agent play during 1000 game",
"_, is_done, _ = self.env.step(action) reward = 0 is_win = new_state == self.cell_count",
"Dict() Dictionnary of all game setting ai_setting : Dict() Dictionnary of all agent",
"return new_state == self.cell_count - 1 def train(self): \"\"\" Make agent play for",
"specific amount of round \"\"\" wins_rate = [0] rounds = [0] win_amount =",
"self.reset() is_win = self.play(False) if is_win: win_amount += 1 return win_amount * 100",
"ylim(0,100) xlim(0,self.setting[\"round_to_train\"]) draw() def test(self): \"\"\" Make agent play during 1000 game to",
"= self.setting[\"reward\"] if is_win else self.setting[\"punish\"] self.agent.update_table(new_state,reward,is_training) if is_done: return new_state == self.cell_count",
"AgentSimpleQLearn(ai_setting) else: self.agent = AgentDoubleQLearn(ai_setting) self.setting = game_setting self.setting[\"lake_type\"] = \"FrozenLake-v1\" if game_setting[\"lake_size\"]",
"64 ai_setting[\"state_count\"] = self.cell_count if(ai_setting[\"q_learning_type\"] == \"simple\"): self.agent = AgentSimpleQLearn(ai_setting) else: self.agent =",
"0 is_win = new_state == self.cell_count - 1 if is_done: reward = self.setting[\"reward\"]",
"round \"\"\" wins_rate = [0] rounds = [0] win_amount = 0 for count",
"= self.cell_count if(ai_setting[\"q_learning_type\"] == \"simple\"): self.agent = AgentSimpleQLearn(ai_setting) else: self.agent = AgentDoubleQLearn(ai_setting) self.setting",
"is_win: win_amount += 1 if (count+1) % int(self.setting[\"round_to_train\"] / 100) == 0: wins_rate.append(win_amount*100/count)",
"\"simple\"): self.agent = AgentSimpleQLearn(ai_setting) else: self.agent = AgentDoubleQLearn(ai_setting) self.setting = game_setting self.setting[\"lake_type\"] =",
"---------- setting : Dict() Dict of all game setting agent : Agent() Agent",
"= self.play(False) if is_win: win_amount += 1 return win_amount * 100 / 1000",
"Dict() Dict of all game setting agent : Agent() Agent object that will",
"game_setting, ai_setting): \"\"\" Create agent object using ai_setting and set gym environment up",
"Create agent object using ai_setting and set gym environment up Parameters ---------- game_setting",
"\"4x4\" else \"FrozenLake8x8-v1\" self.env = gym.make(self.setting[\"lake_type\"]) self.reset() def reset(self): \"\"\" Reset gym environment",
"% int(self.setting[\"round_to_train\"] / 100) == 0: wins_rate.append(win_amount*100/count) rounds.append(count) figure() plot(rounds,wins_rate) title(\"Win rate over",
"the game train(): Make agent play for specific amount of round test(): Make",
"agent setting \"\"\" game_setting[\"lake_type\"] = \"FrozenLake-v1\" if game_setting[\"lake_size\"] == \"4x4\" else \"FrozenLake8x8-v1\" self.cell_count",
"specific amount of round test(): Make agent play during 1000 game to make",
"True: action = self.agent.next_step() new_state, _, is_done, _ = self.env.step(action) reward = 0",
"Make agent play until end of the game Parameters ---------- is_training : boolean",
"game_setting[\"lake_type\"] = \"FrozenLake-v1\" if game_setting[\"lake_size\"] == \"4x4\" else \"FrozenLake8x8-v1\" self.cell_count = 16 if",
"agent play for specific amount of round \"\"\" wins_rate = [0] rounds =",
"\"\"\" game_setting[\"lake_type\"] = \"FrozenLake-v1\" if game_setting[\"lake_size\"] == \"4x4\" else \"FrozenLake8x8-v1\" self.cell_count = 16",
": Dict() Dictionnary of all game setting ai_setting : Dict() Dictionnary of all",
"his q-table \"\"\" while True: action = self.agent.next_step() new_state, _, is_done, _ =",
"* class Frozenlake(): \"\"\" A class to manage a frozen lake from gym",
"time\") ylim(0,100) xlim(0,self.setting[\"round_to_train\"]) draw() def test(self): \"\"\" Make agent play during 1000 game",
"Agent object that will play and learn env : Env() Object that store",
"setting agent : Agent() Agent object that will play and learn env :",
"count in progressbar(range(self.setting[\"round_to_train\"]),\"Entrainement\",33): self.reset() is_win = self.play() if is_win: win_amount += 1 if",
"self.cell_count if(ai_setting[\"q_learning_type\"] == \"simple\"): self.agent = AgentSimpleQLearn(ai_setting) else: self.agent = AgentDoubleQLearn(ai_setting) self.setting =",
"frozen lake from gym lib and make an agent play. ... Attributes ----------",
"gym environment play(is_training=True): Make agent play until end of the game train(): Make",
"else: self.agent = AgentDoubleQLearn(ai_setting) self.setting = game_setting self.setting[\"lake_type\"] = \"FrozenLake-v1\" if game_setting[\"lake_size\"] ==",
"else \"FrozenLake8x8-v1\" self.cell_count = 16 if game_setting[\"lake_size\"] == \"4x4\" else 64 ai_setting[\"state_count\"] =",
"plot(rounds,wins_rate) title(\"Win rate over training time\") ylim(0,100) xlim(0,self.setting[\"round_to_train\"]) draw() def test(self): \"\"\" Make",
"Frozenlake(): \"\"\" A class to manage a frozen lake from gym lib and",
"\"FrozenLake-v1\" if game_setting[\"lake_size\"] == \"4x4\" else \"FrozenLake8x8-v1\" self.cell_count = 16 if game_setting[\"lake_size\"] ==",
"win_amount += 1 if (count+1) % int(self.setting[\"round_to_train\"] / 100) == 0: wins_rate.append(win_amount*100/count) rounds.append(count)",
"setting ai_setting : Dict() Dictionnary of all agent setting \"\"\" game_setting[\"lake_type\"] = \"FrozenLake-v1\"",
"import * class Frozenlake(): \"\"\" A class to manage a frozen lake from",
"16 if game_setting[\"lake_size\"] == \"4x4\" else 64 ai_setting[\"state_count\"] = self.cell_count if(ai_setting[\"q_learning_type\"] == \"simple\"):",
"- 1 def train(self): \"\"\" Make agent play for specific amount of round",
"[0] win_amount = 0 for count in progressbar(range(self.setting[\"round_to_train\"]),\"Entrainement\",33): self.reset() is_win = self.play() if",
"= new_state == self.cell_count - 1 if is_done: reward = self.setting[\"reward\"] if is_win",
"progressbar(range(self.setting[\"round_to_train\"]),\"Entrainement\",33): self.reset() is_win = self.play() if is_win: win_amount += 1 if (count+1) %",
"Agent() Agent object that will play and learn env : Env() Object that",
"<gh_stars>1-10 import gym from agent import * from progressBar import * from matplotlib.pyplot",
"import gym from agent import * from progressBar import * from matplotlib.pyplot import",
"Make agent play until end of the game train(): Make agent play for",
"make statistics \"\"\" def __init__(self, game_setting, ai_setting): \"\"\" Create agent object using ai_setting",
"during 1000 game to make statistics \"\"\" win_amount = 0 for _ in",
"title(\"Win rate over training time\") ylim(0,100) xlim(0,self.setting[\"round_to_train\"]) draw() def test(self): \"\"\" Make agent",
"game_setting[\"lake_size\"] == \"4x4\" else \"FrozenLake8x8-v1\" self.cell_count = 16 if game_setting[\"lake_size\"] == \"4x4\" else",
"= [0] win_amount = 0 for count in progressbar(range(self.setting[\"round_to_train\"]),\"Entrainement\",33): self.reset() is_win = self.play()",
"rounds = [0] win_amount = 0 for count in progressbar(range(self.setting[\"round_to_train\"]),\"Entrainement\",33): self.reset() is_win =",
"statistics \"\"\" def __init__(self, game_setting, ai_setting): \"\"\" Create agent object using ai_setting and",
"agent play until end of the game Parameters ---------- is_training : boolean true",
"reward = 0 is_win = new_state == self.cell_count - 1 if is_done: reward",
"from progressBar import * from matplotlib.pyplot import * class Frozenlake(): \"\"\" A class",
"if is_win else self.setting[\"punish\"] self.agent.update_table(new_state,reward,is_training) if is_done: return new_state == self.cell_count - 1",
"self.cell_count - 1 if is_done: reward = self.setting[\"reward\"] if is_win else self.setting[\"punish\"] self.agent.update_table(new_state,reward,is_training)",
"environment Methods ------- reset(): Reset gym environment play(is_training=True): Make agent play until end",
"\"\"\" Reset gym environment \"\"\" self.env.reset() def play(self, is_training=True): \"\"\" Make agent play",
"if (count+1) % int(self.setting[\"round_to_train\"] / 100) == 0: wins_rate.append(win_amount*100/count) rounds.append(count) figure() plot(rounds,wins_rate) title(\"Win",
"in progressbar(range(1000),\"Test\",33): self.reset() is_win = self.play(False) if is_win: win_amount += 1 return win_amount",
"play until end of the game Parameters ---------- is_training : boolean true if",
"1000 game to make statistics \"\"\" win_amount = 0 for _ in progressbar(range(1000),\"Test\",33):",
"Dictionnary of all agent setting \"\"\" game_setting[\"lake_type\"] = \"FrozenLake-v1\" if game_setting[\"lake_size\"] == \"4x4\"",
"of all game setting ai_setting : Dict() Dictionnary of all agent setting \"\"\"",
"... Attributes ---------- setting : Dict() Dict of all game setting agent :",
"Dict() Dictionnary of all agent setting \"\"\" game_setting[\"lake_type\"] = \"FrozenLake-v1\" if game_setting[\"lake_size\"] ==",
"wins_rate.append(win_amount*100/count) rounds.append(count) figure() plot(rounds,wins_rate) title(\"Win rate over training time\") ylim(0,100) xlim(0,self.setting[\"round_to_train\"]) draw() def",
"def play(self, is_training=True): \"\"\" Make agent play until end of the game Parameters",
"the game Parameters ---------- is_training : boolean true if the agent will learn",
"+= 1 if (count+1) % int(self.setting[\"round_to_train\"] / 100) == 0: wins_rate.append(win_amount*100/count) rounds.append(count) figure()",
"is_win = self.play(False) if is_win: win_amount += 1 return win_amount * 100 /",
"/ 100) == 0: wins_rate.append(win_amount*100/count) rounds.append(count) figure() plot(rounds,wins_rate) title(\"Win rate over training time\")",
"of the game Parameters ---------- is_training : boolean true if the agent will",
"using ai_setting and set gym environment up Parameters ---------- game_setting : Dict() Dictionnary",
"if is_done: return new_state == self.cell_count - 1 def train(self): \"\"\" Make agent",
"_ = self.env.step(action) reward = 0 is_win = new_state == self.cell_count - 1",
"gym environment up Parameters ---------- game_setting : Dict() Dictionnary of all game setting",
"\"FrozenLake-v1\" if game_setting[\"lake_size\"] == \"4x4\" else \"FrozenLake8x8-v1\" self.env = gym.make(self.setting[\"lake_type\"]) self.reset() def reset(self):",
"== self.cell_count - 1 if is_done: reward = self.setting[\"reward\"] if is_win else self.setting[\"punish\"]",
"ai_setting[\"state_count\"] = self.cell_count if(ai_setting[\"q_learning_type\"] == \"simple\"): self.agent = AgentSimpleQLearn(ai_setting) else: self.agent = AgentDoubleQLearn(ai_setting)",
"Dictionnary of all game setting ai_setting : Dict() Dictionnary of all agent setting",
"statistics \"\"\" win_amount = 0 for _ in progressbar(range(1000),\"Test\",33): self.reset() is_win = self.play(False)",
"= 0 for count in progressbar(range(self.setting[\"round_to_train\"]),\"Entrainement\",33): self.reset() is_win = self.play() if is_win: win_amount",
"= self.agent.next_step() new_state, _, is_done, _ = self.env.step(action) reward = 0 is_win =",
"draw() def test(self): \"\"\" Make agent play during 1000 game to make statistics",
"\"\"\" def __init__(self, game_setting, ai_setting): \"\"\" Create agent object using ai_setting and set",
"self.agent = AgentSimpleQLearn(ai_setting) else: self.agent = AgentDoubleQLearn(ai_setting) self.setting = game_setting self.setting[\"lake_type\"] = \"FrozenLake-v1\"",
"= 0 is_win = new_state == self.cell_count - 1 if is_done: reward =",
"== \"4x4\" else 64 ai_setting[\"state_count\"] = self.cell_count if(ai_setting[\"q_learning_type\"] == \"simple\"): self.agent = AgentSimpleQLearn(ai_setting)",
"\"\"\" wins_rate = [0] rounds = [0] win_amount = 0 for count in",
"\"\"\" Make agent play until end of the game Parameters ---------- is_training :",
"[0] rounds = [0] win_amount = 0 for count in progressbar(range(self.setting[\"round_to_train\"]),\"Entrainement\",33): self.reset() is_win",
"wins_rate = [0] rounds = [0] win_amount = 0 for count in progressbar(range(self.setting[\"round_to_train\"]),\"Entrainement\",33):",
"amount of round test(): Make agent play during 1000 game to make statistics",
"- 1 if is_done: reward = self.setting[\"reward\"] if is_win else self.setting[\"punish\"] self.agent.update_table(new_state,reward,is_training) if",
"figure() plot(rounds,wins_rate) title(\"Win rate over training time\") ylim(0,100) xlim(0,self.setting[\"round_to_train\"]) draw() def test(self): \"\"\"",
"agent play. ... Attributes ---------- setting : Dict() Dict of all game setting",
": boolean true if the agent will learn and update his q-table \"\"\"",
"== \"4x4\" else \"FrozenLake8x8-v1\" self.env = gym.make(self.setting[\"lake_type\"]) self.reset() def reset(self): \"\"\" Reset gym",
"win_amount = 0 for _ in progressbar(range(1000),\"Test\",33): self.reset() is_win = self.play(False) if is_win:",
"\"\"\" Make agent play for specific amount of round \"\"\" wins_rate = [0]",
"play during 1000 game to make statistics \"\"\" win_amount = 0 for _",
"learn env : Env() Object that store all the gym environment Methods -------",
"gym environment \"\"\" self.env.reset() def play(self, is_training=True): \"\"\" Make agent play until end",
"an agent play. ... Attributes ---------- setting : Dict() Dict of all game",
"= self.play() if is_win: win_amount += 1 if (count+1) % int(self.setting[\"round_to_train\"] / 100)",
"environment up Parameters ---------- game_setting : Dict() Dictionnary of all game setting ai_setting",
"\"\"\" Make agent play during 1000 game to make statistics \"\"\" win_amount =",
"class Frozenlake(): \"\"\" A class to manage a frozen lake from gym lib",
"\"\"\" Create agent object using ai_setting and set gym environment up Parameters ----------",
"AgentDoubleQLearn(ai_setting) self.setting = game_setting self.setting[\"lake_type\"] = \"FrozenLake-v1\" if game_setting[\"lake_size\"] == \"4x4\" else \"FrozenLake8x8-v1\"",
"boolean true if the agent will learn and update his q-table \"\"\" while",
"during 1000 game to make statistics \"\"\" def __init__(self, game_setting, ai_setting): \"\"\" Create",
"xlim(0,self.setting[\"round_to_train\"]) draw() def test(self): \"\"\" Make agent play during 1000 game to make",
": Dict() Dictionnary of all agent setting \"\"\" game_setting[\"lake_type\"] = \"FrozenLake-v1\" if game_setting[\"lake_size\"]",
"progressBar import * from matplotlib.pyplot import * class Frozenlake(): \"\"\" A class to",
"Parameters ---------- game_setting : Dict() Dictionnary of all game setting ai_setting : Dict()",
"in progressbar(range(self.setting[\"round_to_train\"]),\"Entrainement\",33): self.reset() is_win = self.play() if is_win: win_amount += 1 if (count+1)",
"---------- is_training : boolean true if the agent will learn and update his",
"self.env.reset() def play(self, is_training=True): \"\"\" Make agent play until end of the game",
"int(self.setting[\"round_to_train\"] / 100) == 0: wins_rate.append(win_amount*100/count) rounds.append(count) figure() plot(rounds,wins_rate) title(\"Win rate over training",
"game setting agent : Agent() Agent object that will play and learn env",
"= game_setting self.setting[\"lake_type\"] = \"FrozenLake-v1\" if game_setting[\"lake_size\"] == \"4x4\" else \"FrozenLake8x8-v1\" self.env =",
"1 if is_done: reward = self.setting[\"reward\"] if is_win else self.setting[\"punish\"] self.agent.update_table(new_state,reward,is_training) if is_done:",
"set gym environment up Parameters ---------- game_setting : Dict() Dictionnary of all game",
"== self.cell_count - 1 def train(self): \"\"\" Make agent play for specific amount",
"if is_done: reward = self.setting[\"reward\"] if is_win else self.setting[\"punish\"] self.agent.update_table(new_state,reward,is_training) if is_done: return",
"reward = self.setting[\"reward\"] if is_win else self.setting[\"punish\"] self.agent.update_table(new_state,reward,is_training) if is_done: return new_state ==",
"setting : Dict() Dict of all game setting agent : Agent() Agent object",
"new_state == self.cell_count - 1 if is_done: reward = self.setting[\"reward\"] if is_win else",
"progressbar(range(1000),\"Test\",33): self.reset() is_win = self.play(False) if is_win: win_amount += 1 return win_amount *",
"agent play during 1000 game to make statistics \"\"\" def __init__(self, game_setting, ai_setting):",
"will play and learn env : Env() Object that store all the gym",
"over training time\") ylim(0,100) xlim(0,self.setting[\"round_to_train\"]) draw() def test(self): \"\"\" Make agent play during",
"all game setting ai_setting : Dict() Dictionnary of all agent setting \"\"\" game_setting[\"lake_type\"]",
"from gym lib and make an agent play. ... Attributes ---------- setting :",
"= [0] rounds = [0] win_amount = 0 for count in progressbar(range(self.setting[\"round_to_train\"]),\"Entrainement\",33): self.reset()",
"self.setting[\"lake_type\"] = \"FrozenLake-v1\" if game_setting[\"lake_size\"] == \"4x4\" else \"FrozenLake8x8-v1\" self.env = gym.make(self.setting[\"lake_type\"]) self.reset()",
"Reset gym environment play(is_training=True): Make agent play until end of the game train():",
"gym lib and make an agent play. ... Attributes ---------- setting : Dict()",
"ai_setting): \"\"\" Create agent object using ai_setting and set gym environment up Parameters",
"reset(self): \"\"\" Reset gym environment \"\"\" self.env.reset() def play(self, is_training=True): \"\"\" Make agent",
"make statistics \"\"\" win_amount = 0 for _ in progressbar(range(1000),\"Test\",33): self.reset() is_win =",
"of round test(): Make agent play during 1000 game to make statistics \"\"\"",
"is_training : boolean true if the agent will learn and update his q-table",
"Make agent play for specific amount of round \"\"\" wins_rate = [0] rounds",
"\"4x4\" else 64 ai_setting[\"state_count\"] = self.cell_count if(ai_setting[\"q_learning_type\"] == \"simple\"): self.agent = AgentSimpleQLearn(ai_setting) else:",
"all agent setting \"\"\" game_setting[\"lake_type\"] = \"FrozenLake-v1\" if game_setting[\"lake_size\"] == \"4x4\" else \"FrozenLake8x8-v1\"",
"environment \"\"\" self.env.reset() def play(self, is_training=True): \"\"\" Make agent play until end of",
"lake from gym lib and make an agent play. ... Attributes ---------- setting",
"= AgentSimpleQLearn(ai_setting) else: self.agent = AgentDoubleQLearn(ai_setting) self.setting = game_setting self.setting[\"lake_type\"] = \"FrozenLake-v1\" if",
"== 0: wins_rate.append(win_amount*100/count) rounds.append(count) figure() plot(rounds,wins_rate) title(\"Win rate over training time\") ylim(0,100) xlim(0,self.setting[\"round_to_train\"])",
"is_win = self.play() if is_win: win_amount += 1 if (count+1) % int(self.setting[\"round_to_train\"] /",
"win_amount = 0 for count in progressbar(range(self.setting[\"round_to_train\"]),\"Entrainement\",33): self.reset() is_win = self.play() if is_win:",
"self.setting[\"punish\"] self.agent.update_table(new_state,reward,is_training) if is_done: return new_state == self.cell_count - 1 def train(self): \"\"\"",
"0: wins_rate.append(win_amount*100/count) rounds.append(count) figure() plot(rounds,wins_rate) title(\"Win rate over training time\") ylim(0,100) xlim(0,self.setting[\"round_to_train\"]) draw()"
] |
[
"0.1, # variance of location on x-axis 0.1, # variance of location on",
"jacfwd, jit import matplotlib.pyplot as plt from src.environments import DiffDriveRobot from util import",
"https://github.com/AtsushiSakai/PythonRobotics \"\"\" from functools import partial from estimation import ExtendedKalmanFilter, KalmanFilter import jax.numpy",
"x_hat = jnp.zeros(4) # [x, y, yaw, velocity] x_cov = jnp.eye(4) Q =",
"P=x_cov, u=u, z=obs) history.update(x=info['x'], z=obs, x_hat=x_hat, covariance=x_cov) if t % 100 == 0:",
"as jnp import numpy as np from jax import jacfwd, jit import matplotlib.pyplot",
"numpy as np from jax import jacfwd, jit import matplotlib.pyplot as plt from",
"from https://github.com/AtsushiSakai/PythonRobotics \"\"\" from functools import partial from estimation import ExtendedKalmanFilter, KalmanFilter import",
"import matplotlib.pyplot as plt from src.environments import DiffDriveRobot from util import plot, History",
"v = 1.0 # [m/s] yawrate = 0.1 # [rad/s] u = jnp.array([v,",
"location on y-axis jnp.deg2rad(0.5), # variance of yaw angle 0.1 # variance of",
"= jnp.zeros(4) # [x, y, yaw, velocity] x_cov = jnp.eye(4) Q = jnp.diag(jnp.array([",
"range(5000): print(t) u = controller(x_hat) # [velocity, yaw_rate] obs, _, _, info =",
"matplotlib.pyplot as plt from src.environments import DiffDriveRobot from util import plot, History def",
"* jnp.cos(x[2]) * dt, x[1] + x[3] * jnp.sin(x[2]) * dt, x[2] +",
"* dt, x[2] + u[1] * dt, u[0] ]) + w def _observation_model(x,",
"= 0.1 # [rad/s] u = jnp.array([v, yawrate]) return u def main(): env",
"[0, 1, 0, 0]]) return H @ x + v def controller(x): v",
"for t in range(5000): print(t) u = controller(x_hat) # [velocity, yaw_rate] obs, _,",
"_, _, info = env.step(u) x_hat, x_cov = filter(x=x_hat, P=x_cov, u=u, z=obs) history.update(x=info['x'],",
"dt, x[1] + x[3] * jnp.sin(x[2]) * dt, x[2] + u[1] * dt,",
"on y-axis jnp.deg2rad(0.5), # variance of yaw angle 0.1 # variance of velocity",
"from estimation import ExtendedKalmanFilter, KalmanFilter import jax.numpy as jnp import numpy as np",
"history.update(x=x_hat, z=z, x_hat=x_hat, covariance=x_cov) for t in range(5000): print(t) u = controller(x_hat) #",
"return H @ x + v def controller(x): v = 1.0 # [m/s]",
"u, w, dt=0.01): return jnp.array([ x[0] + x[3] * jnp.cos(x[2]) * dt, x[1]",
"return u def main(): env = DiffDriveRobot() z = env.reset() x_hat = jnp.zeros(4)",
"predict state covariance R = jnp.diag(jnp.array([2, 2])) ** 2 # Observation x,y position",
"Observation x,y position covariance filter = ExtendedKalmanFilter( process_model=_motion_model, observation_model=_observation_model, process_noise_covariance=Q, observation_noise_covariance=R ) filter",
"dt, x[2] + u[1] * dt, u[0] ]) + w def _observation_model(x, v):",
"import numpy as np from jax import jacfwd, jit import matplotlib.pyplot as plt",
"u=u, z=obs) history.update(x=info['x'], z=obs, x_hat=x_hat, covariance=x_cov) if t % 100 == 0: plot(data=history)",
"+ x[3] * jnp.cos(x[2]) * dt, x[1] + x[3] * jnp.sin(x[2]) * dt,",
"x[3] * jnp.cos(x[2]) * dt, x[1] + x[3] * jnp.sin(x[2]) * dt, x[2]",
"0, 0, 0], [0, 1, 0, 0]]) return H @ x + v",
"covariance=x_cov) for t in range(5000): print(t) u = controller(x_hat) # [velocity, yaw_rate] obs,",
"z=obs, x_hat=x_hat, covariance=x_cov) if t % 100 == 0: plot(data=history) if __name__ ==",
"controller(x): v = 1.0 # [m/s] yawrate = 0.1 # [rad/s] u =",
"* jnp.sin(x[2]) * dt, x[2] + u[1] * dt, u[0] ]) + w",
"]) + w def _observation_model(x, v): H = jnp.array([[1, 0, 0, 0], [0,",
"x_hat=x_hat, covariance=x_cov) for t in range(5000): print(t) u = controller(x_hat) # [velocity, yaw_rate]",
"jnp.zeros(4) # [x, y, yaw, velocity] x_cov = jnp.eye(4) Q = jnp.diag(jnp.array([ 0.1,",
"= filter(x=x_hat, P=x_cov, u=u, z=obs) history.update(x=info['x'], z=obs, x_hat=x_hat, covariance=x_cov) if t % 100",
"= jnp.array([[1, 0, 0, 0], [0, 1, 0, 0]]) return H @ x",
"+ w def _observation_model(x, v): H = jnp.array([[1, 0, 0, 0], [0, 1,",
"def controller(x): v = 1.0 # [m/s] yawrate = 0.1 # [rad/s] u",
"0]]) return H @ x + v def controller(x): v = 1.0 #",
"2 # Observation x,y position covariance filter = ExtendedKalmanFilter( process_model=_motion_model, observation_model=_observation_model, process_noise_covariance=Q, observation_noise_covariance=R",
"R = jnp.diag(jnp.array([2, 2])) ** 2 # Observation x,y position covariance filter =",
"= History() history.update(x=x_hat, z=z, x_hat=x_hat, covariance=x_cov) for t in range(5000): print(t) u =",
"return jnp.array([ x[0] + x[3] * jnp.cos(x[2]) * dt, x[1] + x[3] *",
"x_hat, x_cov = filter(x=x_hat, P=x_cov, u=u, z=obs) history.update(x=info['x'], z=obs, x_hat=x_hat, covariance=x_cov) if t",
"import DiffDriveRobot from util import plot, History def _motion_model(x, u, w, dt=0.01): return",
"# [velocity, yaw_rate] obs, _, _, info = env.step(u) x_hat, x_cov = filter(x=x_hat,",
"history.update(x=info['x'], z=obs, x_hat=x_hat, covariance=x_cov) if t % 100 == 0: plot(data=history) if __name__",
"yawrate]) return u def main(): env = DiffDriveRobot() z = env.reset() x_hat =",
"u = jnp.array([v, yawrate]) return u def main(): env = DiffDriveRobot() z =",
"controller(x_hat) # [velocity, yaw_rate] obs, _, _, info = env.step(u) x_hat, x_cov =",
"])) ** 2 # predict state covariance R = jnp.diag(jnp.array([2, 2])) ** 2",
"u def main(): env = DiffDriveRobot() z = env.reset() x_hat = jnp.zeros(4) #",
"jit(filter) history = History() history.update(x=x_hat, z=z, x_hat=x_hat, covariance=x_cov) for t in range(5000): print(t)",
"import ExtendedKalmanFilter, KalmanFilter import jax.numpy as jnp import numpy as np from jax",
"velocity] x_cov = jnp.eye(4) Q = jnp.diag(jnp.array([ 0.1, # variance of location on",
"from functools import partial from estimation import ExtendedKalmanFilter, KalmanFilter import jax.numpy as jnp",
"= jnp.diag(jnp.array([2, 2])) ** 2 # Observation x,y position covariance filter = ExtendedKalmanFilter(",
"jnp import numpy as np from jax import jacfwd, jit import matplotlib.pyplot as",
"variance of location on y-axis jnp.deg2rad(0.5), # variance of yaw angle 0.1 #",
"y-axis jnp.deg2rad(0.5), # variance of yaw angle 0.1 # variance of velocity ]))",
"_motion_model(x, u, w, dt=0.01): return jnp.array([ x[0] + x[3] * jnp.cos(x[2]) * dt,",
"jnp.array([v, yawrate]) return u def main(): env = DiffDriveRobot() z = env.reset() x_hat",
"x[3] * jnp.sin(x[2]) * dt, x[2] + u[1] * dt, u[0] ]) +",
"# variance of velocity ])) ** 2 # predict state covariance R =",
"* dt, x[1] + x[3] * jnp.sin(x[2]) * dt, x[2] + u[1] *",
"covariance filter = ExtendedKalmanFilter( process_model=_motion_model, observation_model=_observation_model, process_noise_covariance=Q, observation_noise_covariance=R ) filter = jit(filter) history",
"x[2] + u[1] * dt, u[0] ]) + w def _observation_model(x, v): H",
"= 1.0 # [m/s] yawrate = 0.1 # [rad/s] u = jnp.array([v, yawrate])",
"0.1, # variance of location on y-axis jnp.deg2rad(0.5), # variance of yaw angle",
"# [rad/s] u = jnp.array([v, yawrate]) return u def main(): env = DiffDriveRobot()",
"variance of yaw angle 0.1 # variance of velocity ])) ** 2 #",
"# [x, y, yaw, velocity] x_cov = jnp.eye(4) Q = jnp.diag(jnp.array([ 0.1, #",
"# variance of yaw angle 0.1 # variance of velocity ])) ** 2",
"t in range(5000): print(t) u = controller(x_hat) # [velocity, yaw_rate] obs, _, _,",
"main(): env = DiffDriveRobot() z = env.reset() x_hat = jnp.zeros(4) # [x, y,",
"= jnp.diag(jnp.array([ 0.1, # variance of location on x-axis 0.1, # variance of",
"z = env.reset() x_hat = jnp.zeros(4) # [x, y, yaw, velocity] x_cov =",
"obs, _, _, info = env.step(u) x_hat, x_cov = filter(x=x_hat, P=x_cov, u=u, z=obs)",
"filter(x=x_hat, P=x_cov, u=u, z=obs) history.update(x=info['x'], z=obs, x_hat=x_hat, covariance=x_cov) if t % 100 ==",
"= jit(filter) history = History() history.update(x=x_hat, z=z, x_hat=x_hat, covariance=x_cov) for t in range(5000):",
"= env.reset() x_hat = jnp.zeros(4) # [x, y, yaw, velocity] x_cov = jnp.eye(4)",
"Code from https://github.com/AtsushiSakai/PythonRobotics \"\"\" from functools import partial from estimation import ExtendedKalmanFilter, KalmanFilter",
"# [m/s] yawrate = 0.1 # [rad/s] u = jnp.array([v, yawrate]) return u",
"u[1] * dt, u[0] ]) + w def _observation_model(x, v): H = jnp.array([[1,",
"jit import matplotlib.pyplot as plt from src.environments import DiffDriveRobot from util import plot,",
"= jnp.eye(4) Q = jnp.diag(jnp.array([ 0.1, # variance of location on x-axis 0.1,",
"+ u[1] * dt, u[0] ]) + w def _observation_model(x, v): H =",
"y, yaw, velocity] x_cov = jnp.eye(4) Q = jnp.diag(jnp.array([ 0.1, # variance of",
"[x, y, yaw, velocity] x_cov = jnp.eye(4) Q = jnp.diag(jnp.array([ 0.1, # variance",
"def _motion_model(x, u, w, dt=0.01): return jnp.array([ x[0] + x[3] * jnp.cos(x[2]) *",
"0.1 # variance of velocity ])) ** 2 # predict state covariance R",
"+ v def controller(x): v = 1.0 # [m/s] yawrate = 0.1 #",
"Q = jnp.diag(jnp.array([ 0.1, # variance of location on x-axis 0.1, # variance",
"of location on y-axis jnp.deg2rad(0.5), # variance of yaw angle 0.1 # variance",
"jnp.diag(jnp.array([2, 2])) ** 2 # Observation x,y position covariance filter = ExtendedKalmanFilter( process_model=_motion_model,",
"of location on x-axis 0.1, # variance of location on y-axis jnp.deg2rad(0.5), #",
"yaw_rate] obs, _, _, info = env.step(u) x_hat, x_cov = filter(x=x_hat, P=x_cov, u=u,",
"DiffDriveRobot from util import plot, History def _motion_model(x, u, w, dt=0.01): return jnp.array([",
"x-axis 0.1, # variance of location on y-axis jnp.deg2rad(0.5), # variance of yaw",
"jnp.sin(x[2]) * dt, x[2] + u[1] * dt, u[0] ]) + w def",
"partial from estimation import ExtendedKalmanFilter, KalmanFilter import jax.numpy as jnp import numpy as",
"jnp.diag(jnp.array([ 0.1, # variance of location on x-axis 0.1, # variance of location",
"as np from jax import jacfwd, jit import matplotlib.pyplot as plt from src.environments",
"jax.numpy as jnp import numpy as np from jax import jacfwd, jit import",
"def _observation_model(x, v): H = jnp.array([[1, 0, 0, 0], [0, 1, 0, 0]])",
"yawrate = 0.1 # [rad/s] u = jnp.array([v, yawrate]) return u def main():",
"** 2 # predict state covariance R = jnp.diag(jnp.array([2, 2])) ** 2 #",
"2 # predict state covariance R = jnp.diag(jnp.array([2, 2])) ** 2 # Observation",
"process_noise_covariance=Q, observation_noise_covariance=R ) filter = jit(filter) history = History() history.update(x=x_hat, z=z, x_hat=x_hat, covariance=x_cov)",
"in range(5000): print(t) u = controller(x_hat) # [velocity, yaw_rate] obs, _, _, info",
"x[0] + x[3] * jnp.cos(x[2]) * dt, x[1] + x[3] * jnp.sin(x[2]) *",
"v def controller(x): v = 1.0 # [m/s] yawrate = 0.1 # [rad/s]",
"x_cov = filter(x=x_hat, P=x_cov, u=u, z=obs) history.update(x=info['x'], z=obs, x_hat=x_hat, covariance=x_cov) if t %",
"env = DiffDriveRobot() z = env.reset() x_hat = jnp.zeros(4) # [x, y, yaw,",
"of yaw angle 0.1 # variance of velocity ])) ** 2 # predict",
"of velocity ])) ** 2 # predict state covariance R = jnp.diag(jnp.array([2, 2]))",
"2])) ** 2 # Observation x,y position covariance filter = ExtendedKalmanFilter( process_model=_motion_model, observation_model=_observation_model,",
"import jax.numpy as jnp import numpy as np from jax import jacfwd, jit",
") filter = jit(filter) history = History() history.update(x=x_hat, z=z, x_hat=x_hat, covariance=x_cov) for t",
"state covariance R = jnp.diag(jnp.array([2, 2])) ** 2 # Observation x,y position covariance",
"jnp.cos(x[2]) * dt, x[1] + x[3] * jnp.sin(x[2]) * dt, x[2] + u[1]",
"observation_noise_covariance=R ) filter = jit(filter) history = History() history.update(x=x_hat, z=z, x_hat=x_hat, covariance=x_cov) for",
"yaw, velocity] x_cov = jnp.eye(4) Q = jnp.diag(jnp.array([ 0.1, # variance of location",
"KalmanFilter import jax.numpy as jnp import numpy as np from jax import jacfwd,",
"DiffDriveRobot() z = env.reset() x_hat = jnp.zeros(4) # [x, y, yaw, velocity] x_cov",
"from util import plot, History def _motion_model(x, u, w, dt=0.01): return jnp.array([ x[0]",
"variance of velocity ])) ** 2 # predict state covariance R = jnp.diag(jnp.array([2,",
"jax import jacfwd, jit import matplotlib.pyplot as plt from src.environments import DiffDriveRobot from",
"covariance R = jnp.diag(jnp.array([2, 2])) ** 2 # Observation x,y position covariance filter",
"[rad/s] u = jnp.array([v, yawrate]) return u def main(): env = DiffDriveRobot() z",
"H = jnp.array([[1, 0, 0, 0], [0, 1, 0, 0]]) return H @",
"Adapted Code from https://github.com/AtsushiSakai/PythonRobotics \"\"\" from functools import partial from estimation import ExtendedKalmanFilter,",
"History() history.update(x=x_hat, z=z, x_hat=x_hat, covariance=x_cov) for t in range(5000): print(t) u = controller(x_hat)",
"functools import partial from estimation import ExtendedKalmanFilter, KalmanFilter import jax.numpy as jnp import",
"np from jax import jacfwd, jit import matplotlib.pyplot as plt from src.environments import",
"= controller(x_hat) # [velocity, yaw_rate] obs, _, _, info = env.step(u) x_hat, x_cov",
"@ x + v def controller(x): v = 1.0 # [m/s] yawrate =",
"def main(): env = DiffDriveRobot() z = env.reset() x_hat = jnp.zeros(4) # [x,",
"x_cov = jnp.eye(4) Q = jnp.diag(jnp.array([ 0.1, # variance of location on x-axis",
"variance of location on x-axis 0.1, # variance of location on y-axis jnp.deg2rad(0.5),",
"observation_model=_observation_model, process_noise_covariance=Q, observation_noise_covariance=R ) filter = jit(filter) history = History() history.update(x=x_hat, z=z, x_hat=x_hat,",
"env.reset() x_hat = jnp.zeros(4) # [x, y, yaw, velocity] x_cov = jnp.eye(4) Q",
"# Observation x,y position covariance filter = ExtendedKalmanFilter( process_model=_motion_model, observation_model=_observation_model, process_noise_covariance=Q, observation_noise_covariance=R )",
"yaw angle 0.1 # variance of velocity ])) ** 2 # predict state",
"covariance=x_cov) if t % 100 == 0: plot(data=history) if __name__ == '__main__': main()",
"v): H = jnp.array([[1, 0, 0, 0], [0, 1, 0, 0]]) return H",
"x[1] + x[3] * jnp.sin(x[2]) * dt, x[2] + u[1] * dt, u[0]",
"= ExtendedKalmanFilter( process_model=_motion_model, observation_model=_observation_model, process_noise_covariance=Q, observation_noise_covariance=R ) filter = jit(filter) history = History()",
"ExtendedKalmanFilter( process_model=_motion_model, observation_model=_observation_model, process_noise_covariance=Q, observation_noise_covariance=R ) filter = jit(filter) history = History() history.update(x=x_hat,",
"+ x[3] * jnp.sin(x[2]) * dt, x[2] + u[1] * dt, u[0] ])",
"= env.step(u) x_hat, x_cov = filter(x=x_hat, P=x_cov, u=u, z=obs) history.update(x=info['x'], z=obs, x_hat=x_hat, covariance=x_cov)",
"filter = ExtendedKalmanFilter( process_model=_motion_model, observation_model=_observation_model, process_noise_covariance=Q, observation_noise_covariance=R ) filter = jit(filter) history =",
"_observation_model(x, v): H = jnp.array([[1, 0, 0, 0], [0, 1, 0, 0]]) return",
"\"\"\" from functools import partial from estimation import ExtendedKalmanFilter, KalmanFilter import jax.numpy as",
"angle 0.1 # variance of velocity ])) ** 2 # predict state covariance",
"[m/s] yawrate = 0.1 # [rad/s] u = jnp.array([v, yawrate]) return u def",
"as plt from src.environments import DiffDriveRobot from util import plot, History def _motion_model(x,",
"* dt, u[0] ]) + w def _observation_model(x, v): H = jnp.array([[1, 0,",
"x + v def controller(x): v = 1.0 # [m/s] yawrate = 0.1",
"estimation import ExtendedKalmanFilter, KalmanFilter import jax.numpy as jnp import numpy as np from",
"from jax import jacfwd, jit import matplotlib.pyplot as plt from src.environments import DiffDriveRobot",
"util import plot, History def _motion_model(x, u, w, dt=0.01): return jnp.array([ x[0] +",
"** 2 # Observation x,y position covariance filter = ExtendedKalmanFilter( process_model=_motion_model, observation_model=_observation_model, process_noise_covariance=Q,",
"plot, History def _motion_model(x, u, w, dt=0.01): return jnp.array([ x[0] + x[3] *",
"process_model=_motion_model, observation_model=_observation_model, process_noise_covariance=Q, observation_noise_covariance=R ) filter = jit(filter) history = History() history.update(x=x_hat, z=z,",
"dt, u[0] ]) + w def _observation_model(x, v): H = jnp.array([[1, 0, 0,",
"from src.environments import DiffDriveRobot from util import plot, History def _motion_model(x, u, w,",
"position covariance filter = ExtendedKalmanFilter( process_model=_motion_model, observation_model=_observation_model, process_noise_covariance=Q, observation_noise_covariance=R ) filter = jit(filter)",
"x,y position covariance filter = ExtendedKalmanFilter( process_model=_motion_model, observation_model=_observation_model, process_noise_covariance=Q, observation_noise_covariance=R ) filter =",
"z=z, x_hat=x_hat, covariance=x_cov) for t in range(5000): print(t) u = controller(x_hat) # [velocity,",
"ExtendedKalmanFilter, KalmanFilter import jax.numpy as jnp import numpy as np from jax import",
"1, 0, 0]]) return H @ x + v def controller(x): v =",
"env.step(u) x_hat, x_cov = filter(x=x_hat, P=x_cov, u=u, z=obs) history.update(x=info['x'], z=obs, x_hat=x_hat, covariance=x_cov) if",
"import plot, History def _motion_model(x, u, w, dt=0.01): return jnp.array([ x[0] + x[3]",
"w, dt=0.01): return jnp.array([ x[0] + x[3] * jnp.cos(x[2]) * dt, x[1] +",
"History def _motion_model(x, u, w, dt=0.01): return jnp.array([ x[0] + x[3] * jnp.cos(x[2])",
"info = env.step(u) x_hat, x_cov = filter(x=x_hat, P=x_cov, u=u, z=obs) history.update(x=info['x'], z=obs, x_hat=x_hat,",
"# variance of location on x-axis 0.1, # variance of location on y-axis",
"# variance of location on y-axis jnp.deg2rad(0.5), # variance of yaw angle 0.1",
"= DiffDriveRobot() z = env.reset() x_hat = jnp.zeros(4) # [x, y, yaw, velocity]",
"w def _observation_model(x, v): H = jnp.array([[1, 0, 0, 0], [0, 1, 0,",
"dt=0.01): return jnp.array([ x[0] + x[3] * jnp.cos(x[2]) * dt, x[1] + x[3]",
"import partial from estimation import ExtendedKalmanFilter, KalmanFilter import jax.numpy as jnp import numpy",
"on x-axis 0.1, # variance of location on y-axis jnp.deg2rad(0.5), # variance of",
"plt from src.environments import DiffDriveRobot from util import plot, History def _motion_model(x, u,",
"history = History() history.update(x=x_hat, z=z, x_hat=x_hat, covariance=x_cov) for t in range(5000): print(t) u",
"jnp.array([[1, 0, 0, 0], [0, 1, 0, 0]]) return H @ x +",
"H @ x + v def controller(x): v = 1.0 # [m/s] yawrate",
"\"\"\" Adapted Code from https://github.com/AtsushiSakai/PythonRobotics \"\"\" from functools import partial from estimation import",
"0, 0], [0, 1, 0, 0]]) return H @ x + v def",
"x_hat=x_hat, covariance=x_cov) if t % 100 == 0: plot(data=history) if __name__ == '__main__':",
"jnp.deg2rad(0.5), # variance of yaw angle 0.1 # variance of velocity ])) **",
"velocity ])) ** 2 # predict state covariance R = jnp.diag(jnp.array([2, 2])) **",
"print(t) u = controller(x_hat) # [velocity, yaw_rate] obs, _, _, info = env.step(u)",
"0.1 # [rad/s] u = jnp.array([v, yawrate]) return u def main(): env =",
"import jacfwd, jit import matplotlib.pyplot as plt from src.environments import DiffDriveRobot from util",
"[velocity, yaw_rate] obs, _, _, info = env.step(u) x_hat, x_cov = filter(x=x_hat, P=x_cov,",
"z=obs) history.update(x=info['x'], z=obs, x_hat=x_hat, covariance=x_cov) if t % 100 == 0: plot(data=history) if",
"location on x-axis 0.1, # variance of location on y-axis jnp.deg2rad(0.5), # variance",
"filter = jit(filter) history = History() history.update(x=x_hat, z=z, x_hat=x_hat, covariance=x_cov) for t in",
"0], [0, 1, 0, 0]]) return H @ x + v def controller(x):",
"= jnp.array([v, yawrate]) return u def main(): env = DiffDriveRobot() z = env.reset()",
"jnp.array([ x[0] + x[3] * jnp.cos(x[2]) * dt, x[1] + x[3] * jnp.sin(x[2])",
"src.environments import DiffDriveRobot from util import plot, History def _motion_model(x, u, w, dt=0.01):",
"jnp.eye(4) Q = jnp.diag(jnp.array([ 0.1, # variance of location on x-axis 0.1, #",
"_, info = env.step(u) x_hat, x_cov = filter(x=x_hat, P=x_cov, u=u, z=obs) history.update(x=info['x'], z=obs,",
"# predict state covariance R = jnp.diag(jnp.array([2, 2])) ** 2 # Observation x,y",
"1.0 # [m/s] yawrate = 0.1 # [rad/s] u = jnp.array([v, yawrate]) return",
"u = controller(x_hat) # [velocity, yaw_rate] obs, _, _, info = env.step(u) x_hat,",
"0, 0]]) return H @ x + v def controller(x): v = 1.0",
"u[0] ]) + w def _observation_model(x, v): H = jnp.array([[1, 0, 0, 0],"
] |
[
"setuptools setuptools.setup( name=\"uniqpy\", version=\"0.1.3\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"UNIQUAC-based tool for multicomponent VLEs\", long_description=\"uniqpy\", long_description_content_type=\"\",",
"multicomponent VLEs\", long_description=\"uniqpy\", long_description_content_type=\"\", url=\"https://github.com/DNKonanov/uni_cli\", project_urls={ \"Bug Tracker\": \"https://github.com/DNKonanov/uni_cli\", }, classifiers=[ \"Programming Language",
"\"Programming Language :: Python :: 3\", \"License :: OSI Approved :: MIT License\",",
":: Python :: 3\", \"License :: OSI Approved :: MIT License\", \"Operating System",
":: OSI Approved :: MIT License\", \"Operating System :: OS Independent\", ], python_requires=\">=3.7\",",
"OS Independent\", ], python_requires=\">=3.7\", include_package_data=True, packages=['uniqpy'], install_requires=[ 'numpy', 'scipy' ], entry_points={ 'console_scripts': [",
"}, classifiers=[ \"Programming Language :: Python :: 3\", \"License :: OSI Approved ::",
"\"Bug Tracker\": \"https://github.com/DNKonanov/uni_cli\", }, classifiers=[ \"Programming Language :: Python :: 3\", \"License ::",
"include_package_data=True, packages=['uniqpy'], install_requires=[ 'numpy', 'scipy' ], entry_points={ 'console_scripts': [ 'uniqpy=uniqpy.uni_cli:main' ] } )",
"long_description=\"uniqpy\", long_description_content_type=\"\", url=\"https://github.com/DNKonanov/uni_cli\", project_urls={ \"Bug Tracker\": \"https://github.com/DNKonanov/uni_cli\", }, classifiers=[ \"Programming Language :: Python",
"classifiers=[ \"Programming Language :: Python :: 3\", \"License :: OSI Approved :: MIT",
"Language :: Python :: 3\", \"License :: OSI Approved :: MIT License\", \"Operating",
"License\", \"Operating System :: OS Independent\", ], python_requires=\">=3.7\", include_package_data=True, packages=['uniqpy'], install_requires=[ 'numpy', 'scipy'",
"project_urls={ \"Bug Tracker\": \"https://github.com/DNKonanov/uni_cli\", }, classifiers=[ \"Programming Language :: Python :: 3\", \"License",
"OSI Approved :: MIT License\", \"Operating System :: OS Independent\", ], python_requires=\">=3.7\", include_package_data=True,",
":: 3\", \"License :: OSI Approved :: MIT License\", \"Operating System :: OS",
"Independent\", ], python_requires=\">=3.7\", include_package_data=True, packages=['uniqpy'], install_requires=[ 'numpy', 'scipy' ], entry_points={ 'console_scripts': [ 'uniqpy=uniqpy.uni_cli:main'",
"for multicomponent VLEs\", long_description=\"uniqpy\", long_description_content_type=\"\", url=\"https://github.com/DNKonanov/uni_cli\", project_urls={ \"Bug Tracker\": \"https://github.com/DNKonanov/uni_cli\", }, classifiers=[ \"Programming",
":: MIT License\", \"Operating System :: OS Independent\", ], python_requires=\">=3.7\", include_package_data=True, packages=['uniqpy'], install_requires=[",
"MIT License\", \"Operating System :: OS Independent\", ], python_requires=\">=3.7\", include_package_data=True, packages=['uniqpy'], install_requires=[ 'numpy',",
"3\", \"License :: OSI Approved :: MIT License\", \"Operating System :: OS Independent\",",
"import setuptools setuptools.setup( name=\"uniqpy\", version=\"0.1.3\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"UNIQUAC-based tool for multicomponent VLEs\", long_description=\"uniqpy\",",
"setuptools.setup( name=\"uniqpy\", version=\"0.1.3\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"UNIQUAC-based tool for multicomponent VLEs\", long_description=\"uniqpy\", long_description_content_type=\"\", url=\"https://github.com/DNKonanov/uni_cli\",",
"\"Operating System :: OS Independent\", ], python_requires=\">=3.7\", include_package_data=True, packages=['uniqpy'], install_requires=[ 'numpy', 'scipy' ],",
"long_description_content_type=\"\", url=\"https://github.com/DNKonanov/uni_cli\", project_urls={ \"Bug Tracker\": \"https://github.com/DNKonanov/uni_cli\", }, classifiers=[ \"Programming Language :: Python ::",
"url=\"https://github.com/DNKonanov/uni_cli\", project_urls={ \"Bug Tracker\": \"https://github.com/DNKonanov/uni_cli\", }, classifiers=[ \"Programming Language :: Python :: 3\",",
"\"License :: OSI Approved :: MIT License\", \"Operating System :: OS Independent\", ],",
"python_requires=\">=3.7\", include_package_data=True, packages=['uniqpy'], install_requires=[ 'numpy', 'scipy' ], entry_points={ 'console_scripts': [ 'uniqpy=uniqpy.uni_cli:main' ] }",
"VLEs\", long_description=\"uniqpy\", long_description_content_type=\"\", url=\"https://github.com/DNKonanov/uni_cli\", project_urls={ \"Bug Tracker\": \"https://github.com/DNKonanov/uni_cli\", }, classifiers=[ \"Programming Language ::",
"<reponame>DNKonanov/uni_cli import setuptools setuptools.setup( name=\"uniqpy\", version=\"0.1.3\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"UNIQUAC-based tool for multicomponent VLEs\",",
"System :: OS Independent\", ], python_requires=\">=3.7\", include_package_data=True, packages=['uniqpy'], install_requires=[ 'numpy', 'scipy' ], entry_points={",
"author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"UNIQUAC-based tool for multicomponent VLEs\", long_description=\"uniqpy\", long_description_content_type=\"\", url=\"https://github.com/DNKonanov/uni_cli\", project_urls={ \"Bug Tracker\":",
"\"https://github.com/DNKonanov/uni_cli\", }, classifiers=[ \"Programming Language :: Python :: 3\", \"License :: OSI Approved",
"], python_requires=\">=3.7\", include_package_data=True, packages=['uniqpy'], install_requires=[ 'numpy', 'scipy' ], entry_points={ 'console_scripts': [ 'uniqpy=uniqpy.uni_cli:main' ]",
"version=\"0.1.3\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"UNIQUAC-based tool for multicomponent VLEs\", long_description=\"uniqpy\", long_description_content_type=\"\", url=\"https://github.com/DNKonanov/uni_cli\", project_urls={ \"Bug",
":: OS Independent\", ], python_requires=\">=3.7\", include_package_data=True, packages=['uniqpy'], install_requires=[ 'numpy', 'scipy' ], entry_points={ 'console_scripts':",
"description=\"UNIQUAC-based tool for multicomponent VLEs\", long_description=\"uniqpy\", long_description_content_type=\"\", url=\"https://github.com/DNKonanov/uni_cli\", project_urls={ \"Bug Tracker\": \"https://github.com/DNKonanov/uni_cli\", },",
"name=\"uniqpy\", version=\"0.1.3\", author=\"<NAME>\", author_email=\"<EMAIL>\", description=\"UNIQUAC-based tool for multicomponent VLEs\", long_description=\"uniqpy\", long_description_content_type=\"\", url=\"https://github.com/DNKonanov/uni_cli\", project_urls={",
"tool for multicomponent VLEs\", long_description=\"uniqpy\", long_description_content_type=\"\", url=\"https://github.com/DNKonanov/uni_cli\", project_urls={ \"Bug Tracker\": \"https://github.com/DNKonanov/uni_cli\", }, classifiers=[",
"Approved :: MIT License\", \"Operating System :: OS Independent\", ], python_requires=\">=3.7\", include_package_data=True, packages=['uniqpy'],",
"author_email=\"<EMAIL>\", description=\"UNIQUAC-based tool for multicomponent VLEs\", long_description=\"uniqpy\", long_description_content_type=\"\", url=\"https://github.com/DNKonanov/uni_cli\", project_urls={ \"Bug Tracker\": \"https://github.com/DNKonanov/uni_cli\",",
"Python :: 3\", \"License :: OSI Approved :: MIT License\", \"Operating System ::",
"Tracker\": \"https://github.com/DNKonanov/uni_cli\", }, classifiers=[ \"Programming Language :: Python :: 3\", \"License :: OSI"
] |
[
"y = fetch_libsvm(\"news20.binary\") C_min = 2 / norm(X.T @ y, ord=np.inf) C =",
"converge\") warnings.filterwarnings(\"ignore\", message=\"Liblinear failed to converge\") X, y = fetch_libsvm(\"news20.binary\") C_min = 2",
"= linear_model.LogisticRegression( C=C, solver=\"liblinear\", penalty='l1', fit_intercept=False, max_iter=n_iter, random_state=0, tol=1e-10).fit(X, y) t_libl.append(time.time() - t0)",
"2 / norm(X.T @ y, ord=np.inf) C = 20 * C_min def pobj_logreg(w):",
"[] t_celer = [] for n_iter in range(10): t0 = time.time() clf =",
"= plt.figure(figsize=(4, 2), constrained_layout=True) plt.semilogy(t_celer, pobj_celer - p_star, label=\"Celer-PN\") plt.semilogy(t_libl, pobj_libl - p_star,",
"C = 20 * C_min def pobj_logreg(w): return np.sum(np.log(1 + np.exp(-y * (X",
"clf = LogisticRegression( C=C, solver=\"celer-pn\", max_iter=n_iter, tol=0).fit(X, y) t_celer.append(time.time() - t0) w_celer =",
"fetch_libsvm(\"news20.binary\") C_min = 2 / norm(X.T @ y, ord=np.inf) C = 20 *",
"= LogisticRegression( C=C, solver=\"celer-pn\", max_iter=n_iter, tol=0).fit(X, y) t_celer.append(time.time() - t0) w_celer = clf.coef_.ravel()",
"t0 = time.time() clf = LogisticRegression( C=C, solver=\"celer-pn\", max_iter=n_iter, tol=0).fit(X, y) t_celer.append(time.time() -",
"20 * C_min def pobj_logreg(w): return np.sum(np.log(1 + np.exp(-y * (X @ w))))",
"= [] t_celer = [] for n_iter in range(10): t0 = time.time() clf",
"[] t_libl = [] for n_iter in np.arange(0, 50, 10): t0 = time.time()",
"pobj_libl = [] t_libl = [] for n_iter in np.arange(0, 50, 10): t0",
"np.sum(np.log(1 + np.exp(-y * (X @ w)))) + 1. / C * norm(w,",
"= [] t_libl = [] for n_iter in np.arange(0, 50, 10): t0 =",
"linear_model.LogisticRegression( C=C, solver=\"liblinear\", penalty='l1', fit_intercept=False, max_iter=n_iter, random_state=0, tol=1e-10).fit(X, y) t_libl.append(time.time() - t0) w_libl",
"pobj_logreg(w): return np.sum(np.log(1 + np.exp(-y * (X @ w)))) + 1. / C",
"LogisticRegression warnings.filterwarnings(\"ignore\", message=\"Objective did not converge\") warnings.filterwarnings(\"ignore\", message=\"Liblinear failed to converge\") X, y",
"= np.array(pobj_libl) p_star = min(pobj_celer.min(), pobj_libl.min()) plt.close(\"all\") fig = plt.figure(figsize=(4, 2), constrained_layout=True) plt.semilogy(t_celer,",
"np.exp(-y * (X @ w)))) + 1. / C * norm(w, ord=1) pobj_celer",
"backend ================================================================== \"\"\" import time import warnings import numpy as np from numpy.linalg",
"plt.figure(figsize=(4, 2), constrained_layout=True) plt.semilogy(t_celer, pobj_celer - p_star, label=\"Celer-PN\") plt.semilogy(t_libl, pobj_libl - p_star, label=\"liblinear\")",
"message=\"Liblinear failed to converge\") X, y = fetch_libsvm(\"news20.binary\") C_min = 2 / norm(X.T",
"np from numpy.linalg import norm import matplotlib.pyplot as plt from sklearn import linear_model",
"plt.close(\"all\") fig = plt.figure(figsize=(4, 2), constrained_layout=True) plt.semilogy(t_celer, pobj_celer - p_star, label=\"Celer-PN\") plt.semilogy(t_libl, pobj_libl",
"clf.coef_.ravel() pobj_libl.append(pobj_logreg(w_libl)) pobj_libl = np.array(pobj_libl) p_star = min(pobj_celer.min(), pobj_libl.min()) plt.close(\"all\") fig = plt.figure(figsize=(4,",
"= fetch_libsvm(\"news20.binary\") C_min = 2 / norm(X.T @ y, ord=np.inf) C = 20",
"time.time() clf = LogisticRegression( C=C, solver=\"celer-pn\", max_iter=n_iter, tol=0).fit(X, y) t_celer.append(time.time() - t0) w_celer",
"np.arange(0, 50, 10): t0 = time.time() clf = linear_model.LogisticRegression( C=C, solver=\"liblinear\", penalty='l1', fit_intercept=False,",
"[] for n_iter in range(10): t0 = time.time() clf = LogisticRegression( C=C, solver=\"celer-pn\",",
"================================================================== Compare LogisticRegression solver with sklearn's liblinear backend ================================================================== \"\"\" import time import",
"import warnings import numpy as np from numpy.linalg import norm import matplotlib.pyplot as",
"norm import matplotlib.pyplot as plt from sklearn import linear_model from libsvmdata import fetch_libsvm",
"for n_iter in np.arange(0, 50, 10): t0 = time.time() clf = linear_model.LogisticRegression( C=C,",
"linear_model from libsvmdata import fetch_libsvm from celer import LogisticRegression warnings.filterwarnings(\"ignore\", message=\"Objective did not",
"- t0) w_libl = clf.coef_.ravel() pobj_libl.append(pobj_logreg(w_libl)) pobj_libl = np.array(pobj_libl) p_star = min(pobj_celer.min(), pobj_libl.min())",
"y, ord=np.inf) C = 20 * C_min def pobj_logreg(w): return np.sum(np.log(1 + np.exp(-y",
"= np.array(pobj_celer) pobj_libl = [] t_libl = [] for n_iter in np.arange(0, 50,",
"tol=1e-10).fit(X, y) t_libl.append(time.time() - t0) w_libl = clf.coef_.ravel() pobj_libl.append(pobj_logreg(w_libl)) pobj_libl = np.array(pobj_libl) p_star",
"solver with sklearn's liblinear backend ================================================================== \"\"\" import time import warnings import numpy",
"+ 1. / C * norm(w, ord=1) pobj_celer = [] t_celer = []",
"celer import LogisticRegression warnings.filterwarnings(\"ignore\", message=\"Objective did not converge\") warnings.filterwarnings(\"ignore\", message=\"Liblinear failed to converge\")",
"warnings import numpy as np from numpy.linalg import norm import matplotlib.pyplot as plt",
"p_star, label=\"Celer-PN\") plt.semilogy(t_libl, pobj_libl - p_star, label=\"liblinear\") plt.legend() plt.xlabel(\"Time (s)\") plt.ylabel(\"objective suboptimality\") plt.show(block=False)",
"= clf.coef_.ravel() pobj_celer.append(pobj_logreg(w_celer)) pobj_celer = np.array(pobj_celer) pobj_libl = [] t_libl = [] for",
"import time import warnings import numpy as np from numpy.linalg import norm import",
"/ C * norm(w, ord=1) pobj_celer = [] t_celer = [] for n_iter",
"from sklearn import linear_model from libsvmdata import fetch_libsvm from celer import LogisticRegression warnings.filterwarnings(\"ignore\",",
"norm(w, ord=1) pobj_celer = [] t_celer = [] for n_iter in range(10): t0",
"import matplotlib.pyplot as plt from sklearn import linear_model from libsvmdata import fetch_libsvm from",
"clf.coef_.ravel() pobj_celer.append(pobj_logreg(w_celer)) pobj_celer = np.array(pobj_celer) pobj_libl = [] t_libl = [] for n_iter",
"= clf.coef_.ravel() pobj_libl.append(pobj_logreg(w_libl)) pobj_libl = np.array(pobj_libl) p_star = min(pobj_celer.min(), pobj_libl.min()) plt.close(\"all\") fig =",
"y) t_libl.append(time.time() - t0) w_libl = clf.coef_.ravel() pobj_libl.append(pobj_logreg(w_libl)) pobj_libl = np.array(pobj_libl) p_star =",
"- p_star, label=\"Celer-PN\") plt.semilogy(t_libl, pobj_libl - p_star, label=\"liblinear\") plt.legend() plt.xlabel(\"Time (s)\") plt.ylabel(\"objective suboptimality\")",
"pobj_libl.append(pobj_logreg(w_libl)) pobj_libl = np.array(pobj_libl) p_star = min(pobj_celer.min(), pobj_libl.min()) plt.close(\"all\") fig = plt.figure(figsize=(4, 2),",
"pobj_celer = np.array(pobj_celer) pobj_libl = [] t_libl = [] for n_iter in np.arange(0,",
"sklearn's liblinear backend ================================================================== \"\"\" import time import warnings import numpy as np",
"fetch_libsvm from celer import LogisticRegression warnings.filterwarnings(\"ignore\", message=\"Objective did not converge\") warnings.filterwarnings(\"ignore\", message=\"Liblinear failed",
"with sklearn's liblinear backend ================================================================== \"\"\" import time import warnings import numpy as",
"= 2 / norm(X.T @ y, ord=np.inf) C = 20 * C_min def",
"w)))) + 1. / C * norm(w, ord=1) pobj_celer = [] t_celer =",
"time import warnings import numpy as np from numpy.linalg import norm import matplotlib.pyplot",
"in np.arange(0, 50, 10): t0 = time.time() clf = linear_model.LogisticRegression( C=C, solver=\"liblinear\", penalty='l1',",
"np.array(pobj_celer) pobj_libl = [] t_libl = [] for n_iter in np.arange(0, 50, 10):",
"pobj_libl = np.array(pobj_libl) p_star = min(pobj_celer.min(), pobj_libl.min()) plt.close(\"all\") fig = plt.figure(figsize=(4, 2), constrained_layout=True)",
"= min(pobj_celer.min(), pobj_libl.min()) plt.close(\"all\") fig = plt.figure(figsize=(4, 2), constrained_layout=True) plt.semilogy(t_celer, pobj_celer - p_star,",
"p_star = min(pobj_celer.min(), pobj_libl.min()) plt.close(\"all\") fig = plt.figure(figsize=(4, 2), constrained_layout=True) plt.semilogy(t_celer, pobj_celer -",
"(X @ w)))) + 1. / C * norm(w, ord=1) pobj_celer = []",
"pobj_libl.min()) plt.close(\"all\") fig = plt.figure(figsize=(4, 2), constrained_layout=True) plt.semilogy(t_celer, pobj_celer - p_star, label=\"Celer-PN\") plt.semilogy(t_libl,",
"50, 10): t0 = time.time() clf = linear_model.LogisticRegression( C=C, solver=\"liblinear\", penalty='l1', fit_intercept=False, max_iter=n_iter,",
"@ y, ord=np.inf) C = 20 * C_min def pobj_logreg(w): return np.sum(np.log(1 +",
"ord=1) pobj_celer = [] t_celer = [] for n_iter in range(10): t0 =",
"* (X @ w)))) + 1. / C * norm(w, ord=1) pobj_celer =",
"to converge\") X, y = fetch_libsvm(\"news20.binary\") C_min = 2 / norm(X.T @ y,",
"message=\"Objective did not converge\") warnings.filterwarnings(\"ignore\", message=\"Liblinear failed to converge\") X, y = fetch_libsvm(\"news20.binary\")",
"- t0) w_celer = clf.coef_.ravel() pobj_celer.append(pobj_logreg(w_celer)) pobj_celer = np.array(pobj_celer) pobj_libl = [] t_libl",
"t0 = time.time() clf = linear_model.LogisticRegression( C=C, solver=\"liblinear\", penalty='l1', fit_intercept=False, max_iter=n_iter, random_state=0, tol=1e-10).fit(X,",
"solver=\"celer-pn\", max_iter=n_iter, tol=0).fit(X, y) t_celer.append(time.time() - t0) w_celer = clf.coef_.ravel() pobj_celer.append(pobj_logreg(w_celer)) pobj_celer =",
"10): t0 = time.time() clf = linear_model.LogisticRegression( C=C, solver=\"liblinear\", penalty='l1', fit_intercept=False, max_iter=n_iter, random_state=0,",
"= time.time() clf = linear_model.LogisticRegression( C=C, solver=\"liblinear\", penalty='l1', fit_intercept=False, max_iter=n_iter, random_state=0, tol=1e-10).fit(X, y)",
"y) t_celer.append(time.time() - t0) w_celer = clf.coef_.ravel() pobj_celer.append(pobj_logreg(w_celer)) pobj_celer = np.array(pobj_celer) pobj_libl =",
"import fetch_libsvm from celer import LogisticRegression warnings.filterwarnings(\"ignore\", message=\"Objective did not converge\") warnings.filterwarnings(\"ignore\", message=\"Liblinear",
"C * norm(w, ord=1) pobj_celer = [] t_celer = [] for n_iter in",
"C=C, solver=\"liblinear\", penalty='l1', fit_intercept=False, max_iter=n_iter, random_state=0, tol=1e-10).fit(X, y) t_libl.append(time.time() - t0) w_libl =",
"[] for n_iter in np.arange(0, 50, 10): t0 = time.time() clf = linear_model.LogisticRegression(",
"2), constrained_layout=True) plt.semilogy(t_celer, pobj_celer - p_star, label=\"Celer-PN\") plt.semilogy(t_libl, pobj_libl - p_star, label=\"liblinear\") plt.legend()",
"return np.sum(np.log(1 + np.exp(-y * (X @ w)))) + 1. / C *",
"import norm import matplotlib.pyplot as plt from sklearn import linear_model from libsvmdata import",
"for n_iter in range(10): t0 = time.time() clf = LogisticRegression( C=C, solver=\"celer-pn\", max_iter=n_iter,",
"as plt from sklearn import linear_model from libsvmdata import fetch_libsvm from celer import",
"warnings.filterwarnings(\"ignore\", message=\"Objective did not converge\") warnings.filterwarnings(\"ignore\", message=\"Liblinear failed to converge\") X, y =",
"def pobj_logreg(w): return np.sum(np.log(1 + np.exp(-y * (X @ w)))) + 1. /",
"t_libl.append(time.time() - t0) w_libl = clf.coef_.ravel() pobj_libl.append(pobj_logreg(w_libl)) pobj_libl = np.array(pobj_libl) p_star = min(pobj_celer.min(),",
"fig = plt.figure(figsize=(4, 2), constrained_layout=True) plt.semilogy(t_celer, pobj_celer - p_star, label=\"Celer-PN\") plt.semilogy(t_libl, pobj_libl -",
"import numpy as np from numpy.linalg import norm import matplotlib.pyplot as plt from",
"plt.semilogy(t_celer, pobj_celer - p_star, label=\"Celer-PN\") plt.semilogy(t_libl, pobj_libl - p_star, label=\"liblinear\") plt.legend() plt.xlabel(\"Time (s)\")",
"pobj_celer - p_star, label=\"Celer-PN\") plt.semilogy(t_libl, pobj_libl - p_star, label=\"liblinear\") plt.legend() plt.xlabel(\"Time (s)\") plt.ylabel(\"objective",
"n_iter in range(10): t0 = time.time() clf = LogisticRegression( C=C, solver=\"celer-pn\", max_iter=n_iter, tol=0).fit(X,",
"\"\"\" ================================================================== Compare LogisticRegression solver with sklearn's liblinear backend ================================================================== \"\"\" import time",
"t_celer.append(time.time() - t0) w_celer = clf.coef_.ravel() pobj_celer.append(pobj_logreg(w_celer)) pobj_celer = np.array(pobj_celer) pobj_libl = []",
"@ w)))) + 1. / C * norm(w, ord=1) pobj_celer = [] t_celer",
"ord=np.inf) C = 20 * C_min def pobj_logreg(w): return np.sum(np.log(1 + np.exp(-y *",
"= time.time() clf = LogisticRegression( C=C, solver=\"celer-pn\", max_iter=n_iter, tol=0).fit(X, y) t_celer.append(time.time() - t0)",
"1. / C * norm(w, ord=1) pobj_celer = [] t_celer = [] for",
"random_state=0, tol=1e-10).fit(X, y) t_libl.append(time.time() - t0) w_libl = clf.coef_.ravel() pobj_libl.append(pobj_logreg(w_libl)) pobj_libl = np.array(pobj_libl)",
"warnings.filterwarnings(\"ignore\", message=\"Liblinear failed to converge\") X, y = fetch_libsvm(\"news20.binary\") C_min = 2 /",
"solver=\"liblinear\", penalty='l1', fit_intercept=False, max_iter=n_iter, random_state=0, tol=1e-10).fit(X, y) t_libl.append(time.time() - t0) w_libl = clf.coef_.ravel()",
"from celer import LogisticRegression warnings.filterwarnings(\"ignore\", message=\"Objective did not converge\") warnings.filterwarnings(\"ignore\", message=\"Liblinear failed to",
"= 20 * C_min def pobj_logreg(w): return np.sum(np.log(1 + np.exp(-y * (X @",
"C_min def pobj_logreg(w): return np.sum(np.log(1 + np.exp(-y * (X @ w)))) + 1.",
"import linear_model from libsvmdata import fetch_libsvm from celer import LogisticRegression warnings.filterwarnings(\"ignore\", message=\"Objective did",
"liblinear backend ================================================================== \"\"\" import time import warnings import numpy as np from",
"= [] for n_iter in range(10): t0 = time.time() clf = LogisticRegression( C=C,",
"not converge\") warnings.filterwarnings(\"ignore\", message=\"Liblinear failed to converge\") X, y = fetch_libsvm(\"news20.binary\") C_min =",
"t_libl = [] for n_iter in np.arange(0, 50, 10): t0 = time.time() clf",
"fit_intercept=False, max_iter=n_iter, random_state=0, tol=1e-10).fit(X, y) t_libl.append(time.time() - t0) w_libl = clf.coef_.ravel() pobj_libl.append(pobj_logreg(w_libl)) pobj_libl",
"LogisticRegression( C=C, solver=\"celer-pn\", max_iter=n_iter, tol=0).fit(X, y) t_celer.append(time.time() - t0) w_celer = clf.coef_.ravel() pobj_celer.append(pobj_logreg(w_celer))",
"numpy.linalg import norm import matplotlib.pyplot as plt from sklearn import linear_model from libsvmdata",
"from libsvmdata import fetch_libsvm from celer import LogisticRegression warnings.filterwarnings(\"ignore\", message=\"Objective did not converge\")",
"================================================================== \"\"\" import time import warnings import numpy as np from numpy.linalg import",
"in range(10): t0 = time.time() clf = LogisticRegression( C=C, solver=\"celer-pn\", max_iter=n_iter, tol=0).fit(X, y)",
"n_iter in np.arange(0, 50, 10): t0 = time.time() clf = linear_model.LogisticRegression( C=C, solver=\"liblinear\",",
"= [] for n_iter in np.arange(0, 50, 10): t0 = time.time() clf =",
"* C_min def pobj_logreg(w): return np.sum(np.log(1 + np.exp(-y * (X @ w)))) +",
"libsvmdata import fetch_libsvm from celer import LogisticRegression warnings.filterwarnings(\"ignore\", message=\"Objective did not converge\") warnings.filterwarnings(\"ignore\",",
"import LogisticRegression warnings.filterwarnings(\"ignore\", message=\"Objective did not converge\") warnings.filterwarnings(\"ignore\", message=\"Liblinear failed to converge\") X,",
"did not converge\") warnings.filterwarnings(\"ignore\", message=\"Liblinear failed to converge\") X, y = fetch_libsvm(\"news20.binary\") C_min",
"pobj_celer.append(pobj_logreg(w_celer)) pobj_celer = np.array(pobj_celer) pobj_libl = [] t_libl = [] for n_iter in",
"numpy as np from numpy.linalg import norm import matplotlib.pyplot as plt from sklearn",
"matplotlib.pyplot as plt from sklearn import linear_model from libsvmdata import fetch_libsvm from celer",
"plt from sklearn import linear_model from libsvmdata import fetch_libsvm from celer import LogisticRegression",
"LogisticRegression solver with sklearn's liblinear backend ================================================================== \"\"\" import time import warnings import",
"converge\") X, y = fetch_libsvm(\"news20.binary\") C_min = 2 / norm(X.T @ y, ord=np.inf)",
"clf = linear_model.LogisticRegression( C=C, solver=\"liblinear\", penalty='l1', fit_intercept=False, max_iter=n_iter, random_state=0, tol=1e-10).fit(X, y) t_libl.append(time.time() -",
"C=C, solver=\"celer-pn\", max_iter=n_iter, tol=0).fit(X, y) t_celer.append(time.time() - t0) w_celer = clf.coef_.ravel() pobj_celer.append(pobj_logreg(w_celer)) pobj_celer",
"time.time() clf = linear_model.LogisticRegression( C=C, solver=\"liblinear\", penalty='l1', fit_intercept=False, max_iter=n_iter, random_state=0, tol=1e-10).fit(X, y) t_libl.append(time.time()",
"+ np.exp(-y * (X @ w)))) + 1. / C * norm(w, ord=1)",
"max_iter=n_iter, random_state=0, tol=1e-10).fit(X, y) t_libl.append(time.time() - t0) w_libl = clf.coef_.ravel() pobj_libl.append(pobj_logreg(w_libl)) pobj_libl =",
"min(pobj_celer.min(), pobj_libl.min()) plt.close(\"all\") fig = plt.figure(figsize=(4, 2), constrained_layout=True) plt.semilogy(t_celer, pobj_celer - p_star, label=\"Celer-PN\")",
"constrained_layout=True) plt.semilogy(t_celer, pobj_celer - p_star, label=\"Celer-PN\") plt.semilogy(t_libl, pobj_libl - p_star, label=\"liblinear\") plt.legend() plt.xlabel(\"Time",
"norm(X.T @ y, ord=np.inf) C = 20 * C_min def pobj_logreg(w): return np.sum(np.log(1",
"t0) w_libl = clf.coef_.ravel() pobj_libl.append(pobj_logreg(w_libl)) pobj_libl = np.array(pobj_libl) p_star = min(pobj_celer.min(), pobj_libl.min()) plt.close(\"all\")",
"t0) w_celer = clf.coef_.ravel() pobj_celer.append(pobj_logreg(w_celer)) pobj_celer = np.array(pobj_celer) pobj_libl = [] t_libl =",
"w_celer = clf.coef_.ravel() pobj_celer.append(pobj_logreg(w_celer)) pobj_celer = np.array(pobj_celer) pobj_libl = [] t_libl = []",
"\"\"\" import time import warnings import numpy as np from numpy.linalg import norm",
"t_celer = [] for n_iter in range(10): t0 = time.time() clf = LogisticRegression(",
"max_iter=n_iter, tol=0).fit(X, y) t_celer.append(time.time() - t0) w_celer = clf.coef_.ravel() pobj_celer.append(pobj_logreg(w_celer)) pobj_celer = np.array(pobj_celer)",
"as np from numpy.linalg import norm import matplotlib.pyplot as plt from sklearn import",
"/ norm(X.T @ y, ord=np.inf) C = 20 * C_min def pobj_logreg(w): return",
"Compare LogisticRegression solver with sklearn's liblinear backend ================================================================== \"\"\" import time import warnings",
"failed to converge\") X, y = fetch_libsvm(\"news20.binary\") C_min = 2 / norm(X.T @",
"pobj_celer = [] t_celer = [] for n_iter in range(10): t0 = time.time()",
"C_min = 2 / norm(X.T @ y, ord=np.inf) C = 20 * C_min",
"range(10): t0 = time.time() clf = LogisticRegression( C=C, solver=\"celer-pn\", max_iter=n_iter, tol=0).fit(X, y) t_celer.append(time.time()",
"tol=0).fit(X, y) t_celer.append(time.time() - t0) w_celer = clf.coef_.ravel() pobj_celer.append(pobj_logreg(w_celer)) pobj_celer = np.array(pobj_celer) pobj_libl",
"penalty='l1', fit_intercept=False, max_iter=n_iter, random_state=0, tol=1e-10).fit(X, y) t_libl.append(time.time() - t0) w_libl = clf.coef_.ravel() pobj_libl.append(pobj_logreg(w_libl))",
"from numpy.linalg import norm import matplotlib.pyplot as plt from sklearn import linear_model from",
"np.array(pobj_libl) p_star = min(pobj_celer.min(), pobj_libl.min()) plt.close(\"all\") fig = plt.figure(figsize=(4, 2), constrained_layout=True) plt.semilogy(t_celer, pobj_celer",
"* norm(w, ord=1) pobj_celer = [] t_celer = [] for n_iter in range(10):",
"sklearn import linear_model from libsvmdata import fetch_libsvm from celer import LogisticRegression warnings.filterwarnings(\"ignore\", message=\"Objective",
"X, y = fetch_libsvm(\"news20.binary\") C_min = 2 / norm(X.T @ y, ord=np.inf) C",
"w_libl = clf.coef_.ravel() pobj_libl.append(pobj_logreg(w_libl)) pobj_libl = np.array(pobj_libl) p_star = min(pobj_celer.min(), pobj_libl.min()) plt.close(\"all\") fig"
] |
[
"+ '_2' self.samweb.modifyDefinition(defname,defname=defname2) d = self.samweb.descDefinitionDict(defname2) assert defname2 == d[\"defname\"] self.samweb.deleteDefinition(defname2) class TestDefinitionCommands(testbase.SAMWebCmdTest):",
"assert defname in d d = self.samweb.descDefinitionDict(defname) assert defname == d[\"defname\"] defname2 =",
"self.samweb.descDefinitionDict(defname2) assert defname2 == d[\"defname\"] self.samweb.deleteDefinition(defname2) class TestDefinitionCommands(testbase.SAMWebCmdTest): def test_takeSnapshot(self): cmdline = '-e",
"\"illingwo\", \"samdev\") d = self.samweb.descDefinition(defname) assert defname in d d = self.samweb.descDefinitionDict(defname) assert",
"'-e samdev take-snapshot %s' % defname self.check_cmd_return(cmdline.split()) assert \"1\\n\" == self.stdout if __name__",
"import samweb_cli import time,os defname = 'test-project' class TestDefinition(testbase.SamdevTest): def test_descDefinition_DefNotFound(self): fake_def_name =",
"d = self.samweb.descDefinitionDict(defname) assert d['defname'] == defname def test_snapshot(self): output = self.samweb.takeSnapshot(defname) self.assertEquals(int(output),1)",
"def test_takeSnapshot(self): cmdline = '-e samdev take-snapshot %s' % defname self.check_cmd_return(cmdline.split()) assert \"1\\n\"",
"in output d = self.samweb.descDefinitionDict(defname) assert d['defname'] == defname def test_snapshot(self): output =",
"import time,os defname = 'test-project' class TestDefinition(testbase.SamdevTest): def test_descDefinition_DefNotFound(self): fake_def_name = 'doesnotexist_%d' %",
"/usr/bin/env python import testbase import unittest import samweb_client import samweb_cli import time,os defname",
"fake_def_name) def test_descDefinition(self): output = self.samweb.descDefinition(defname) assert defname in output d = self.samweb.descDefinitionDict(defname)",
"defname def test_snapshot(self): output = self.samweb.takeSnapshot(defname) self.assertEquals(int(output),1) def test_create_rename_delete_definition(self): defname = 'samweb_client_test_def_%s_%d' %",
"d[\"defname\"] defname2 = defname + '_2' self.samweb.modifyDefinition(defname,defname=defname2) d = self.samweb.descDefinitionDict(defname2) assert defname2 ==",
"dummy\", \"illingwo\", \"samdev\") d = self.samweb.descDefinition(defname) assert defname in d d = self.samweb.descDefinitionDict(defname)",
"import samweb_client import samweb_cli import time,os defname = 'test-project' class TestDefinition(testbase.SamdevTest): def test_descDefinition_DefNotFound(self):",
"\"samdev\") d = self.samweb.descDefinition(defname) assert defname in d d = self.samweb.descDefinitionDict(defname) assert defname",
"time,os defname = 'test-project' class TestDefinition(testbase.SamdevTest): def test_descDefinition_DefNotFound(self): fake_def_name = 'doesnotexist_%d' % time.time()",
"d d = self.samweb.descDefinitionDict(defname) assert defname == d[\"defname\"] defname2 = defname + '_2'",
"output = self.samweb.descDefinition(defname) assert defname in output d = self.samweb.descDefinitionDict(defname) assert d['defname'] ==",
"self.samweb.descDefinition(defname) assert defname in d d = self.samweb.descDefinitionDict(defname) assert defname == d[\"defname\"] defname2",
"test_descDefinition(self): output = self.samweb.descDefinition(defname) assert defname in output d = self.samweb.descDefinitionDict(defname) assert d['defname']",
"defname2 = defname + '_2' self.samweb.modifyDefinition(defname,defname=defname2) d = self.samweb.descDefinitionDict(defname2) assert defname2 == d[\"defname\"]",
"= 'doesnotexist_%d' % time.time() self.assertRaises(samweb_client.exceptions.DefinitionNotFound, self.samweb.descDefinition, fake_def_name) self.assertRaises(samweb_client.exceptions.DefinitionNotFound, self.samweb.descDefinitionDict, fake_def_name) def test_descDefinition(self): output",
"test_descDefinition_DefNotFound(self): fake_def_name = 'doesnotexist_%d' % time.time() self.assertRaises(samweb_client.exceptions.DefinitionNotFound, self.samweb.descDefinition, fake_def_name) self.assertRaises(samweb_client.exceptions.DefinitionNotFound, self.samweb.descDefinitionDict, fake_def_name) def",
"int(time.time())) self.samweb.createDefinition(defname, \"file_name dummy\", \"illingwo\", \"samdev\") d = self.samweb.descDefinition(defname) assert defname in d",
"'test-project' class TestDefinition(testbase.SamdevTest): def test_descDefinition_DefNotFound(self): fake_def_name = 'doesnotexist_%d' % time.time() self.assertRaises(samweb_client.exceptions.DefinitionNotFound, self.samweb.descDefinition, fake_def_name)",
"= 'samweb_client_test_def_%s_%d' % (os.getpid(), int(time.time())) self.samweb.createDefinition(defname, \"file_name dummy\", \"illingwo\", \"samdev\") d = self.samweb.descDefinition(defname)",
"defname + '_2' self.samweb.modifyDefinition(defname,defname=defname2) d = self.samweb.descDefinitionDict(defname2) assert defname2 == d[\"defname\"] self.samweb.deleteDefinition(defname2) class",
"testbase import unittest import samweb_client import samweb_cli import time,os defname = 'test-project' class",
"self.assertRaises(samweb_client.exceptions.DefinitionNotFound, self.samweb.descDefinition, fake_def_name) self.assertRaises(samweb_client.exceptions.DefinitionNotFound, self.samweb.descDefinitionDict, fake_def_name) def test_descDefinition(self): output = self.samweb.descDefinition(defname) assert defname",
"'samweb_client_test_def_%s_%d' % (os.getpid(), int(time.time())) self.samweb.createDefinition(defname, \"file_name dummy\", \"illingwo\", \"samdev\") d = self.samweb.descDefinition(defname) assert",
"self.assertRaises(samweb_client.exceptions.DefinitionNotFound, self.samweb.descDefinitionDict, fake_def_name) def test_descDefinition(self): output = self.samweb.descDefinition(defname) assert defname in output d",
"= '-e samdev take-snapshot %s' % defname self.check_cmd_return(cmdline.split()) assert \"1\\n\" == self.stdout if",
"assert d['defname'] == defname def test_snapshot(self): output = self.samweb.takeSnapshot(defname) self.assertEquals(int(output),1) def test_create_rename_delete_definition(self): defname",
"time.time() self.assertRaises(samweb_client.exceptions.DefinitionNotFound, self.samweb.descDefinition, fake_def_name) self.assertRaises(samweb_client.exceptions.DefinitionNotFound, self.samweb.descDefinitionDict, fake_def_name) def test_descDefinition(self): output = self.samweb.descDefinition(defname) assert",
"fake_def_name) self.assertRaises(samweb_client.exceptions.DefinitionNotFound, self.samweb.descDefinitionDict, fake_def_name) def test_descDefinition(self): output = self.samweb.descDefinition(defname) assert defname in output",
"= self.samweb.descDefinitionDict(defname2) assert defname2 == d[\"defname\"] self.samweb.deleteDefinition(defname2) class TestDefinitionCommands(testbase.SAMWebCmdTest): def test_takeSnapshot(self): cmdline =",
"samweb_cli import time,os defname = 'test-project' class TestDefinition(testbase.SamdevTest): def test_descDefinition_DefNotFound(self): fake_def_name = 'doesnotexist_%d'",
"defname in d d = self.samweb.descDefinitionDict(defname) assert defname == d[\"defname\"] defname2 = defname",
"= self.samweb.descDefinition(defname) assert defname in d d = self.samweb.descDefinitionDict(defname) assert defname == d[\"defname\"]",
"== defname def test_snapshot(self): output = self.samweb.takeSnapshot(defname) self.assertEquals(int(output),1) def test_create_rename_delete_definition(self): defname = 'samweb_client_test_def_%s_%d'",
"= self.samweb.descDefinitionDict(defname) assert d['defname'] == defname def test_snapshot(self): output = self.samweb.takeSnapshot(defname) self.assertEquals(int(output),1) def",
"defname = 'samweb_client_test_def_%s_%d' % (os.getpid(), int(time.time())) self.samweb.createDefinition(defname, \"file_name dummy\", \"illingwo\", \"samdev\") d =",
"def test_create_rename_delete_definition(self): defname = 'samweb_client_test_def_%s_%d' % (os.getpid(), int(time.time())) self.samweb.createDefinition(defname, \"file_name dummy\", \"illingwo\", \"samdev\")",
"assert defname in output d = self.samweb.descDefinitionDict(defname) assert d['defname'] == defname def test_snapshot(self):",
"self.samweb.deleteDefinition(defname2) class TestDefinitionCommands(testbase.SAMWebCmdTest): def test_takeSnapshot(self): cmdline = '-e samdev take-snapshot %s' % defname",
"self.samweb.modifyDefinition(defname,defname=defname2) d = self.samweb.descDefinitionDict(defname2) assert defname2 == d[\"defname\"] self.samweb.deleteDefinition(defname2) class TestDefinitionCommands(testbase.SAMWebCmdTest): def test_takeSnapshot(self):",
"(os.getpid(), int(time.time())) self.samweb.createDefinition(defname, \"file_name dummy\", \"illingwo\", \"samdev\") d = self.samweb.descDefinition(defname) assert defname in",
"test_create_rename_delete_definition(self): defname = 'samweb_client_test_def_%s_%d' % (os.getpid(), int(time.time())) self.samweb.createDefinition(defname, \"file_name dummy\", \"illingwo\", \"samdev\") d",
"defname == d[\"defname\"] defname2 = defname + '_2' self.samweb.modifyDefinition(defname,defname=defname2) d = self.samweb.descDefinitionDict(defname2) assert",
"assert defname2 == d[\"defname\"] self.samweb.deleteDefinition(defname2) class TestDefinitionCommands(testbase.SAMWebCmdTest): def test_takeSnapshot(self): cmdline = '-e samdev",
"take-snapshot %s' % defname self.check_cmd_return(cmdline.split()) assert \"1\\n\" == self.stdout if __name__ == '__main__':",
"\"file_name dummy\", \"illingwo\", \"samdev\") d = self.samweb.descDefinition(defname) assert defname in d d =",
"def test_descDefinition_DefNotFound(self): fake_def_name = 'doesnotexist_%d' % time.time() self.assertRaises(samweb_client.exceptions.DefinitionNotFound, self.samweb.descDefinition, fake_def_name) self.assertRaises(samweb_client.exceptions.DefinitionNotFound, self.samweb.descDefinitionDict, fake_def_name)",
"samweb_client import samweb_cli import time,os defname = 'test-project' class TestDefinition(testbase.SamdevTest): def test_descDefinition_DefNotFound(self): fake_def_name",
"in d d = self.samweb.descDefinitionDict(defname) assert defname == d[\"defname\"] defname2 = defname +",
"samdev take-snapshot %s' % defname self.check_cmd_return(cmdline.split()) assert \"1\\n\" == self.stdout if __name__ ==",
"= self.samweb.descDefinitionDict(defname) assert defname == d[\"defname\"] defname2 = defname + '_2' self.samweb.modifyDefinition(defname,defname=defname2) d",
"% (os.getpid(), int(time.time())) self.samweb.createDefinition(defname, \"file_name dummy\", \"illingwo\", \"samdev\") d = self.samweb.descDefinition(defname) assert defname",
"output d = self.samweb.descDefinitionDict(defname) assert d['defname'] == defname def test_snapshot(self): output = self.samweb.takeSnapshot(defname)",
"test_snapshot(self): output = self.samweb.takeSnapshot(defname) self.assertEquals(int(output),1) def test_create_rename_delete_definition(self): defname = 'samweb_client_test_def_%s_%d' % (os.getpid(), int(time.time()))",
"fake_def_name = 'doesnotexist_%d' % time.time() self.assertRaises(samweb_client.exceptions.DefinitionNotFound, self.samweb.descDefinition, fake_def_name) self.assertRaises(samweb_client.exceptions.DefinitionNotFound, self.samweb.descDefinitionDict, fake_def_name) def test_descDefinition(self):",
"self.samweb.createDefinition(defname, \"file_name dummy\", \"illingwo\", \"samdev\") d = self.samweb.descDefinition(defname) assert defname in d d",
"d = self.samweb.descDefinition(defname) assert defname in d d = self.samweb.descDefinitionDict(defname) assert defname ==",
"TestDefinitionCommands(testbase.SAMWebCmdTest): def test_takeSnapshot(self): cmdline = '-e samdev take-snapshot %s' % defname self.check_cmd_return(cmdline.split()) assert",
"self.samweb.descDefinition, fake_def_name) self.assertRaises(samweb_client.exceptions.DefinitionNotFound, self.samweb.descDefinitionDict, fake_def_name) def test_descDefinition(self): output = self.samweb.descDefinition(defname) assert defname in",
"= defname + '_2' self.samweb.modifyDefinition(defname,defname=defname2) d = self.samweb.descDefinitionDict(defname2) assert defname2 == d[\"defname\"] self.samweb.deleteDefinition(defname2)",
"= self.samweb.descDefinition(defname) assert defname in output d = self.samweb.descDefinitionDict(defname) assert d['defname'] == defname",
"#! /usr/bin/env python import testbase import unittest import samweb_client import samweb_cli import time,os",
"class TestDefinition(testbase.SamdevTest): def test_descDefinition_DefNotFound(self): fake_def_name = 'doesnotexist_%d' % time.time() self.assertRaises(samweb_client.exceptions.DefinitionNotFound, self.samweb.descDefinition, fake_def_name) self.assertRaises(samweb_client.exceptions.DefinitionNotFound,",
"unittest import samweb_client import samweb_cli import time,os defname = 'test-project' class TestDefinition(testbase.SamdevTest): def",
"== d[\"defname\"] self.samweb.deleteDefinition(defname2) class TestDefinitionCommands(testbase.SAMWebCmdTest): def test_takeSnapshot(self): cmdline = '-e samdev take-snapshot %s'",
"% time.time() self.assertRaises(samweb_client.exceptions.DefinitionNotFound, self.samweb.descDefinition, fake_def_name) self.assertRaises(samweb_client.exceptions.DefinitionNotFound, self.samweb.descDefinitionDict, fake_def_name) def test_descDefinition(self): output = self.samweb.descDefinition(defname)",
"self.assertEquals(int(output),1) def test_create_rename_delete_definition(self): defname = 'samweb_client_test_def_%s_%d' % (os.getpid(), int(time.time())) self.samweb.createDefinition(defname, \"file_name dummy\", \"illingwo\",",
"defname = 'test-project' class TestDefinition(testbase.SamdevTest): def test_descDefinition_DefNotFound(self): fake_def_name = 'doesnotexist_%d' % time.time() self.assertRaises(samweb_client.exceptions.DefinitionNotFound,",
"'_2' self.samweb.modifyDefinition(defname,defname=defname2) d = self.samweb.descDefinitionDict(defname2) assert defname2 == d[\"defname\"] self.samweb.deleteDefinition(defname2) class TestDefinitionCommands(testbase.SAMWebCmdTest): def",
"defname2 == d[\"defname\"] self.samweb.deleteDefinition(defname2) class TestDefinitionCommands(testbase.SAMWebCmdTest): def test_takeSnapshot(self): cmdline = '-e samdev take-snapshot",
"def test_descDefinition(self): output = self.samweb.descDefinition(defname) assert defname in output d = self.samweb.descDefinitionDict(defname) assert",
"self.samweb.descDefinitionDict(defname) assert defname == d[\"defname\"] defname2 = defname + '_2' self.samweb.modifyDefinition(defname,defname=defname2) d =",
"self.samweb.takeSnapshot(defname) self.assertEquals(int(output),1) def test_create_rename_delete_definition(self): defname = 'samweb_client_test_def_%s_%d' % (os.getpid(), int(time.time())) self.samweb.createDefinition(defname, \"file_name dummy\",",
"cmdline = '-e samdev take-snapshot %s' % defname self.check_cmd_return(cmdline.split()) assert \"1\\n\" == self.stdout",
"%s' % defname self.check_cmd_return(cmdline.split()) assert \"1\\n\" == self.stdout if __name__ == '__main__': unittest.main()",
"defname in output d = self.samweb.descDefinitionDict(defname) assert d['defname'] == defname def test_snapshot(self): output",
"self.samweb.descDefinitionDict(defname) assert d['defname'] == defname def test_snapshot(self): output = self.samweb.takeSnapshot(defname) self.assertEquals(int(output),1) def test_create_rename_delete_definition(self):",
"= 'test-project' class TestDefinition(testbase.SamdevTest): def test_descDefinition_DefNotFound(self): fake_def_name = 'doesnotexist_%d' % time.time() self.assertRaises(samweb_client.exceptions.DefinitionNotFound, self.samweb.descDefinition,",
"def test_snapshot(self): output = self.samweb.takeSnapshot(defname) self.assertEquals(int(output),1) def test_create_rename_delete_definition(self): defname = 'samweb_client_test_def_%s_%d' % (os.getpid(),",
"class TestDefinitionCommands(testbase.SAMWebCmdTest): def test_takeSnapshot(self): cmdline = '-e samdev take-snapshot %s' % defname self.check_cmd_return(cmdline.split())",
"python import testbase import unittest import samweb_client import samweb_cli import time,os defname =",
"self.samweb.descDefinitionDict, fake_def_name) def test_descDefinition(self): output = self.samweb.descDefinition(defname) assert defname in output d =",
"self.samweb.descDefinition(defname) assert defname in output d = self.samweb.descDefinitionDict(defname) assert d['defname'] == defname def",
"import unittest import samweb_client import samweb_cli import time,os defname = 'test-project' class TestDefinition(testbase.SamdevTest):",
"== d[\"defname\"] defname2 = defname + '_2' self.samweb.modifyDefinition(defname,defname=defname2) d = self.samweb.descDefinitionDict(defname2) assert defname2",
"'doesnotexist_%d' % time.time() self.assertRaises(samweb_client.exceptions.DefinitionNotFound, self.samweb.descDefinition, fake_def_name) self.assertRaises(samweb_client.exceptions.DefinitionNotFound, self.samweb.descDefinitionDict, fake_def_name) def test_descDefinition(self): output =",
"assert defname == d[\"defname\"] defname2 = defname + '_2' self.samweb.modifyDefinition(defname,defname=defname2) d = self.samweb.descDefinitionDict(defname2)",
"TestDefinition(testbase.SamdevTest): def test_descDefinition_DefNotFound(self): fake_def_name = 'doesnotexist_%d' % time.time() self.assertRaises(samweb_client.exceptions.DefinitionNotFound, self.samweb.descDefinition, fake_def_name) self.assertRaises(samweb_client.exceptions.DefinitionNotFound, self.samweb.descDefinitionDict,",
"import testbase import unittest import samweb_client import samweb_cli import time,os defname = 'test-project'",
"= self.samweb.takeSnapshot(defname) self.assertEquals(int(output),1) def test_create_rename_delete_definition(self): defname = 'samweb_client_test_def_%s_%d' % (os.getpid(), int(time.time())) self.samweb.createDefinition(defname, \"file_name",
"test_takeSnapshot(self): cmdline = '-e samdev take-snapshot %s' % defname self.check_cmd_return(cmdline.split()) assert \"1\\n\" ==",
"d['defname'] == defname def test_snapshot(self): output = self.samweb.takeSnapshot(defname) self.assertEquals(int(output),1) def test_create_rename_delete_definition(self): defname =",
"d = self.samweb.descDefinitionDict(defname2) assert defname2 == d[\"defname\"] self.samweb.deleteDefinition(defname2) class TestDefinitionCommands(testbase.SAMWebCmdTest): def test_takeSnapshot(self): cmdline",
"d = self.samweb.descDefinitionDict(defname) assert defname == d[\"defname\"] defname2 = defname + '_2' self.samweb.modifyDefinition(defname,defname=defname2)",
"output = self.samweb.takeSnapshot(defname) self.assertEquals(int(output),1) def test_create_rename_delete_definition(self): defname = 'samweb_client_test_def_%s_%d' % (os.getpid(), int(time.time())) self.samweb.createDefinition(defname,",
"d[\"defname\"] self.samweb.deleteDefinition(defname2) class TestDefinitionCommands(testbase.SAMWebCmdTest): def test_takeSnapshot(self): cmdline = '-e samdev take-snapshot %s' %"
] |
[
"index(int): Index. batch_size(int): Batch Size. max_len_src(int): Max length for resource. max_len_trg(int): Max length",
"* (max_src_len - len(line)) for line in sorted_src_lines ] input_lines_trg = [ [",
"self.src[idx][\"data\"] = [] self.trg[idx][\"data\"] = [] # Populate buffer for src, trg in",
"] sent1 = Variable(torch.LongTensor(sent1)).cuda() sent2 = Variable(torch.LongTensor(sent2)).cuda() labels = Variable(torch.LongTensor(labels)).cuda() sent1_lens = (",
"else: sorted_words = [x[0] for x in sorted_word2id] for ind, word in enumerate(sorted_words):",
"word not in vocab: vocab[word] = 1 else: vocab[word] += 1 word2id, id2word",
"need to reset the contents of the current buffer. \"\"\" # Reset the",
"Change to python3+. # from itertools import zip class DataIterator(object): \"\"\"Data Iterator.\"\"\" @staticmethod",
"- len(line)) for line in sorted_trg_lines ] # For pytroch 0.4 with torch.no_grad():",
"Check if save directory exists. if not os.path.exists(self.save_dir): raise ValueError(\"Could not find save",
"self.word2id[\"<unk>\"] for w in line ] + [self.word2id[\"<pad>\"]] * (max_sent2_len - len(line)) for",
"vocab: del vocab[\"<pad>\"] if \"</s>\" in vocab: del vocab[\"</s>\"] if \"<unk>\" in vocab:",
"the files. self.f_src = [ open(fname, \"r\", encoding=\"utf-8\") for fname in self.fname_src ]",
"of train/dev/test is a tab-separate file of the form premise \\t hypothesis \\t",
"sorted_word2id[:vocab_size]] else: sorted_words = [x[0] for x in sorted_word2id] for ind, word in",
"tasknames(list): The list of task names. save_dir(str): The saving dir. buffer_size(float): Buffer size.",
"= Variable(torch.LongTensor(input_lines_trg)).cuda() output_lines_trg = Variable(torch.LongTensor(output_lines_trg)).cuda() # sorted_src_lens = Variable( # torch.LongTensor(sorted_src_lens) # ).squeeze().cuda()",
"numpy as np import torch from sklearn.utils import shuffle from torch.autograd import Variable",
"\"seq2seq\", } class NLIIterator(DataIterator): \"\"\"Data iterator for tokenized NLI datasets.\"\"\" def __init__( self,",
"to avoid issue with calling .append above self.src[idx][\"data\"] = list(self.src[idx][\"data\"]) self.trg[idx][\"data\"] = list(self.trg[idx][\"data\"])",
"\"\"\"Sort sentences by decreasing length within a minibatch for `torch.nn.utils.packed_padded_sequence`\"\"\" src_lens = [len(line)",
"\"<pad>\", 2: \"</s>\", 3: \"<unk>\"} sorted_word2id = sorted( vocab.items(), key=operator.itemgetter(1), reverse=True ) if",
"[ {\"data\": [], \"word2id\": None, \"id2word\": None} for i in range(len(self.fname_trg)) ] self.build_vocab()",
"self.lowercase = lowercase # Open a list of file pointers to all the",
"len(self.trg[idx][\"data\"]) # Cast things to list to avoid issue with calling .append above",
"if isinstance(sentence, str): if lowercase: sentence = sentence.lower() if not charlevel: sentence =",
"self.src[corpus_idx][\"word2id\"] else self.src[corpus_idx][\"word2id\"][\"<unk>\"] for w in line ] + [self.src[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_src_len -",
"4] = word return word2id, id2word def construct_vocab( self, sentences, vocab_size, lowercase=False, charlevel=False",
"else: vocab[word] += 1 word2id, id2word = self._trim_vocab(vocab, vocab_size) return word2id, id2word class",
"= Variable(torch.LongTensor(input_lines_trg)).cuda() output_lines_trg = Variable(torch.LongTensor(output_lines_trg)).cuda() sorted_src_lens = ( Variable(torch.LongTensor(sorted_src_lens), volatile=True) .squeeze() .cuda() )",
"in enumerate(sorted_words): word2id[word] = ind + 4 for ind, word in enumerate(sorted_words): id2word[ind",
"vocab[\"word2id\"], vocab[\"id2word\"] # If not, compute the vocab from scratch and store a",
"vocab. trg_vocab_size(int): The size of target vocab. tasknames(list): The list of task names.",
"argument self.vocab = pickle.load(open(self.vocab, \"rb\")) self.word2id = self.vocab[\"word2id\"] self.id2word = self.vocab[\"id2word\"] self.vocab_size =",
"\"id2word\": None} for i in range(len(self.fname_src)) ] self.trg = [ {\"data\": [], \"word2id\":",
"= [sent2[idx] for idx in sorted_sent2_indices] rev_sent2 = np.argsort(sorted_sent2_indices) sorted_sent1_lens = [len(line) for",
"enumerate(sorted_words): word2id[word] = ind + 4 for ind, word in enumerate(sorted_words): id2word[ind +",
"= Variable(torch.LongTensor(input_lines_src)).cuda() input_lines_trg = Variable(torch.LongTensor(input_lines_trg)).cuda() output_lines_trg = Variable(torch.LongTensor(output_lines_trg)).cuda() # sorted_src_lens = Variable( #",
"word return word2id, id2word def construct_vocab( self, sentences, vocab_size, lowercase=False, charlevel=False ): \"\"\"Create",
"] input_lines_trg = [ [ trg_word2id[w] if w in trg_word2id else trg_word2id[\"<unk>\"] for",
"for src, trg in zip(self.f_src[idx], self.f_trg[idx]): if len(self.src[idx][\"data\"]) == self.buffer_size: break if self.lowercase:",
"[self.word2id[\"<pad>\"]] * (max_sent1_len - len(line)) for line in sorted_sent1_lines ] sent2 = [",
"lists to torch tensors input_lines_src = Variable(torch.LongTensor(input_lines_src)).cuda() input_lines_trg = Variable(torch.LongTensor(input_lines_trg)).cuda() output_lines_trg = Variable(torch.LongTensor(output_lines_trg)).cuda()",
"itertools import zip class DataIterator(object): \"\"\"Data Iterator.\"\"\" @staticmethod def _trim_vocab(vocab, vocab_size): \"\"\"Discard start,",
"for x in self.train_lines] + [x[1] for x in self.train_lines], self.vocab_size, lowercase=self.lowercase, )",
"config, model, train_iterator, criterion, task_idx, lowercase=False ): \"\"\"Compute validation loss for a task.",
"sentences. reset(bool): If need to reset the contents of the current buffer. \"\"\"",
"get_parallel_minibatch(self, index, batch_size, sent_type=\"train\"): \"\"\"Prepare minibatch. Args: index(int): The index for line. batch_size(int):",
"sentence.split() for word in sentence: if word not in vocab: vocab[word] = 1",
"else: self.src[idx][\"data\"].append(src.split()) self.trg[idx][\"data\"].append(trg.split()) # Sort sentences by decreasing length (hacky bucketing) self.src[idx][\"data\"], self.trg[idx][\"data\"]",
"for fname in self.fname_trg ] # Initialize dictionaries that contain sentences & word",
"= self.vocab[\"id2word\"] self.vocab_size = len(self.word2id) else: self.word2id, self.id2word = self.construct_vocab( [x[0] for x",
"= [len(line) for line in src_lines] sorted_indices = np.argsort(src_lens)[::-1] sorted_src_lines = [src_lines[idx] for",
"self._reset_filepointer(idx) for idx in range(len(self.src)): self.fetch_buffer(idx) def _reset_filepointer(self, idx): \"\"\"Reset file pointer. Args:",
"for line in sorted_trg_lines ] # For pytroch 0.4 with torch.no_grad(): input_lines_src =",
"sorted_words = [x[0] for x in sorted_word2id] for ind, word in enumerate(sorted_words): word2id[word]",
"decreasing length (hacky bucketing) self.src[idx][\"data\"], self.trg[idx][\"data\"] = zip( *sorted( zip(self.src[idx][\"data\"], self.trg[idx][\"data\"]), key=lambda x:",
".cuda() ) return { \"input_src\": input_lines_src, \"input_trg\": input_lines_trg, \"output_trg\": output_lines_trg, \"src_lens\": sorted_src_lens, \"type\":",
"*sorted( zip(self.src[idx][\"data\"], self.trg[idx][\"data\"]), key=lambda x: len(x[0]), reverse=True, ) ) \"\"\"If buffer isn't full",
"the target vocabulary. if os.path.exists(os.path.join(self.save_dir, \"trg_vocab.pkl\")): vocab = pickle.load( open(os.path.join(self.save_dir, \"trg_vocab.pkl\"), \"rb\") )",
"id2word[ind + 4] = word return word2id, id2word def construct_vocab( self, sentences, vocab_size,",
"} class NLIIterator(DataIterator): \"\"\"Data iterator for tokenized NLI datasets.\"\"\" def __init__( self, train,",
"= self.dev_lines else: lines = self.test_lines sent1 = [ [\"<s>\"] + line[0].split() +",
"index for source. trg_word2id(list): Word to index for target. Returns: Dict for seq2seq",
"vocab_size(int): The size of the vocabulary. lowercase(bool): If lowercase the dataset. vocab(Union[bytes,str): The",
"for w in line ] + [self.word2id[\"<pad>\"]] * (max_sent2_len - len(line)) for line",
"id2word = self.construct_vocab( itertools.chain.from_iterable(self.f_src), self.src_vocab_size, self.lowercase, ) pickle.dump( {\"word2id\": word2id, \"id2word\": id2word}, open(os.path.join(self.save_dir,",
"All rights reserved. # Licensed under the MIT License. \"\"\"Minibatching utilities.\"\"\" import itertools",
"= [ [\"<s>\"] + line[: max_len_trg - 2] + [\"</s>\"] for line in",
"a cache. else: word2id, id2word = self.construct_vocab( itertools.chain.from_iterable(self.f_src), self.src_vocab_size, self.lowercase, ) pickle.dump( {\"word2id\":",
"] + [self.src[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_src_len - len(line)) for line in sorted_src_lines ] input_lines_trg",
"w in self.trg[corpus_idx][\"word2id\"] else self.trg[corpus_idx][\"word2id\"][\"<unk>\"] for w in line[1:] ] + [self.trg[corpus_idx][\"word2id\"][\"<pad>\"]] *",
"= word2id trg_vocab_dump[self.tasknames[idx]][\"id2word\"] = id2word pickle.dump( trg_vocab_dump, open(os.path.join(self.save_dir, \"trg_vocab.pkl\"), \"wb\"), ) def shuffle_dataset(self,",
"idx(int): Index used to fetch the sentences. reset(bool): If need to reset the",
"self.trg[corpus_idx][\"word2id\"] else self.trg[corpus_idx][\"word2id\"][\"<unk>\"] for w in line[1:] ] + [self.trg[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_trg_len -",
"\"sent1\": sent1, \"sent2\": sent2, \"sent1_lens\": sent1_lens, \"sent2_lens\": sent2_lens, \"rev_sent1\": rev_sent1, \"rev_sent2\": rev_sent2, \"labels\":",
"words to indices input_lines_src = [ [ self.src[corpus_idx][\"word2id\"][w] if w in self.src[corpus_idx][\"word2id\"] else",
"of src-trg pairs return { \"input_src\": input_lines_src, \"input_trg\": input_lines_trg, \"output_trg\": output_lines_trg, \"src_lens\": sorted_src_lens,",
"* (max_trg_len - len(line)) for line in sorted_trg_lines ] # Cast lists to",
"= config[\"data\"][\"paths\"][task_idx][\"val_src\"] val_trg = config[\"data\"][\"paths\"][task_idx][\"val_trg\"] if lowercase: val_src = [ line.strip().lower().split() for line",
"minibatch. Args: index(int): The index for line. batch_size(int): Batch size. sent_type(str): Type of",
"not os.path.exists(self.save_dir): raise ValueError(\"Could not find save dir : %s\" % self.save_dir) #",
"self.fname_trg = trg self.src_vocab_size = src_vocab_size self.trg_vocab_size = trg_vocab_size self.tasknames = tasknames self.save_dir",
"sent_type=\"train\"): \"\"\"Prepare minibatch. Args: index(int): The index for line. batch_size(int): Batch size. sent_type(str):",
"with torch.no_grad(): input_lines_src = Variable(torch.LongTensor(input_lines_src)).cuda() input_lines_trg = Variable(torch.LongTensor(input_lines_trg)).cuda() output_lines_trg = Variable(torch.LongTensor(output_lines_trg)).cuda() # sorted_src_lens",
"lowercase=False, seed=0, ): \"\"\"Initialize params. Args: src(list): source dataset. trg(list): target dataset. src_vocab_size(int):",
"self.src[corpus_idx][\"data\"][ index : index + batch_size ] ] trg_lines = [ [\"<s>\"] +",
"corpus[\"word2id\"], corpus[\"id2word\"] = word2id, id2word # Do the same for the target vocabulary.",
"calling .append above self.src[idx][\"data\"] = list(self.src[idx][\"data\"]) self.trg[idx][\"data\"] = list(self.trg[idx][\"data\"]) self._reset_filepointer(idx) self.fetch_buffer(idx, reset=False) def",
"model(minibatch, task_idx) loss = criterion( decoder_logit.contiguous().view(-1, decoder_logit.size(2)), minibatch[\"output_trg\"].contiguous().view(-1), ) # losses.append(loss.data[0]) losses.append(loss.item()) return",
"sorted_src_lens, \"type\": \"seq2seq\", } def compute_validation_loss( config, model, train_iterator, criterion, task_idx, lowercase=False ):",
"index + batch_size] ] labels = [ self.text2label[line[2]] for line in lines[index :",
"rev_sent2 = ( Variable(torch.LongTensor(rev_sent2), requires_grad=False) .squeeze() .cuda() ) return { \"sent1\": sent1, \"sent2\":",
"and unk tokens if already present. Args: vocab(list): Vocabulary. vocab_size(int): The size of",
"\"nli\", } def get_validation_minibatch( src, trg, index, batch_size, src_word2id, trg_word2id ): \"\"\"Prepare minibatch.",
"idx, (corpus, fname) in enumerate(zip(self.trg, self.f_trg)): word2id, id2word = self.construct_vocab( fname, self.trg_vocab_size, self.lowercase",
"buffer_size self.lowercase = lowercase # Open a list of file pointers to all",
"val_src = config[\"data\"][\"paths\"][task_idx][\"val_src\"] val_trg = config[\"data\"][\"paths\"][task_idx][\"val_trg\"] if lowercase: val_src = [ line.strip().lower().split() for",
"Args: src(list): source dataset. trg(list): target dataset. src_vocab_size(int): The size of source vocab.",
"The size of source vocab. trg_vocab_size(int): The size of target vocab. tasknames(list): The",
"= self._trim_vocab(vocab, vocab_size) return word2id, id2word class BufferedDataIterator(DataIterator): \"\"\"Multi Parallel corpus data iterator.\"\"\"",
"trg_vocab_dump = {} for idx, (corpus, fname) in enumerate(zip(self.trg, self.f_trg)): word2id, id2word =",
"\"\"\"Data Iterator.\"\"\" @staticmethod def _trim_vocab(vocab, vocab_size): \"\"\"Discard start, end, pad and unk tokens",
"issue with calling .append above self.src[idx][\"data\"] = list(self.src[idx][\"data\"]) self.trg[idx][\"data\"] = list(self.trg[idx][\"data\"]) self._reset_filepointer(idx) self.fetch_buffer(idx,",
"self.src_vocab_size, self.lowercase, ) pickle.dump( {\"word2id\": word2id, \"id2word\": id2word}, open(os.path.join(self.save_dir, \"src_vocab.pkl\"), \"wb\"), ) for",
"range(len(self.fname_trg)) ] self.build_vocab() \"\"\"Reset file pointers to the start after reading the file",
"for w in line ] + [self.word2id[\"<pad>\"]] * (max_sent1_len - len(line)) for line",
"[trg_word2id[\"<pad>\"]] * (max_trg_len - len(line)) for line in sorted_trg_lines ] # For pytroch",
"# Reset the contents of the current buffer. if reset: self.src[idx][\"data\"] = []",
"vocabulary. if os.path.exists(os.path.join(self.save_dir, \"trg_vocab.pkl\")): vocab = pickle.load( open(os.path.join(self.save_dir, \"trg_vocab.pkl\"), \"rb\") ) for idx,",
"get_parallel_minibatch( self, corpus_idx, index, batch_size, max_len_src, max_len_trg ): \"\"\"Prepare minibatch. Args: corpus_idx(int): Corpus",
"[ {\"data\": [], \"word2id\": None, \"id2word\": None} for i in range(len(self.fname_src)) ] self.trg",
"- len(line)) for line in sorted_sent1_lines ] sent2 = [ [ self.word2id[w] if",
".cuda() ) return { \"sent1\": sent1, \"sent2\": sent2, \"sent1_lens\": sent1_lens, \"sent2_lens\": sent2_lens, \"rev_sent1\":",
"pointers to all the files. self.f_src = [ open(fname, \"r\", encoding=\"utf-8\") for fname",
"= [x[0] for x in sorted_word2id[:vocab_size]] else: sorted_words = [x[0] for x in",
"src(list): source dataset. trg(list): target dataset. src_vocab_size(int): The size of source vocab. trg_vocab_size(int):",
"self.vocab_size = vocab_size self.lowercase = lowercase self.vocab = vocab self.train_lines = [ line.strip().lower().split(\"\\t\")",
"self.src[corpus_idx][\"word2id\"][\"<unk>\"] for w in line ] + [self.src[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_src_len - len(line)) for",
"2] + [\"</s>\"] for line in self.src[corpus_idx][\"data\"][ index : index + batch_size ]",
"zip( *sorted( zip(self.src[idx][\"data\"], self.trg[idx][\"data\"]), key=lambda x: len(x[0]), reverse=True, ) ) \"\"\"If buffer isn't",
"Variable(torch.LongTensor(input_lines_src)).cuda() input_lines_trg = Variable(torch.LongTensor(input_lines_trg)).cuda() output_lines_trg = Variable(torch.LongTensor(output_lines_trg)).cuda() sorted_src_lens = ( Variable(torch.LongTensor(sorted_src_lens), volatile=True) .squeeze()",
"index + batch_size] ] src_lens = [len(line) for line in src_lines] sorted_indices =",
"len(line)) for line in sorted_trg_lines ] # Cast lists to torch tensors input_lines_src",
"index list. id2word(list): Index to word list. \"\"\" if \"<s>\" in vocab: del",
"if len(self.src[idx][\"data\"]) < self.buffer_size: assert len(self.src[idx][\"data\"]) == len(self.trg[idx][\"data\"]) # Cast things to list",
"Size. max_len_src(int): Max length for resource. max_len_trg(int): Max length ofr target. Returns: minibatch",
"self.trg_vocab_size = trg_vocab_size self.tasknames = tasknames self.save_dir = save_dir self.buffer_size = buffer_size self.lowercase",
"self.construct_vocab( itertools.chain.from_iterable(self.f_src), self.src_vocab_size, self.lowercase, ) pickle.dump( {\"word2id\": word2id, \"id2word\": id2word}, open(os.path.join(self.save_dir, \"src_vocab.pkl\"), \"wb\"),",
"= self.vocab[\"word2id\"] self.id2word = self.vocab[\"id2word\"] self.vocab_size = len(self.word2id) else: self.word2id, self.id2word = self.construct_vocab(",
") if vocab_size != -1: sorted_words = [x[0] for x in sorted_word2id[:vocab_size]] else:",
"\"rb\")) self.word2id = self.vocab[\"word2id\"] self.id2word = self.vocab[\"id2word\"] self.vocab_size = len(self.word2id) else: self.word2id, self.id2word",
"def _reset_filepointer(self, idx): \"\"\"Reset file pointer. Args: idx(int): Index used to reset file",
"for the file. batch_size(int): batch size. src_word2id(list): Word to index for source. trg_word2id(list):",
"open(val_trg, \"r\", encoding=\"utf-8\") ] else: val_src = [ line.strip().split() for line in open(val_src,",
"= len(self.word2id) else: self.word2id, self.id2word = self.construct_vocab( [x[0] for x in self.train_lines] +",
"+ line[: max_len_trg - 2] + [\"</s>\"] for line in self.trg[corpus_idx][\"data\"][ index :",
"The size of the vocabulary. lowercase(bool): If lowercase the dataset. vocab(Union[bytes,str): The list",
"open(self.fname_src[idx], \"r\", encoding=\"utf-8\") self.f_trg[idx] = open(self.fname_trg[idx], \"r\", encoding=\"utf-8\") def fetch_buffer(self, idx, reset=True): \"\"\"Fetch",
"reading the contents of the file, cycle around. \"\"\" if len(self.src[idx][\"data\"]) < self.buffer_size:",
"= test self.vocab_size = vocab_size self.lowercase = lowercase self.vocab = vocab self.train_lines =",
"in sorted_src_lines ] input_lines_trg = [ [ trg_word2id[w] if w in trg_word2id else",
"sorted_src_lines] sorted_trg_lens = [len(line) for line in sorted_trg_lines] max_src_len = max(sorted_src_lens) max_trg_len =",
"source data. trg(list): target data. index(int): index for the file. batch_size(int): batch size.",
"] else: val_src = [ line.strip().split() for line in open(val_src, \"r\", encoding=\"utf-8\") ]",
"\"src_lens\": sorted_src_lens, \"type\": \"seq2seq\", } def compute_validation_loss( config, model, train_iterator, criterion, task_idx, lowercase=False",
"[ [\"<s>\"] + line[1].split() + [\"</s>\"] for line in lines[index : index +",
") rev_sent2 = ( Variable(torch.LongTensor(rev_sent2), requires_grad=False) .squeeze() .cuda() ) return { \"sent1\": sent1,",
"open(val_trg, \"r\", encoding=\"utf-8\") ] batch_size = config[\"training\"][\"batch_size\"] losses = [] for j in",
"save_dir(str): The saving dir. buffer_size(float): Buffer size. lowercase(bool): if lowercase the data. \"\"\"",
"enumerate(zip(self.trg, self.f_trg)): word2id, id2word = self.construct_vocab( fname, self.trg_vocab_size, self.lowercase ) corpus[\"word2id\"], corpus[\"id2word\"] =",
".view(len(sorted_src_lens)) .cuda() ) return { \"input_src\": input_lines_src, \"input_trg\": input_lines_trg, \"output_trg\": output_lines_trg, \"src_lens\": sorted_src_lens,",
"{\"entailment\": 0, \"neutral\": 1, \"contradiction\": 2} self.shuffle_dataset() def shuffle_dataset(self): \"\"\"Shuffle training data.\"\"\" self.train_lines",
"for line in sorted_trg_lines ] output_lines_trg = [ [ self.trg[corpus_idx][\"word2id\"][w] if w in",
"[ [\"<s>\"] + line[: max_len_src - 2] + [\"</s>\"] for line in self.src[corpus_idx][\"data\"][",
"in sentence: if word not in vocab: vocab[word] = 1 else: vocab[word] +=",
"src_lines = [ [\"<s>\"] + line + [\"</s>\"] for line in src[index :",
"line in open(val_trg, \"r\", encoding=\"utf-8\") ] batch_size = config[\"training\"][\"batch_size\"] losses = [] for",
"[ open(fname, \"r\", encoding=\"utf-8\") for fname in self.fname_src ] self.f_trg = [ open(fname,",
"Variable(torch.LongTensor(labels)).cuda() sent1_lens = ( Variable(torch.LongTensor(sorted_sent1_lens), requires_grad=False) .squeeze() .cuda() ) sent2_lens = ( Variable(torch.LongTensor(sorted_sent2_lens),",
"start after reading the file to build vocabularies.\"\"\" for idx in range(len(self.src)): self._reset_filepointer(idx)",
"The saving dir. buffer_size(float): Buffer size. lowercase(bool): if lowercase the data. \"\"\" self.seed",
"vocab = pickle.load( open(os.path.join(self.save_dir, \"trg_vocab.pkl\"), \"rb\") ) for idx, (corpus, fname) in enumerate(zip(self.trg,",
"+ [\"</s>\"] for line in trg[index : index + batch_size] ] src_lens =",
"if lowercase: sentence = sentence.lower() if not charlevel: sentence = sentence.split() for word",
"\"rev_sent2\": rev_sent2, \"labels\": labels, \"type\": \"nli\", } def get_validation_minibatch( src, trg, index, batch_size,",
"Microsoft Corporation. All rights reserved. # Licensed under the MIT License. \"\"\"Minibatching utilities.\"\"\"",
"sorted_src_lens = [len(line) for line in sorted_src_lines] sorted_trg_lens = [len(line) for line in",
"= [ [ trg_word2id[w] if w in trg_word2id else trg_word2id[\"<unk>\"] for w in",
"torch.no_grad(): input_lines_src = Variable(torch.LongTensor(input_lines_src)).cuda() input_lines_trg = Variable(torch.LongTensor(input_lines_trg)).cuda() output_lines_trg = Variable(torch.LongTensor(output_lines_trg)).cuda() # sorted_src_lens =",
"\"input_src\": input_lines_src, \"input_trg\": input_lines_trg, \"output_trg\": output_lines_trg, \"src_lens\": sorted_src_lens, \"type\": \"seq2seq\", } def compute_validation_loss(",
"sorted( vocab.items(), key=operator.itemgetter(1), reverse=True ) if vocab_size != -1: sorted_words = [x[0] for",
"BufferedDataIterator(DataIterator): \"\"\"Multi Parallel corpus data iterator.\"\"\" def __init__( self, src, trg, src_vocab_size, trg_vocab_size,",
"itertools import operator import os import pickle import numpy as np import torch",
"vocab=None, seed=0 ): \"\"\"Initialize params. Each of train/dev/test is a tab-separate file of",
"x in sorted_word2id[:vocab_size]] else: sorted_words = [x[0] for x in sorted_word2id] for ind,",
"for idx in sorted_indices] sorted_trg_lines = [trg_lines[idx] for idx in sorted_indices] sorted_src_lens =",
"sorted_src_lens = ( Variable(torch.LongTensor(sorted_src_lens), volatile=True) .squeeze() .cuda() ) # Return minibatch of src-trg",
"sorted_sent1_lens = [len(line) for line in sorted_sent1_lines] sorted_sent2_lens = [len(line) for line in",
"= save_dir self.buffer_size = buffer_size self.lowercase = lowercase # Open a list of",
"batch training. \"\"\" if sent_type == \"train\": lines = self.train_lines elif sent_type ==",
"sent_type == \"train\": lines = self.train_lines elif sent_type == \"dev\": lines = self.dev_lines",
"losses = [] for j in range(0, len(val_src), batch_size): minibatch = get_validation_minibatch( val_src,",
"for line in sent2] sorted_sent2_indices = np.argsort(sent2_lens)[::-1] sorted_sent2_lines = [sent2[idx] for idx in",
"[ self.word2id[w] if w in self.word2id else self.word2id[\"<unk>\"] for w in line ]",
"lowercase the dataset. vocab(Union[bytes,str): The list of the vocabulary. \"\"\" self.seed = seed",
"in self.word2id else self.word2id[\"<unk>\"] for w in line ] + [self.word2id[\"<pad>\"]] * (max_sent1_len",
"] trg_lines = [ [\"<s>\"] + line + [\"</s>\"] for line in trg[index",
"The size of the vocabulary. Returns: word2id(list): Word to index list. id2word(list): Index",
"in src[index : index + batch_size] ] trg_lines = [ [\"<s>\"] + line",
"the form premise \\t hypothesis \\t label. Args: train(torch.Tensor): Training dataset. dev(torch.Tensor): Validation",
"of target vocab. tasknames(list): The list of task names. save_dir(str): The saving dir.",
"Variable(torch.LongTensor(input_lines_trg)).cuda() output_lines_trg = Variable(torch.LongTensor(output_lines_trg)).cuda() # sorted_src_lens = Variable( # torch.LongTensor(sorted_src_lens) # ).squeeze().cuda() sorted_src_lens",
"2] + [\"</s>\"] for line in self.trg[corpus_idx][\"data\"][ index : index + batch_size ]",
"batch_size] ] trg_lines = [ [\"<s>\"] + line + [\"</s>\"] for line in",
"= max(sorted_sent1_lens) max_sent2_len = max(sorted_sent2_lens) sent1 = [ [ self.word2id[w] if w in",
"= [ line.strip().lower().split(\"\\t\") for line in open(self.test, encoding=\"utf-8\") ] if self.vocab is not",
"in open(val_trg, \"r\", encoding=\"utf-8\") ] batch_size = config[\"training\"][\"batch_size\"] losses = [] for j",
"self.trg[idx][\"data\"].append(trg.lower().split()) else: self.src[idx][\"data\"].append(src.split()) self.trg[idx][\"data\"].append(trg.split()) # Sort sentences by decreasing length (hacky bucketing) self.src[idx][\"data\"],",
"in line[:-1] ] + [trg_word2id[\"<pad>\"]] * (max_trg_len - len(line)) for line in sorted_trg_lines",
"w in trg_word2id else trg_word2id[\"<unk>\"] for w in line[1:] ] + [trg_word2id[\"<pad>\"]] *",
"< self.buffer_size: assert len(self.src[idx][\"data\"]) == len(self.trg[idx][\"data\"]) # Cast things to list to avoid",
"in sorted_word2id] for ind, word in enumerate(sorted_words): word2id[word] = ind + 4 for",
": index + batch_size] ] sent1_lens = [len(line) for line in sent1] sorted_sent1_indices",
"list of task names. save_dir(str): The saving dir. buffer_size(float): Buffer size. lowercase(bool): if",
"of the current buffer. \"\"\" # Reset the contents of the current buffer.",
"doesn't take an encoding argument self.vocab = pickle.load(open(self.vocab, \"rb\")) self.word2id = self.vocab[\"word2id\"] self.id2word",
"id2word(list): Index to word list. \"\"\" if \"<s>\" in vocab: del vocab[\"<s>\"] if",
"== \"dev\": lines = self.dev_lines else: lines = self.test_lines sent1 = [ [\"<s>\"]",
"range(len(self.fname_src)) ] self.trg = [ {\"data\": [], \"word2id\": None, \"id2word\": None} for i",
"[len(line) for line in sent2] sorted_sent2_indices = np.argsort(sent2_lens)[::-1] sorted_sent2_lines = [sent2[idx] for idx",
"# If not, compute the vocab from scratch and store a cache. else:",
"If lowercase the sentences. charlevel(bool): If need to split the sentence with space.",
"build_vocab(self): \"\"\"Build a memory efficient vocab.\"\"\" # Construct common source vocab. # Check",
"= [src_lines[idx] for idx in sorted_indices] sorted_trg_lines = [trg_lines[idx] for idx in sorted_indices]",
"self, train, dev, test, vocab_size, lowercase=True, vocab=None, seed=0 ): \"\"\"Initialize params. Each of",
"in self.train_lines] + [x[1] for x in self.train_lines], self.vocab_size, lowercase=self.lowercase, ) # Label",
"src_lens = [len(line) for line in src_lines] sorted_indices = np.argsort(src_lens)[::-1] sorted_src_lines = [src_lines[idx]",
"= {0: \"<s>\", 1: \"<pad>\", 2: \"</s>\", 3: \"<unk>\"} sorted_word2id = sorted( vocab.items(),",
"\"\"\"Shuffle current buffer.\"\"\" self.src[idx][\"data\"], self.trg[idx][\"data\"] = shuffle( self.src[idx][\"data\"], self.trg[idx][\"data\"], random_state=self.seed, ) def get_parallel_minibatch(",
"line in lines[index : index + batch_size] ] sent2 = [ [\"<s>\"] +",
"lines = self.test_lines sent1 = [ [\"<s>\"] + line[0].split() + [\"</s>\"] for line",
".cuda() ) rev_sent2 = ( Variable(torch.LongTensor(rev_sent2), requires_grad=False) .squeeze() .cuda() ) return { \"sent1\":",
"the data. Returns: float as the mean of the loss. \"\"\" val_src =",
"None} for i in range(len(self.fname_src)) ] self.trg = [ {\"data\": [], \"word2id\": None,",
"of the current buffer. if reset: self.src[idx][\"data\"] = [] self.trg[idx][\"data\"] = [] #",
"= list(self.src[idx][\"data\"]) self.trg[idx][\"data\"] = list(self.trg[idx][\"data\"]) self._reset_filepointer(idx) self.fetch_buffer(idx, reset=False) def build_vocab(self): \"\"\"Build a memory",
"# Cast things to list to avoid issue with calling .append above self.src[idx][\"data\"]",
"): \"\"\"Create vocabulary. Args: sentences(list): The list of sentences. vocab_size(int): The size of",
"np.argsort(sorted_sent2_indices) sorted_sent1_lens = [len(line) for line in sorted_sent1_lines] sorted_sent2_lens = [len(line) for line",
"= [len(line) for line in sent1] sorted_sent1_indices = np.argsort(sent1_lens)[::-1] sorted_sent1_lines = [sent1[idx] for",
"self.word2id[\"<unk>\"] for w in line ] + [self.word2id[\"<pad>\"]] * (max_sent1_len - len(line)) for",
"= {\"<s>\": 0, \"<pad>\": 1, \"</s>\": 2, \"<unk>\": 3} id2word = {0: \"<s>\",",
"by decreasing length within a minibatch for `torch.nn.utils.packed_padded_sequence`\"\"\" src_lens = [len(line) for line",
"volatile=True) .squeeze() .cuda() ) # Return minibatch of src-trg pairs return { \"input_src\":",
"[trg_word2id[\"<pad>\"]] * (max_trg_len - len(line)) for line in sorted_trg_lines ] output_lines_trg = [",
"for target. Returns: Dict for seq2seq model. \"\"\" src_lines = [ [\"<s>\"] +",
"src-trg pairs return { \"input_src\": input_lines_src, \"input_trg\": input_lines_trg, \"output_trg\": output_lines_trg, \"src_lens\": sorted_src_lens, \"type\":",
"= id2word pickle.dump( trg_vocab_dump, open(os.path.join(self.save_dir, \"trg_vocab.pkl\"), \"wb\"), ) def shuffle_dataset(self, idx): \"\"\"Shuffle current",
"\"wb\"), ) for corpus in self.src: corpus[\"word2id\"], corpus[\"id2word\"] = word2id, id2word # Do",
"Variable(torch.LongTensor(output_lines_trg)).cuda() sorted_src_lens = ( Variable(torch.LongTensor(sorted_src_lens), volatile=True) .squeeze() .cuda() ) # Return minibatch of",
"sent2] sorted_sent2_indices = np.argsort(sent2_lens)[::-1] sorted_sent2_lines = [sent2[idx] for idx in sorted_sent2_indices] rev_sent2 =",
"save directory exists. if not os.path.exists(self.save_dir): raise ValueError(\"Could not find save dir :",
"pickle import numpy as np import torch from sklearn.utils import shuffle from torch.autograd",
"# Check if a cached vocab file exists. if os.path.exists(os.path.join(self.save_dir, \"src_vocab.pkl\")): vocab =",
"labels, \"type\": \"nli\", } def get_validation_minibatch( src, trg, index, batch_size, src_word2id, trg_word2id ):",
"[ [ trg_word2id[w] if w in trg_word2id else trg_word2id[\"<unk>\"] for w in line[1:]",
"for w in line] + [src_word2id[\"<pad>\"]] * (max_src_len - len(line)) for line in",
"sentence.lower() if not charlevel: sentence = sentence.split() for word in sentence: if word",
"[] self.trg[idx][\"data\"] = [] # Populate buffer for src, trg in zip(self.f_src[idx], self.f_trg[idx]):",
"+ batch_size ] ] trg_lines = [ [\"<s>\"] + line[: max_len_trg - 2]",
"[\"<s>\"] + line[: max_len_trg - 2] + [\"</s>\"] for line in self.trg[corpus_idx][\"data\"][ index",
"max_src_len = max(sorted_src_lens) max_trg_len = max(sorted_trg_lens) input_lines_src = [ [src_word2id[w] if w in",
"\"r\", encoding=\"utf-8\") def fetch_buffer(self, idx, reset=True): \"\"\"Fetch sentences from the file into the",
"assert len(self.src[idx][\"data\"]) == len(self.trg[idx][\"data\"]) # Cast things to list to avoid issue with",
"\"\"\" # Reset the contents of the current buffer. if reset: self.src[idx][\"data\"] =",
"word2id(list): Word to index list. id2word(list): Index to word list. \"\"\" vocab =",
"if vocab_size != -1: sorted_words = [x[0] for x in sorted_word2id[:vocab_size]] else: sorted_words",
"self.trg[idx][\"data\"] = zip( *sorted( zip(self.src[idx][\"data\"], self.trg[idx][\"data\"]), key=lambda x: len(x[0]), reverse=True, ) ) \"\"\"If",
"[ [ self.src[corpus_idx][\"word2id\"][w] if w in self.src[corpus_idx][\"word2id\"] else self.src[corpus_idx][\"word2id\"][\"<unk>\"] for w in line",
"(corpus, fname) in enumerate(zip(self.trg, self.f_trg)): word2id, id2word = ( vocab[self.tasknames[idx]][\"word2id\"], vocab[self.tasknames[idx]][\"id2word\"], ) corpus[\"word2id\"],",
"mean of the loss. \"\"\" val_src = config[\"data\"][\"paths\"][task_idx][\"val_src\"] val_trg = config[\"data\"][\"paths\"][task_idx][\"val_trg\"] if lowercase:",
"corpus_idx(int): Corpus Index. index(int): Index. batch_size(int): Batch Size. max_len_src(int): Max length for resource.",
"self.vocab[\"id2word\"] self.vocab_size = len(self.word2id) else: self.word2id, self.id2word = self.construct_vocab( [x[0] for x in",
"= [len(line) for line in sorted_sent1_lines] sorted_sent2_lens = [len(line) for line in sorted_sent2_lines]",
"[ [ self.trg[corpus_idx][\"word2id\"][w] if w in self.trg[corpus_idx][\"word2id\"] else self.trg[corpus_idx][\"word2id\"][\"<unk>\"] for w in line[:-1]",
"[ [\"<s>\"] + line[: max_len_trg - 2] + [\"</s>\"] for line in self.trg[corpus_idx][\"data\"][",
"vocabulary. lowercase(bool): If lowercase the sentences. charlevel(bool): If need to split the sentence",
"self.train_lines] + [x[1] for x in self.train_lines], self.vocab_size, lowercase=self.lowercase, ) # Label text",
"seed=0 ): \"\"\"Initialize params. Each of train/dev/test is a tab-separate file of the",
"== len(self.trg[idx][\"data\"]) # Cast things to list to avoid issue with calling .append",
"self.tasknames = tasknames self.save_dir = save_dir self.buffer_size = buffer_size self.lowercase = lowercase #",
"] trg_lines = [ [\"<s>\"] + line[: max_len_trg - 2] + [\"</s>\"] for",
"\"</s>\": 2, \"<unk>\": 3} id2word = {0: \"<s>\", 1: \"<pad>\", 2: \"</s>\", 3:",
"else: trg_vocab_dump = {} for idx, (corpus, fname) in enumerate(zip(self.trg, self.f_trg)): word2id, id2word",
"of vocabulary. lowercase(bool): If lowercase the sentences. charlevel(bool): If need to split the",
"shuffle from torch.autograd import Variable # Change to python3+. # from itertools import",
"hypothesis \\t label. Args: train(torch.Tensor): Training dataset. dev(torch.Tensor): Validation dataset. test(torch.Tensor): Testing dataset.",
"] output_lines_trg = [ [ self.trg[corpus_idx][\"word2id\"][w] if w in self.trg[corpus_idx][\"word2id\"] else self.trg[corpus_idx][\"word2id\"][\"<unk>\"] for",
"tokenized NLI datasets.\"\"\" def __init__( self, train, dev, test, vocab_size, lowercase=True, vocab=None, seed=0",
"del vocab[\"<s>\"] if \"<pad>\" in vocab: del vocab[\"<pad>\"] if \"</s>\" in vocab: del",
"= vocab[\"word2id\"], vocab[\"id2word\"] # If not, compute the vocab from scratch and store",
"def _trim_vocab(vocab, vocab_size): \"\"\"Discard start, end, pad and unk tokens if already present.",
"sent1 = Variable(torch.LongTensor(sent1)).cuda() sent2 = Variable(torch.LongTensor(sent2)).cuda() labels = Variable(torch.LongTensor(labels)).cuda() sent1_lens = ( Variable(torch.LongTensor(sorted_sent1_lens),",
"\"input_trg\": input_lines_trg, \"output_trg\": output_lines_trg, \"src_lens\": sorted_src_lens, \"type\": \"seq2seq\", } class NLIIterator(DataIterator): \"\"\"Data iterator",
"lowercase # Open a list of file pointers to all the files. self.f_src",
"- len(line)) for line in sorted_sent2_lines ] sent1 = Variable(torch.LongTensor(sent1)).cuda() sent2 = Variable(torch.LongTensor(sent2)).cuda()",
"= Variable(torch.LongTensor(output_lines_trg)).cuda() # sorted_src_lens = Variable( # torch.LongTensor(sorted_src_lens) # ).squeeze().cuda() sorted_src_lens = (",
"sorted_sent2_lens = [len(line) for line in sorted_sent2_lines] max_sent1_len = max(sorted_sent1_lens) max_sent2_len = max(sorted_sent2_lens)",
"reserved. # Licensed under the MIT License. \"\"\"Minibatching utilities.\"\"\" import itertools import operator",
"\"output_trg\": output_lines_trg, \"src_lens\": sorted_src_lens, \"type\": \"seq2seq\", } class NLIIterator(DataIterator): \"\"\"Data iterator for tokenized",
"val_trg = config[\"data\"][\"paths\"][task_idx][\"val_trg\"] if lowercase: val_src = [ line.strip().lower().split() for line in open(val_src,",
"[len(line) for line in sorted_trg_lines] max_src_len = max(sorted_src_lens) max_trg_len = max(sorted_trg_lens) # Map",
"sent1, \"sent2\": sent2, \"sent1_lens\": sent1_lens, \"sent2_lens\": sent2_lens, \"rev_sent1\": rev_sent1, \"rev_sent2\": rev_sent2, \"labels\": labels,",
"line ] + [self.word2id[\"<pad>\"]] * (max_sent1_len - len(line)) for line in sorted_sent1_lines ]",
"in sorted_sent1_lines] sorted_sent2_lens = [len(line) for line in sorted_sent2_lines] max_sent1_len = max(sorted_sent1_lens) max_sent2_len",
"encoding=\"utf-8\") ] self.test_lines = [ line.strip().lower().split(\"\\t\") for line in open(self.test, encoding=\"utf-8\") ] if",
"# Initialize dictionaries that contain sentences & word mapping dicts self.src = [",
".append above self.src[idx][\"data\"] = list(self.src[idx][\"data\"]) self.trg[idx][\"data\"] = list(self.trg[idx][\"data\"]) self._reset_filepointer(idx) self.fetch_buffer(idx, reset=False) def build_vocab(self):",
"sorted_sent2_indices] rev_sent2 = np.argsort(sorted_sent2_indices) sorted_sent1_lens = [len(line) for line in sorted_sent1_lines] sorted_sent2_lens =",
"np.argsort(src_lens)[::-1] sorted_src_lines = [src_lines[idx] for idx in sorted_indices] sorted_trg_lines = [trg_lines[idx] for idx",
"line in sorted_sent1_lines] sorted_sent2_lens = [len(line) for line in sorted_sent2_lines] max_sent1_len = max(sorted_sent1_lens)",
"vocab: del vocab[\"</s>\"] if \"<unk>\" in vocab: del vocab[\"<unk>\"] word2id = {\"<s>\": 0,",
"loss. task_idx(int): Task index. lowercase(bool): If lowercase the data. Returns: float as the",
"open(self.fname_trg[idx], \"r\", encoding=\"utf-8\") def fetch_buffer(self, idx, reset=True): \"\"\"Fetch sentences from the file into",
"word2id[word] = ind + 4 for ind, word in enumerate(sorted_words): id2word[ind + 4]",
"pickle.load( open(os.path.join(self.save_dir, \"trg_vocab.pkl\"), \"rb\") ) for idx, (corpus, fname) in enumerate(zip(self.trg, self.f_trg)): word2id,",
"( Variable(torch.LongTensor(sorted_src_lens), volatile=True) .squeeze() .cuda() ) # Return minibatch of src-trg pairs return",
"open(os.path.join(self.save_dir, \"src_vocab.pkl\"), \"rb\") ) word2id, id2word = vocab[\"word2id\"], vocab[\"id2word\"] # If not, compute",
"1 word2id, id2word = self._trim_vocab(vocab, vocab_size) return word2id, id2word class BufferedDataIterator(DataIterator): \"\"\"Multi Parallel",
"\"src_lens\": sorted_src_lens, \"type\": \"seq2seq\", } class NLIIterator(DataIterator): \"\"\"Data iterator for tokenized NLI datasets.\"\"\"",
"= vocab_size self.lowercase = lowercase self.vocab = vocab self.train_lines = [ line.strip().lower().split(\"\\t\") for",
"batch_size] ] src_lens = [len(line) for line in src_lines] sorted_indices = np.argsort(src_lens)[::-1] sorted_src_lines",
"word2id trg_vocab_dump[self.tasknames[idx]][\"id2word\"] = id2word pickle.dump( trg_vocab_dump, open(os.path.join(self.save_dir, \"trg_vocab.pkl\"), \"wb\"), ) def shuffle_dataset(self, idx):",
"for line in open(val_src, \"r\", encoding=\"utf-8\") ] val_trg = [ line.strip().lower().split() for line",
"already present. Args: vocab(list): Vocabulary. vocab_size(int): The size of the vocabulary. Returns: word2id(list):",
"# Do the same for the target vocabulary. if os.path.exists(os.path.join(self.save_dir, \"trg_vocab.pkl\")): vocab =",
"sent2_lens = ( Variable(torch.LongTensor(sorted_sent2_lens), requires_grad=False) .squeeze() .cuda() ) rev_sent1 = ( Variable(torch.LongTensor(rev_sent1), requires_grad=False)",
"# For pytroch 0.4 with torch.no_grad(): input_lines_src = Variable(torch.LongTensor(input_lines_src)).cuda() input_lines_trg = Variable(torch.LongTensor(input_lines_trg)).cuda() output_lines_trg",
"output_lines_trg, \"src_lens\": sorted_src_lens, \"type\": \"seq2seq\", } class NLIIterator(DataIterator): \"\"\"Data iterator for tokenized NLI",
"else self.src[corpus_idx][\"word2id\"][\"<unk>\"] for w in line ] + [self.src[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_src_len - len(line))",
"lines[index : index + batch_size] ] sent2 = [ [\"<s>\"] + line[1].split() +",
") def get_parallel_minibatch( self, corpus_idx, index, batch_size, max_len_src, max_len_trg ): \"\"\"Prepare minibatch. Args:",
": index + batch_size] ] sent2 = [ [\"<s>\"] + line[1].split() + [\"</s>\"]",
"buffer for src, trg in zip(self.f_src[idx], self.f_trg[idx]): if len(self.src[idx][\"data\"]) == self.buffer_size: break if",
"class DataIterator(object): \"\"\"Data Iterator.\"\"\" @staticmethod def _trim_vocab(vocab, vocab_size): \"\"\"Discard start, end, pad and",
"file pointer. \"\"\" self.f_src[idx] = open(self.fname_src[idx], \"r\", encoding=\"utf-8\") self.f_trg[idx] = open(self.fname_trg[idx], \"r\", encoding=\"utf-8\")",
"criterion(nn.CrossEntropyLoss): criterion function for loss. task_idx(int): Task index. lowercase(bool): If lowercase the data.",
"Word to index for target. Returns: Dict for seq2seq model. \"\"\" src_lines =",
"sorted_trg_lines] max_src_len = max(sorted_src_lens) max_trg_len = max(sorted_trg_lens) input_lines_src = [ [src_word2id[w] if w",
"iterator.\"\"\" def __init__( self, src, trg, src_vocab_size, trg_vocab_size, tasknames, save_dir, buffer_size=1e6, lowercase=False, seed=0,",
"Variable(torch.LongTensor(rev_sent2), requires_grad=False) .squeeze() .cuda() ) return { \"sent1\": sent1, \"sent2\": sent2, \"sent1_lens\": sent1_lens,",
"import itertools import operator import os import pickle import numpy as np import",
"the vocabulary. \"\"\" self.seed = seed self.train = train self.dev = dev self.test",
"{ \"input_src\": input_lines_src, \"input_trg\": input_lines_trg, \"output_trg\": output_lines_trg, \"src_lens\": sorted_src_lens, \"type\": \"seq2seq\", } def",
"{\"word2id\": word2id, \"id2word\": id2word}, open(os.path.join(self.save_dir, \"src_vocab.pkl\"), \"wb\"), ) for corpus in self.src: corpus[\"word2id\"],",
"if reset: self.src[idx][\"data\"] = [] self.trg[idx][\"data\"] = [] # Populate buffer for src,",
"sentence: if word not in vocab: vocab[word] = 1 else: vocab[word] += 1",
"buffer_size(float): Buffer size. lowercase(bool): if lowercase the data. \"\"\" self.seed = seed self.fname_src",
"self.lowercase = lowercase self.vocab = vocab self.train_lines = [ line.strip().lower().split(\"\\t\") for line in",
"a task. Args: config(dict): configuration list. model(MultitaskModel): model. train_iterator(BufferedDataIterator): Multi Parallel corpus data",
"index + batch_size] ] sent1_lens = [len(line) for line in sent1] sorted_sent1_indices =",
"sorted_sent1_lines] sorted_sent2_lens = [len(line) for line in sorted_sent2_lines] max_sent1_len = max(sorted_sent1_lens) max_sent2_len =",
"w in self.word2id else self.word2id[\"<unk>\"] for w in line ] + [self.word2id[\"<pad>\"]] *",
"from scratch and store a cache. else: word2id, id2word = self.construct_vocab( itertools.chain.from_iterable(self.f_src), self.src_vocab_size,",
"= src self.fname_trg = trg self.src_vocab_size = src_vocab_size self.trg_vocab_size = trg_vocab_size self.tasknames =",
"line] + [src_word2id[\"<pad>\"]] * (max_src_len - len(line)) for line in sorted_src_lines ] input_lines_trg",
"line in sorted_trg_lines] max_src_len = max(sorted_src_lens) max_trg_len = max(sorted_trg_lens) input_lines_src = [ [src_word2id[w]",
"in vocab: vocab[word] = 1 else: vocab[word] += 1 word2id, id2word = self._trim_vocab(vocab,",
"input_lines_src = [ [ self.src[corpus_idx][\"word2id\"][w] if w in self.src[corpus_idx][\"word2id\"] else self.src[corpus_idx][\"word2id\"][\"<unk>\"] for w",
"in enumerate(zip(self.trg, self.f_trg)): word2id, id2word = ( vocab[self.tasknames[idx]][\"word2id\"], vocab[self.tasknames[idx]][\"id2word\"], ) corpus[\"word2id\"], corpus[\"id2word\"] =",
"= word2id, id2word # Do the same for the target vocabulary. if os.path.exists(os.path.join(self.save_dir,",
"trg_vocab_dump[self.tasknames[idx]][\"id2word\"] = id2word pickle.dump( trg_vocab_dump, open(os.path.join(self.save_dir, \"trg_vocab.pkl\"), \"wb\"), ) def shuffle_dataset(self, idx): \"\"\"Shuffle",
"= [ [ self.src[corpus_idx][\"word2id\"][w] if w in self.src[corpus_idx][\"word2id\"] else self.src[corpus_idx][\"word2id\"][\"<unk>\"] for w in",
"size of vocabulary. lowercase(bool): If lowercase the sentences. charlevel(bool): If need to split",
"\"<pad>\" in vocab: del vocab[\"<pad>\"] if \"</s>\" in vocab: del vocab[\"</s>\"] if \"<unk>\"",
"pickle.dump( {\"word2id\": word2id, \"id2word\": id2word}, open(os.path.join(self.save_dir, \"src_vocab.pkl\"), \"wb\"), ) for corpus in self.src:",
"= ( Variable(torch.LongTensor(sorted_sent1_lens), requires_grad=False) .squeeze() .cuda() ) sent2_lens = ( Variable(torch.LongTensor(sorted_sent2_lens), requires_grad=False) .squeeze()",
"trg_word2id ): \"\"\"Prepare minibatch. Args: src(list): source data. trg(list): target data. index(int): index",
"len(val_src), batch_size): minibatch = get_validation_minibatch( val_src, val_trg, j, batch_size, train_iterator.src[task_idx][\"word2id\"], train_iterator.trg[task_idx][\"word2id\"], ) decoder_logit",
"+ [\"</s>\"] for line in lines[index : index + batch_size] ] labels =",
"\"\"\"Multi Parallel corpus data iterator.\"\"\" def __init__( self, src, trg, src_vocab_size, trg_vocab_size, tasknames,",
"reverse=True, ) ) \"\"\"If buffer isn't full after reading the contents of the",
"list of file pointers to all the files. self.f_src = [ open(fname, \"r\",",
"word2id, id2word def construct_vocab( self, sentences, vocab_size, lowercase=False, charlevel=False ): \"\"\"Create vocabulary. Args:",
"os.path.exists(os.path.join(self.save_dir, \"trg_vocab.pkl\")): vocab = pickle.load( open(os.path.join(self.save_dir, \"trg_vocab.pkl\"), \"rb\") ) for idx, (corpus, fname)",
"# -*- coding: utf-8 -*- # Copyright (c) Microsoft Corporation. All rights reserved.",
"{\"<s>\": 0, \"<pad>\": 1, \"</s>\": 2, \"<unk>\": 3} id2word = {0: \"<s>\", 1:",
"None} for i in range(len(self.fname_trg)) ] self.build_vocab() \"\"\"Reset file pointers to the start",
"encoding=\"utf-8\") ] self.dev_lines = [ line.strip().lower().split(\"\\t\") for line in open(self.dev, encoding=\"utf-8\") ] self.test_lines",
"Variable(torch.LongTensor(input_lines_src)).cuda() input_lines_trg = Variable(torch.LongTensor(input_lines_trg)).cuda() output_lines_trg = Variable(torch.LongTensor(output_lines_trg)).cuda() # sorted_src_lens = Variable( # torch.LongTensor(sorted_src_lens)",
"mapping. self.text2label = {\"entailment\": 0, \"neutral\": 1, \"contradiction\": 2} self.shuffle_dataset() def shuffle_dataset(self): \"\"\"Shuffle",
"split the sentence with space. Returns: word2id(list): Word to index list. id2word(list): Index",
"] + [trg_word2id[\"<pad>\"]] * (max_trg_len - len(line)) for line in sorted_trg_lines ] #",
"seed=0, ): \"\"\"Initialize params. Args: src(list): source dataset. trg(list): target dataset. src_vocab_size(int): The",
"Validation dataset. test(torch.Tensor): Testing dataset. vocab_size(int): The size of the vocabulary. lowercase(bool): If",
"for batch training. \"\"\" if sent_type == \"train\": lines = self.train_lines elif sent_type",
"the same for the target vocabulary. if os.path.exists(os.path.join(self.save_dir, \"trg_vocab.pkl\")): vocab = pickle.load( open(os.path.join(self.save_dir,",
"self.word2id[w] if w in self.word2id else self.word2id[\"<unk>\"] for w in line ] +",
"len(x[0]), reverse=True, ) ) \"\"\"If buffer isn't full after reading the contents of",
"+ [\"</s>\"] for line in self.src[corpus_idx][\"data\"][ index : index + batch_size ] ]",
"[ [\"<s>\"] + line[0].split() + [\"</s>\"] for line in lines[index : index +",
"] + [self.word2id[\"<pad>\"]] * (max_sent1_len - len(line)) for line in sorted_sent1_lines ] sent2",
"self.lowercase ) corpus[\"word2id\"], corpus[\"id2word\"] = word2id, id2word trg_vocab_dump[self.tasknames[idx]] = {} trg_vocab_dump[self.tasknames[idx]][\"word2id\"] = word2id",
"val_trg = [ line.strip().split() for line in open(val_trg, \"r\", encoding=\"utf-8\") ] batch_size =",
"[ open(fname, \"r\", encoding=\"utf-8\") for fname in self.fname_trg ] # Initialize dictionaries that",
"os.path.exists(os.path.join(self.save_dir, \"src_vocab.pkl\")): vocab = pickle.load( open(os.path.join(self.save_dir, \"src_vocab.pkl\"), \"rb\") ) word2id, id2word = vocab[\"word2id\"],",
"sorted_trg_lines = [trg_lines[idx] for idx in sorted_indices] sorted_src_lens = [len(line) for line in",
"= dev self.test = test self.vocab_size = vocab_size self.lowercase = lowercase self.vocab =",
"as the mean of the loss. \"\"\" val_src = config[\"data\"][\"paths\"][task_idx][\"val_src\"] val_trg = config[\"data\"][\"paths\"][task_idx][\"val_trg\"]",
"trg(list): target data. index(int): index for the file. batch_size(int): batch size. src_word2id(list): Word",
"self.f_src = [ open(fname, \"r\", encoding=\"utf-8\") for fname in self.fname_src ] self.f_trg =",
"src(list): source data. trg(list): target data. index(int): index for the file. batch_size(int): batch",
"in sorted_sent2_lines] max_sent1_len = max(sorted_sent1_lens) max_sent2_len = max(sorted_sent2_lens) sent1 = [ [ self.word2id[w]",
"\"</s>\", 3: \"<unk>\"} sorted_word2id = sorted( vocab.items(), key=operator.itemgetter(1), reverse=True ) if vocab_size !=",
"\"r\", encoding=\"utf-8\") ] batch_size = config[\"training\"][\"batch_size\"] losses = [] for j in range(0,",
"= train self.dev = dev self.test = test self.vocab_size = vocab_size self.lowercase =",
"fname) in enumerate(zip(self.trg, self.f_trg)): word2id, id2word = ( vocab[self.tasknames[idx]][\"word2id\"], vocab[self.tasknames[idx]][\"id2word\"], ) corpus[\"word2id\"], corpus[\"id2word\"]",
"in vocab: del vocab[\"</s>\"] if \"<unk>\" in vocab: del vocab[\"<unk>\"] word2id = {\"<s>\":",
"in sorted_trg_lines ] # For pytroch 0.4 with torch.no_grad(): input_lines_src = Variable(torch.LongTensor(input_lines_src)).cuda() input_lines_trg",
"avoid issue with calling .append above self.src[idx][\"data\"] = list(self.src[idx][\"data\"]) self.trg[idx][\"data\"] = list(self.trg[idx][\"data\"]) self._reset_filepointer(idx)",
"else self.word2id[\"<unk>\"] for w in line ] + [self.word2id[\"<pad>\"]] * (max_sent2_len - len(line))",
"trg_vocab_size(int): The size of target vocab. tasknames(list): The list of task names. save_dir(str):",
"self.train_lines], self.vocab_size, lowercase=self.lowercase, ) # Label text to class mapping. self.text2label = {\"entailment\":",
"] output_lines_trg = [ [ trg_word2id[w] if w in trg_word2id else trg_word2id[\"<unk>\"] for",
"str): if lowercase: sentence = sentence.lower() if not charlevel: sentence = sentence.split() for",
"] self.test_lines = [ line.strip().lower().split(\"\\t\") for line in open(self.test, encoding=\"utf-8\") ] if self.vocab",
"+ [\"</s>\"] for line in src[index : index + batch_size] ] trg_lines =",
"vocab_size, lowercase=False, charlevel=False ): \"\"\"Create vocabulary. Args: sentences(list): The list of sentences. vocab_size(int):",
"train self.dev = dev self.test = test self.vocab_size = vocab_size self.lowercase = lowercase",
"if already present. Args: vocab(list): Vocabulary. vocab_size(int): The size of the vocabulary. Returns:",
"\"seq2seq\", } def compute_validation_loss( config, model, train_iterator, criterion, task_idx, lowercase=False ): \"\"\"Compute validation",
"line in open(self.test, encoding=\"utf-8\") ] if self.vocab is not None: # binary mode",
"class BufferedDataIterator(DataIterator): \"\"\"Multi Parallel corpus data iterator.\"\"\" def __init__( self, src, trg, src_vocab_size,",
"line[:-1] ] + [trg_word2id[\"<pad>\"]] * (max_trg_len - len(line)) for line in sorted_trg_lines ]",
"efficient vocab.\"\"\" # Construct common source vocab. # Check if save directory exists.",
"vocab[\"<pad>\"] if \"</s>\" in vocab: del vocab[\"</s>\"] if \"<unk>\" in vocab: del vocab[\"<unk>\"]",
"The size of vocabulary. lowercase(bool): If lowercase the sentences. charlevel(bool): If need to",
"dir. buffer_size(float): Buffer size. lowercase(bool): if lowercase the data. \"\"\" self.seed = seed",
"id2word = {0: \"<s>\", 1: \"<pad>\", 2: \"</s>\", 3: \"<unk>\"} sorted_word2id = sorted(",
"around. \"\"\" if len(self.src[idx][\"data\"]) < self.buffer_size: assert len(self.src[idx][\"data\"]) == len(self.trg[idx][\"data\"]) # Cast things",
"[ [ self.word2id[w] if w in self.word2id else self.word2id[\"<unk>\"] for w in line",
"if w in trg_word2id else trg_word2id[\"<unk>\"] for w in line[:-1] ] + [trg_word2id[\"<pad>\"]]",
"dataset. trg(list): target dataset. src_vocab_size(int): The size of source vocab. trg_vocab_size(int): The size",
"in line ] + [self.word2id[\"<pad>\"]] * (max_sent2_len - len(line)) for line in sorted_sent2_lines",
"else trg_word2id[\"<unk>\"] for w in line[1:] ] + [trg_word2id[\"<pad>\"]] * (max_trg_len - len(line))",
"form premise \\t hypothesis \\t label. Args: train(torch.Tensor): Training dataset. dev(torch.Tensor): Validation dataset.",
"open(os.path.join(self.save_dir, \"trg_vocab.pkl\"), \"rb\") ) for idx, (corpus, fname) in enumerate(zip(self.trg, self.f_trg)): word2id, id2word",
"for line in open(val_src, \"r\", encoding=\"utf-8\") ] val_trg = [ line.strip().split() for line",
"current buffer.\"\"\" self.src[idx][\"data\"], self.trg[idx][\"data\"] = shuffle( self.src[idx][\"data\"], self.trg[idx][\"data\"], random_state=self.seed, ) def get_parallel_minibatch( self,",
"Cast lists to torch tensors input_lines_src = Variable(torch.LongTensor(input_lines_src)).cuda() input_lines_trg = Variable(torch.LongTensor(input_lines_trg)).cuda() output_lines_trg =",
"function for loss. task_idx(int): Task index. lowercase(bool): If lowercase the data. Returns: float",
"for i in range(len(self.fname_trg)) ] self.build_vocab() \"\"\"Reset file pointers to the start after",
"line in sent1] sorted_sent1_indices = np.argsort(sent1_lens)[::-1] sorted_sent1_lines = [sent1[idx] for idx in sorted_sent1_indices]",
"source vocab. trg_vocab_size(int): The size of target vocab. tasknames(list): The list of task",
"3} id2word = {0: \"<s>\", 1: \"<pad>\", 2: \"</s>\", 3: \"<unk>\"} sorted_word2id =",
"if self.vocab is not None: # binary mode doesn't take an encoding argument",
"requires_grad=False) .squeeze() .cuda() ) sent2_lens = ( Variable(torch.LongTensor(sorted_sent2_lens), requires_grad=False) .squeeze() .cuda() ) rev_sent1",
"batch_size(int): batch size. src_word2id(list): Word to index for source. trg_word2id(list): Word to index",
"is a tab-separate file of the form premise \\t hypothesis \\t label. Args:",
"in open(val_src, \"r\", encoding=\"utf-8\") ] val_trg = [ line.strip().split() for line in open(val_trg,",
"find save dir : %s\" % self.save_dir) # Check if a cached vocab",
"index for line. batch_size(int): Batch size. sent_type(str): Type of dataset. Returns: dict for",
"sentence = sentence.lower() if not charlevel: sentence = sentence.split() for word in sentence:",
"sent1_lens = ( Variable(torch.LongTensor(sorted_sent1_lens), requires_grad=False) .squeeze() .cuda() ) sent2_lens = ( Variable(torch.LongTensor(sorted_sent2_lens), requires_grad=False)",
"in line[1:] ] + [trg_word2id[\"<pad>\"]] * (max_trg_len - len(line)) for line in sorted_trg_lines",
"[ line.strip().lower().split(\"\\t\") for line in open(self.test, encoding=\"utf-8\") ] if self.vocab is not None:",
") corpus[\"word2id\"], corpus[\"id2word\"] = word2id, id2word else: trg_vocab_dump = {} for idx, (corpus,",
"= tasknames self.save_dir = save_dir self.buffer_size = buffer_size self.lowercase = lowercase # Open",
"resource. max_len_trg(int): Max length ofr target. Returns: minibatch of src-trg pairs(dict). \"\"\" src_lines",
"self.src: corpus[\"word2id\"], corpus[\"id2word\"] = word2id, id2word # Do the same for the target",
"in self.src[corpus_idx][\"word2id\"] else self.src[corpus_idx][\"word2id\"][\"<unk>\"] for w in line ] + [self.src[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_src_len",
"pairs return { \"input_src\": input_lines_src, \"input_trg\": input_lines_trg, \"output_trg\": output_lines_trg, \"src_lens\": sorted_src_lens, \"type\": \"seq2seq\",",
"os.path.exists(self.save_dir): raise ValueError(\"Could not find save dir : %s\" % self.save_dir) # Check",
"= [ line.strip().split() for line in open(val_trg, \"r\", encoding=\"utf-8\") ] batch_size = config[\"training\"][\"batch_size\"]",
"size of the vocabulary. lowercase(bool): If lowercase the dataset. vocab(Union[bytes,str): The list of",
") for corpus in self.src: corpus[\"word2id\"], corpus[\"id2word\"] = word2id, id2word # Do the",
"def fetch_buffer(self, idx, reset=True): \"\"\"Fetch sentences from the file into the buffer. Args:",
"task. Args: config(dict): configuration list. model(MultitaskModel): model. train_iterator(BufferedDataIterator): Multi Parallel corpus data iterator.",
"for w in line[:-1] ] + [trg_word2id[\"<pad>\"]] * (max_trg_len - len(line)) for line",
"( Variable(torch.LongTensor(sorted_src_lens)) .view(len(sorted_src_lens)) .cuda() ) return { \"input_src\": input_lines_src, \"input_trg\": input_lines_trg, \"output_trg\": output_lines_trg,",
"self.trg[corpus_idx][\"data\"][ index : index + batch_size ] ] \"\"\"Sort sentences by decreasing length",
"+ [trg_word2id[\"<pad>\"]] * (max_trg_len - len(line)) for line in sorted_trg_lines ] output_lines_trg =",
"decreasing length within a minibatch for `torch.nn.utils.packed_padded_sequence`\"\"\" src_lens = [len(line) for line in",
"Check if a cached vocab file exists. if os.path.exists(os.path.join(self.save_dir, \"src_vocab.pkl\")): vocab = pickle.load(",
"( Variable(torch.LongTensor(rev_sent1), requires_grad=False) .squeeze() .cuda() ) rev_sent2 = ( Variable(torch.LongTensor(rev_sent2), requires_grad=False) .squeeze() .cuda()",
"for w in line ] + [self.src[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_src_len - len(line)) for line",
"__init__( self, src, trg, src_vocab_size, trg_vocab_size, tasknames, save_dir, buffer_size=1e6, lowercase=False, seed=0, ): \"\"\"Initialize",
"sentences from the file into the buffer. Args: idx(int): Index used to fetch",
"np.argsort(sorted_sent1_indices) sent2_lens = [len(line) for line in sent2] sorted_sent2_indices = np.argsort(sent2_lens)[::-1] sorted_sent2_lines =",
").squeeze().cuda() sorted_src_lens = ( Variable(torch.LongTensor(sorted_src_lens)) .view(len(sorted_src_lens)) .cuda() ) return { \"input_src\": input_lines_src, \"input_trg\":",
"the contents of the current buffer. if reset: self.src[idx][\"data\"] = [] self.trg[idx][\"data\"] =",
"): \"\"\"Initialize params. Args: src(list): source dataset. trg(list): target dataset. src_vocab_size(int): The size",
"len(line)) for line in sorted_trg_lines ] # For pytroch 0.4 with torch.no_grad(): input_lines_src",
"batch_size] ] labels = [ self.text2label[line[2]] for line in lines[index : index +",
"to fetch the sentences. reset(bool): If need to reset the contents of the",
"for line in sorted_trg_lines] max_src_len = max(sorted_src_lens) max_trg_len = max(sorted_trg_lens) # Map words",
"= {\"entailment\": 0, \"neutral\": 1, \"contradiction\": 2} self.shuffle_dataset() def shuffle_dataset(self): \"\"\"Shuffle training data.\"\"\"",
"\"r\", encoding=\"utf-8\") for fname in self.fname_trg ] # Initialize dictionaries that contain sentences",
"= [ {\"data\": [], \"word2id\": None, \"id2word\": None} for i in range(len(self.fname_trg)) ]",
"-*- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the",
"line.strip().lower().split(\"\\t\") for line in open(self.train, encoding=\"utf-8\") ] self.dev_lines = [ line.strip().lower().split(\"\\t\") for line",
"Max length for resource. max_len_trg(int): Max length ofr target. Returns: minibatch of src-trg",
"+ line[0].split() + [\"</s>\"] for line in lines[index : index + batch_size] ]",
"lowercase(bool): if lowercase the data. \"\"\" self.seed = seed self.fname_src = src self.fname_trg",
": index + batch_size] ] trg_lines = [ [\"<s>\"] + line + [\"</s>\"]",
"+ batch_size] ] trg_lines = [ [\"<s>\"] + line + [\"</s>\"] for line",
"list(self.src[idx][\"data\"]) self.trg[idx][\"data\"] = list(self.trg[idx][\"data\"]) self._reset_filepointer(idx) self.fetch_buffer(idx, reset=False) def build_vocab(self): \"\"\"Build a memory efficient",
"reset(bool): If need to reset the contents of the current buffer. \"\"\" #",
"input_lines_trg = Variable(torch.LongTensor(input_lines_trg)).cuda() output_lines_trg = Variable(torch.LongTensor(output_lines_trg)).cuda() # sorted_src_lens = Variable( # torch.LongTensor(sorted_src_lens) #",
"idx in sorted_indices] sorted_trg_lines = [trg_lines[idx] for idx in sorted_indices] sorted_src_lens = [len(line)",
"#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) Microsoft Corporation. All",
".cuda() ) # Return minibatch of src-trg pairs return { \"input_src\": input_lines_src, \"input_trg\":",
"\"\"\"Initialize params. Each of train/dev/test is a tab-separate file of the form premise",
"in trg[index : index + batch_size] ] src_lens = [len(line) for line in",
"the file. batch_size(int): batch size. src_word2id(list): Word to index for source. trg_word2id(list): Word",
"- len(line)) for line in sorted_trg_lines ] output_lines_trg = [ [ trg_word2id[w] if",
"in self.fname_trg ] # Initialize dictionaries that contain sentences & word mapping dicts",
"from sklearn.utils import shuffle from torch.autograd import Variable # Change to python3+. #",
"train_iterator(BufferedDataIterator): Multi Parallel corpus data iterator. criterion(nn.CrossEntropyLoss): criterion function for loss. task_idx(int): Task",
"import shuffle from torch.autograd import Variable # Change to python3+. # from itertools",
"2} self.shuffle_dataset() def shuffle_dataset(self): \"\"\"Shuffle training data.\"\"\" self.train_lines = shuffle(self.train_lines, random_state=self.seed) def get_parallel_minibatch(self,",
"self.dev = dev self.test = test self.vocab_size = vocab_size self.lowercase = lowercase self.vocab",
"iterator for tokenized NLI datasets.\"\"\" def __init__( self, train, dev, test, vocab_size, lowercase=True,",
"[x[0] for x in sorted_word2id] for ind, word in enumerate(sorted_words): word2id[word] = ind",
"batch size. src_word2id(list): Word to index for source. trg_word2id(list): Word to index for",
"src, trg in zip(self.f_src[idx], self.f_trg[idx]): if len(self.src[idx][\"data\"]) == self.buffer_size: break if self.lowercase: self.src[idx][\"data\"].append(src.lower().split())",
"that contain sentences & word mapping dicts self.src = [ {\"data\": [], \"word2id\":",
"for line in open(self.train, encoding=\"utf-8\") ] self.dev_lines = [ line.strip().lower().split(\"\\t\") for line in",
"= [ line.strip().lower().split() for line in open(val_src, \"r\", encoding=\"utf-8\") ] val_trg = [",
"lines[index : index + batch_size] ] labels = [ self.text2label[line[2]] for line in",
"[\"</s>\"] for line in src[index : index + batch_size] ] trg_lines = [",
"for line in src[index : index + batch_size] ] trg_lines = [ [\"<s>\"]",
"= sentence.split() for word in sentence: if word not in vocab: vocab[word] =",
"(max_trg_len - len(line)) for line in sorted_trg_lines ] # For pytroch 0.4 with",
"\"rev_sent1\": rev_sent1, \"rev_sent2\": rev_sent2, \"labels\": labels, \"type\": \"nli\", } def get_validation_minibatch( src, trg,",
"vocab[word] += 1 word2id, id2word = self._trim_vocab(vocab, vocab_size) return word2id, id2word class BufferedDataIterator(DataIterator):",
"sorted_src_lines ] input_lines_trg = [ [ self.trg[corpus_idx][\"word2id\"][w] if w in self.trg[corpus_idx][\"word2id\"] else self.trg[corpus_idx][\"word2id\"][\"<unk>\"]",
"_trim_vocab(vocab, vocab_size): \"\"\"Discard start, end, pad and unk tokens if already present. Args:",
"idx in sorted_sent1_indices] rev_sent1 = np.argsort(sorted_sent1_indices) sent2_lens = [len(line) for line in sent2]",
"%s\" % self.save_dir) # Check if a cached vocab file exists. if os.path.exists(os.path.join(self.save_dir,",
"in sorted_indices] sorted_src_lens = [len(line) for line in sorted_src_lines] sorted_trg_lens = [len(line) for",
"to index for source. trg_word2id(list): Word to index for target. Returns: Dict for",
"directory exists. if not os.path.exists(self.save_dir): raise ValueError(\"Could not find save dir : %s\"",
"in enumerate(zip(self.trg, self.f_trg)): word2id, id2word = self.construct_vocab( fname, self.trg_vocab_size, self.lowercase ) corpus[\"word2id\"], corpus[\"id2word\"]",
"encoding=\"utf-8\") ] batch_size = config[\"training\"][\"batch_size\"] losses = [] for j in range(0, len(val_src),",
"[sent2[idx] for idx in sorted_sent2_indices] rev_sent2 = np.argsort(sorted_sent2_indices) sorted_sent1_lens = [len(line) for line",
"(c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. \"\"\"Minibatching",
"for idx, (corpus, fname) in enumerate(zip(self.trg, self.f_trg)): word2id, id2word = self.construct_vocab( fname, self.trg_vocab_size,",
"line.strip().lower().split(\"\\t\") for line in open(self.dev, encoding=\"utf-8\") ] self.test_lines = [ line.strip().lower().split(\"\\t\") for line",
"License. \"\"\"Minibatching utilities.\"\"\" import itertools import operator import os import pickle import numpy",
"word2id = {\"<s>\": 0, \"<pad>\": 1, \"</s>\": 2, \"<unk>\": 3} id2word = {0:",
"Variable(torch.LongTensor(sent1)).cuda() sent2 = Variable(torch.LongTensor(sent2)).cuda() labels = Variable(torch.LongTensor(labels)).cuda() sent1_lens = ( Variable(torch.LongTensor(sorted_sent1_lens), requires_grad=False) .squeeze()",
"vocab: del vocab[\"<unk>\"] word2id = {\"<s>\": 0, \"<pad>\": 1, \"</s>\": 2, \"<unk>\": 3}",
"{\"data\": [], \"word2id\": None, \"id2word\": None} for i in range(len(self.fname_src)) ] self.trg =",
"val_src, val_trg, j, batch_size, train_iterator.src[task_idx][\"word2id\"], train_iterator.trg[task_idx][\"word2id\"], ) decoder_logit = model(minibatch, task_idx) loss =",
"decoder_logit.contiguous().view(-1, decoder_logit.size(2)), minibatch[\"output_trg\"].contiguous().view(-1), ) # losses.append(loss.data[0]) losses.append(loss.item()) return np.mean(losses) # Original source: https://github.com/Maluuba/gensen",
"to torch tensors input_lines_src = Variable(torch.LongTensor(input_lines_src)).cuda() input_lines_trg = Variable(torch.LongTensor(input_lines_trg)).cuda() output_lines_trg = Variable(torch.LongTensor(output_lines_trg)).cuda() sorted_src_lens",
"= src_vocab_size self.trg_vocab_size = trg_vocab_size self.tasknames = tasknames self.save_dir = save_dir self.buffer_size =",
"sent2 = [ [\"<s>\"] + line[1].split() + [\"</s>\"] for line in lines[index :",
"to all the files. self.f_src = [ open(fname, \"r\", encoding=\"utf-8\") for fname in",
"requires_grad=False) .squeeze() .cuda() ) rev_sent2 = ( Variable(torch.LongTensor(rev_sent2), requires_grad=False) .squeeze() .cuda() ) return",
"lowercase(bool): If lowercase the sentences. charlevel(bool): If need to split the sentence with",
"criterion, task_idx, lowercase=False ): \"\"\"Compute validation loss for a task. Args: config(dict): configuration",
"the vocabulary. Returns: word2id(list): Word to index list. id2word(list): Index to word list.",
"\"<s>\", 1: \"<pad>\", 2: \"</s>\", 3: \"<unk>\"} sorted_word2id = sorted( vocab.items(), key=operator.itemgetter(1), reverse=True",
"( vocab[self.tasknames[idx]][\"word2id\"], vocab[self.tasknames[idx]][\"id2word\"], ) corpus[\"word2id\"], corpus[\"id2word\"] = word2id, id2word else: trg_vocab_dump = {}",
"vocab = pickle.load( open(os.path.join(self.save_dir, \"src_vocab.pkl\"), \"rb\") ) word2id, id2word = vocab[\"word2id\"], vocab[\"id2word\"] #",
"take an encoding argument self.vocab = pickle.load(open(self.vocab, \"rb\")) self.word2id = self.vocab[\"word2id\"] self.id2word =",
"word2id, id2word = vocab[\"word2id\"], vocab[\"id2word\"] # If not, compute the vocab from scratch",
"self.save_dir = save_dir self.buffer_size = buffer_size self.lowercase = lowercase # Open a list",
"Variable(torch.LongTensor(sorted_src_lens), volatile=True) .squeeze() .cuda() ) # Return minibatch of src-trg pairs return {",
"max(sorted_trg_lens) input_lines_src = [ [src_word2id[w] if w in src else src_word2id[\"<unk>\"] for w",
"batch_size(int): Batch size. sent_type(str): Type of dataset. Returns: dict for batch training. \"\"\"",
"index(int): The index for line. batch_size(int): Batch size. sent_type(str): Type of dataset. Returns:",
"if lowercase: val_src = [ line.strip().lower().split() for line in open(val_src, \"r\", encoding=\"utf-8\") ]",
"(max_src_len - len(line)) for line in sorted_src_lines ] input_lines_trg = [ [ self.trg[corpus_idx][\"word2id\"][w]",
"vocab. # Check if save directory exists. if not os.path.exists(self.save_dir): raise ValueError(\"Could not",
"= self.construct_vocab( [x[0] for x in self.train_lines] + [x[1] for x in self.train_lines],",
"Do the same for the target vocabulary. if os.path.exists(os.path.join(self.save_dir, \"trg_vocab.pkl\")): vocab = pickle.load(",
"val_trg, j, batch_size, train_iterator.src[task_idx][\"word2id\"], train_iterator.trg[task_idx][\"word2id\"], ) decoder_logit = model(minibatch, task_idx) loss = criterion(",
"sorted_src_lens = Variable( # torch.LongTensor(sorted_src_lens) # ).squeeze().cuda() sorted_src_lens = ( Variable(torch.LongTensor(sorted_src_lens)) .view(len(sorted_src_lens)) .cuda()",
"train_iterator.src[task_idx][\"word2id\"], train_iterator.trg[task_idx][\"word2id\"], ) decoder_logit = model(minibatch, task_idx) loss = criterion( decoder_logit.contiguous().view(-1, decoder_logit.size(2)), minibatch[\"output_trg\"].contiguous().view(-1),",
"= trg self.src_vocab_size = src_vocab_size self.trg_vocab_size = trg_vocab_size self.tasknames = tasknames self.save_dir =",
"dataset. src_vocab_size(int): The size of source vocab. trg_vocab_size(int): The size of target vocab.",
"1 else: vocab[word] += 1 word2id, id2word = self._trim_vocab(vocab, vocab_size) return word2id, id2word",
"else src_word2id[\"<unk>\"] for w in line] + [src_word2id[\"<pad>\"]] * (max_src_len - len(line)) for",
"= config[\"data\"][\"paths\"][task_idx][\"val_trg\"] if lowercase: val_src = [ line.strip().lower().split() for line in open(val_src, \"r\",",
"src_vocab_size(int): The size of source vocab. trg_vocab_size(int): The size of target vocab. tasknames(list):",
"in self.src: corpus[\"word2id\"], corpus[\"id2word\"] = word2id, id2word # Do the same for the",
"for line in sorted_src_lines] sorted_trg_lens = [len(line) for line in sorted_trg_lines] max_src_len =",
"for line in sorted_trg_lines ] # Cast lists to torch tensors input_lines_src =",
"trg, index, batch_size, src_word2id, trg_word2id ): \"\"\"Prepare minibatch. Args: src(list): source data. trg(list):",
"0, \"<pad>\": 1, \"</s>\": 2, \"<unk>\": 3} id2word = {0: \"<s>\", 1: \"<pad>\",",
"[ self.trg[corpus_idx][\"word2id\"][w] if w in self.trg[corpus_idx][\"word2id\"] else self.trg[corpus_idx][\"word2id\"][\"<unk>\"] for w in line[1:] ]",
"save dir : %s\" % self.save_dir) # Check if a cached vocab file",
"vocabulary. Returns: word2id(list): Word to index list. id2word(list): Index to word list. \"\"\"",
"line[1:] ] + [self.trg[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_trg_len - len(line)) for line in sorted_trg_lines ]",
"= [] for j in range(0, len(val_src), batch_size): minibatch = get_validation_minibatch( val_src, val_trg,",
"\"\"\" self.seed = seed self.train = train self.dev = dev self.test = test",
"line. batch_size(int): Batch size. sent_type(str): Type of dataset. Returns: dict for batch training.",
"\"type\": \"nli\", } def get_validation_minibatch( src, trg, index, batch_size, src_word2id, trg_word2id ): \"\"\"Prepare",
"target. Returns: Dict for seq2seq model. \"\"\" src_lines = [ [\"<s>\"] + line",
"+ 4] = word return word2id, id2word def construct_vocab( self, sentences, vocab_size, lowercase=False,",
"= trg_vocab_size self.tasknames = tasknames self.save_dir = save_dir self.buffer_size = buffer_size self.lowercase =",
"for line in lines[index : index + batch_size] ] sent1_lens = [len(line) for",
".squeeze() .cuda() ) return { \"sent1\": sent1, \"sent2\": sent2, \"sent1_lens\": sent1_lens, \"sent2_lens\": sent2_lens,",
"= shuffle( self.src[idx][\"data\"], self.trg[idx][\"data\"], random_state=self.seed, ) def get_parallel_minibatch( self, corpus_idx, index, batch_size, max_len_src,",
"self.vocab[\"word2id\"] self.id2word = self.vocab[\"id2word\"] self.vocab_size = len(self.word2id) else: self.word2id, self.id2word = self.construct_vocab( [x[0]",
"pytroch 0.4 with torch.no_grad(): input_lines_src = Variable(torch.LongTensor(input_lines_src)).cuda() input_lines_trg = Variable(torch.LongTensor(input_lines_trg)).cuda() output_lines_trg = Variable(torch.LongTensor(output_lines_trg)).cuda()",
"vocab[word] = 1 else: vocab[word] += 1 word2id, id2word = self._trim_vocab(vocab, vocab_size) return",
"range(0, len(val_src), batch_size): minibatch = get_validation_minibatch( val_src, val_trg, j, batch_size, train_iterator.src[task_idx][\"word2id\"], train_iterator.trg[task_idx][\"word2id\"], )",
"input_lines_trg = [ [ self.trg[corpus_idx][\"word2id\"][w] if w in self.trg[corpus_idx][\"word2id\"] else self.trg[corpus_idx][\"word2id\"][\"<unk>\"] for w",
"{ \"input_src\": input_lines_src, \"input_trg\": input_lines_trg, \"output_trg\": output_lines_trg, \"src_lens\": sorted_src_lens, \"type\": \"seq2seq\", } class",
"= Variable(torch.LongTensor(output_lines_trg)).cuda() sorted_src_lens = ( Variable(torch.LongTensor(sorted_src_lens), volatile=True) .squeeze() .cuda() ) # Return minibatch",
"NLIIterator(DataIterator): \"\"\"Data iterator for tokenized NLI datasets.\"\"\" def __init__( self, train, dev, test,",
"sorted_indices] sorted_trg_lines = [trg_lines[idx] for idx in sorted_indices] sorted_src_lens = [len(line) for line",
"data iterator.\"\"\" def __init__( self, src, trg, src_vocab_size, trg_vocab_size, tasknames, save_dir, buffer_size=1e6, lowercase=False,",
"utilities.\"\"\" import itertools import operator import os import pickle import numpy as np",
"line in src_lines] sorted_indices = np.argsort(src_lens)[::-1] sorted_src_lines = [src_lines[idx] for idx in sorted_indices]",
"lowercase self.vocab = vocab self.train_lines = [ line.strip().lower().split(\"\\t\") for line in open(self.train, encoding=\"utf-8\")",
".squeeze() .cuda() ) sent2_lens = ( Variable(torch.LongTensor(sorted_sent2_lens), requires_grad=False) .squeeze() .cuda() ) rev_sent1 =",
") return { \"sent1\": sent1, \"sent2\": sent2, \"sent1_lens\": sent1_lens, \"sent2_lens\": sent2_lens, \"rev_sent1\": rev_sent1,",
"vocab_size, lowercase=True, vocab=None, seed=0 ): \"\"\"Initialize params. Each of train/dev/test is a tab-separate",
"train/dev/test is a tab-separate file of the form premise \\t hypothesis \\t label.",
"self.word2id else self.word2id[\"<unk>\"] for w in line ] + [self.word2id[\"<pad>\"]] * (max_sent1_len -",
"size. sent_type(str): Type of dataset. Returns: dict for batch training. \"\"\" if sent_type",
"= [ line.strip().lower().split() for line in open(val_trg, \"r\", encoding=\"utf-8\") ] else: val_src =",
"current buffer. \"\"\" # Reset the contents of the current buffer. if reset:",
"[ line.strip().lower().split(\"\\t\") for line in open(self.dev, encoding=\"utf-8\") ] self.test_lines = [ line.strip().lower().split(\"\\t\") for",
": index + batch_size] ] src_lens = [len(line) for line in src_lines] sorted_indices",
"to reset file pointer. \"\"\" self.f_src[idx] = open(self.fname_src[idx], \"r\", encoding=\"utf-8\") self.f_trg[idx] = open(self.fname_trg[idx],",
"\"r\", encoding=\"utf-8\") self.f_trg[idx] = open(self.fname_trg[idx], \"r\", encoding=\"utf-8\") def fetch_buffer(self, idx, reset=True): \"\"\"Fetch sentences",
"open(os.path.join(self.save_dir, \"trg_vocab.pkl\"), \"wb\"), ) def shuffle_dataset(self, idx): \"\"\"Shuffle current buffer.\"\"\" self.src[idx][\"data\"], self.trg[idx][\"data\"] =",
"model, train_iterator, criterion, task_idx, lowercase=False ): \"\"\"Compute validation loss for a task. Args:",
"for j in range(0, len(val_src), batch_size): minibatch = get_validation_minibatch( val_src, val_trg, j, batch_size,",
"pickle.dump( trg_vocab_dump, open(os.path.join(self.save_dir, \"trg_vocab.pkl\"), \"wb\"), ) def shuffle_dataset(self, idx): \"\"\"Shuffle current buffer.\"\"\" self.src[idx][\"data\"],",
"\"rb\") ) word2id, id2word = vocab[\"word2id\"], vocab[\"id2word\"] # If not, compute the vocab",
"self.word2id = self.vocab[\"word2id\"] self.id2word = self.vocab[\"id2word\"] self.vocab_size = len(self.word2id) else: self.word2id, self.id2word =",
"requires_grad=False) .squeeze() .cuda() ) rev_sent1 = ( Variable(torch.LongTensor(rev_sent1), requires_grad=False) .squeeze() .cuda() ) rev_sent2",
"exists. if not os.path.exists(self.save_dir): raise ValueError(\"Could not find save dir : %s\" %",
"else: val_src = [ line.strip().split() for line in open(val_src, \"r\", encoding=\"utf-8\") ] val_trg",
"sent1 = [ [\"<s>\"] + line[0].split() + [\"</s>\"] for line in lines[index :",
"return word2id, id2word class BufferedDataIterator(DataIterator): \"\"\"Multi Parallel corpus data iterator.\"\"\" def __init__( self,",
"corpus[\"id2word\"] = word2id, id2word trg_vocab_dump[self.tasknames[idx]] = {} trg_vocab_dump[self.tasknames[idx]][\"word2id\"] = word2id trg_vocab_dump[self.tasknames[idx]][\"id2word\"] = id2word",
"compute_validation_loss( config, model, train_iterator, criterion, task_idx, lowercase=False ): \"\"\"Compute validation loss for a",
"= word2id, id2word else: trg_vocab_dump = {} for idx, (corpus, fname) in enumerate(zip(self.trg,",
"batch_size, train_iterator.src[task_idx][\"word2id\"], train_iterator.trg[task_idx][\"word2id\"], ) decoder_logit = model(minibatch, task_idx) loss = criterion( decoder_logit.contiguous().view(-1, decoder_logit.size(2)),",
"batch_size, src_word2id, trg_word2id ): \"\"\"Prepare minibatch. Args: src(list): source data. trg(list): target data.",
"size of source vocab. trg_vocab_size(int): The size of target vocab. tasknames(list): The list",
"return { \"input_src\": input_lines_src, \"input_trg\": input_lines_trg, \"output_trg\": output_lines_trg, \"src_lens\": sorted_src_lens, \"type\": \"seq2seq\", }",
"* (max_sent1_len - len(line)) for line in sorted_sent1_lines ] sent2 = [ [",
"under the MIT License. \"\"\"Minibatching utilities.\"\"\" import itertools import operator import os import",
"python3+. # from itertools import zip class DataIterator(object): \"\"\"Data Iterator.\"\"\" @staticmethod def _trim_vocab(vocab,",
"for idx in range(len(self.src)): self._reset_filepointer(idx) for idx in range(len(self.src)): self.fetch_buffer(idx) def _reset_filepointer(self, idx):",
"open(val_src, \"r\", encoding=\"utf-8\") ] val_trg = [ line.strip().lower().split() for line in open(val_trg, \"r\",",
"= ( Variable(torch.LongTensor(sorted_src_lens), volatile=True) .squeeze() .cuda() ) # Return minibatch of src-trg pairs",
"task names. save_dir(str): The saving dir. buffer_size(float): Buffer size. lowercase(bool): if lowercase the",
"else self.trg[corpus_idx][\"word2id\"][\"<unk>\"] for w in line[1:] ] + [self.trg[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_trg_len - len(line))",
"self.train_lines elif sent_type == \"dev\": lines = self.dev_lines else: lines = self.test_lines sent1",
"in src else src_word2id[\"<unk>\"] for w in line] + [src_word2id[\"<pad>\"]] * (max_src_len -",
"cache. else: word2id, id2word = self.construct_vocab( itertools.chain.from_iterable(self.f_src), self.src_vocab_size, self.lowercase, ) pickle.dump( {\"word2id\": word2id,",
"line in open(val_src, \"r\", encoding=\"utf-8\") ] val_trg = [ line.strip().lower().split() for line in",
"encoding=\"utf-8\") for fname in self.fname_trg ] # Initialize dictionaries that contain sentences &",
"batch_size] ] sent2 = [ [\"<s>\"] + line[1].split() + [\"</s>\"] for line in",
"length (hacky bucketing) self.src[idx][\"data\"], self.trg[idx][\"data\"] = zip( *sorted( zip(self.src[idx][\"data\"], self.trg[idx][\"data\"]), key=lambda x: len(x[0]),",
"== self.buffer_size: break if self.lowercase: self.src[idx][\"data\"].append(src.lower().split()) self.trg[idx][\"data\"].append(trg.lower().split()) else: self.src[idx][\"data\"].append(src.split()) self.trg[idx][\"data\"].append(trg.split()) # Sort sentences",
"seed self.train = train self.dev = dev self.test = test self.vocab_size = vocab_size",
"if a cached vocab file exists. if os.path.exists(os.path.join(self.save_dir, \"src_vocab.pkl\")): vocab = pickle.load( open(os.path.join(self.save_dir,",
"self.trg[idx][\"data\"] = shuffle( self.src[idx][\"data\"], self.trg[idx][\"data\"], random_state=self.seed, ) def get_parallel_minibatch( self, corpus_idx, index, batch_size,",
"= [len(line) for line in sent2] sorted_sent2_indices = np.argsort(sent2_lens)[::-1] sorted_sent2_lines = [sent2[idx] for",
"lowercase the data. \"\"\" self.seed = seed self.fname_src = src self.fname_trg = trg",
"index, batch_size, sent_type=\"train\"): \"\"\"Prepare minibatch. Args: index(int): The index for line. batch_size(int): Batch",
"corpus[\"word2id\"], corpus[\"id2word\"] = word2id, id2word trg_vocab_dump[self.tasknames[idx]] = {} trg_vocab_dump[self.tasknames[idx]][\"word2id\"] = word2id trg_vocab_dump[self.tasknames[idx]][\"id2word\"] =",
"of src-trg pairs(dict). \"\"\" src_lines = [ [\"<s>\"] + line[: max_len_src - 2]",
"src[index : index + batch_size] ] trg_lines = [ [\"<s>\"] + line +",
"= Variable(torch.LongTensor(labels)).cuda() sent1_lens = ( Variable(torch.LongTensor(sorted_sent1_lens), requires_grad=False) .squeeze() .cuda() ) sent2_lens = (",
"for x in sorted_word2id] for ind, word in enumerate(sorted_words): word2id[word] = ind +",
"vocabulary. Args: sentences(list): The list of sentences. vocab_size(int): The size of vocabulary. lowercase(bool):",
"in sorted_indices] sorted_trg_lines = [trg_lines[idx] for idx in sorted_indices] sorted_src_lens = [len(line) for",
"Variable(torch.LongTensor(rev_sent1), requires_grad=False) .squeeze() .cuda() ) rev_sent2 = ( Variable(torch.LongTensor(rev_sent2), requires_grad=False) .squeeze() .cuda() )",
"target vocabulary. if os.path.exists(os.path.join(self.save_dir, \"trg_vocab.pkl\")): vocab = pickle.load( open(os.path.join(self.save_dir, \"trg_vocab.pkl\"), \"rb\") ) for",
"the current buffer. if reset: self.src[idx][\"data\"] = [] self.trg[idx][\"data\"] = [] # Populate",
"+ line[: max_len_src - 2] + [\"</s>\"] for line in self.src[corpus_idx][\"data\"][ index :",
"= [ [\"<s>\"] + line[0].split() + [\"</s>\"] for line in lines[index : index",
"for line in self.src[corpus_idx][\"data\"][ index : index + batch_size ] ] trg_lines =",
"# Sort sentences by decreasing length (hacky bucketing) self.src[idx][\"data\"], self.trg[idx][\"data\"] = zip( *sorted(",
"space. Returns: word2id(list): Word to index list. id2word(list): Index to word list. \"\"\"",
"[] # Populate buffer for src, trg in zip(self.f_src[idx], self.f_trg[idx]): if len(self.src[idx][\"data\"]) ==",
"= seed self.train = train self.dev = dev self.test = test self.vocab_size =",
"] \"\"\"Sort sentences by decreasing length within a minibatch for `torch.nn.utils.packed_padded_sequence`\"\"\" src_lens =",
"len(self.word2id) else: self.word2id, self.id2word = self.construct_vocab( [x[0] for x in self.train_lines] + [x[1]",
"trg[index : index + batch_size] ] src_lens = [len(line) for line in src_lines]",
"dir : %s\" % self.save_dir) # Check if a cached vocab file exists.",
"lowercase=False, charlevel=False ): \"\"\"Create vocabulary. Args: sentences(list): The list of sentences. vocab_size(int): The",
"max_len_src - 2] + [\"</s>\"] for line in self.src[corpus_idx][\"data\"][ index : index +",
"self.id2word = self.construct_vocab( [x[0] for x in self.train_lines] + [x[1] for x in",
"\"<unk>\": 3} id2word = {0: \"<s>\", 1: \"<pad>\", 2: \"</s>\", 3: \"<unk>\"} sorted_word2id",
"zip(self.f_src[idx], self.f_trg[idx]): if len(self.src[idx][\"data\"]) == self.buffer_size: break if self.lowercase: self.src[idx][\"data\"].append(src.lower().split()) self.trg[idx][\"data\"].append(trg.lower().split()) else: self.src[idx][\"data\"].append(src.split())",
"line in sorted_sent2_lines] max_sent1_len = max(sorted_sent1_lens) max_sent2_len = max(sorted_sent2_lens) sent1 = [ [",
"idx(int): Index used to reset file pointer. \"\"\" self.f_src[idx] = open(self.fname_src[idx], \"r\", encoding=\"utf-8\")",
"labels = Variable(torch.LongTensor(labels)).cuda() sent1_lens = ( Variable(torch.LongTensor(sorted_sent1_lens), requires_grad=False) .squeeze() .cuda() ) sent2_lens =",
"= lowercase self.vocab = vocab self.train_lines = [ line.strip().lower().split(\"\\t\") for line in open(self.train,",
"id2word def construct_vocab( self, sentences, vocab_size, lowercase=False, charlevel=False ): \"\"\"Create vocabulary. Args: sentences(list):",
"decoder_logit = model(minibatch, task_idx) loss = criterion( decoder_logit.contiguous().view(-1, decoder_logit.size(2)), minibatch[\"output_trg\"].contiguous().view(-1), ) # losses.append(loss.data[0])",
"= word return word2id, id2word def construct_vocab( self, sentences, vocab_size, lowercase=False, charlevel=False ):",
"idx): \"\"\"Shuffle current buffer.\"\"\" self.src[idx][\"data\"], self.trg[idx][\"data\"] = shuffle( self.src[idx][\"data\"], self.trg[idx][\"data\"], random_state=self.seed, ) def",
"sent2_lens, \"rev_sent1\": rev_sent1, \"rev_sent2\": rev_sent2, \"labels\": labels, \"type\": \"nli\", } def get_validation_minibatch( src,",
"criterion function for loss. task_idx(int): Task index. lowercase(bool): If lowercase the data. Returns:",
"open(self.test, encoding=\"utf-8\") ] if self.vocab is not None: # binary mode doesn't take",
"Open a list of file pointers to all the files. self.f_src = [",
"vocab. tasknames(list): The list of task names. save_dir(str): The saving dir. buffer_size(float): Buffer",
"self.fname_trg ] # Initialize dictionaries that contain sentences & word mapping dicts self.src",
"in self.fname_src ] self.f_trg = [ open(fname, \"r\", encoding=\"utf-8\") for fname in self.fname_trg",
"test, vocab_size, lowercase=True, vocab=None, seed=0 ): \"\"\"Initialize params. Each of train/dev/test is a",
"- len(line)) for line in sorted_trg_lines ] # Cast lists to torch tensors",
"+= 1 word2id, id2word = self._trim_vocab(vocab, vocab_size) return word2id, id2word class BufferedDataIterator(DataIterator): \"\"\"Multi",
"max(sorted_trg_lens) # Map words to indices input_lines_src = [ [ self.src[corpus_idx][\"word2id\"][w] if w",
"The index for line. batch_size(int): Batch size. sent_type(str): Type of dataset. Returns: dict",
"loss. \"\"\" val_src = config[\"data\"][\"paths\"][task_idx][\"val_src\"] val_trg = config[\"data\"][\"paths\"][task_idx][\"val_trg\"] if lowercase: val_src = [",
"src_vocab_size, trg_vocab_size, tasknames, save_dir, buffer_size=1e6, lowercase=False, seed=0, ): \"\"\"Initialize params. Args: src(list): source",
"sent_type(str): Type of dataset. Returns: dict for batch training. \"\"\" if sent_type ==",
"sent_type == \"dev\": lines = self.dev_lines else: lines = self.test_lines sent1 = [",
"trg_lines = [ [\"<s>\"] + line + [\"</s>\"] for line in trg[index :",
"\"\"\"Minibatching utilities.\"\"\" import itertools import operator import os import pickle import numpy as",
"in range(len(self.fname_trg)) ] self.build_vocab() \"\"\"Reset file pointers to the start after reading the",
"if self.lowercase: self.src[idx][\"data\"].append(src.lower().split()) self.trg[idx][\"data\"].append(trg.lower().split()) else: self.src[idx][\"data\"].append(src.split()) self.trg[idx][\"data\"].append(trg.split()) # Sort sentences by decreasing length",
"vocabularies.\"\"\" for idx in range(len(self.src)): self._reset_filepointer(idx) for idx in range(len(self.src)): self.fetch_buffer(idx) def _reset_filepointer(self,",
"[len(line) for line in sorted_trg_lines] max_src_len = max(sorted_src_lens) max_trg_len = max(sorted_trg_lens) input_lines_src =",
"Index used to reset file pointer. \"\"\" self.f_src[idx] = open(self.fname_src[idx], \"r\", encoding=\"utf-8\") self.f_trg[idx]",
"line.strip().lower().split() for line in open(val_trg, \"r\", encoding=\"utf-8\") ] else: val_src = [ line.strip().split()",
"= ( Variable(torch.LongTensor(sorted_sent2_lens), requires_grad=False) .squeeze() .cuda() ) rev_sent1 = ( Variable(torch.LongTensor(rev_sent1), requires_grad=False) .squeeze()",
"index for target. Returns: Dict for seq2seq model. \"\"\" src_lines = [ [\"<s>\"]",
"sentences by decreasing length (hacky bucketing) self.src[idx][\"data\"], self.trg[idx][\"data\"] = zip( *sorted( zip(self.src[idx][\"data\"], self.trg[idx][\"data\"]),",
"Returns: word2id(list): Word to index list. id2word(list): Index to word list. \"\"\" vocab",
"in line[1:] ] + [self.trg[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_trg_len - len(line)) for line in sorted_trg_lines",
"{} for sentence in sentences: if isinstance(sentence, str): if lowercase: sentence = sentence.lower()",
"names. save_dir(str): The saving dir. buffer_size(float): Buffer size. lowercase(bool): if lowercase the data.",
"self.f_src[idx] = open(self.fname_src[idx], \"r\", encoding=\"utf-8\") self.f_trg[idx] = open(self.fname_trg[idx], \"r\", encoding=\"utf-8\") def fetch_buffer(self, idx,",
"= [ [ self.word2id[w] if w in self.word2id else self.word2id[\"<unk>\"] for w in",
"self.src[idx][\"data\"], self.trg[idx][\"data\"] = shuffle( self.src[idx][\"data\"], self.trg[idx][\"data\"], random_state=self.seed, ) def get_parallel_minibatch( self, corpus_idx, index,",
"[len(line) for line in sent1] sorted_sent1_indices = np.argsort(sent1_lens)[::-1] sorted_sent1_lines = [sent1[idx] for idx",
"len(line)) for line in sorted_trg_lines ] output_lines_trg = [ [ self.trg[corpus_idx][\"word2id\"][w] if w",
"] val_trg = [ line.strip().lower().split() for line in open(val_trg, \"r\", encoding=\"utf-8\") ] else:",
"line in sorted_trg_lines ] # For pytroch 0.4 with torch.no_grad(): input_lines_src = Variable(torch.LongTensor(input_lines_src)).cuda()",
"trg_word2id(list): Word to index for target. Returns: Dict for seq2seq model. \"\"\" src_lines",
"line in sorted_trg_lines ] output_lines_trg = [ [ self.trg[corpus_idx][\"word2id\"][w] if w in self.trg[corpus_idx][\"word2id\"]",
"line ] + [self.word2id[\"<pad>\"]] * (max_sent2_len - len(line)) for line in sorted_sent2_lines ]",
"] labels = [ self.text2label[line[2]] for line in lines[index : index + batch_size]",
"+ batch_size] ] sent2 = [ [\"<s>\"] + line[1].split() + [\"</s>\"] for line",
"need to split the sentence with space. Returns: word2id(list): Word to index list.",
"for a task. Args: config(dict): configuration list. model(MultitaskModel): model. train_iterator(BufferedDataIterator): Multi Parallel corpus",
"range(len(self.src)): self._reset_filepointer(idx) for idx in range(len(self.src)): self.fetch_buffer(idx) def _reset_filepointer(self, idx): \"\"\"Reset file pointer.",
"pointer. \"\"\" self.f_src[idx] = open(self.fname_src[idx], \"r\", encoding=\"utf-8\") self.f_trg[idx] = open(self.fname_trg[idx], \"r\", encoding=\"utf-8\") def",
"ind + 4 for ind, word in enumerate(sorted_words): id2word[ind + 4] = word",
"= [ line.strip().split() for line in open(val_src, \"r\", encoding=\"utf-8\") ] val_trg = [",
"coding: utf-8 -*- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed",
"Args: idx(int): Index used to reset file pointer. \"\"\" self.f_src[idx] = open(self.fname_src[idx], \"r\",",
"of the vocabulary. lowercase(bool): If lowercase the dataset. vocab(Union[bytes,str): The list of the",
"[src_lines[idx] for idx in sorted_indices] sorted_trg_lines = [trg_lines[idx] for idx in sorted_indices] sorted_src_lens",
"\"r\", encoding=\"utf-8\") ] else: val_src = [ line.strip().split() for line in open(val_src, \"r\",",
"Args: vocab(list): Vocabulary. vocab_size(int): The size of the vocabulary. Returns: word2id(list): Word to",
"+ [\"</s>\"] for line in self.trg[corpus_idx][\"data\"][ index : index + batch_size ] ]",
"0.4 with torch.no_grad(): input_lines_src = Variable(torch.LongTensor(input_lines_src)).cuda() input_lines_trg = Variable(torch.LongTensor(input_lines_trg)).cuda() output_lines_trg = Variable(torch.LongTensor(output_lines_trg)).cuda() #",
"= open(self.fname_src[idx], \"r\", encoding=\"utf-8\") self.f_trg[idx] = open(self.fname_trg[idx], \"r\", encoding=\"utf-8\") def fetch_buffer(self, idx, reset=True):",
"w in line ] + [self.src[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_src_len - len(line)) for line in",
"task_idx(int): Task index. lowercase(bool): If lowercase the data. Returns: float as the mean",
"self.src[idx][\"data\"].append(src.lower().split()) self.trg[idx][\"data\"].append(trg.lower().split()) else: self.src[idx][\"data\"].append(src.split()) self.trg[idx][\"data\"].append(trg.split()) # Sort sentences by decreasing length (hacky bucketing)",
"w in src else src_word2id[\"<unk>\"] for w in line] + [src_word2id[\"<pad>\"]] * (max_src_len",
"self.buffer_size: assert len(self.src[idx][\"data\"]) == len(self.trg[idx][\"data\"]) # Cast things to list to avoid issue",
"line[0].split() + [\"</s>\"] for line in lines[index : index + batch_size] ] sent2",
"= ( Variable(torch.LongTensor(rev_sent1), requires_grad=False) .squeeze() .cuda() ) rev_sent2 = ( Variable(torch.LongTensor(rev_sent2), requires_grad=False) .squeeze()",
"if word not in vocab: vocab[word] = 1 else: vocab[word] += 1 word2id,",
"Reset the contents of the current buffer. if reset: self.src[idx][\"data\"] = [] self.trg[idx][\"data\"]",
"Multi Parallel corpus data iterator. criterion(nn.CrossEntropyLoss): criterion function for loss. task_idx(int): Task index.",
"+ [self.trg[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_trg_len - len(line)) for line in sorted_trg_lines ] # Cast",
"self, sentences, vocab_size, lowercase=False, charlevel=False ): \"\"\"Create vocabulary. Args: sentences(list): The list of",
"if not os.path.exists(self.save_dir): raise ValueError(\"Could not find save dir : %s\" % self.save_dir)",
"trg_word2id[\"<unk>\"] for w in line[:-1] ] + [trg_word2id[\"<pad>\"]] * (max_trg_len - len(line)) for",
") decoder_logit = model(minibatch, task_idx) loss = criterion( decoder_logit.contiguous().view(-1, decoder_logit.size(2)), minibatch[\"output_trg\"].contiguous().view(-1), ) #",
"] self.build_vocab() \"\"\"Reset file pointers to the start after reading the file to",
"if w in self.trg[corpus_idx][\"word2id\"] else self.trg[corpus_idx][\"word2id\"][\"<unk>\"] for w in line[:-1] ] + [self.trg[corpus_idx][\"word2id\"][\"<pad>\"]]",
"i in range(len(self.fname_trg)) ] self.build_vocab() \"\"\"Reset file pointers to the start after reading",
"sorted_src_lines = [src_lines[idx] for idx in sorted_indices] sorted_trg_lines = [trg_lines[idx] for idx in",
"[x[0] for x in sorted_word2id[:vocab_size]] else: sorted_words = [x[0] for x in sorted_word2id]",
"in self.trg[corpus_idx][\"word2id\"] else self.trg[corpus_idx][\"word2id\"][\"<unk>\"] for w in line[1:] ] + [self.trg[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_trg_len",
"Word to index for source. trg_word2id(list): Word to index for target. Returns: Dict",
"\"\"\" val_src = config[\"data\"][\"paths\"][task_idx][\"val_src\"] val_trg = config[\"data\"][\"paths\"][task_idx][\"val_trg\"] if lowercase: val_src = [ line.strip().lower().split()",
"key=operator.itemgetter(1), reverse=True ) if vocab_size != -1: sorted_words = [x[0] for x in",
"batch_size, sent_type=\"train\"): \"\"\"Prepare minibatch. Args: index(int): The index for line. batch_size(int): Batch size.",
"tokens if already present. Args: vocab(list): Vocabulary. vocab_size(int): The size of the vocabulary.",
"def construct_vocab( self, sentences, vocab_size, lowercase=False, charlevel=False ): \"\"\"Create vocabulary. Args: sentences(list): The",
"import os import pickle import numpy as np import torch from sklearn.utils import",
"for line in self.trg[corpus_idx][\"data\"][ index : index + batch_size ] ] \"\"\"Sort sentences",
"= 1 else: vocab[word] += 1 word2id, id2word = self._trim_vocab(vocab, vocab_size) return word2id,",
"max_src_len = max(sorted_src_lens) max_trg_len = max(sorted_trg_lens) # Map words to indices input_lines_src =",
"index, batch_size, src_word2id, trg_word2id ): \"\"\"Prepare minibatch. Args: src(list): source data. trg(list): target",
"list of sentences. vocab_size(int): The size of vocabulary. lowercase(bool): If lowercase the sentences.",
"__init__( self, train, dev, test, vocab_size, lowercase=True, vocab=None, seed=0 ): \"\"\"Initialize params. Each",
"\"\"\"Data iterator for tokenized NLI datasets.\"\"\" def __init__( self, train, dev, test, vocab_size,",
"in self.word2id else self.word2id[\"<unk>\"] for w in line ] + [self.word2id[\"<pad>\"]] * (max_sent2_len",
"w in line ] + [self.word2id[\"<pad>\"]] * (max_sent2_len - len(line)) for line in",
"for ind, word in enumerate(sorted_words): id2word[ind + 4] = word return word2id, id2word",
"corpus[\"word2id\"], corpus[\"id2word\"] = word2id, id2word else: trg_vocab_dump = {} for idx, (corpus, fname)",
"data.\"\"\" self.train_lines = shuffle(self.train_lines, random_state=self.seed) def get_parallel_minibatch(self, index, batch_size, sent_type=\"train\"): \"\"\"Prepare minibatch. Args:",
"\\t label. Args: train(torch.Tensor): Training dataset. dev(torch.Tensor): Validation dataset. test(torch.Tensor): Testing dataset. vocab_size(int):",
"self.src[idx][\"data\"] = list(self.src[idx][\"data\"]) self.trg[idx][\"data\"] = list(self.trg[idx][\"data\"]) self._reset_filepointer(idx) self.fetch_buffer(idx, reset=False) def build_vocab(self): \"\"\"Build a",
"self.train_lines = shuffle(self.train_lines, random_state=self.seed) def get_parallel_minibatch(self, index, batch_size, sent_type=\"train\"): \"\"\"Prepare minibatch. Args: index(int):",
"src, trg, src_vocab_size, trg_vocab_size, tasknames, save_dir, buffer_size=1e6, lowercase=False, seed=0, ): \"\"\"Initialize params. Args:",
"minibatch = get_validation_minibatch( val_src, val_trg, j, batch_size, train_iterator.src[task_idx][\"word2id\"], train_iterator.trg[task_idx][\"word2id\"], ) decoder_logit = model(minibatch,",
"index for the file. batch_size(int): batch size. src_word2id(list): Word to index for source.",
"self.src_vocab_size = src_vocab_size self.trg_vocab_size = trg_vocab_size self.tasknames = tasknames self.save_dir = save_dir self.buffer_size",
"for idx in range(len(self.src)): self.fetch_buffer(idx) def _reset_filepointer(self, idx): \"\"\"Reset file pointer. Args: idx(int):",
"Variable(torch.LongTensor(sorted_src_lens)) .view(len(sorted_src_lens)) .cuda() ) return { \"input_src\": input_lines_src, \"input_trg\": input_lines_trg, \"output_trg\": output_lines_trg, \"src_lens\":",
"ind, word in enumerate(sorted_words): id2word[ind + 4] = word return word2id, id2word def",
"Populate buffer for src, trg in zip(self.f_src[idx], self.f_trg[idx]): if len(self.src[idx][\"data\"]) == self.buffer_size: break",
"list(self.trg[idx][\"data\"]) self._reset_filepointer(idx) self.fetch_buffer(idx, reset=False) def build_vocab(self): \"\"\"Build a memory efficient vocab.\"\"\" # Construct",
"batch_size ] ] \"\"\"Sort sentences by decreasing length within a minibatch for `torch.nn.utils.packed_padded_sequence`\"\"\"",
"\"\"\"Initialize params. Args: src(list): source dataset. trg(list): target dataset. src_vocab_size(int): The size of",
"[self.src[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_src_len - len(line)) for line in sorted_src_lines ] input_lines_trg = [",
"in sorted_trg_lines ] # Cast lists to torch tensors input_lines_src = Variable(torch.LongTensor(input_lines_src)).cuda() input_lines_trg",
"vocab[self.tasknames[idx]][\"id2word\"], ) corpus[\"word2id\"], corpus[\"id2word\"] = word2id, id2word else: trg_vocab_dump = {} for idx,",
"vocabulary. \"\"\" self.seed = seed self.train = train self.dev = dev self.test =",
"word2id, id2word else: trg_vocab_dump = {} for idx, (corpus, fname) in enumerate(zip(self.trg, self.f_trg)):",
"for line in sorted_sent2_lines] max_sent1_len = max(sorted_sent1_lens) max_sent2_len = max(sorted_sent2_lens) sent1 = [",
"If lowercase the dataset. vocab(Union[bytes,str): The list of the vocabulary. \"\"\" self.seed =",
"(corpus, fname) in enumerate(zip(self.trg, self.f_trg)): word2id, id2word = self.construct_vocab( fname, self.trg_vocab_size, self.lowercase )",
"max_trg_len = max(sorted_trg_lens) # Map words to indices input_lines_src = [ [ self.src[corpus_idx][\"word2id\"][w]",
"in sorted_trg_lines ] output_lines_trg = [ [ self.trg[corpus_idx][\"word2id\"][w] if w in self.trg[corpus_idx][\"word2id\"] else",
"( Variable(torch.LongTensor(sorted_sent2_lens), requires_grad=False) .squeeze() .cuda() ) rev_sent1 = ( Variable(torch.LongTensor(rev_sent1), requires_grad=False) .squeeze() .cuda()",
"# Open a list of file pointers to all the files. self.f_src =",
"line in self.src[corpus_idx][\"data\"][ index : index + batch_size ] ] trg_lines = [",
"Corporation. All rights reserved. # Licensed under the MIT License. \"\"\"Minibatching utilities.\"\"\" import",
") for idx, (corpus, fname) in enumerate(zip(self.trg, self.f_trg)): word2id, id2word = ( vocab[self.tasknames[idx]][\"word2id\"],",
"line in sorted_src_lines ] input_lines_trg = [ [ trg_word2id[w] if w in trg_word2id",
"index : index + batch_size ] ] trg_lines = [ [\"<s>\"] + line[:",
"in self.src[corpus_idx][\"data\"][ index : index + batch_size ] ] trg_lines = [ [\"<s>\"]",
"len(line)) for line in sorted_sent2_lines ] sent1 = Variable(torch.LongTensor(sent1)).cuda() sent2 = Variable(torch.LongTensor(sent2)).cuda() labels",
"self.src[idx][\"data\"].append(src.split()) self.trg[idx][\"data\"].append(trg.split()) # Sort sentences by decreasing length (hacky bucketing) self.src[idx][\"data\"], self.trg[idx][\"data\"] =",
"src, trg, index, batch_size, src_word2id, trg_word2id ): \"\"\"Prepare minibatch. Args: src(list): source data.",
"\"rb\") ) for idx, (corpus, fname) in enumerate(zip(self.trg, self.f_trg)): word2id, id2word = (",
"\"input_src\": input_lines_src, \"input_trg\": input_lines_trg, \"output_trg\": output_lines_trg, \"src_lens\": sorted_src_lens, \"type\": \"seq2seq\", } class NLIIterator(DataIterator):",
"( Variable(torch.LongTensor(sorted_sent1_lens), requires_grad=False) .squeeze() .cuda() ) sent2_lens = ( Variable(torch.LongTensor(sorted_sent2_lens), requires_grad=False) .squeeze() .cuda()",
"above self.src[idx][\"data\"] = list(self.src[idx][\"data\"]) self.trg[idx][\"data\"] = list(self.trg[idx][\"data\"]) self._reset_filepointer(idx) self.fetch_buffer(idx, reset=False) def build_vocab(self): \"\"\"Build",
"corpus_idx, index, batch_size, max_len_src, max_len_trg ): \"\"\"Prepare minibatch. Args: corpus_idx(int): Corpus Index. index(int):",
"None, \"id2word\": None} for i in range(len(self.fname_trg)) ] self.build_vocab() \"\"\"Reset file pointers to",
"line in sorted_src_lines] sorted_trg_lens = [len(line) for line in sorted_trg_lines] max_src_len = max(sorted_src_lens)",
"np.argsort(sent2_lens)[::-1] sorted_sent2_lines = [sent2[idx] for idx in sorted_sent2_indices] rev_sent2 = np.argsort(sorted_sent2_indices) sorted_sent1_lens =",
"charlevel(bool): If need to split the sentence with space. Returns: word2id(list): Word to",
"dicts self.src = [ {\"data\": [], \"word2id\": None, \"id2word\": None} for i in",
"{\"data\": [], \"word2id\": None, \"id2word\": None} for i in range(len(self.fname_trg)) ] self.build_vocab() \"\"\"Reset",
"self.fname_src = src self.fname_trg = trg self.src_vocab_size = src_vocab_size self.trg_vocab_size = trg_vocab_size self.tasknames",
"= ( vocab[self.tasknames[idx]][\"word2id\"], vocab[self.tasknames[idx]][\"id2word\"], ) corpus[\"word2id\"], corpus[\"id2word\"] = word2id, id2word else: trg_vocab_dump =",
"= zip( *sorted( zip(self.src[idx][\"data\"], self.trg[idx][\"data\"]), key=lambda x: len(x[0]), reverse=True, ) ) \"\"\"If buffer",
"trg_vocab_dump, open(os.path.join(self.save_dir, \"trg_vocab.pkl\"), \"wb\"), ) def shuffle_dataset(self, idx): \"\"\"Shuffle current buffer.\"\"\" self.src[idx][\"data\"], self.trg[idx][\"data\"]",
"[ self.text2label[line[2]] for line in lines[index : index + batch_size] ] sent1_lens =",
"[ [ trg_word2id[w] if w in trg_word2id else trg_word2id[\"<unk>\"] for w in line[:-1]",
"+ line[1].split() + [\"</s>\"] for line in lines[index : index + batch_size] ]",
"if \"<s>\" in vocab: del vocab[\"<s>\"] if \"<pad>\" in vocab: del vocab[\"<pad>\"] if",
"lowercase: val_src = [ line.strip().lower().split() for line in open(val_src, \"r\", encoding=\"utf-8\") ] val_trg",
"vocab(Union[bytes,str): The list of the vocabulary. \"\"\" self.seed = seed self.train = train",
"shuffle(self.train_lines, random_state=self.seed) def get_parallel_minibatch(self, index, batch_size, sent_type=\"train\"): \"\"\"Prepare minibatch. Args: index(int): The index",
"id2word class BufferedDataIterator(DataIterator): \"\"\"Multi Parallel corpus data iterator.\"\"\" def __init__( self, src, trg,",
"= ( Variable(torch.LongTensor(rev_sent2), requires_grad=False) .squeeze() .cuda() ) return { \"sent1\": sent1, \"sent2\": sent2,",
"target. Returns: minibatch of src-trg pairs(dict). \"\"\" src_lines = [ [\"<s>\"] + line[:",
"in open(self.train, encoding=\"utf-8\") ] self.dev_lines = [ line.strip().lower().split(\"\\t\") for line in open(self.dev, encoding=\"utf-8\")",
"sorted_trg_lines ] output_lines_trg = [ [ self.trg[corpus_idx][\"word2id\"][w] if w in self.trg[corpus_idx][\"word2id\"] else self.trg[corpus_idx][\"word2id\"][\"<unk>\"]",
"corpus data iterator.\"\"\" def __init__( self, src, trg, src_vocab_size, trg_vocab_size, tasknames, save_dir, buffer_size=1e6,",
"= self.construct_vocab( fname, self.trg_vocab_size, self.lowercase ) corpus[\"word2id\"], corpus[\"id2word\"] = word2id, id2word trg_vocab_dump[self.tasknames[idx]] =",
"= sentence.lower() if not charlevel: sentence = sentence.split() for word in sentence: if",
"[self.trg[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_trg_len - len(line)) for line in sorted_trg_lines ] # Cast lists",
"Sort sentences by decreasing length (hacky bucketing) self.src[idx][\"data\"], self.trg[idx][\"data\"] = zip( *sorted( zip(self.src[idx][\"data\"],",
"batch_size] ] sent1_lens = [len(line) for line in sent1] sorted_sent1_indices = np.argsort(sent1_lens)[::-1] sorted_sent1_lines",
"[len(line) for line in src_lines] sorted_indices = np.argsort(src_lens)[::-1] sorted_src_lines = [src_lines[idx] for idx",
"{} trg_vocab_dump[self.tasknames[idx]][\"word2id\"] = word2id trg_vocab_dump[self.tasknames[idx]][\"id2word\"] = id2word pickle.dump( trg_vocab_dump, open(os.path.join(self.save_dir, \"trg_vocab.pkl\"), \"wb\"), )",
"the file to build vocabularies.\"\"\" for idx in range(len(self.src)): self._reset_filepointer(idx) for idx in",
"for w in line[1:] ] + [trg_word2id[\"<pad>\"]] * (max_trg_len - len(line)) for line",
"batch_size ] ] trg_lines = [ [\"<s>\"] + line[: max_len_trg - 2] +",
"[src_word2id[w] if w in src else src_word2id[\"<unk>\"] for w in line] + [src_word2id[\"<pad>\"]]",
"for idx in sorted_indices] sorted_src_lens = [len(line) for line in sorted_src_lines] sorted_trg_lens =",
"line in sent2] sorted_sent2_indices = np.argsort(sent2_lens)[::-1] sorted_sent2_lines = [sent2[idx] for idx in sorted_sent2_indices]",
"fetch the sentences. reset(bool): If need to reset the contents of the current",
"[ line.strip().split() for line in open(val_src, \"r\", encoding=\"utf-8\") ] val_trg = [ line.strip().split()",
"4 for ind, word in enumerate(sorted_words): id2word[ind + 4] = word return word2id,",
"The list of task names. save_dir(str): The saving dir. buffer_size(float): Buffer size. lowercase(bool):",
"Returns: Dict for seq2seq model. \"\"\" src_lines = [ [\"<s>\"] + line +",
"list. id2word(list): Index to word list. \"\"\" vocab = {} for sentence in",
"corpus data iterator. criterion(nn.CrossEntropyLoss): criterion function for loss. task_idx(int): Task index. lowercase(bool): If",
"to reset the contents of the current buffer. \"\"\" # Reset the contents",
"] ] \"\"\"Sort sentences by decreasing length within a minibatch for `torch.nn.utils.packed_padded_sequence`\"\"\" src_lens",
"of the form premise \\t hypothesis \\t label. Args: train(torch.Tensor): Training dataset. dev(torch.Tensor):",
"= get_validation_minibatch( val_src, val_trg, j, batch_size, train_iterator.src[task_idx][\"word2id\"], train_iterator.trg[task_idx][\"word2id\"], ) decoder_logit = model(minibatch, task_idx)",
"= [len(line) for line in sorted_src_lines] sorted_trg_lens = [len(line) for line in sorted_trg_lines]",
"def get_validation_minibatch( src, trg, index, batch_size, src_word2id, trg_word2id ): \"\"\"Prepare minibatch. Args: src(list):",
"sent1_lens = [len(line) for line in sent1] sorted_sent1_indices = np.argsort(sent1_lens)[::-1] sorted_sent1_lines = [sent1[idx]",
"for sentence in sentences: if isinstance(sentence, str): if lowercase: sentence = sentence.lower() if",
"from itertools import zip class DataIterator(object): \"\"\"Data Iterator.\"\"\" @staticmethod def _trim_vocab(vocab, vocab_size): \"\"\"Discard",
"self, corpus_idx, index, batch_size, max_len_src, max_len_trg ): \"\"\"Prepare minibatch. Args: corpus_idx(int): Corpus Index.",
"for line in trg[index : index + batch_size] ] src_lens = [len(line) for",
"Buffer size. lowercase(bool): if lowercase the data. \"\"\" self.seed = seed self.fname_src =",
"to word list. \"\"\" if \"<s>\" in vocab: del vocab[\"<s>\"] if \"<pad>\" in",
"self.train = train self.dev = dev self.test = test self.vocab_size = vocab_size self.lowercase",
"[\"<s>\"] + line[: max_len_src - 2] + [\"</s>\"] for line in self.src[corpus_idx][\"data\"][ index",
"file pointers to all the files. self.f_src = [ open(fname, \"r\", encoding=\"utf-8\") for",
"line in open(val_trg, \"r\", encoding=\"utf-8\") ] else: val_src = [ line.strip().split() for line",
"Variable(torch.LongTensor(sorted_sent1_lens), requires_grad=False) .squeeze() .cuda() ) sent2_lens = ( Variable(torch.LongTensor(sorted_sent2_lens), requires_grad=False) .squeeze() .cuda() )",
"trg self.src_vocab_size = src_vocab_size self.trg_vocab_size = trg_vocab_size self.tasknames = tasknames self.save_dir = save_dir",
"): \"\"\"Initialize params. Each of train/dev/test is a tab-separate file of the form",
"elif sent_type == \"dev\": lines = self.dev_lines else: lines = self.test_lines sent1 =",
"trg in zip(self.f_src[idx], self.f_trg[idx]): if len(self.src[idx][\"data\"]) == self.buffer_size: break if self.lowercase: self.src[idx][\"data\"].append(src.lower().split()) self.trg[idx][\"data\"].append(trg.lower().split())",
"self.train_lines = [ line.strip().lower().split(\"\\t\") for line in open(self.train, encoding=\"utf-8\") ] self.dev_lines = [",
"train(torch.Tensor): Training dataset. dev(torch.Tensor): Validation dataset. test(torch.Tensor): Testing dataset. vocab_size(int): The size of",
"in src_lines] sorted_indices = np.argsort(src_lens)[::-1] sorted_src_lines = [src_lines[idx] for idx in sorted_indices] sorted_trg_lines",
"length ofr target. Returns: minibatch of src-trg pairs(dict). \"\"\" src_lines = [ [\"<s>\"]",
"dict for batch training. \"\"\" if sent_type == \"train\": lines = self.train_lines elif",
"[ self.src[corpus_idx][\"word2id\"][w] if w in self.src[corpus_idx][\"word2id\"] else self.src[corpus_idx][\"word2id\"][\"<unk>\"] for w in line ]",
"- len(line)) for line in sorted_src_lines ] input_lines_trg = [ [ self.trg[corpus_idx][\"word2id\"][w] if",
"\"<s>\" in vocab: del vocab[\"<s>\"] if \"<pad>\" in vocab: del vocab[\"<pad>\"] if \"</s>\"",
"to list to avoid issue with calling .append above self.src[idx][\"data\"] = list(self.src[idx][\"data\"]) self.trg[idx][\"data\"]",
"* (max_sent2_len - len(line)) for line in sorted_sent2_lines ] sent1 = Variable(torch.LongTensor(sent1)).cuda() sent2",
"] sent2 = [ [ self.word2id[w] if w in self.word2id else self.word2id[\"<unk>\"] for",
"a minibatch for `torch.nn.utils.packed_padded_sequence`\"\"\" src_lens = [len(line) for line in src_lines] sorted_indices =",
"[ [src_word2id[w] if w in src else src_word2id[\"<unk>\"] for w in line] +",
"not in vocab: vocab[word] = 1 else: vocab[word] += 1 word2id, id2word =",
"= [ [src_word2id[w] if w in src else src_word2id[\"<unk>\"] for w in line]",
"[], \"word2id\": None, \"id2word\": None} for i in range(len(self.fname_src)) ] self.trg = [",
"Construct common source vocab. # Check if save directory exists. if not os.path.exists(self.save_dir):",
"line[: max_len_src - 2] + [\"</s>\"] for line in self.src[corpus_idx][\"data\"][ index : index",
"reset=False) def build_vocab(self): \"\"\"Build a memory efficient vocab.\"\"\" # Construct common source vocab.",
"in lines[index : index + batch_size] ] sent1_lens = [len(line) for line in",
"def get_parallel_minibatch( self, corpus_idx, index, batch_size, max_len_src, max_len_trg ): \"\"\"Prepare minibatch. Args: corpus_idx(int):",
"self.fetch_buffer(idx, reset=False) def build_vocab(self): \"\"\"Build a memory efficient vocab.\"\"\" # Construct common source",
"random_state=self.seed) def get_parallel_minibatch(self, index, batch_size, sent_type=\"train\"): \"\"\"Prepare minibatch. Args: index(int): The index for",
"& word mapping dicts self.src = [ {\"data\": [], \"word2id\": None, \"id2word\": None}",
"list. id2word(list): Index to word list. \"\"\" if \"<s>\" in vocab: del vocab[\"<s>\"]",
"random_state=self.seed, ) def get_parallel_minibatch( self, corpus_idx, index, batch_size, max_len_src, max_len_trg ): \"\"\"Prepare minibatch.",
"os import pickle import numpy as np import torch from sklearn.utils import shuffle",
"self.f_trg[idx]): if len(self.src[idx][\"data\"]) == self.buffer_size: break if self.lowercase: self.src[idx][\"data\"].append(src.lower().split()) self.trg[idx][\"data\"].append(trg.lower().split()) else: self.src[idx][\"data\"].append(src.split()) self.trg[idx][\"data\"].append(trg.split())",
"] # Cast lists to torch tensors input_lines_src = Variable(torch.LongTensor(input_lines_src)).cuda() input_lines_trg = Variable(torch.LongTensor(input_lines_trg)).cuda()",
"break if self.lowercase: self.src[idx][\"data\"].append(src.lower().split()) self.trg[idx][\"data\"].append(trg.lower().split()) else: self.src[idx][\"data\"].append(src.split()) self.trg[idx][\"data\"].append(trg.split()) # Sort sentences by decreasing",
"src_lines] sorted_indices = np.argsort(src_lens)[::-1] sorted_src_lines = [src_lines[idx] for idx in sorted_indices] sorted_trg_lines =",
"(max_sent1_len - len(line)) for line in sorted_sent1_lines ] sent2 = [ [ self.word2id[w]",
"after reading the contents of the file, cycle around. \"\"\" if len(self.src[idx][\"data\"]) <",
"-*- coding: utf-8 -*- # Copyright (c) Microsoft Corporation. All rights reserved. #",
"fname) in enumerate(zip(self.trg, self.f_trg)): word2id, id2word = self.construct_vocab( fname, self.trg_vocab_size, self.lowercase ) corpus[\"word2id\"],",
"and store a cache. else: word2id, id2word = self.construct_vocab( itertools.chain.from_iterable(self.f_src), self.src_vocab_size, self.lowercase, )",
"by decreasing length (hacky bucketing) self.src[idx][\"data\"], self.trg[idx][\"data\"] = zip( *sorted( zip(self.src[idx][\"data\"], self.trg[idx][\"data\"]), key=lambda",
"to class mapping. self.text2label = {\"entailment\": 0, \"neutral\": 1, \"contradiction\": 2} self.shuffle_dataset() def",
"word in enumerate(sorted_words): word2id[word] = ind + 4 for ind, word in enumerate(sorted_words):",
"len(line)) for line in sorted_src_lines ] input_lines_trg = [ [ self.trg[corpus_idx][\"word2id\"][w] if w",
"common source vocab. # Check if save directory exists. if not os.path.exists(self.save_dir): raise",
"idx in range(len(self.src)): self.fetch_buffer(idx) def _reset_filepointer(self, idx): \"\"\"Reset file pointer. Args: idx(int): Index",
"import Variable # Change to python3+. # from itertools import zip class DataIterator(object):",
"raise ValueError(\"Could not find save dir : %s\" % self.save_dir) # Check if",
"Corpus Index. index(int): Index. batch_size(int): Batch Size. max_len_src(int): Max length for resource. max_len_trg(int):",
"pairs(dict). \"\"\" src_lines = [ [\"<s>\"] + line[: max_len_src - 2] + [\"</s>\"]",
"rev_sent2 = np.argsort(sorted_sent2_indices) sorted_sent1_lens = [len(line) for line in sorted_sent1_lines] sorted_sent2_lens = [len(line)",
"\"sent1_lens\": sent1_lens, \"sent2_lens\": sent2_lens, \"rev_sent1\": rev_sent1, \"rev_sent2\": rev_sent2, \"labels\": labels, \"type\": \"nli\", }",
"= Variable(torch.LongTensor(input_lines_src)).cuda() input_lines_trg = Variable(torch.LongTensor(input_lines_trg)).cuda() output_lines_trg = Variable(torch.LongTensor(output_lines_trg)).cuda() sorted_src_lens = ( Variable(torch.LongTensor(sorted_src_lens), volatile=True)",
"vocab_size(int): The size of the vocabulary. Returns: word2id(list): Word to index list. id2word(list):",
"list. \"\"\" vocab = {} for sentence in sentences: if isinstance(sentence, str): if",
"+ [x[1] for x in self.train_lines], self.vocab_size, lowercase=self.lowercase, ) # Label text to",
"\"src_vocab.pkl\"), \"rb\") ) word2id, id2word = vocab[\"word2id\"], vocab[\"id2word\"] # If not, compute the",
"the contents of the current buffer. \"\"\" # Reset the contents of the",
"line in self.trg[corpus_idx][\"data\"][ index : index + batch_size ] ] \"\"\"Sort sentences by",
"batch_size = config[\"training\"][\"batch_size\"] losses = [] for j in range(0, len(val_src), batch_size): minibatch",
"Iterator.\"\"\" @staticmethod def _trim_vocab(vocab, vocab_size): \"\"\"Discard start, end, pad and unk tokens if",
"tasknames self.save_dir = save_dir self.buffer_size = buffer_size self.lowercase = lowercase # Open a",
"self.buffer_size: break if self.lowercase: self.src[idx][\"data\"].append(src.lower().split()) self.trg[idx][\"data\"].append(trg.lower().split()) else: self.src[idx][\"data\"].append(src.split()) self.trg[idx][\"data\"].append(trg.split()) # Sort sentences by",
"= seed self.fname_src = src self.fname_trg = trg self.src_vocab_size = src_vocab_size self.trg_vocab_size =",
"corpus[\"id2word\"] = word2id, id2word # Do the same for the target vocabulary. if",
"end, pad and unk tokens if already present. Args: vocab(list): Vocabulary. vocab_size(int): The",
"= vocab self.train_lines = [ line.strip().lower().split(\"\\t\") for line in open(self.train, encoding=\"utf-8\") ] self.dev_lines",
"for resource. max_len_trg(int): Max length ofr target. Returns: minibatch of src-trg pairs(dict). \"\"\"",
"batch_size, max_len_src, max_len_trg ): \"\"\"Prepare minibatch. Args: corpus_idx(int): Corpus Index. index(int): Index. batch_size(int):",
"MIT License. \"\"\"Minibatching utilities.\"\"\" import itertools import operator import os import pickle import",
"+ [self.word2id[\"<pad>\"]] * (max_sent2_len - len(line)) for line in sorted_sent2_lines ] sent1 =",
"in vocab: del vocab[\"<unk>\"] word2id = {\"<s>\": 0, \"<pad>\": 1, \"</s>\": 2, \"<unk>\":",
"Args: idx(int): Index used to fetch the sentences. reset(bool): If need to reset",
"\"sent2\": sent2, \"sent1_lens\": sent1_lens, \"sent2_lens\": sent2_lens, \"rev_sent1\": rev_sent1, \"rev_sent2\": rev_sent2, \"labels\": labels, \"type\":",
"the MIT License. \"\"\"Minibatching utilities.\"\"\" import itertools import operator import os import pickle",
"to index list. id2word(list): Index to word list. \"\"\" vocab = {} for",
"[\"</s>\"] for line in lines[index : index + batch_size] ] sent2 = [",
"Variable( # torch.LongTensor(sorted_src_lens) # ).squeeze().cuda() sorted_src_lens = ( Variable(torch.LongTensor(sorted_src_lens)) .view(len(sorted_src_lens)) .cuda() ) return",
"size. lowercase(bool): if lowercase the data. \"\"\" self.seed = seed self.fname_src = src",
"sent1_lens, \"sent2_lens\": sent2_lens, \"rev_sent1\": rev_sent1, \"rev_sent2\": rev_sent2, \"labels\": labels, \"type\": \"nli\", } def",
"x in self.train_lines], self.vocab_size, lowercase=self.lowercase, ) # Label text to class mapping. self.text2label",
"line in sorted_trg_lines] max_src_len = max(sorted_src_lens) max_trg_len = max(sorted_trg_lens) # Map words to",
"the contents of the file, cycle around. \"\"\" if len(self.src[idx][\"data\"]) < self.buffer_size: assert",
"in range(len(self.src)): self._reset_filepointer(idx) for idx in range(len(self.src)): self.fetch_buffer(idx) def _reset_filepointer(self, idx): \"\"\"Reset file",
"self.lowercase: self.src[idx][\"data\"].append(src.lower().split()) self.trg[idx][\"data\"].append(trg.lower().split()) else: self.src[idx][\"data\"].append(src.split()) self.trg[idx][\"data\"].append(trg.split()) # Sort sentences by decreasing length (hacky",
"val_src = [ line.strip().split() for line in open(val_src, \"r\", encoding=\"utf-8\") ] val_trg =",
"sorted_src_lens = ( Variable(torch.LongTensor(sorted_src_lens)) .view(len(sorted_src_lens)) .cuda() ) return { \"input_src\": input_lines_src, \"input_trg\": input_lines_trg,",
"save_dir, buffer_size=1e6, lowercase=False, seed=0, ): \"\"\"Initialize params. Args: src(list): source dataset. trg(list): target",
"for word in sentence: if word not in vocab: vocab[word] = 1 else:",
"= [ [ self.trg[corpus_idx][\"word2id\"][w] if w in self.trg[corpus_idx][\"word2id\"] else self.trg[corpus_idx][\"word2id\"][\"<unk>\"] for w in",
"self.vocab = vocab self.train_lines = [ line.strip().lower().split(\"\\t\") for line in open(self.train, encoding=\"utf-8\") ]",
"line.strip().lower().split() for line in open(val_src, \"r\", encoding=\"utf-8\") ] val_trg = [ line.strip().lower().split() for",
"premise \\t hypothesis \\t label. Args: train(torch.Tensor): Training dataset. dev(torch.Tensor): Validation dataset. test(torch.Tensor):",
"if os.path.exists(os.path.join(self.save_dir, \"trg_vocab.pkl\")): vocab = pickle.load( open(os.path.join(self.save_dir, \"trg_vocab.pkl\"), \"rb\") ) for idx, (corpus,",
"= [len(line) for line in sorted_trg_lines] max_src_len = max(sorted_src_lens) max_trg_len = max(sorted_trg_lens) input_lines_src",
"# from itertools import zip class DataIterator(object): \"\"\"Data Iterator.\"\"\" @staticmethod def _trim_vocab(vocab, vocab_size):",
"in sorted_trg_lines ] output_lines_trg = [ [ trg_word2id[w] if w in trg_word2id else",
"vocab = {} for sentence in sentences: if isinstance(sentence, str): if lowercase: sentence",
"sorted_sent1_indices = np.argsort(sent1_lens)[::-1] sorted_sent1_lines = [sent1[idx] for idx in sorted_sent1_indices] rev_sent1 = np.argsort(sorted_sent1_indices)",
"validation loss for a task. Args: config(dict): configuration list. model(MultitaskModel): model. train_iterator(BufferedDataIterator): Multi",
"- 2] + [\"</s>\"] for line in self.src[corpus_idx][\"data\"][ index : index + batch_size",
"ValueError(\"Could not find save dir : %s\" % self.save_dir) # Check if a",
"+ batch_size] ] labels = [ self.text2label[line[2]] for line in lines[index : index",
"for loss. task_idx(int): Task index. lowercase(bool): If lowercase the data. Returns: float as",
"index list. id2word(list): Index to word list. \"\"\" vocab = {} for sentence",
"file, cycle around. \"\"\" if len(self.src[idx][\"data\"]) < self.buffer_size: assert len(self.src[idx][\"data\"]) == len(self.trg[idx][\"data\"]) #",
"line in sorted_sent2_lines ] sent1 = Variable(torch.LongTensor(sent1)).cuda() sent2 = Variable(torch.LongTensor(sent2)).cuda() labels = Variable(torch.LongTensor(labels)).cuda()",
"0, \"neutral\": 1, \"contradiction\": 2} self.shuffle_dataset() def shuffle_dataset(self): \"\"\"Shuffle training data.\"\"\" self.train_lines =",
"= max(sorted_src_lens) max_trg_len = max(sorted_trg_lens) input_lines_src = [ [src_word2id[w] if w in src",
"of the file, cycle around. \"\"\" if len(self.src[idx][\"data\"]) < self.buffer_size: assert len(self.src[idx][\"data\"]) ==",
"\"\"\"Reset file pointer. Args: idx(int): Index used to reset file pointer. \"\"\" self.f_src[idx]",
"[len(line) for line in sorted_src_lines] sorted_trg_lens = [len(line) for line in sorted_trg_lines] max_src_len",
"!= -1: sorted_words = [x[0] for x in sorted_word2id[:vocab_size]] else: sorted_words = [x[0]",
"batch_size): minibatch = get_validation_minibatch( val_src, val_trg, j, batch_size, train_iterator.src[task_idx][\"word2id\"], train_iterator.trg[task_idx][\"word2id\"], ) decoder_logit =",
"of the vocabulary. \"\"\" self.seed = seed self.train = train self.dev = dev",
"\"\"\" src_lines = [ [\"<s>\"] + line + [\"</s>\"] for line in src[index",
"def shuffle_dataset(self): \"\"\"Shuffle training data.\"\"\" self.train_lines = shuffle(self.train_lines, random_state=self.seed) def get_parallel_minibatch(self, index, batch_size,",
"2: \"</s>\", 3: \"<unk>\"} sorted_word2id = sorted( vocab.items(), key=operator.itemgetter(1), reverse=True ) if vocab_size",
"{ \"sent1\": sent1, \"sent2\": sent2, \"sent1_lens\": sent1_lens, \"sent2_lens\": sent2_lens, \"rev_sent1\": rev_sent1, \"rev_sent2\": rev_sent2,",
"python # -*- coding: utf-8 -*- # Copyright (c) Microsoft Corporation. All rights",
"line.strip().lower().split(\"\\t\") for line in open(self.test, encoding=\"utf-8\") ] if self.vocab is not None: #",
"self.trg[idx][\"data\"] = list(self.trg[idx][\"data\"]) self._reset_filepointer(idx) self.fetch_buffer(idx, reset=False) def build_vocab(self): \"\"\"Build a memory efficient vocab.\"\"\"",
"] sent2 = [ [\"<s>\"] + line[1].split() + [\"</s>\"] for line in lines[index",
"class NLIIterator(DataIterator): \"\"\"Data iterator for tokenized NLI datasets.\"\"\" def __init__( self, train, dev,",
"\"trg_vocab.pkl\")): vocab = pickle.load( open(os.path.join(self.save_dir, \"trg_vocab.pkl\"), \"rb\") ) for idx, (corpus, fname) in",
"self.vocab = pickle.load(open(self.vocab, \"rb\")) self.word2id = self.vocab[\"word2id\"] self.id2word = self.vocab[\"id2word\"] self.vocab_size = len(self.word2id)",
"\"\"\"Prepare minibatch. Args: index(int): The index for line. batch_size(int): Batch size. sent_type(str): Type",
"sentence = sentence.split() for word in sentence: if word not in vocab: vocab[word]",
"sorted_trg_lines ] # Cast lists to torch tensors input_lines_src = Variable(torch.LongTensor(input_lines_src)).cuda() input_lines_trg =",
"reset: self.src[idx][\"data\"] = [] self.trg[idx][\"data\"] = [] # Populate buffer for src, trg",
"class mapping. self.text2label = {\"entailment\": 0, \"neutral\": 1, \"contradiction\": 2} self.shuffle_dataset() def shuffle_dataset(self):",
"params. Args: src(list): source dataset. trg(list): target dataset. src_vocab_size(int): The size of source",
"\"<unk>\" in vocab: del vocab[\"<unk>\"] word2id = {\"<s>\": 0, \"<pad>\": 1, \"</s>\": 2,",
"max_len_trg ): \"\"\"Prepare minibatch. Args: corpus_idx(int): Corpus Index. index(int): Index. batch_size(int): Batch Size.",
"word2id, id2word = self._trim_vocab(vocab, vocab_size) return word2id, id2word class BufferedDataIterator(DataIterator): \"\"\"Multi Parallel corpus",
"dataset. dev(torch.Tensor): Validation dataset. test(torch.Tensor): Testing dataset. vocab_size(int): The size of the vocabulary.",
"isn't full after reading the contents of the file, cycle around. \"\"\" if",
"id2word pickle.dump( trg_vocab_dump, open(os.path.join(self.save_dir, \"trg_vocab.pkl\"), \"wb\"), ) def shuffle_dataset(self, idx): \"\"\"Shuffle current buffer.\"\"\"",
"max(sorted_src_lens) max_trg_len = max(sorted_trg_lens) # Map words to indices input_lines_src = [ [",
"sorted_sent2_indices = np.argsort(sent2_lens)[::-1] sorted_sent2_lines = [sent2[idx] for idx in sorted_sent2_indices] rev_sent2 = np.argsort(sorted_sent2_indices)",
"len(line)) for line in sorted_sent1_lines ] sent2 = [ [ self.word2id[w] if w",
"config[\"data\"][\"paths\"][task_idx][\"val_trg\"] if lowercase: val_src = [ line.strip().lower().split() for line in open(val_src, \"r\", encoding=\"utf-8\")",
"model. train_iterator(BufferedDataIterator): Multi Parallel corpus data iterator. criterion(nn.CrossEntropyLoss): criterion function for loss. task_idx(int):",
"del vocab[\"<unk>\"] word2id = {\"<s>\": 0, \"<pad>\": 1, \"</s>\": 2, \"<unk>\": 3} id2word",
"size of target vocab. tasknames(list): The list of task names. save_dir(str): The saving",
"\"train\": lines = self.train_lines elif sent_type == \"dev\": lines = self.dev_lines else: lines",
"in open(self.dev, encoding=\"utf-8\") ] self.test_lines = [ line.strip().lower().split(\"\\t\") for line in open(self.test, encoding=\"utf-8\")",
"= [ [\"<s>\"] + line[1].split() + [\"</s>\"] for line in lines[index : index",
"self.trg[idx][\"data\"] = [] # Populate buffer for src, trg in zip(self.f_src[idx], self.f_trg[idx]): if",
"self.word2id, self.id2word = self.construct_vocab( [x[0] for x in self.train_lines] + [x[1] for x",
"config(dict): configuration list. model(MultitaskModel): model. train_iterator(BufferedDataIterator): Multi Parallel corpus data iterator. criterion(nn.CrossEntropyLoss): criterion",
"vocab: del vocab[\"<s>\"] if \"<pad>\" in vocab: del vocab[\"<pad>\"] if \"</s>\" in vocab:",
"vocab_size) return word2id, id2word class BufferedDataIterator(DataIterator): \"\"\"Multi Parallel corpus data iterator.\"\"\" def __init__(",
"self.vocab_size, lowercase=self.lowercase, ) # Label text to class mapping. self.text2label = {\"entailment\": 0,",
"size. src_word2id(list): Word to index for source. trg_word2id(list): Word to index for target.",
"- 2] + [\"</s>\"] for line in self.trg[corpus_idx][\"data\"][ index : index + batch_size",
"Index to word list. \"\"\" vocab = {} for sentence in sentences: if",
"line in trg[index : index + batch_size] ] src_lens = [len(line) for line",
"src_word2id[\"<unk>\"] for w in line] + [src_word2id[\"<pad>\"]] * (max_src_len - len(line)) for line",
"file. batch_size(int): batch size. src_word2id(list): Word to index for source. trg_word2id(list): Word to",
"for line in sorted_sent1_lines ] sent2 = [ [ self.word2id[w] if w in",
"[sent1[idx] for idx in sorted_sent1_indices] rev_sent1 = np.argsort(sorted_sent1_indices) sent2_lens = [len(line) for line",
"} def get_validation_minibatch( src, trg, index, batch_size, src_word2id, trg_word2id ): \"\"\"Prepare minibatch. Args:",
"to index for target. Returns: Dict for seq2seq model. \"\"\" src_lines = [",
"\"wb\"), ) def shuffle_dataset(self, idx): \"\"\"Shuffle current buffer.\"\"\" self.src[idx][\"data\"], self.trg[idx][\"data\"] = shuffle( self.src[idx][\"data\"],",
"trg_vocab_size self.tasknames = tasknames self.save_dir = save_dir self.buffer_size = buffer_size self.lowercase = lowercase",
"word2id, \"id2word\": id2word}, open(os.path.join(self.save_dir, \"src_vocab.pkl\"), \"wb\"), ) for corpus in self.src: corpus[\"word2id\"], corpus[\"id2word\"]",
"= [ self.text2label[line[2]] for line in lines[index : index + batch_size] ] sent1_lens",
"): \"\"\"Prepare minibatch. Args: src(list): source data. trg(list): target data. index(int): index for",
"dataset. test(torch.Tensor): Testing dataset. vocab_size(int): The size of the vocabulary. lowercase(bool): If lowercase",
"vocab_size): \"\"\"Discard start, end, pad and unk tokens if already present. Args: vocab(list):",
"of sentences. vocab_size(int): The size of vocabulary. lowercase(bool): If lowercase the sentences. charlevel(bool):",
"if w in self.word2id else self.word2id[\"<unk>\"] for w in line ] + [self.word2id[\"<pad>\"]]",
"sorted_src_lines ] input_lines_trg = [ [ trg_word2id[w] if w in trg_word2id else trg_word2id[\"<unk>\"]",
") \"\"\"If buffer isn't full after reading the contents of the file, cycle",
"reset file pointer. \"\"\" self.f_src[idx] = open(self.fname_src[idx], \"r\", encoding=\"utf-8\") self.f_trg[idx] = open(self.fname_trg[idx], \"r\",",
"line in sorted_trg_lines ] output_lines_trg = [ [ trg_word2id[w] if w in trg_word2id",
"line + [\"</s>\"] for line in src[index : index + batch_size] ] trg_lines",
"binary mode doesn't take an encoding argument self.vocab = pickle.load(open(self.vocab, \"rb\")) self.word2id =",
"3: \"<unk>\"} sorted_word2id = sorted( vocab.items(), key=operator.itemgetter(1), reverse=True ) if vocab_size != -1:",
"contents of the current buffer. \"\"\" # Reset the contents of the current",
"target data. index(int): index for the file. batch_size(int): batch size. src_word2id(list): Word to",
"compute the vocab from scratch and store a cache. else: word2id, id2word =",
"if lowercase the data. \"\"\" self.seed = seed self.fname_src = src self.fname_trg =",
"vocab from scratch and store a cache. else: word2id, id2word = self.construct_vocab( itertools.chain.from_iterable(self.f_src),",
"= [ [\"<s>\"] + line[: max_len_src - 2] + [\"</s>\"] for line in",
"import operator import os import pickle import numpy as np import torch from",
"train_iterator, criterion, task_idx, lowercase=False ): \"\"\"Compute validation loss for a task. Args: config(dict):",
"dev self.test = test self.vocab_size = vocab_size self.lowercase = lowercase self.vocab = vocab",
"in sorted_src_lines] sorted_trg_lens = [len(line) for line in sorted_trg_lines] max_src_len = max(sorted_src_lens) max_trg_len",
"in sorted_sent1_lines ] sent2 = [ [ self.word2id[w] if w in self.word2id else",
"] self.dev_lines = [ line.strip().lower().split(\"\\t\") for line in open(self.dev, encoding=\"utf-8\") ] self.test_lines =",
"= [trg_lines[idx] for idx in sorted_indices] sorted_src_lens = [len(line) for line in sorted_src_lines]",
"idx): \"\"\"Reset file pointer. Args: idx(int): Index used to reset file pointer. \"\"\"",
"sent1 = [ [ self.word2id[w] if w in self.word2id else self.word2id[\"<unk>\"] for w",
"self.buffer_size = buffer_size self.lowercase = lowercase # Open a list of file pointers",
"contain sentences & word mapping dicts self.src = [ {\"data\": [], \"word2id\": None,",
"file exists. if os.path.exists(os.path.join(self.save_dir, \"src_vocab.pkl\")): vocab = pickle.load( open(os.path.join(self.save_dir, \"src_vocab.pkl\"), \"rb\") ) word2id,",
"(max_trg_len - len(line)) for line in sorted_trg_lines ] # Cast lists to torch",
"else: word2id, id2word = self.construct_vocab( itertools.chain.from_iterable(self.f_src), self.src_vocab_size, self.lowercase, ) pickle.dump( {\"word2id\": word2id, \"id2word\":",
"if \"</s>\" in vocab: del vocab[\"</s>\"] if \"<unk>\" in vocab: del vocab[\"<unk>\"] word2id",
"cached vocab file exists. if os.path.exists(os.path.join(self.save_dir, \"src_vocab.pkl\")): vocab = pickle.load( open(os.path.join(self.save_dir, \"src_vocab.pkl\"), \"rb\")",
"(max_trg_len - len(line)) for line in sorted_trg_lines ] output_lines_trg = [ [ trg_word2id[w]",
"self.f_trg = [ open(fname, \"r\", encoding=\"utf-8\") for fname in self.fname_trg ] # Initialize",
"input_lines_src = [ [src_word2id[w] if w in src else src_word2id[\"<unk>\"] for w in",
"\"\"\" if len(self.src[idx][\"data\"]) < self.buffer_size: assert len(self.src[idx][\"data\"]) == len(self.trg[idx][\"data\"]) # Cast things to",
"vocab[\"</s>\"] if \"<unk>\" in vocab: del vocab[\"<unk>\"] word2id = {\"<s>\": 0, \"<pad>\": 1,",
"w in line[1:] ] + [self.trg[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_trg_len - len(line)) for line in",
"\"\"\"Create vocabulary. Args: sentences(list): The list of sentences. vocab_size(int): The size of vocabulary.",
"pad and unk tokens if already present. Args: vocab(list): Vocabulary. vocab_size(int): The size",
"torch tensors input_lines_src = Variable(torch.LongTensor(input_lines_src)).cuda() input_lines_trg = Variable(torch.LongTensor(input_lines_trg)).cuda() output_lines_trg = Variable(torch.LongTensor(output_lines_trg)).cuda() sorted_src_lens =",
"index : index + batch_size ] ] \"\"\"Sort sentences by decreasing length within",
"\"r\", encoding=\"utf-8\") for fname in self.fname_src ] self.f_trg = [ open(fname, \"r\", encoding=\"utf-8\")",
"output_lines_trg = [ [ trg_word2id[w] if w in trg_word2id else trg_word2id[\"<unk>\"] for w",
"not charlevel: sentence = sentence.split() for word in sentence: if word not in",
"index. lowercase(bool): If lowercase the data. Returns: float as the mean of the",
"max_trg_len = max(sorted_trg_lens) input_lines_src = [ [src_word2id[w] if w in src else src_word2id[\"<unk>\"]",
"a list of file pointers to all the files. self.f_src = [ open(fname,",
"self.shuffle_dataset() def shuffle_dataset(self): \"\"\"Shuffle training data.\"\"\" self.train_lines = shuffle(self.train_lines, random_state=self.seed) def get_parallel_minibatch(self, index,",
"self.src[idx][\"data\"], self.trg[idx][\"data\"] = zip( *sorted( zip(self.src[idx][\"data\"], self.trg[idx][\"data\"]), key=lambda x: len(x[0]), reverse=True, ) )",
"id2word = self.construct_vocab( fname, self.trg_vocab_size, self.lowercase ) corpus[\"word2id\"], corpus[\"id2word\"] = word2id, id2word trg_vocab_dump[self.tasknames[idx]]",
"corpus[\"id2word\"] = word2id, id2word else: trg_vocab_dump = {} for idx, (corpus, fname) in",
"Args: train(torch.Tensor): Training dataset. dev(torch.Tensor): Validation dataset. test(torch.Tensor): Testing dataset. vocab_size(int): The size",
"-1: sorted_words = [x[0] for x in sorted_word2id[:vocab_size]] else: sorted_words = [x[0] for",
"trg_lines = [ [\"<s>\"] + line[: max_len_trg - 2] + [\"</s>\"] for line",
"sorted_sent1_indices] rev_sent1 = np.argsort(sorted_sent1_indices) sent2_lens = [len(line) for line in sent2] sorted_sent2_indices =",
"[ [\"<s>\"] + line + [\"</s>\"] for line in trg[index : index +",
"None: # binary mode doesn't take an encoding argument self.vocab = pickle.load(open(self.vocab, \"rb\"))",
"trg(list): target dataset. src_vocab_size(int): The size of source vocab. trg_vocab_size(int): The size of",
"in sorted_word2id[:vocab_size]] else: sorted_words = [x[0] for x in sorted_word2id] for ind, word",
"save_dir self.buffer_size = buffer_size self.lowercase = lowercase # Open a list of file",
"idx in sorted_sent2_indices] rev_sent2 = np.argsort(sorted_sent2_indices) sorted_sent1_lens = [len(line) for line in sorted_sent1_lines]",
"shuffle_dataset(self, idx): \"\"\"Shuffle current buffer.\"\"\" self.src[idx][\"data\"], self.trg[idx][\"data\"] = shuffle( self.src[idx][\"data\"], self.trg[idx][\"data\"], random_state=self.seed, )",
"): \"\"\"Compute validation loss for a task. Args: config(dict): configuration list. model(MultitaskModel): model.",
"for idx in sorted_sent2_indices] rev_sent2 = np.argsort(sorted_sent2_indices) sorted_sent1_lens = [len(line) for line in",
"\"\"\"If buffer isn't full after reading the contents of the file, cycle around.",
"sent2, \"sent1_lens\": sent1_lens, \"sent2_lens\": sent2_lens, \"rev_sent1\": rev_sent1, \"rev_sent2\": rev_sent2, \"labels\": labels, \"type\": \"nli\",",
"None, \"id2word\": None} for i in range(len(self.fname_src)) ] self.trg = [ {\"data\": [],",
"= np.argsort(sorted_sent2_indices) sorted_sent1_lens = [len(line) for line in sorted_sent1_lines] sorted_sent2_lens = [len(line) for",
"label. Args: train(torch.Tensor): Training dataset. dev(torch.Tensor): Validation dataset. test(torch.Tensor): Testing dataset. vocab_size(int): The",
"sorted_sent1_lines ] sent2 = [ [ self.word2id[w] if w in self.word2id else self.word2id[\"<unk>\"]",
"sorted_src_lens, \"type\": \"seq2seq\", } class NLIIterator(DataIterator): \"\"\"Data iterator for tokenized NLI datasets.\"\"\" def",
"vocab[\"<unk>\"] word2id = {\"<s>\": 0, \"<pad>\": 1, \"</s>\": 2, \"<unk>\": 3} id2word =",
"\"type\": \"seq2seq\", } class NLIIterator(DataIterator): \"\"\"Data iterator for tokenized NLI datasets.\"\"\" def __init__(",
"vocab[self.tasknames[idx]][\"word2id\"], vocab[self.tasknames[idx]][\"id2word\"], ) corpus[\"word2id\"], corpus[\"id2word\"] = word2id, id2word else: trg_vocab_dump = {} for",
"id2word # Do the same for the target vocabulary. if os.path.exists(os.path.join(self.save_dir, \"trg_vocab.pkl\")): vocab",
"to index list. id2word(list): Index to word list. \"\"\" if \"<s>\" in vocab:",
"source dataset. trg(list): target dataset. src_vocab_size(int): The size of source vocab. trg_vocab_size(int): The",
"lowercase: sentence = sentence.lower() if not charlevel: sentence = sentence.split() for word in",
"del vocab[\"</s>\"] if \"<unk>\" in vocab: del vocab[\"<unk>\"] word2id = {\"<s>\": 0, \"<pad>\":",
"encoding=\"utf-8\") for fname in self.fname_src ] self.f_trg = [ open(fname, \"r\", encoding=\"utf-8\") for",
"config[\"data\"][\"paths\"][task_idx][\"val_src\"] val_trg = config[\"data\"][\"paths\"][task_idx][\"val_trg\"] if lowercase: val_src = [ line.strip().lower().split() for line in",
"= model(minibatch, task_idx) loss = criterion( decoder_logit.contiguous().view(-1, decoder_logit.size(2)), minibatch[\"output_trg\"].contiguous().view(-1), ) # losses.append(loss.data[0]) losses.append(loss.item())",
"index + batch_size] ] trg_lines = [ [\"<s>\"] + line + [\"</s>\"] for",
"output_lines_trg = [ [ self.trg[corpus_idx][\"word2id\"][w] if w in self.trg[corpus_idx][\"word2id\"] else self.trg[corpus_idx][\"word2id\"][\"<unk>\"] for w",
"+ [self.trg[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_trg_len - len(line)) for line in sorted_trg_lines ] output_lines_trg =",
"self.f_trg)): word2id, id2word = self.construct_vocab( fname, self.trg_vocab_size, self.lowercase ) corpus[\"word2id\"], corpus[\"id2word\"] = word2id,",
"word in enumerate(sorted_words): id2word[ind + 4] = word return word2id, id2word def construct_vocab(",
"range(len(self.src)): self.fetch_buffer(idx) def _reset_filepointer(self, idx): \"\"\"Reset file pointer. Args: idx(int): Index used to",
"word list. \"\"\" if \"<s>\" in vocab: del vocab[\"<s>\"] if \"<pad>\" in vocab:",
"fname, self.trg_vocab_size, self.lowercase ) corpus[\"word2id\"], corpus[\"id2word\"] = word2id, id2word trg_vocab_dump[self.tasknames[idx]] = {} trg_vocab_dump[self.tasknames[idx]][\"word2id\"]",
"in trg_word2id else trg_word2id[\"<unk>\"] for w in line[1:] ] + [trg_word2id[\"<pad>\"]] * (max_trg_len",
"line[1:] ] + [trg_word2id[\"<pad>\"]] * (max_trg_len - len(line)) for line in sorted_trg_lines ]",
"line ] + [self.src[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_src_len - len(line)) for line in sorted_src_lines ]",
"rev_sent1 = ( Variable(torch.LongTensor(rev_sent1), requires_grad=False) .squeeze() .cuda() ) rev_sent2 = ( Variable(torch.LongTensor(rev_sent2), requires_grad=False)",
"* (max_trg_len - len(line)) for line in sorted_trg_lines ] output_lines_trg = [ [",
"] + [self.trg[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_trg_len - len(line)) for line in sorted_trg_lines ] #",
"= max(sorted_trg_lens) # Map words to indices input_lines_src = [ [ self.src[corpus_idx][\"word2id\"][w] if",
"self.f_trg)): word2id, id2word = ( vocab[self.tasknames[idx]][\"word2id\"], vocab[self.tasknames[idx]][\"id2word\"], ) corpus[\"word2id\"], corpus[\"id2word\"] = word2id, id2word",
"float as the mean of the loss. \"\"\" val_src = config[\"data\"][\"paths\"][task_idx][\"val_src\"] val_trg =",
"import pickle import numpy as np import torch from sklearn.utils import shuffle from",
"len(line)) for line in sorted_src_lines ] input_lines_trg = [ [ trg_word2id[w] if w",
"of task names. save_dir(str): The saving dir. buffer_size(float): Buffer size. lowercase(bool): if lowercase",
"open(fname, \"r\", encoding=\"utf-8\") for fname in self.fname_trg ] # Initialize dictionaries that contain",
"= buffer_size self.lowercase = lowercase # Open a list of file pointers to",
"lowercase=False ): \"\"\"Compute validation loss for a task. Args: config(dict): configuration list. model(MultitaskModel):",
") return { \"input_src\": input_lines_src, \"input_trg\": input_lines_trg, \"output_trg\": output_lines_trg, \"src_lens\": sorted_src_lens, \"type\": \"seq2seq\",",
"Returns: dict for batch training. \"\"\" if sent_type == \"train\": lines = self.train_lines",
"self.lowercase, ) pickle.dump( {\"word2id\": word2id, \"id2word\": id2word}, open(os.path.join(self.save_dir, \"src_vocab.pkl\"), \"wb\"), ) for corpus",
"data. index(int): index for the file. batch_size(int): batch size. src_word2id(list): Word to index",
"line in sorted_src_lines ] input_lines_trg = [ [ self.trg[corpus_idx][\"word2id\"][w] if w in self.trg[corpus_idx][\"word2id\"]",
"return word2id, id2word def construct_vocab( self, sentences, vocab_size, lowercase=False, charlevel=False ): \"\"\"Create vocabulary.",
"max_len_trg - 2] + [\"</s>\"] for line in self.trg[corpus_idx][\"data\"][ index : index +",
"[ line.strip().lower().split() for line in open(val_trg, \"r\", encoding=\"utf-8\") ] else: val_src = [",
"len(self.src[idx][\"data\"]) == self.buffer_size: break if self.lowercase: self.src[idx][\"data\"].append(src.lower().split()) self.trg[idx][\"data\"].append(trg.lower().split()) else: self.src[idx][\"data\"].append(src.split()) self.trg[idx][\"data\"].append(trg.split()) # Sort",
"= max(sorted_src_lens) max_trg_len = max(sorted_trg_lens) # Map words to indices input_lines_src = [",
"for idx, (corpus, fname) in enumerate(zip(self.trg, self.f_trg)): word2id, id2word = ( vocab[self.tasknames[idx]][\"word2id\"], vocab[self.tasknames[idx]][\"id2word\"],",
"w in line[:-1] ] + [trg_word2id[\"<pad>\"]] * (max_trg_len - len(line)) for line in",
"= [ [\"<s>\"] + line + [\"</s>\"] for line in trg[index : index",
"\"\"\" src_lines = [ [\"<s>\"] + line[: max_len_src - 2] + [\"</s>\"] for",
"\"\"\"Discard start, end, pad and unk tokens if already present. Args: vocab(list): Vocabulary.",
"\"</s>\" in vocab: del vocab[\"</s>\"] if \"<unk>\" in vocab: del vocab[\"<unk>\"] word2id =",
"= self.train_lines elif sent_type == \"dev\": lines = self.dev_lines else: lines = self.test_lines",
"the file, cycle around. \"\"\" if len(self.src[idx][\"data\"]) < self.buffer_size: assert len(self.src[idx][\"data\"]) == len(self.trg[idx][\"data\"])",
"word2id, id2word = ( vocab[self.tasknames[idx]][\"word2id\"], vocab[self.tasknames[idx]][\"id2word\"], ) corpus[\"word2id\"], corpus[\"id2word\"] = word2id, id2word else:",
"sorted_trg_lines] max_src_len = max(sorted_src_lens) max_trg_len = max(sorted_trg_lens) # Map words to indices input_lines_src",
"in vocab: del vocab[\"<pad>\"] if \"</s>\" in vocab: del vocab[\"</s>\"] if \"<unk>\" in",
"self.trg = [ {\"data\": [], \"word2id\": None, \"id2word\": None} for i in range(len(self.fname_trg))",
"[ line.strip().lower().split() for line in open(val_src, \"r\", encoding=\"utf-8\") ] val_trg = [ line.strip().lower().split()",
"id2word}, open(os.path.join(self.save_dir, \"src_vocab.pkl\"), \"wb\"), ) for corpus in self.src: corpus[\"word2id\"], corpus[\"id2word\"] = word2id,",
"trg_vocab_dump[self.tasknames[idx]][\"word2id\"] = word2id trg_vocab_dump[self.tasknames[idx]][\"id2word\"] = id2word pickle.dump( trg_vocab_dump, open(os.path.join(self.save_dir, \"trg_vocab.pkl\"), \"wb\"), ) def",
"for line in sorted_trg_lines ] output_lines_trg = [ [ trg_word2id[w] if w in",
"[\"<s>\"] + line[1].split() + [\"</s>\"] for line in lines[index : index + batch_size]",
"test self.vocab_size = vocab_size self.lowercase = lowercase self.vocab = vocab self.train_lines = [",
"trg_vocab_size, tasknames, save_dir, buffer_size=1e6, lowercase=False, seed=0, ): \"\"\"Initialize params. Args: src(list): source dataset.",
"Word to index list. id2word(list): Index to word list. \"\"\" if \"<s>\" in",
"fname in self.fname_src ] self.f_trg = [ open(fname, \"r\", encoding=\"utf-8\") for fname in",
"an encoding argument self.vocab = pickle.load(open(self.vocab, \"rb\")) self.word2id = self.vocab[\"word2id\"] self.id2word = self.vocab[\"id2word\"]",
"Batch size. sent_type(str): Type of dataset. Returns: dict for batch training. \"\"\" if",
"\"id2word\": None} for i in range(len(self.fname_trg)) ] self.build_vocab() \"\"\"Reset file pointers to the",
"isinstance(sentence, str): if lowercase: sentence = sentence.lower() if not charlevel: sentence = sentence.split()",
"vocabulary. lowercase(bool): If lowercase the dataset. vocab(Union[bytes,str): The list of the vocabulary. \"\"\"",
"vocab file exists. if os.path.exists(os.path.join(self.save_dir, \"src_vocab.pkl\")): vocab = pickle.load( open(os.path.join(self.save_dir, \"src_vocab.pkl\"), \"rb\") )",
"= lowercase # Open a list of file pointers to all the files.",
"criterion( decoder_logit.contiguous().view(-1, decoder_logit.size(2)), minibatch[\"output_trg\"].contiguous().view(-1), ) # losses.append(loss.data[0]) losses.append(loss.item()) return np.mean(losses) # Original source:",
"= {} for idx, (corpus, fname) in enumerate(zip(self.trg, self.f_trg)): word2id, id2word = self.construct_vocab(",
"= [ open(fname, \"r\", encoding=\"utf-8\") for fname in self.fname_src ] self.f_trg = [",
"utf-8 -*- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under",
"output_lines_trg = Variable(torch.LongTensor(output_lines_trg)).cuda() # sorted_src_lens = Variable( # torch.LongTensor(sorted_src_lens) # ).squeeze().cuda() sorted_src_lens =",
"[\"<s>\"] + line + [\"</s>\"] for line in src[index : index + batch_size]",
"corpus in self.src: corpus[\"word2id\"], corpus[\"id2word\"] = word2id, id2word # Do the same for",
") word2id, id2word = vocab[\"word2id\"], vocab[\"id2word\"] # If not, compute the vocab from",
"scratch and store a cache. else: word2id, id2word = self.construct_vocab( itertools.chain.from_iterable(self.f_src), self.src_vocab_size, self.lowercase,",
"current buffer. if reset: self.src[idx][\"data\"] = [] self.trg[idx][\"data\"] = [] # Populate buffer",
"for x in sorted_word2id[:vocab_size]] else: sorted_words = [x[0] for x in sorted_word2id] for",
"charlevel=False ): \"\"\"Create vocabulary. Args: sentences(list): The list of sentences. vocab_size(int): The size",
"sorted_word2id] for ind, word in enumerate(sorted_words): word2id[word] = ind + 4 for ind,",
"= np.argsort(src_lens)[::-1] sorted_src_lines = [src_lines[idx] for idx in sorted_indices] sorted_trg_lines = [trg_lines[idx] for",
"lowercase=True, vocab=None, seed=0 ): \"\"\"Initialize params. Each of train/dev/test is a tab-separate file",
"[\"</s>\"] for line in self.trg[corpus_idx][\"data\"][ index : index + batch_size ] ] \"\"\"Sort",
"data. trg(list): target data. index(int): index for the file. batch_size(int): batch size. src_word2id(list):",
"full after reading the contents of the file, cycle around. \"\"\" if len(self.src[idx][\"data\"])",
"Args: sentences(list): The list of sentences. vocab_size(int): The size of vocabulary. lowercase(bool): If",
"(max_src_len - len(line)) for line in sorted_src_lines ] input_lines_trg = [ [ trg_word2id[w]",
"\"src_vocab.pkl\")): vocab = pickle.load( open(os.path.join(self.save_dir, \"src_vocab.pkl\"), \"rb\") ) word2id, id2word = vocab[\"word2id\"], vocab[\"id2word\"]",
": index + batch_size ] ] \"\"\"Sort sentences by decreasing length within a",
"[ trg_word2id[w] if w in trg_word2id else trg_word2id[\"<unk>\"] for w in line[:-1] ]",
"word in sentence: if word not in vocab: vocab[word] = 1 else: vocab[word]",
"ind, word in enumerate(sorted_words): word2id[word] = ind + 4 for ind, word in",
"self.word2id else self.word2id[\"<unk>\"] for w in line ] + [self.word2id[\"<pad>\"]] * (max_sent2_len -",
"_reset_filepointer(self, idx): \"\"\"Reset file pointer. Args: idx(int): Index used to reset file pointer.",
"sorted_words = [x[0] for x in sorted_word2id[:vocab_size]] else: sorted_words = [x[0] for x",
"for x in self.train_lines], self.vocab_size, lowercase=self.lowercase, ) # Label text to class mapping.",
"in range(len(self.src)): self.fetch_buffer(idx) def _reset_filepointer(self, idx): \"\"\"Reset file pointer. Args: idx(int): Index used",
"for line in sorted_sent1_lines] sorted_sent2_lens = [len(line) for line in sorted_sent2_lines] max_sent1_len =",
"line in open(self.dev, encoding=\"utf-8\") ] self.test_lines = [ line.strip().lower().split(\"\\t\") for line in open(self.test,",
"reset=True): \"\"\"Fetch sentences from the file into the buffer. Args: idx(int): Index used",
"self.vocab_size = len(self.word2id) else: self.word2id, self.id2word = self.construct_vocab( [x[0] for x in self.train_lines]",
"tab-separate file of the form premise \\t hypothesis \\t label. Args: train(torch.Tensor): Training",
"+ batch_size] ] src_lens = [len(line) for line in src_lines] sorted_indices = np.argsort(src_lens)[::-1]",
"[ line.strip().split() for line in open(val_trg, \"r\", encoding=\"utf-8\") ] batch_size = config[\"training\"][\"batch_size\"] losses",
"the mean of the loss. \"\"\" val_src = config[\"data\"][\"paths\"][task_idx][\"val_src\"] val_trg = config[\"data\"][\"paths\"][task_idx][\"val_trg\"] if",
"(hacky bucketing) self.src[idx][\"data\"], self.trg[idx][\"data\"] = zip( *sorted( zip(self.src[idx][\"data\"], self.trg[idx][\"data\"]), key=lambda x: len(x[0]), reverse=True,",
"# Map words to indices input_lines_src = [ [ self.src[corpus_idx][\"word2id\"][w] if w in",
"line[:-1] ] + [self.trg[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_trg_len - len(line)) for line in sorted_trg_lines ]",
"] + [self.word2id[\"<pad>\"]] * (max_sent2_len - len(line)) for line in sorted_sent2_lines ] sent1",
"lowercase the sentences. charlevel(bool): If need to split the sentence with space. Returns:",
"target vocab. tasknames(list): The list of task names. save_dir(str): The saving dir. buffer_size(float):",
"present. Args: vocab(list): Vocabulary. vocab_size(int): The size of the vocabulary. Returns: word2id(list): Word",
"from torch.autograd import Variable # Change to python3+. # from itertools import zip",
"buffer. \"\"\" # Reset the contents of the current buffer. if reset: self.src[idx][\"data\"]",
"DataIterator(object): \"\"\"Data Iterator.\"\"\" @staticmethod def _trim_vocab(vocab, vocab_size): \"\"\"Discard start, end, pad and unk",
"If need to reset the contents of the current buffer. \"\"\" # Reset",
"encoding=\"utf-8\") ] val_trg = [ line.strip().lower().split() for line in open(val_trg, \"r\", encoding=\"utf-8\") ]",
"w in line] + [src_word2id[\"<pad>\"]] * (max_src_len - len(line)) for line in sorted_src_lines",
"\"\"\" self.seed = seed self.fname_src = src self.fname_trg = trg self.src_vocab_size = src_vocab_size",
"file into the buffer. Args: idx(int): Index used to fetch the sentences. reset(bool):",
"Args: index(int): The index for line. batch_size(int): Batch size. sent_type(str): Type of dataset.",
"self.text2label[line[2]] for line in lines[index : index + batch_size] ] sent1_lens = [len(line)",
"sorted_trg_lines ] # For pytroch 0.4 with torch.no_grad(): input_lines_src = Variable(torch.LongTensor(input_lines_src)).cuda() input_lines_trg =",
".cuda() ) rev_sent1 = ( Variable(torch.LongTensor(rev_sent1), requires_grad=False) .squeeze() .cuda() ) rev_sent2 = (",
"self.seed = seed self.train = train self.dev = dev self.test = test self.vocab_size",
") sent2_lens = ( Variable(torch.LongTensor(sorted_sent2_lens), requires_grad=False) .squeeze() .cuda() ) rev_sent1 = ( Variable(torch.LongTensor(rev_sent1),",
"in line] + [src_word2id[\"<pad>\"]] * (max_src_len - len(line)) for line in sorted_src_lines ]",
"] val_trg = [ line.strip().split() for line in open(val_trg, \"r\", encoding=\"utf-8\") ] batch_size",
"self.src[idx][\"data\"], self.trg[idx][\"data\"], random_state=self.seed, ) def get_parallel_minibatch( self, corpus_idx, index, batch_size, max_len_src, max_len_trg ):",
"= max(sorted_trg_lens) input_lines_src = [ [src_word2id[w] if w in src else src_word2id[\"<unk>\"] for",
"\"trg_vocab.pkl\"), \"wb\"), ) def shuffle_dataset(self, idx): \"\"\"Shuffle current buffer.\"\"\" self.src[idx][\"data\"], self.trg[idx][\"data\"] = shuffle(",
"a tab-separate file of the form premise \\t hypothesis \\t label. Args: train(torch.Tensor):",
"Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License.",
"word2id, id2word class BufferedDataIterator(DataIterator): \"\"\"Multi Parallel corpus data iterator.\"\"\" def __init__( self, src,",
"trg_word2id[w] if w in trg_word2id else trg_word2id[\"<unk>\"] for w in line[:-1] ] +",
".squeeze() .cuda() ) # Return minibatch of src-trg pairs return { \"input_src\": input_lines_src,",
"input_lines_src = Variable(torch.LongTensor(input_lines_src)).cuda() input_lines_trg = Variable(torch.LongTensor(input_lines_trg)).cuda() output_lines_trg = Variable(torch.LongTensor(output_lines_trg)).cuda() sorted_src_lens = ( Variable(torch.LongTensor(sorted_src_lens),",
"src else src_word2id[\"<unk>\"] for w in line] + [src_word2id[\"<pad>\"]] * (max_src_len - len(line))",
"= pickle.load(open(self.vocab, \"rb\")) self.word2id = self.vocab[\"word2id\"] self.id2word = self.vocab[\"id2word\"] self.vocab_size = len(self.word2id) else:",
"buffer isn't full after reading the contents of the file, cycle around. \"\"\"",
"src_lines = [ [\"<s>\"] + line[: max_len_src - 2] + [\"</s>\"] for line",
"self.fetch_buffer(idx) def _reset_filepointer(self, idx): \"\"\"Reset file pointer. Args: idx(int): Index used to reset",
"line[: max_len_trg - 2] + [\"</s>\"] for line in self.trg[corpus_idx][\"data\"][ index : index",
"to indices input_lines_src = [ [ self.src[corpus_idx][\"word2id\"][w] if w in self.src[corpus_idx][\"word2id\"] else self.src[corpus_idx][\"word2id\"][\"<unk>\"]",
"line in lines[index : index + batch_size] ] sent1_lens = [len(line) for line",
"torch from sklearn.utils import shuffle from torch.autograd import Variable # Change to python3+.",
"line in open(val_src, \"r\", encoding=\"utf-8\") ] val_trg = [ line.strip().split() for line in",
"\"dev\": lines = self.dev_lines else: lines = self.test_lines sent1 = [ [\"<s>\"] +",
"idx, (corpus, fname) in enumerate(zip(self.trg, self.f_trg)): word2id, id2word = ( vocab[self.tasknames[idx]][\"word2id\"], vocab[self.tasknames[idx]][\"id2word\"], )",
"minibatch. Args: corpus_idx(int): Corpus Index. index(int): Index. batch_size(int): Batch Size. max_len_src(int): Max length",
".squeeze() .cuda() ) rev_sent1 = ( Variable(torch.LongTensor(rev_sent1), requires_grad=False) .squeeze() .cuda() ) rev_sent2 =",
"buffer. Args: idx(int): Index used to fetch the sentences. reset(bool): If need to",
"# binary mode doesn't take an encoding argument self.vocab = pickle.load(open(self.vocab, \"rb\")) self.word2id",
"= pickle.load( open(os.path.join(self.save_dir, \"trg_vocab.pkl\"), \"rb\") ) for idx, (corpus, fname) in enumerate(zip(self.trg, self.f_trg)):",
"Args: corpus_idx(int): Corpus Index. index(int): Index. batch_size(int): Batch Size. max_len_src(int): Max length for",
"sorted_sent2_lines ] sent1 = Variable(torch.LongTensor(sent1)).cuda() sent2 = Variable(torch.LongTensor(sent2)).cuda() labels = Variable(torch.LongTensor(labels)).cuda() sent1_lens =",
"a cached vocab file exists. if os.path.exists(os.path.join(self.save_dir, \"src_vocab.pkl\")): vocab = pickle.load( open(os.path.join(self.save_dir, \"src_vocab.pkl\"),",
"sent2 = [ [ self.word2id[w] if w in self.word2id else self.word2id[\"<unk>\"] for w",
"( Variable(torch.LongTensor(rev_sent2), requires_grad=False) .squeeze() .cuda() ) return { \"sent1\": sent1, \"sent2\": sent2, \"sent1_lens\":",
"max_sent1_len = max(sorted_sent1_lens) max_sent2_len = max(sorted_sent2_lens) sent1 = [ [ self.word2id[w] if w",
"line.strip().split() for line in open(val_trg, \"r\", encoding=\"utf-8\") ] batch_size = config[\"training\"][\"batch_size\"] losses =",
"config[\"training\"][\"batch_size\"] losses = [] for j in range(0, len(val_src), batch_size): minibatch = get_validation_minibatch(",
"training data.\"\"\" self.train_lines = shuffle(self.train_lines, random_state=self.seed) def get_parallel_minibatch(self, index, batch_size, sent_type=\"train\"): \"\"\"Prepare minibatch.",
"\"\"\"Reset file pointers to the start after reading the file to build vocabularies.\"\"\"",
"# Check if save directory exists. if not os.path.exists(self.save_dir): raise ValueError(\"Could not find",
"else: lines = self.test_lines sent1 = [ [\"<s>\"] + line[0].split() + [\"</s>\"] for",
"vocab[\"id2word\"] # If not, compute the vocab from scratch and store a cache.",
"sent2 = Variable(torch.LongTensor(sent2)).cuda() labels = Variable(torch.LongTensor(labels)).cuda() sent1_lens = ( Variable(torch.LongTensor(sorted_sent1_lens), requires_grad=False) .squeeze() .cuda()",
"reading the file to build vocabularies.\"\"\" for idx in range(len(self.src)): self._reset_filepointer(idx) for idx",
"= criterion( decoder_logit.contiguous().view(-1, decoder_logit.size(2)), minibatch[\"output_trg\"].contiguous().view(-1), ) # losses.append(loss.data[0]) losses.append(loss.item()) return np.mean(losses) # Original",
"Initialize dictionaries that contain sentences & word mapping dicts self.src = [ {\"data\":",
"for w in line[:-1] ] + [self.trg[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_trg_len - len(line)) for line",
"self._reset_filepointer(idx) self.fetch_buffer(idx, reset=False) def build_vocab(self): \"\"\"Build a memory efficient vocab.\"\"\" # Construct common",
"word2id, id2word = self.construct_vocab( itertools.chain.from_iterable(self.f_src), self.src_vocab_size, self.lowercase, ) pickle.dump( {\"word2id\": word2id, \"id2word\": id2word},",
"max_len_trg(int): Max length ofr target. Returns: minibatch of src-trg pairs(dict). \"\"\" src_lines =",
"self.trg[corpus_idx][\"word2id\"][w] if w in self.trg[corpus_idx][\"word2id\"] else self.trg[corpus_idx][\"word2id\"][\"<unk>\"] for w in line[:-1] ] +",
"zip class DataIterator(object): \"\"\"Data Iterator.\"\"\" @staticmethod def _trim_vocab(vocab, vocab_size): \"\"\"Discard start, end, pad",
"things to list to avoid issue with calling .append above self.src[idx][\"data\"] = list(self.src[idx][\"data\"])",
"= [len(line) for line in sorted_sent2_lines] max_sent1_len = max(sorted_sent1_lens) max_sent2_len = max(sorted_sent2_lens) sent1",
"If lowercase the data. Returns: float as the mean of the loss. \"\"\"",
"same for the target vocabulary. if os.path.exists(os.path.join(self.save_dir, \"trg_vocab.pkl\")): vocab = pickle.load( open(os.path.join(self.save_dir, \"trg_vocab.pkl\"),",
"of dataset. Returns: dict for batch training. \"\"\" if sent_type == \"train\": lines",
"Cast things to list to avoid issue with calling .append above self.src[idx][\"data\"] =",
"\"contradiction\": 2} self.shuffle_dataset() def shuffle_dataset(self): \"\"\"Shuffle training data.\"\"\" self.train_lines = shuffle(self.train_lines, random_state=self.seed) def",
"1: \"<pad>\", 2: \"</s>\", 3: \"<unk>\"} sorted_word2id = sorted( vocab.items(), key=operator.itemgetter(1), reverse=True )",
"] src_lens = [len(line) for line in src_lines] sorted_indices = np.argsort(src_lens)[::-1] sorted_src_lines =",
"input_lines_trg = [ [ trg_word2id[w] if w in trg_word2id else trg_word2id[\"<unk>\"] for w",
"buffer.\"\"\" self.src[idx][\"data\"], self.trg[idx][\"data\"] = shuffle( self.src[idx][\"data\"], self.trg[idx][\"data\"], random_state=self.seed, ) def get_parallel_minibatch( self, corpus_idx,",
"in sentences: if isinstance(sentence, str): if lowercase: sentence = sentence.lower() if not charlevel:",
"[\"</s>\"] for line in lines[index : index + batch_size] ] labels = [",
"trg_word2id else trg_word2id[\"<unk>\"] for w in line[:-1] ] + [trg_word2id[\"<pad>\"]] * (max_trg_len -",
"buffer. if reset: self.src[idx][\"data\"] = [] self.trg[idx][\"data\"] = [] # Populate buffer for",
"\"src_vocab.pkl\"), \"wb\"), ) for corpus in self.src: corpus[\"word2id\"], corpus[\"id2word\"] = word2id, id2word #",
"vocab(list): Vocabulary. vocab_size(int): The size of the vocabulary. Returns: word2id(list): Word to index",
"vocab.items(), key=operator.itemgetter(1), reverse=True ) if vocab_size != -1: sorted_words = [x[0] for x",
"= [ {\"data\": [], \"word2id\": None, \"id2word\": None} for i in range(len(self.fname_src)) ]",
"in sorted_sent2_lines ] sent1 = Variable(torch.LongTensor(sent1)).cuda() sent2 = Variable(torch.LongTensor(sent2)).cuda() labels = Variable(torch.LongTensor(labels)).cuda() sent1_lens",
"data. Returns: float as the mean of the loss. \"\"\" val_src = config[\"data\"][\"paths\"][task_idx][\"val_src\"]",
"if \"<pad>\" in vocab: del vocab[\"<pad>\"] if \"</s>\" in vocab: del vocab[\"</s>\"] if",
"self.trg[idx][\"data\"].append(trg.split()) # Sort sentences by decreasing length (hacky bucketing) self.src[idx][\"data\"], self.trg[idx][\"data\"] = zip(",
"self.dev_lines else: lines = self.test_lines sent1 = [ [\"<s>\"] + line[0].split() + [\"</s>\"]",
"max_len_src(int): Max length for resource. max_len_trg(int): Max length ofr target. Returns: minibatch of",
"Variable(torch.LongTensor(input_lines_trg)).cuda() output_lines_trg = Variable(torch.LongTensor(output_lines_trg)).cuda() sorted_src_lens = ( Variable(torch.LongTensor(sorted_src_lens), volatile=True) .squeeze() .cuda() ) #",
"1, \"</s>\": 2, \"<unk>\": 3} id2word = {0: \"<s>\", 1: \"<pad>\", 2: \"</s>\",",
"max_sent2_len = max(sorted_sent2_lens) sent1 = [ [ self.word2id[w] if w in self.word2id else",
"in open(self.test, encoding=\"utf-8\") ] if self.vocab is not None: # binary mode doesn't",
"in self.trg[corpus_idx][\"word2id\"] else self.trg[corpus_idx][\"word2id\"][\"<unk>\"] for w in line[:-1] ] + [self.trg[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_trg_len",
"model(MultitaskModel): model. train_iterator(BufferedDataIterator): Multi Parallel corpus data iterator. criterion(nn.CrossEntropyLoss): criterion function for loss.",
") rev_sent1 = ( Variable(torch.LongTensor(rev_sent1), requires_grad=False) .squeeze() .cuda() ) rev_sent2 = ( Variable(torch.LongTensor(rev_sent2),",
"from the file into the buffer. Args: idx(int): Index used to fetch the",
"len(line)) for line in sorted_trg_lines ] output_lines_trg = [ [ trg_word2id[w] if w",
"else trg_word2id[\"<unk>\"] for w in line[:-1] ] + [trg_word2id[\"<pad>\"]] * (max_trg_len - len(line))",
"if w in self.trg[corpus_idx][\"word2id\"] else self.trg[corpus_idx][\"word2id\"][\"<unk>\"] for w in line[1:] ] + [self.trg[corpus_idx][\"word2id\"][\"<pad>\"]]",
"(max_sent2_len - len(line)) for line in sorted_sent2_lines ] sent1 = Variable(torch.LongTensor(sent1)).cuda() sent2 =",
"self.trg[corpus_idx][\"word2id\"][\"<unk>\"] for w in line[:-1] ] + [self.trg[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_trg_len - len(line)) for",
"idx in range(len(self.src)): self._reset_filepointer(idx) for idx in range(len(self.src)): self.fetch_buffer(idx) def _reset_filepointer(self, idx): \"\"\"Reset",
"= {} for sentence in sentences: if isinstance(sentence, str): if lowercase: sentence =",
"reset the contents of the current buffer. \"\"\" # Reset the contents of",
"self.fname_src ] self.f_trg = [ open(fname, \"r\", encoding=\"utf-8\") for fname in self.fname_trg ]",
"file of the form premise \\t hypothesis \\t label. Args: train(torch.Tensor): Training dataset.",
"for source. trg_word2id(list): Word to index for target. Returns: Dict for seq2seq model.",
"Index. index(int): Index. batch_size(int): Batch Size. max_len_src(int): Max length for resource. max_len_trg(int): Max",
"self.save_dir) # Check if a cached vocab file exists. if os.path.exists(os.path.join(self.save_dir, \"src_vocab.pkl\")): vocab",
"] sent1_lens = [len(line) for line in sent1] sorted_sent1_indices = np.argsort(sent1_lens)[::-1] sorted_sent1_lines =",
"word2id, id2word = self.construct_vocab( fname, self.trg_vocab_size, self.lowercase ) corpus[\"word2id\"], corpus[\"id2word\"] = word2id, id2word",
"self.dev_lines = [ line.strip().lower().split(\"\\t\") for line in open(self.dev, encoding=\"utf-8\") ] self.test_lines = [",
"sentences(list): The list of sentences. vocab_size(int): The size of vocabulary. lowercase(bool): If lowercase",
"self.vocab is not None: # binary mode doesn't take an encoding argument self.vocab",
"for line in open(val_trg, \"r\", encoding=\"utf-8\") ] else: val_src = [ line.strip().split() for",
"for line in sent1] sorted_sent1_indices = np.argsort(sent1_lens)[::-1] sorted_sent1_lines = [sent1[idx] for idx in",
"input_lines_src, \"input_trg\": input_lines_trg, \"output_trg\": output_lines_trg, \"src_lens\": sorted_src_lens, \"type\": \"seq2seq\", } def compute_validation_loss( config,",
"# Populate buffer for src, trg in zip(self.f_src[idx], self.f_trg[idx]): if len(self.src[idx][\"data\"]) == self.buffer_size:",
"operator import os import pickle import numpy as np import torch from sklearn.utils",
"src self.fname_trg = trg self.src_vocab_size = src_vocab_size self.trg_vocab_size = trg_vocab_size self.tasknames = tasknames",
"task_idx, lowercase=False ): \"\"\"Compute validation loss for a task. Args: config(dict): configuration list.",
"requires_grad=False) .squeeze() .cuda() ) return { \"sent1\": sent1, \"sent2\": sent2, \"sent1_lens\": sent1_lens, \"sent2_lens\":",
"= pickle.load( open(os.path.join(self.save_dir, \"src_vocab.pkl\"), \"rb\") ) word2id, id2word = vocab[\"word2id\"], vocab[\"id2word\"] # If",
"in enumerate(sorted_words): id2word[ind + 4] = word return word2id, id2word def construct_vocab( self,",
"cycle around. \"\"\" if len(self.src[idx][\"data\"]) < self.buffer_size: assert len(self.src[idx][\"data\"]) == len(self.trg[idx][\"data\"]) # Cast",
"open(self.dev, encoding=\"utf-8\") ] self.test_lines = [ line.strip().lower().split(\"\\t\") for line in open(self.test, encoding=\"utf-8\") ]",
"sentences: if isinstance(sentence, str): if lowercase: sentence = sentence.lower() if not charlevel: sentence",
"If need to split the sentence with space. Returns: word2id(list): Word to index",
"rights reserved. # Licensed under the MIT License. \"\"\"Minibatching utilities.\"\"\" import itertools import",
"self.src[corpus_idx][\"word2id\"][w] if w in self.src[corpus_idx][\"word2id\"] else self.src[corpus_idx][\"word2id\"][\"<unk>\"] for w in line ] +",
"\"trg_vocab.pkl\"), \"rb\") ) for idx, (corpus, fname) in enumerate(zip(self.trg, self.f_trg)): word2id, id2word =",
"source. trg_word2id(list): Word to index for target. Returns: Dict for seq2seq model. \"\"\"",
"Variable(torch.LongTensor(sorted_sent2_lens), requires_grad=False) .squeeze() .cuda() ) rev_sent1 = ( Variable(torch.LongTensor(rev_sent1), requires_grad=False) .squeeze() .cuda() )",
"lines[index : index + batch_size] ] sent1_lens = [len(line) for line in sent1]",
"the sentences. charlevel(bool): If need to split the sentence with space. Returns: word2id(list):",
"loss = criterion( decoder_logit.contiguous().view(-1, decoder_logit.size(2)), minibatch[\"output_trg\"].contiguous().view(-1), ) # losses.append(loss.data[0]) losses.append(loss.item()) return np.mean(losses) #",
"sorted_trg_lens = [len(line) for line in sorted_trg_lines] max_src_len = max(sorted_src_lens) max_trg_len = max(sorted_trg_lens)",
"sent1] sorted_sent1_indices = np.argsort(sent1_lens)[::-1] sorted_sent1_lines = [sent1[idx] for idx in sorted_sent1_indices] rev_sent1 =",
"in vocab: del vocab[\"<s>\"] if \"<pad>\" in vocab: del vocab[\"<pad>\"] if \"</s>\" in",
"j, batch_size, train_iterator.src[task_idx][\"word2id\"], train_iterator.trg[task_idx][\"word2id\"], ) decoder_logit = model(minibatch, task_idx) loss = criterion( decoder_logit.contiguous().view(-1,",
"Returns: word2id(list): Word to index list. id2word(list): Index to word list. \"\"\" if",
"\"\"\"Prepare minibatch. Args: corpus_idx(int): Corpus Index. index(int): Index. batch_size(int): Batch Size. max_len_src(int): Max",
"= config[\"training\"][\"batch_size\"] losses = [] for j in range(0, len(val_src), batch_size): minibatch =",
"= [ line.strip().lower().split(\"\\t\") for line in open(self.train, encoding=\"utf-8\") ] self.dev_lines = [ line.strip().lower().split(\"\\t\")",
"in open(val_trg, \"r\", encoding=\"utf-8\") ] else: val_src = [ line.strip().split() for line in",
"\"\"\" vocab = {} for sentence in sentences: if isinstance(sentence, str): if lowercase:",
"contents of the file, cycle around. \"\"\" if len(self.src[idx][\"data\"]) < self.buffer_size: assert len(self.src[idx][\"data\"])",
"If not, compute the vocab from scratch and store a cache. else: word2id,",
"in lines[index : index + batch_size] ] sent2 = [ [\"<s>\"] + line[1].split()",
"[src_word2id[\"<pad>\"]] * (max_src_len - len(line)) for line in sorted_src_lines ] input_lines_trg = [",
"sentences, vocab_size, lowercase=False, charlevel=False ): \"\"\"Create vocabulary. Args: sentences(list): The list of sentences.",
"= np.argsort(sent1_lens)[::-1] sorted_sent1_lines = [sent1[idx] for idx in sorted_sent1_indices] rev_sent1 = np.argsort(sorted_sent1_indices) sent2_lens",
"self.build_vocab() \"\"\"Reset file pointers to the start after reading the file to build",
"index(int): index for the file. batch_size(int): batch size. src_word2id(list): Word to index for",
"else self.trg[corpus_idx][\"word2id\"][\"<unk>\"] for w in line[:-1] ] + [self.trg[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_trg_len - len(line))",
"= Variable( # torch.LongTensor(sorted_src_lens) # ).squeeze().cuda() sorted_src_lens = ( Variable(torch.LongTensor(sorted_src_lens)) .view(len(sorted_src_lens)) .cuda() )",
"sorted_sent2_lines] max_sent1_len = max(sorted_sent1_lens) max_sent2_len = max(sorted_sent2_lens) sent1 = [ [ self.word2id[w] if",
"sorted_sent2_lines = [sent2[idx] for idx in sorted_sent2_indices] rev_sent2 = np.argsort(sorted_sent2_indices) sorted_sent1_lens = [len(line)",
"self.f_trg[idx] = open(self.fname_trg[idx], \"r\", encoding=\"utf-8\") def fetch_buffer(self, idx, reset=True): \"\"\"Fetch sentences from the",
"for line in open(self.test, encoding=\"utf-8\") ] if self.vocab is not None: # binary",
"self.trg[idx][\"data\"]), key=lambda x: len(x[0]), reverse=True, ) ) \"\"\"If buffer isn't full after reading",
"encoding=\"utf-8\") def fetch_buffer(self, idx, reset=True): \"\"\"Fetch sentences from the file into the buffer.",
"minibatch of src-trg pairs return { \"input_src\": input_lines_src, \"input_trg\": input_lines_trg, \"output_trg\": output_lines_trg, \"src_lens\":",
"file to build vocabularies.\"\"\" for idx in range(len(self.src)): self._reset_filepointer(idx) for idx in range(len(self.src)):",
"shuffle_dataset(self): \"\"\"Shuffle training data.\"\"\" self.train_lines = shuffle(self.train_lines, random_state=self.seed) def get_parallel_minibatch(self, index, batch_size, sent_type=\"train\"):",
"+ line + [\"</s>\"] for line in src[index : index + batch_size] ]",
"the vocabulary. lowercase(bool): If lowercase the dataset. vocab(Union[bytes,str): The list of the vocabulary.",
") def shuffle_dataset(self, idx): \"\"\"Shuffle current buffer.\"\"\" self.src[idx][\"data\"], self.trg[idx][\"data\"] = shuffle( self.src[idx][\"data\"], self.trg[idx][\"data\"],",
") # Return minibatch of src-trg pairs return { \"input_src\": input_lines_src, \"input_trg\": input_lines_trg,",
"params. Each of train/dev/test is a tab-separate file of the form premise \\t",
"\"<pad>\": 1, \"</s>\": 2, \"<unk>\": 3} id2word = {0: \"<s>\", 1: \"<pad>\", 2:",
"Label text to class mapping. self.text2label = {\"entailment\": 0, \"neutral\": 1, \"contradiction\": 2}",
"x: len(x[0]), reverse=True, ) ) \"\"\"If buffer isn't full after reading the contents",
"self.id2word = self.vocab[\"id2word\"] self.vocab_size = len(self.word2id) else: self.word2id, self.id2word = self.construct_vocab( [x[0] for",
"buffer_size=1e6, lowercase=False, seed=0, ): \"\"\"Initialize params. Args: src(list): source dataset. trg(list): target dataset.",
"lowercase the data. Returns: float as the mean of the loss. \"\"\" val_src",
"to the start after reading the file to build vocabularies.\"\"\" for idx in",
"\"\"\" if sent_type == \"train\": lines = self.train_lines elif sent_type == \"dev\": lines",
"construct_vocab( self, sentences, vocab_size, lowercase=False, charlevel=False ): \"\"\"Create vocabulary. Args: sentences(list): The list",
"list. model(MultitaskModel): model. train_iterator(BufferedDataIterator): Multi Parallel corpus data iterator. criterion(nn.CrossEntropyLoss): criterion function for",
"@staticmethod def _trim_vocab(vocab, vocab_size): \"\"\"Discard start, end, pad and unk tokens if already",
"] ] trg_lines = [ [\"<s>\"] + line[: max_len_trg - 2] + [\"</s>\"]",
"+ [src_word2id[\"<pad>\"]] * (max_src_len - len(line)) for line in sorted_src_lines ] input_lines_trg =",
"Variable # Change to python3+. # from itertools import zip class DataIterator(object): \"\"\"Data",
"Training dataset. dev(torch.Tensor): Validation dataset. test(torch.Tensor): Testing dataset. vocab_size(int): The size of the",
"= open(self.fname_trg[idx], \"r\", encoding=\"utf-8\") def fetch_buffer(self, idx, reset=True): \"\"\"Fetch sentences from the file",
"vocab.\"\"\" # Construct common source vocab. # Check if save directory exists. if",
"after reading the file to build vocabularies.\"\"\" for idx in range(len(self.src)): self._reset_filepointer(idx) for",
"val_src = [ line.strip().lower().split() for line in open(val_src, \"r\", encoding=\"utf-8\") ] val_trg =",
"= sorted( vocab.items(), key=operator.itemgetter(1), reverse=True ) if vocab_size != -1: sorted_words = [x[0]",
"if len(self.src[idx][\"data\"]) == self.buffer_size: break if self.lowercase: self.src[idx][\"data\"].append(src.lower().split()) self.trg[idx][\"data\"].append(trg.lower().split()) else: self.src[idx][\"data\"].append(src.split()) self.trg[idx][\"data\"].append(trg.split()) #",
"id2word = ( vocab[self.tasknames[idx]][\"word2id\"], vocab[self.tasknames[idx]][\"id2word\"], ) corpus[\"word2id\"], corpus[\"id2word\"] = word2id, id2word else: trg_vocab_dump",
"+ [trg_word2id[\"<pad>\"]] * (max_trg_len - len(line)) for line in sorted_trg_lines ] # For",
"else self.word2id[\"<unk>\"] for w in line ] + [self.word2id[\"<pad>\"]] * (max_sent1_len - len(line))",
"to python3+. # from itertools import zip class DataIterator(object): \"\"\"Data Iterator.\"\"\" @staticmethod def",
"self._trim_vocab(vocab, vocab_size) return word2id, id2word class BufferedDataIterator(DataIterator): \"\"\"Multi Parallel corpus data iterator.\"\"\" def",
"w in line[1:] ] + [trg_word2id[\"<pad>\"]] * (max_trg_len - len(line)) for line in",
"self.test = test self.vocab_size = vocab_size self.lowercase = lowercase self.vocab = vocab self.train_lines",
"The list of sentences. vocab_size(int): The size of vocabulary. lowercase(bool): If lowercase the",
"train_iterator.trg[task_idx][\"word2id\"], ) decoder_logit = model(minibatch, task_idx) loss = criterion( decoder_logit.contiguous().view(-1, decoder_logit.size(2)), minibatch[\"output_trg\"].contiguous().view(-1), )",
"size of the vocabulary. Returns: word2id(list): Word to index list. id2word(list): Index to",
"to build vocabularies.\"\"\" for idx in range(len(self.src)): self._reset_filepointer(idx) for idx in range(len(self.src)): self.fetch_buffer(idx)",
"w in line[:-1] ] + [self.trg[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_trg_len - len(line)) for line in",
"Type of dataset. Returns: dict for batch training. \"\"\" if sent_type == \"train\":",
"ofr target. Returns: minibatch of src-trg pairs(dict). \"\"\" src_lines = [ [\"<s>\"] +",
"for line in src_lines] sorted_indices = np.argsort(src_lens)[::-1] sorted_src_lines = [src_lines[idx] for idx in",
"sentences & word mapping dicts self.src = [ {\"data\": [], \"word2id\": None, \"id2word\":",
"\"id2word\": id2word}, open(os.path.join(self.save_dir, \"src_vocab.pkl\"), \"wb\"), ) for corpus in self.src: corpus[\"word2id\"], corpus[\"id2word\"] =",
"id2word trg_vocab_dump[self.tasknames[idx]] = {} trg_vocab_dump[self.tasknames[idx]][\"word2id\"] = word2id trg_vocab_dump[self.tasknames[idx]][\"id2word\"] = id2word pickle.dump( trg_vocab_dump, open(os.path.join(self.save_dir,",
"index + batch_size] ] sent2 = [ [\"<s>\"] + line[1].split() + [\"</s>\"] for",
"[\"</s>\"] for line in trg[index : index + batch_size] ] src_lens = [len(line)",
"def shuffle_dataset(self, idx): \"\"\"Shuffle current buffer.\"\"\" self.src[idx][\"data\"], self.trg[idx][\"data\"] = shuffle( self.src[idx][\"data\"], self.trg[idx][\"data\"], random_state=self.seed,",
": index + batch_size] ] labels = [ self.text2label[line[2]] for line in lines[index",
"len(self.src[idx][\"data\"]) < self.buffer_size: assert len(self.src[idx][\"data\"]) == len(self.trg[idx][\"data\"]) # Cast things to list to",
"training. \"\"\" if sent_type == \"train\": lines = self.train_lines elif sent_type == \"dev\":",
"if sent_type == \"train\": lines = self.train_lines elif sent_type == \"dev\": lines =",
"sklearn.utils import shuffle from torch.autograd import Variable # Change to python3+. # from",
"= [len(line) for line in sorted_trg_lines] max_src_len = max(sorted_src_lens) max_trg_len = max(sorted_trg_lens) #",
"] + [self.trg[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_trg_len - len(line)) for line in sorted_trg_lines ] output_lines_trg",
"self.trg[corpus_idx][\"word2id\"][\"<unk>\"] for w in line[1:] ] + [self.trg[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_trg_len - len(line)) for",
"word2id, id2word trg_vocab_dump[self.tasknames[idx]] = {} trg_vocab_dump[self.tasknames[idx]][\"word2id\"] = word2id trg_vocab_dump[self.tasknames[idx]][\"id2word\"] = id2word pickle.dump( trg_vocab_dump,",
"2, \"<unk>\": 3} id2word = {0: \"<s>\", 1: \"<pad>\", 2: \"</s>\", 3: \"<unk>\"}",
"sentence with space. Returns: word2id(list): Word to index list. id2word(list): Index to word",
"Word to index list. id2word(list): Index to word list. \"\"\" vocab = {}",
"in sorted_sent1_indices] rev_sent1 = np.argsort(sorted_sent1_indices) sent2_lens = [len(line) for line in sent2] sorted_sent2_indices",
"np import torch from sklearn.utils import shuffle from torch.autograd import Variable # Change",
"\"\"\"Compute validation loss for a task. Args: config(dict): configuration list. model(MultitaskModel): model. train_iterator(BufferedDataIterator):",
"for fname in self.fname_src ] self.f_trg = [ open(fname, \"r\", encoding=\"utf-8\") for fname",
"self.construct_vocab( [x[0] for x in self.train_lines] + [x[1] for x in self.train_lines], self.vocab_size,",
"if w in self.src[corpus_idx][\"word2id\"] else self.src[corpus_idx][\"word2id\"][\"<unk>\"] for w in line ] + [self.src[corpus_idx][\"word2id\"][\"<pad>\"]]",
"itertools.chain.from_iterable(self.f_src), self.src_vocab_size, self.lowercase, ) pickle.dump( {\"word2id\": word2id, \"id2word\": id2word}, open(os.path.join(self.save_dir, \"src_vocab.pkl\"), \"wb\"), )",
"the buffer. Args: idx(int): Index used to fetch the sentences. reset(bool): If need",
".squeeze() .cuda() ) rev_sent2 = ( Variable(torch.LongTensor(rev_sent2), requires_grad=False) .squeeze() .cuda() ) return {",
"def build_vocab(self): \"\"\"Build a memory efficient vocab.\"\"\" # Construct common source vocab. #",
"def compute_validation_loss( config, model, train_iterator, criterion, task_idx, lowercase=False ): \"\"\"Compute validation loss for",
"# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT",
"[], \"word2id\": None, \"id2word\": None} for i in range(len(self.fname_trg)) ] self.build_vocab() \"\"\"Reset file",
"id2word = vocab[\"word2id\"], vocab[\"id2word\"] # If not, compute the vocab from scratch and",
"np.argsort(sent1_lens)[::-1] sorted_sent1_lines = [sent1[idx] for idx in sorted_sent1_indices] rev_sent1 = np.argsort(sorted_sent1_indices) sent2_lens =",
"saving dir. buffer_size(float): Buffer size. lowercase(bool): if lowercase the data. \"\"\" self.seed =",
"list. \"\"\" if \"<s>\" in vocab: del vocab[\"<s>\"] if \"<pad>\" in vocab: del",
"in range(len(self.fname_src)) ] self.trg = [ {\"data\": [], \"word2id\": None, \"id2word\": None} for",
"[x[1] for x in self.train_lines], self.vocab_size, lowercase=self.lowercase, ) # Label text to class",
"length for resource. max_len_trg(int): Max length ofr target. Returns: minibatch of src-trg pairs(dict).",
"the dataset. vocab(Union[bytes,str): The list of the vocabulary. \"\"\" self.seed = seed self.train",
"id2word(list): Index to word list. \"\"\" vocab = {} for sentence in sentences:",
"+ 4 for ind, word in enumerate(sorted_words): id2word[ind + 4] = word return",
"\"\"\" if \"<s>\" in vocab: del vocab[\"<s>\"] if \"<pad>\" in vocab: del vocab[\"<pad>\"]",
"): \"\"\"Prepare minibatch. Args: corpus_idx(int): Corpus Index. index(int): Index. batch_size(int): Batch Size. max_len_src(int):",
"= np.argsort(sorted_sent1_indices) sent2_lens = [len(line) for line in sent2] sorted_sent2_indices = np.argsort(sent2_lens)[::-1] sorted_sent2_lines",
"self.test_lines = [ line.strip().lower().split(\"\\t\") for line in open(self.test, encoding=\"utf-8\") ] if self.vocab is",
"pointers to the start after reading the file to build vocabularies.\"\"\" for idx",
"# Cast lists to torch tensors input_lines_src = Variable(torch.LongTensor(input_lines_src)).cuda() input_lines_trg = Variable(torch.LongTensor(input_lines_trg)).cuda() output_lines_trg",
"# torch.LongTensor(sorted_src_lens) # ).squeeze().cuda() sorted_src_lens = ( Variable(torch.LongTensor(sorted_src_lens)) .view(len(sorted_src_lens)) .cuda() ) return {",
"val_trg = [ line.strip().lower().split() for line in open(val_trg, \"r\", encoding=\"utf-8\") ] else: val_src",
"[\"</s>\"] for line in self.src[corpus_idx][\"data\"][ index : index + batch_size ] ] trg_lines",
"trg, src_vocab_size, trg_vocab_size, tasknames, save_dir, buffer_size=1e6, lowercase=False, seed=0, ): \"\"\"Initialize params. Args: src(list):",
"sentence in sentences: if isinstance(sentence, str): if lowercase: sentence = sentence.lower() if not",
"\"\"\"Shuffle training data.\"\"\" self.train_lines = shuffle(self.train_lines, random_state=self.seed) def get_parallel_minibatch(self, index, batch_size, sent_type=\"train\"): \"\"\"Prepare",
"[ self.trg[corpus_idx][\"word2id\"][w] if w in self.trg[corpus_idx][\"word2id\"] else self.trg[corpus_idx][\"word2id\"][\"<unk>\"] for w in line[:-1] ]",
"= [x[0] for x in sorted_word2id] for ind, word in enumerate(sorted_words): word2id[word] =",
"\"r\", encoding=\"utf-8\") ] val_trg = [ line.strip().split() for line in open(val_trg, \"r\", encoding=\"utf-8\")",
"dev, test, vocab_size, lowercase=True, vocab=None, seed=0 ): \"\"\"Initialize params. Each of train/dev/test is",
"== \"train\": lines = self.train_lines elif sent_type == \"dev\": lines = self.dev_lines else:",
"sorted_indices = np.argsort(src_lens)[::-1] sorted_src_lines = [src_lines[idx] for idx in sorted_indices] sorted_trg_lines = [trg_lines[idx]",
"dictionaries that contain sentences & word mapping dicts self.src = [ {\"data\": [],",
"configuration list. model(MultitaskModel): model. train_iterator(BufferedDataIterator): Multi Parallel corpus data iterator. criterion(nn.CrossEntropyLoss): criterion function",
"\"output_trg\": output_lines_trg, \"src_lens\": sorted_src_lens, \"type\": \"seq2seq\", } def compute_validation_loss( config, model, train_iterator, criterion,",
"pickle.load( open(os.path.join(self.save_dir, \"src_vocab.pkl\"), \"rb\") ) word2id, id2word = vocab[\"word2id\"], vocab[\"id2word\"] # If not,",
"enumerate(zip(self.trg, self.f_trg)): word2id, id2word = ( vocab[self.tasknames[idx]][\"word2id\"], vocab[self.tasknames[idx]][\"id2word\"], ) corpus[\"word2id\"], corpus[\"id2word\"] = word2id,",
"in self.trg[corpus_idx][\"data\"][ index : index + batch_size ] ] \"\"\"Sort sentences by decreasing",
"Index used to fetch the sentences. reset(bool): If need to reset the contents",
"open(fname, \"r\", encoding=\"utf-8\") for fname in self.fname_src ] self.f_trg = [ open(fname, \"r\",",
"lines = self.train_lines elif sent_type == \"dev\": lines = self.dev_lines else: lines =",
"i in range(len(self.fname_src)) ] self.trg = [ {\"data\": [], \"word2id\": None, \"id2word\": None}",
"input_lines_trg, \"output_trg\": output_lines_trg, \"src_lens\": sorted_src_lens, \"type\": \"seq2seq\", } class NLIIterator(DataIterator): \"\"\"Data iterator for",
"\"labels\": labels, \"type\": \"nli\", } def get_validation_minibatch( src, trg, index, batch_size, src_word2id, trg_word2id",
"Licensed under the MIT License. \"\"\"Minibatching utilities.\"\"\" import itertools import operator import os",
"in zip(self.f_src[idx], self.f_trg[idx]): if len(self.src[idx][\"data\"]) == self.buffer_size: break if self.lowercase: self.src[idx][\"data\"].append(src.lower().split()) self.trg[idx][\"data\"].append(trg.lower().split()) else:",
"index + batch_size ] ] trg_lines = [ [\"<s>\"] + line[: max_len_trg -",
"w in self.trg[corpus_idx][\"word2id\"] else self.trg[corpus_idx][\"word2id\"][\"<unk>\"] for w in line[:-1] ] + [self.trg[corpus_idx][\"word2id\"][\"<pad>\"]] *",
"lowercase=self.lowercase, ) # Label text to class mapping. self.text2label = {\"entailment\": 0, \"neutral\":",
"# Label text to class mapping. self.text2label = {\"entailment\": 0, \"neutral\": 1, \"contradiction\":",
"model. \"\"\" src_lines = [ [\"<s>\"] + line + [\"</s>\"] for line in",
"Testing dataset. vocab_size(int): The size of the vocabulary. lowercase(bool): If lowercase the dataset.",
"# Return minibatch of src-trg pairs return { \"input_src\": input_lines_src, \"input_trg\": input_lines_trg, \"output_trg\":",
"[self.word2id[\"<pad>\"]] * (max_sent2_len - len(line)) for line in sorted_sent2_lines ] sent1 = Variable(torch.LongTensor(sent1)).cuda()",
"[trg_lines[idx] for idx in sorted_indices] sorted_src_lens = [len(line) for line in sorted_src_lines] sorted_trg_lens",
"file pointer. Args: idx(int): Index used to reset file pointer. \"\"\" self.f_src[idx] =",
"start, end, pad and unk tokens if already present. Args: vocab(list): Vocabulary. vocab_size(int):",
"vocab[\"<s>\"] if \"<pad>\" in vocab: del vocab[\"<pad>\"] if \"</s>\" in vocab: del vocab[\"</s>\"]",
"Parallel corpus data iterator.\"\"\" def __init__( self, src, trg, src_vocab_size, trg_vocab_size, tasknames, save_dir,",
"in sorted_sent2_indices] rev_sent2 = np.argsort(sorted_sent2_indices) sorted_sent1_lens = [len(line) for line in sorted_sent1_lines] sorted_sent2_lens",
"NLI datasets.\"\"\" def __init__( self, train, dev, test, vocab_size, lowercase=True, vocab=None, seed=0 ):",
"in trg_word2id else trg_word2id[\"<unk>\"] for w in line[:-1] ] + [trg_word2id[\"<pad>\"]] * (max_trg_len",
"if not charlevel: sentence = sentence.split() for word in sentence: if word not",
"+ line + [\"</s>\"] for line in trg[index : index + batch_size] ]",
"self.trg[corpus_idx][\"word2id\"] else self.trg[corpus_idx][\"word2id\"][\"<unk>\"] for w in line[:-1] ] + [self.trg[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_trg_len -",
"sentences by decreasing length within a minibatch for `torch.nn.utils.packed_padded_sequence`\"\"\" src_lens = [len(line) for",
") corpus[\"word2id\"], corpus[\"id2word\"] = word2id, id2word trg_vocab_dump[self.tasknames[idx]] = {} trg_vocab_dump[self.tasknames[idx]][\"word2id\"] = word2id trg_vocab_dump[self.tasknames[idx]][\"id2word\"]",
"dataset. Returns: dict for batch training. \"\"\" if sent_type == \"train\": lines =",
"if save directory exists. if not os.path.exists(self.save_dir): raise ValueError(\"Could not find save dir",
"[ line.strip().lower().split(\"\\t\") for line in open(self.train, encoding=\"utf-8\") ] self.dev_lines = [ line.strip().lower().split(\"\\t\") for",
"Returns: minibatch of src-trg pairs(dict). \"\"\" src_lines = [ [\"<s>\"] + line[: max_len_src",
"len(self.src[idx][\"data\"]) == len(self.trg[idx][\"data\"]) # Cast things to list to avoid issue with calling",
".cuda() ) sent2_lens = ( Variable(torch.LongTensor(sorted_sent2_lens), requires_grad=False) .squeeze() .cuda() ) rev_sent1 = (",
"in sorted_trg_lines] max_src_len = max(sorted_src_lens) max_trg_len = max(sorted_trg_lens) # Map words to indices",
"[\"<s>\"] + line + [\"</s>\"] for line in trg[index : index + batch_size]",
"vocab_size self.lowercase = lowercase self.vocab = vocab self.train_lines = [ line.strip().lower().split(\"\\t\") for line",
"+ batch_size] ] sent1_lens = [len(line) for line in sent1] sorted_sent1_indices = np.argsort(sent1_lens)[::-1]",
"[ [\"<s>\"] + line + [\"</s>\"] for line in src[index : index +",
"to split the sentence with space. Returns: word2id(list): Word to index list. id2word(list):",
"] input_lines_trg = [ [ self.trg[corpus_idx][\"word2id\"][w] if w in self.trg[corpus_idx][\"word2id\"] else self.trg[corpus_idx][\"word2id\"][\"<unk>\"] for",
"w in line ] + [self.word2id[\"<pad>\"]] * (max_sent1_len - len(line)) for line in",
"open(os.path.join(self.save_dir, \"src_vocab.pkl\"), \"wb\"), ) for corpus in self.src: corpus[\"word2id\"], corpus[\"id2word\"] = word2id, id2word",
"= [ open(fname, \"r\", encoding=\"utf-8\") for fname in self.fname_trg ] # Initialize dictionaries",
"def get_parallel_minibatch(self, index, batch_size, sent_type=\"train\"): \"\"\"Prepare minibatch. Args: index(int): The index for line.",
"] # For pytroch 0.4 with torch.no_grad(): input_lines_src = Variable(torch.LongTensor(input_lines_src)).cuda() input_lines_trg = Variable(torch.LongTensor(input_lines_trg)).cuda()",
"in lines[index : index + batch_size] ] labels = [ self.text2label[line[2]] for line",
"in line ] + [self.src[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_src_len - len(line)) for line in sorted_src_lines",
"length within a minibatch for `torch.nn.utils.packed_padded_sequence`\"\"\" src_lens = [len(line) for line in src_lines]",
"torch.LongTensor(sorted_src_lens) # ).squeeze().cuda() sorted_src_lens = ( Variable(torch.LongTensor(sorted_src_lens)) .view(len(sorted_src_lens)) .cuda() ) return { \"input_src\":",
"\"\"\"Prepare minibatch. Args: src(list): source data. trg(list): target data. index(int): index for the",
"open(self.train, encoding=\"utf-8\") ] self.dev_lines = [ line.strip().lower().split(\"\\t\") for line in open(self.dev, encoding=\"utf-8\") ]",
"Dict for seq2seq model. \"\"\" src_lines = [ [\"<s>\"] + line + [\"</s>\"]",
"src_vocab_size self.trg_vocab_size = trg_vocab_size self.tasknames = tasknames self.save_dir = save_dir self.buffer_size = buffer_size",
"self.trg_vocab_size, self.lowercase ) corpus[\"word2id\"], corpus[\"id2word\"] = word2id, id2word trg_vocab_dump[self.tasknames[idx]] = {} trg_vocab_dump[self.tasknames[idx]][\"word2id\"] =",
"indices input_lines_src = [ [ self.src[corpus_idx][\"word2id\"][w] if w in self.src[corpus_idx][\"word2id\"] else self.src[corpus_idx][\"word2id\"][\"<unk>\"] for",
"max_len_src, max_len_trg ): \"\"\"Prepare minibatch. Args: corpus_idx(int): Corpus Index. index(int): Index. batch_size(int): Batch",
"] batch_size = config[\"training\"][\"batch_size\"] losses = [] for j in range(0, len(val_src), batch_size):",
"sorted_trg_lines ] output_lines_trg = [ [ trg_word2id[w] if w in trg_word2id else trg_word2id[\"<unk>\"]",
"rev_sent2, \"labels\": labels, \"type\": \"nli\", } def get_validation_minibatch( src, trg, index, batch_size, src_word2id,",
"= [ [\"<s>\"] + line + [\"</s>\"] for line in src[index : index",
"if w in src else src_word2id[\"<unk>\"] for w in line] + [src_word2id[\"<pad>\"]] *",
"to word list. \"\"\" vocab = {} for sentence in sentences: if isinstance(sentence,",
"batch_size(int): Batch Size. max_len_src(int): Max length for resource. max_len_trg(int): Max length ofr target.",
"dataset. vocab_size(int): The size of the vocabulary. lowercase(bool): If lowercase the dataset. vocab(Union[bytes,str):",
"all the files. self.f_src = [ open(fname, \"r\", encoding=\"utf-8\") for fname in self.fname_src",
"into the buffer. Args: idx(int): Index used to fetch the sentences. reset(bool): If",
"line in src[index : index + batch_size] ] trg_lines = [ [\"<s>\"] +",
"the sentences. reset(bool): If need to reset the contents of the current buffer.",
"line + [\"</s>\"] for line in trg[index : index + batch_size] ] src_lens",
"encoding argument self.vocab = pickle.load(open(self.vocab, \"rb\")) self.word2id = self.vocab[\"word2id\"] self.id2word = self.vocab[\"id2word\"] self.vocab_size",
"self.trg[corpus_idx][\"word2id\"][w] if w in self.trg[corpus_idx][\"word2id\"] else self.trg[corpus_idx][\"word2id\"][\"<unk>\"] for w in line[1:] ] +",
"= [] # Populate buffer for src, trg in zip(self.f_src[idx], self.f_trg[idx]): if len(self.src[idx][\"data\"])",
"train, dev, test, vocab_size, lowercase=True, vocab=None, seed=0 ): \"\"\"Initialize params. Each of train/dev/test",
"] + [trg_word2id[\"<pad>\"]] * (max_trg_len - len(line)) for line in sorted_trg_lines ] output_lines_trg",
"Vocabulary. vocab_size(int): The size of the vocabulary. Returns: word2id(list): Word to index list.",
"list to avoid issue with calling .append above self.src[idx][\"data\"] = list(self.src[idx][\"data\"]) self.trg[idx][\"data\"] =",
"= self.test_lines sent1 = [ [\"<s>\"] + line[0].split() + [\"</s>\"] for line in",
"id2word = self._trim_vocab(vocab, vocab_size) return word2id, id2word class BufferedDataIterator(DataIterator): \"\"\"Multi Parallel corpus data",
"[\"<s>\"] + line[0].split() + [\"</s>\"] for line in lines[index : index + batch_size]",
"Index to word list. \"\"\" if \"<s>\" in vocab: del vocab[\"<s>\"] if \"<pad>\"",
"[self.trg[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_trg_len - len(line)) for line in sorted_trg_lines ] output_lines_trg = [",
"as np import torch from sklearn.utils import shuffle from torch.autograd import Variable #",
"[len(line) for line in sorted_sent2_lines] max_sent1_len = max(sorted_sent1_lens) max_sent2_len = max(sorted_sent2_lens) sent1 =",
"seq2seq model. \"\"\" src_lines = [ [\"<s>\"] + line + [\"</s>\"] for line",
"= Variable(torch.LongTensor(sent2)).cuda() labels = Variable(torch.LongTensor(labels)).cuda() sent1_lens = ( Variable(torch.LongTensor(sorted_sent1_lens), requires_grad=False) .squeeze() .cuda() )",
"with space. Returns: word2id(list): Word to index list. id2word(list): Index to word list.",
"idx in sorted_indices] sorted_src_lens = [len(line) for line in sorted_src_lines] sorted_trg_lens = [len(line)",
"seed self.fname_src = src self.fname_trg = trg self.src_vocab_size = src_vocab_size self.trg_vocab_size = trg_vocab_size",
"= ind + 4 for ind, word in enumerate(sorted_words): id2word[ind + 4] =",
"= word2id, id2word trg_vocab_dump[self.tasknames[idx]] = {} trg_vocab_dump[self.tasknames[idx]][\"word2id\"] = word2id trg_vocab_dump[self.tasknames[idx]][\"id2word\"] = id2word pickle.dump(",
"for seq2seq model. \"\"\" src_lines = [ [\"<s>\"] + line + [\"</s>\"] for",
"source vocab. # Check if save directory exists. if not os.path.exists(self.save_dir): raise ValueError(\"Could",
"vocab_size != -1: sorted_words = [x[0] for x in sorted_word2id[:vocab_size]] else: sorted_words =",
"for line in lines[index : index + batch_size] ] sent2 = [ [\"<s>\"]",
"list of the vocabulary. \"\"\" self.seed = seed self.train = train self.dev =",
"vocab self.train_lines = [ line.strip().lower().split(\"\\t\") for line in open(self.train, encoding=\"utf-8\") ] self.dev_lines =",
"trg_word2id else trg_word2id[\"<unk>\"] for w in line[1:] ] + [trg_word2id[\"<pad>\"]] * (max_trg_len -",
"tasknames, save_dir, buffer_size=1e6, lowercase=False, seed=0, ): \"\"\"Initialize params. Args: src(list): source dataset. trg(list):",
"\"word2id\": None, \"id2word\": None} for i in range(len(self.fname_src)) ] self.trg = [ {\"data\":",
") pickle.dump( {\"word2id\": word2id, \"id2word\": id2word}, open(os.path.join(self.save_dir, \"src_vocab.pkl\"), \"wb\"), ) for corpus in",
"# sorted_src_lens = Variable( # torch.LongTensor(sorted_src_lens) # ).squeeze().cuda() sorted_src_lens = ( Variable(torch.LongTensor(sorted_src_lens)) .view(len(sorted_src_lens))",
"index, batch_size, max_len_src, max_len_trg ): \"\"\"Prepare minibatch. Args: corpus_idx(int): Corpus Index. index(int): Index.",
"sentences. vocab_size(int): The size of vocabulary. lowercase(bool): If lowercase the sentences. charlevel(bool): If",
"encoding=\"utf-8\") self.f_trg[idx] = open(self.fname_trg[idx], \"r\", encoding=\"utf-8\") def fetch_buffer(self, idx, reset=True): \"\"\"Fetch sentences from",
"= [] self.trg[idx][\"data\"] = [] # Populate buffer for src, trg in zip(self.f_src[idx],",
"the start after reading the file to build vocabularies.\"\"\" for idx in range(len(self.src)):",
"\"type\": \"seq2seq\", } def compute_validation_loss( config, model, train_iterator, criterion, task_idx, lowercase=False ): \"\"\"Compute",
"The size of target vocab. tasknames(list): The list of task names. save_dir(str): The",
"for idx in sorted_sent1_indices] rev_sent1 = np.argsort(sorted_sent1_indices) sent2_lens = [len(line) for line in",
"max(sorted_sent2_lens) sent1 = [ [ self.word2id[w] if w in self.word2id else self.word2id[\"<unk>\"] for",
"= list(self.trg[idx][\"data\"]) self._reset_filepointer(idx) self.fetch_buffer(idx, reset=False) def build_vocab(self): \"\"\"Build a memory efficient vocab.\"\"\" #",
"word list. \"\"\" vocab = {} for sentence in sentences: if isinstance(sentence, str):",
"rev_sent1 = np.argsort(sorted_sent1_indices) sent2_lens = [len(line) for line in sent2] sorted_sent2_indices = np.argsort(sent2_lens)[::-1]",
"% self.save_dir) # Check if a cached vocab file exists. if os.path.exists(os.path.join(self.save_dir, \"src_vocab.pkl\")):",
"vocab: vocab[word] = 1 else: vocab[word] += 1 word2id, id2word = self._trim_vocab(vocab, vocab_size)",
"= Variable(torch.LongTensor(sent1)).cuda() sent2 = Variable(torch.LongTensor(sent2)).cuda() labels = Variable(torch.LongTensor(labels)).cuda() sent1_lens = ( Variable(torch.LongTensor(sorted_sent1_lens), requires_grad=False)",
"of the loss. \"\"\" val_src = config[\"data\"][\"paths\"][task_idx][\"val_src\"] val_trg = config[\"data\"][\"paths\"][task_idx][\"val_trg\"] if lowercase: val_src",
"w in self.src[corpus_idx][\"word2id\"] else self.src[corpus_idx][\"word2id\"][\"<unk>\"] for w in line ] + [self.src[corpus_idx][\"word2id\"][\"<pad>\"]] *",
"\"r\", encoding=\"utf-8\") ] val_trg = [ line.strip().lower().split() for line in open(val_trg, \"r\", encoding=\"utf-8\")",
"data. \"\"\" self.seed = seed self.fname_src = src self.fname_trg = trg self.src_vocab_size =",
"{0: \"<s>\", 1: \"<pad>\", 2: \"</s>\", 3: \"<unk>\"} sorted_word2id = sorted( vocab.items(), key=operator.itemgetter(1),",
"minibatch of src-trg pairs(dict). \"\"\" src_lines = [ [\"<s>\"] + line[: max_len_src -",
"x in sorted_word2id] for ind, word in enumerate(sorted_words): word2id[word] = ind + 4",
"if os.path.exists(os.path.join(self.save_dir, \"src_vocab.pkl\")): vocab = pickle.load( open(os.path.join(self.save_dir, \"src_vocab.pkl\"), \"rb\") ) word2id, id2word =",
"exists. if os.path.exists(os.path.join(self.save_dir, \"src_vocab.pkl\")): vocab = pickle.load( open(os.path.join(self.save_dir, \"src_vocab.pkl\"), \"rb\") ) word2id, id2word",
"is not None: # binary mode doesn't take an encoding argument self.vocab =",
"Batch Size. max_len_src(int): Max length for resource. max_len_trg(int): Max length ofr target. Returns:",
"for the target vocabulary. if os.path.exists(os.path.join(self.save_dir, \"trg_vocab.pkl\")): vocab = pickle.load( open(os.path.join(self.save_dir, \"trg_vocab.pkl\"), \"rb\")",
"Return minibatch of src-trg pairs return { \"input_src\": input_lines_src, \"input_trg\": input_lines_trg, \"output_trg\": output_lines_trg,",
"sent2_lens = [len(line) for line in sent2] sorted_sent2_indices = np.argsort(sent2_lens)[::-1] sorted_sent2_lines = [sent2[idx]",
"bucketing) self.src[idx][\"data\"], self.trg[idx][\"data\"] = zip( *sorted( zip(self.src[idx][\"data\"], self.trg[idx][\"data\"]), key=lambda x: len(x[0]), reverse=True, )",
"for line in open(self.dev, encoding=\"utf-8\") ] self.test_lines = [ line.strip().lower().split(\"\\t\") for line in",
"for line in open(val_trg, \"r\", encoding=\"utf-8\") ] batch_size = config[\"training\"][\"batch_size\"] losses = []",
"word2id(list): Word to index list. id2word(list): Index to word list. \"\"\" if \"<s>\"",
"fname in self.fname_trg ] # Initialize dictionaries that contain sentences & word mapping",
"index + batch_size ] ] \"\"\"Sort sentences by decreasing length within a minibatch",
"= ( Variable(torch.LongTensor(sorted_src_lens)) .view(len(sorted_src_lens)) .cuda() ) return { \"input_src\": input_lines_src, \"input_trg\": input_lines_trg, \"output_trg\":",
"data iterator. criterion(nn.CrossEntropyLoss): criterion function for loss. task_idx(int): Task index. lowercase(bool): If lowercase",
"encoding=\"utf-8\") ] else: val_src = [ line.strip().split() for line in open(val_src, \"r\", encoding=\"utf-8\")",
"in range(0, len(val_src), batch_size): minibatch = get_validation_minibatch( val_src, val_trg, j, batch_size, train_iterator.src[task_idx][\"word2id\"], train_iterator.trg[task_idx][\"word2id\"],",
"word mapping dicts self.src = [ {\"data\": [], \"word2id\": None, \"id2word\": None} for",
"if \"<unk>\" in vocab: del vocab[\"<unk>\"] word2id = {\"<s>\": 0, \"<pad>\": 1, \"</s>\":",
"of the vocabulary. Returns: word2id(list): Word to index list. id2word(list): Index to word",
"the sentence with space. Returns: word2id(list): Word to index list. id2word(list): Index to",
"sorted_sent1_lines = [sent1[idx] for idx in sorted_sent1_indices] rev_sent1 = np.argsort(sorted_sent1_indices) sent2_lens = [len(line)",
"trg_word2id[w] if w in trg_word2id else trg_word2id[\"<unk>\"] for w in line[1:] ] +",
"self.text2label = {\"entailment\": 0, \"neutral\": 1, \"contradiction\": 2} self.shuffle_dataset() def shuffle_dataset(self): \"\"\"Shuffle training",
"contents of the current buffer. if reset: self.src[idx][\"data\"] = [] self.trg[idx][\"data\"] = []",
"`torch.nn.utils.packed_padded_sequence`\"\"\" src_lens = [len(line) for line in src_lines] sorted_indices = np.argsort(src_lens)[::-1] sorted_src_lines =",
"for `torch.nn.utils.packed_padded_sequence`\"\"\" src_lens = [len(line) for line in src_lines] sorted_indices = np.argsort(src_lens)[::-1] sorted_src_lines",
"not None: # binary mode doesn't take an encoding argument self.vocab = pickle.load(open(self.vocab,",
"charlevel: sentence = sentence.split() for word in sentence: if word not in vocab:",
"+ batch_size ] ] \"\"\"Sort sentences by decreasing length within a minibatch for",
"for line in sorted_sent2_lines ] sent1 = Variable(torch.LongTensor(sent1)).cuda() sent2 = Variable(torch.LongTensor(sent2)).cuda() labels =",
"iterator. criterion(nn.CrossEntropyLoss): criterion function for loss. task_idx(int): Task index. lowercase(bool): If lowercase the",
"= max(sorted_sent2_lens) sent1 = [ [ self.word2id[w] if w in self.word2id else self.word2id[\"<unk>\"]",
"Returns: float as the mean of the loss. \"\"\" val_src = config[\"data\"][\"paths\"][task_idx][\"val_src\"] val_trg",
"within a minibatch for `torch.nn.utils.packed_padded_sequence`\"\"\" src_lens = [len(line) for line in src_lines] sorted_indices",
"a memory efficient vocab.\"\"\" # Construct common source vocab. # Check if save",
"self.construct_vocab( fname, self.trg_vocab_size, self.lowercase ) corpus[\"word2id\"], corpus[\"id2word\"] = word2id, id2word trg_vocab_dump[self.tasknames[idx]] = {}",
"= shuffle(self.train_lines, random_state=self.seed) def get_parallel_minibatch(self, index, batch_size, sent_type=\"train\"): \"\"\"Prepare minibatch. Args: index(int): The",
"dev(torch.Tensor): Validation dataset. test(torch.Tensor): Testing dataset. vocab_size(int): The size of the vocabulary. lowercase(bool):",
"in open(val_src, \"r\", encoding=\"utf-8\") ] val_trg = [ line.strip().lower().split() for line in open(val_trg,",
"\"word2id\": None, \"id2word\": None} for i in range(len(self.fname_trg)) ] self.build_vocab() \"\"\"Reset file pointers",
"for w in line[1:] ] + [self.trg[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_trg_len - len(line)) for line",
"line in open(self.train, encoding=\"utf-8\") ] self.dev_lines = [ line.strip().lower().split(\"\\t\") for line in open(self.dev,",
"Index. batch_size(int): Batch Size. max_len_src(int): Max length for resource. max_len_trg(int): Max length ofr",
"] # Initialize dictionaries that contain sentences & word mapping dicts self.src =",
"lowercase(bool): If lowercase the data. Returns: float as the mean of the loss.",
": %s\" % self.save_dir) # Check if a cached vocab file exists. if",
"self.src = [ {\"data\": [], \"word2id\": None, \"id2word\": None} for i in range(len(self.fname_src))",
"x in self.train_lines] + [x[1] for x in self.train_lines], self.vocab_size, lowercase=self.lowercase, ) #",
"mapping dicts self.src = [ {\"data\": [], \"word2id\": None, \"id2word\": None} for i",
"in line ] + [self.word2id[\"<pad>\"]] * (max_sent1_len - len(line)) for line in sorted_sent1_lines",
"datasets.\"\"\" def __init__( self, train, dev, test, vocab_size, lowercase=True, vocab=None, seed=0 ): \"\"\"Initialize",
"self, src, trg, src_vocab_size, trg_vocab_size, tasknames, save_dir, buffer_size=1e6, lowercase=False, seed=0, ): \"\"\"Initialize params.",
"the data. \"\"\" self.seed = seed self.fname_src = src self.fname_trg = trg self.src_vocab_size",
"src-trg pairs(dict). \"\"\" src_lines = [ [\"<s>\"] + line[: max_len_src - 2] +",
"used to fetch the sentences. reset(bool): If need to reset the contents of",
"for line. batch_size(int): Batch size. sent_type(str): Type of dataset. Returns: dict for batch",
": index + batch_size ] ] trg_lines = [ [\"<s>\"] + line[: max_len_trg",
"for i in range(len(self.fname_src)) ] self.trg = [ {\"data\": [], \"word2id\": None, \"id2word\":",
"Max length ofr target. Returns: minibatch of src-trg pairs(dict). \"\"\" src_lines = [",
"in sorted_src_lines ] input_lines_trg = [ [ self.trg[corpus_idx][\"word2id\"][w] if w in self.trg[corpus_idx][\"word2id\"] else",
"- len(line)) for line in sorted_trg_lines ] output_lines_trg = [ [ self.trg[corpus_idx][\"word2id\"][w] if",
"rev_sent1, \"rev_sent2\": rev_sent2, \"labels\": labels, \"type\": \"nli\", } def get_validation_minibatch( src, trg, index,",
"# Licensed under the MIT License. \"\"\"Minibatching utilities.\"\"\" import itertools import operator import",
"trg_vocab_dump[self.tasknames[idx]] = {} trg_vocab_dump[self.tasknames[idx]][\"word2id\"] = word2id trg_vocab_dump[self.tasknames[idx]][\"id2word\"] = id2word pickle.dump( trg_vocab_dump, open(os.path.join(self.save_dir, \"trg_vocab.pkl\"),",
"+ [\"</s>\"] for line in lines[index : index + batch_size] ] sent2 =",
"line[1].split() + [\"</s>\"] for line in lines[index : index + batch_size] ] labels",
"j in range(0, len(val_src), batch_size): minibatch = get_validation_minibatch( val_src, val_trg, j, batch_size, train_iterator.src[task_idx][\"word2id\"],",
"] if self.vocab is not None: # binary mode doesn't take an encoding",
"key=lambda x: len(x[0]), reverse=True, ) ) \"\"\"If buffer isn't full after reading the",
"of file pointers to all the files. self.f_src = [ open(fname, \"r\", encoding=\"utf-8\")",
"input_lines_src, \"input_trg\": input_lines_trg, \"output_trg\": output_lines_trg, \"src_lens\": sorted_src_lens, \"type\": \"seq2seq\", } class NLIIterator(DataIterator): \"\"\"Data",
"Args: src(list): source data. trg(list): target data. index(int): index for the file. batch_size(int):",
"reverse=True ) if vocab_size != -1: sorted_words = [x[0] for x in sorted_word2id[:vocab_size]]",
"src_word2id, trg_word2id ): \"\"\"Prepare minibatch. Args: src(list): source data. trg(list): target data. index(int):",
"Args: config(dict): configuration list. model(MultitaskModel): model. train_iterator(BufferedDataIterator): Multi Parallel corpus data iterator. criterion(nn.CrossEntropyLoss):",
"mode doesn't take an encoding argument self.vocab = pickle.load(open(self.vocab, \"rb\")) self.word2id = self.vocab[\"word2id\"]",
"\"\"\"Fetch sentences from the file into the buffer. Args: idx(int): Index used to",
"self.seed = seed self.fname_src = src self.fname_trg = trg self.src_vocab_size = src_vocab_size self.trg_vocab_size",
"the vocab from scratch and store a cache. else: word2id, id2word = self.construct_vocab(",
"labels = [ self.text2label[line[2]] for line in lines[index : index + batch_size] ]",
"in sent2] sorted_sent2_indices = np.argsort(sent2_lens)[::-1] sorted_sent2_lines = [sent2[idx] for idx in sorted_sent2_indices] rev_sent2",
"line.strip().split() for line in open(val_src, \"r\", encoding=\"utf-8\") ] val_trg = [ line.strip().split() for",
"store a cache. else: word2id, id2word = self.construct_vocab( itertools.chain.from_iterable(self.f_src), self.src_vocab_size, self.lowercase, ) pickle.dump(",
"get_validation_minibatch( src, trg, index, batch_size, src_word2id, trg_word2id ): \"\"\"Prepare minibatch. Args: src(list): source",
"Parallel corpus data iterator. criterion(nn.CrossEntropyLoss): criterion function for loss. task_idx(int): Task index. lowercase(bool):",
"trg_word2id[\"<unk>\"] for w in line[1:] ] + [trg_word2id[\"<pad>\"]] * (max_trg_len - len(line)) for",
"with calling .append above self.src[idx][\"data\"] = list(self.src[idx][\"data\"]) self.trg[idx][\"data\"] = list(self.trg[idx][\"data\"]) self._reset_filepointer(idx) self.fetch_buffer(idx, reset=False)",
"w in trg_word2id else trg_word2id[\"<unk>\"] for w in line[:-1] ] + [trg_word2id[\"<pad>\"]] *",
"\\t hypothesis \\t label. Args: train(torch.Tensor): Training dataset. dev(torch.Tensor): Validation dataset. test(torch.Tensor): Testing",
"+ [self.src[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_src_len - len(line)) for line in sorted_src_lines ] input_lines_trg =",
"del vocab[\"<pad>\"] if \"</s>\" in vocab: del vocab[\"</s>\"] if \"<unk>\" in vocab: del",
"in sent1] sorted_sent1_indices = np.argsort(sent1_lens)[::-1] sorted_sent1_lines = [sent1[idx] for idx in sorted_sent1_indices] rev_sent1",
"= self.construct_vocab( itertools.chain.from_iterable(self.f_src), self.src_vocab_size, self.lowercase, ) pickle.dump( {\"word2id\": word2id, \"id2word\": id2word}, open(os.path.join(self.save_dir, \"src_vocab.pkl\"),",
"[] for j in range(0, len(val_src), batch_size): minibatch = get_validation_minibatch( val_src, val_trg, j,",
"# ).squeeze().cuda() sorted_src_lens = ( Variable(torch.LongTensor(sorted_src_lens)) .view(len(sorted_src_lens)) .cuda() ) return { \"input_src\": input_lines_src,",
"encoding=\"utf-8\") ] if self.vocab is not None: # binary mode doesn't take an",
"fetch_buffer(self, idx, reset=True): \"\"\"Fetch sentences from the file into the buffer. Args: idx(int):",
"encoding=\"utf-8\") ] val_trg = [ line.strip().split() for line in open(val_trg, \"r\", encoding=\"utf-8\") ]",
"The list of the vocabulary. \"\"\" self.seed = seed self.train = train self.dev",
"output_lines_trg, \"src_lens\": sorted_src_lens, \"type\": \"seq2seq\", } def compute_validation_loss( config, model, train_iterator, criterion, task_idx,",
"] self.trg = [ {\"data\": [], \"word2id\": None, \"id2word\": None} for i in",
"pointer. Args: idx(int): Index used to reset file pointer. \"\"\" self.f_src[idx] = open(self.fname_src[idx],",
"in line[:-1] ] + [self.trg[corpus_idx][\"word2id\"][\"<pad>\"]] * (max_trg_len - len(line)) for line in sorted_trg_lines",
"not, compute the vocab from scratch and store a cache. else: word2id, id2word",
"= np.argsort(sent2_lens)[::-1] sorted_sent2_lines = [sent2[idx] for idx in sorted_sent2_indices] rev_sent2 = np.argsort(sorted_sent2_indices) sorted_sent1_lens",
"\"\"\"Build a memory efficient vocab.\"\"\" # Construct common source vocab. # Check if",
"the loss. \"\"\" val_src = config[\"data\"][\"paths\"][task_idx][\"val_src\"] val_trg = config[\"data\"][\"paths\"][task_idx][\"val_trg\"] if lowercase: val_src =",
"enumerate(sorted_words): id2word[ind + 4] = word return word2id, id2word def construct_vocab( self, sentences,",
"for corpus in self.src: corpus[\"word2id\"], corpus[\"id2word\"] = word2id, id2word # Do the same",
"max(sorted_sent1_lens) max_sent2_len = max(sorted_sent2_lens) sent1 = [ [ self.word2id[w] if w in self.word2id",
"target dataset. src_vocab_size(int): The size of source vocab. trg_vocab_size(int): The size of target",
"# Construct common source vocab. # Check if save directory exists. if not",
"= {} trg_vocab_dump[self.tasknames[idx]][\"word2id\"] = word2id trg_vocab_dump[self.tasknames[idx]][\"id2word\"] = id2word pickle.dump( trg_vocab_dump, open(os.path.join(self.save_dir, \"trg_vocab.pkl\"), \"wb\"),",
"not find save dir : %s\" % self.save_dir) # Check if a cached",
"\"sent2_lens\": sent2_lens, \"rev_sent1\": rev_sent1, \"rev_sent2\": rev_sent2, \"labels\": labels, \"type\": \"nli\", } def get_validation_minibatch(",
") # Label text to class mapping. self.text2label = {\"entailment\": 0, \"neutral\": 1,",
"for line in sorted_src_lines ] input_lines_trg = [ [ trg_word2id[w] if w in",
"self.trg[idx][\"data\"], random_state=self.seed, ) def get_parallel_minibatch( self, corpus_idx, index, batch_size, max_len_src, max_len_trg ): \"\"\"Prepare",
"def __init__( self, src, trg, src_vocab_size, trg_vocab_size, tasknames, save_dir, buffer_size=1e6, lowercase=False, seed=0, ):",
"} def compute_validation_loss( config, model, train_iterator, criterion, task_idx, lowercase=False ): \"\"\"Compute validation loss",
"* (max_trg_len - len(line)) for line in sorted_trg_lines ] # For pytroch 0.4",
"word2id, id2word # Do the same for the target vocabulary. if os.path.exists(os.path.join(self.save_dir, \"trg_vocab.pkl\")):",
"pickle.load(open(self.vocab, \"rb\")) self.word2id = self.vocab[\"word2id\"] self.id2word = self.vocab[\"id2word\"] self.vocab_size = len(self.word2id) else: self.word2id,",
"{} for idx, (corpus, fname) in enumerate(zip(self.trg, self.f_trg)): word2id, id2word = self.construct_vocab( fname,",
"output_lines_trg = Variable(torch.LongTensor(output_lines_trg)).cuda() sorted_src_lens = ( Variable(torch.LongTensor(sorted_src_lens), volatile=True) .squeeze() .cuda() ) # Return",
"[len(line) for line in sorted_sent1_lines] sorted_sent2_lens = [len(line) for line in sorted_sent2_lines] max_sent1_len",
"memory efficient vocab.\"\"\" # Construct common source vocab. # Check if save directory",
"\"neutral\": 1, \"contradiction\": 2} self.shuffle_dataset() def shuffle_dataset(self): \"\"\"Shuffle training data.\"\"\" self.train_lines = shuffle(self.train_lines,",
"line in lines[index : index + batch_size] ] labels = [ self.text2label[line[2]] for",
"used to reset file pointer. \"\"\" self.f_src[idx] = open(self.fname_src[idx], \"r\", encoding=\"utf-8\") self.f_trg[idx] =",
"vocab_size(int): The size of vocabulary. lowercase(bool): If lowercase the sentences. charlevel(bool): If need",
"loss for a task. Args: config(dict): configuration list. model(MultitaskModel): model. train_iterator(BufferedDataIterator): Multi Parallel",
"lines = self.dev_lines else: lines = self.test_lines sent1 = [ [\"<s>\"] + line[0].split()",
"for tokenized NLI datasets.\"\"\" def __init__( self, train, dev, test, vocab_size, lowercase=True, vocab=None,",
"in self.train_lines], self.vocab_size, lowercase=self.lowercase, ) # Label text to class mapping. self.text2label =",
"for line in sorted_trg_lines] max_src_len = max(sorted_src_lens) max_trg_len = max(sorted_trg_lens) input_lines_src = [",
"file pointers to the start after reading the file to build vocabularies.\"\"\" for",
"tensors input_lines_src = Variable(torch.LongTensor(input_lines_src)).cuda() input_lines_trg = Variable(torch.LongTensor(input_lines_trg)).cuda() output_lines_trg = Variable(torch.LongTensor(output_lines_trg)).cuda() sorted_src_lens = (",
"else: self.word2id, self.id2word = self.construct_vocab( [x[0] for x in self.train_lines] + [x[1] for",
"import numpy as np import torch from sklearn.utils import shuffle from torch.autograd import",
"dataset. vocab(Union[bytes,str): The list of the vocabulary. \"\"\" self.seed = seed self.train =",
"+ [self.word2id[\"<pad>\"]] * (max_sent1_len - len(line)) for line in sorted_sent1_lines ] sent2 =",
"def __init__( self, train, dev, test, vocab_size, lowercase=True, vocab=None, seed=0 ): \"\"\"Initialize params.",
"sorted_indices] sorted_src_lens = [len(line) for line in sorted_src_lines] sorted_trg_lens = [len(line) for line",
"line in sorted_sent1_lines ] sent2 = [ [ self.word2id[w] if w in self.word2id",
"zip(self.src[idx][\"data\"], self.trg[idx][\"data\"]), key=lambda x: len(x[0]), reverse=True, ) ) \"\"\"If buffer isn't full after",
"input_lines_trg, \"output_trg\": output_lines_trg, \"src_lens\": sorted_src_lens, \"type\": \"seq2seq\", } def compute_validation_loss( config, model, train_iterator,",
"for line in sorted_src_lines ] input_lines_trg = [ [ self.trg[corpus_idx][\"word2id\"][w] if w in",
"(max_trg_len - len(line)) for line in sorted_trg_lines ] output_lines_trg = [ [ self.trg[corpus_idx][\"word2id\"][w]",
"1, \"contradiction\": 2} self.shuffle_dataset() def shuffle_dataset(self): \"\"\"Shuffle training data.\"\"\" self.train_lines = shuffle(self.train_lines, random_state=self.seed)",
"= [ line.strip().lower().split(\"\\t\") for line in open(self.dev, encoding=\"utf-8\") ] self.test_lines = [ line.strip().lower().split(\"\\t\")",
"\"input_trg\": input_lines_trg, \"output_trg\": output_lines_trg, \"src_lens\": sorted_src_lens, \"type\": \"seq2seq\", } def compute_validation_loss( config, model,",
"# Change to python3+. # from itertools import zip class DataIterator(object): \"\"\"Data Iterator.\"\"\"",
"the current buffer. \"\"\" # Reset the contents of the current buffer. if",
"[ [ self.trg[corpus_idx][\"word2id\"][w] if w in self.trg[corpus_idx][\"word2id\"] else self.trg[corpus_idx][\"word2id\"][\"<unk>\"] for w in line[1:]",
"torch.autograd import Variable # Change to python3+. # from itertools import zip class",
"if w in trg_word2id else trg_word2id[\"<unk>\"] for w in line[1:] ] + [trg_word2id[\"<pad>\"]]",
"lowercase(bool): If lowercase the dataset. vocab(Union[bytes,str): The list of the vocabulary. \"\"\" self.seed",
"return { \"sent1\": sent1, \"sent2\": sent2, \"sent1_lens\": sent1_lens, \"sent2_lens\": sent2_lens, \"rev_sent1\": rev_sent1, \"rev_sent2\":",
"unk tokens if already present. Args: vocab(list): Vocabulary. vocab_size(int): The size of the",
"minibatch for `torch.nn.utils.packed_padded_sequence`\"\"\" src_lens = [len(line) for line in src_lines] sorted_indices = np.argsort(src_lens)[::-1]",
"\"<unk>\"} sorted_word2id = sorted( vocab.items(), key=operator.itemgetter(1), reverse=True ) if vocab_size != -1: sorted_words",
"test(torch.Tensor): Testing dataset. vocab_size(int): The size of the vocabulary. lowercase(bool): If lowercase the",
"src_word2id(list): Word to index for source. trg_word2id(list): Word to index for target. Returns:",
"Variable(torch.LongTensor(sent2)).cuda() labels = Variable(torch.LongTensor(labels)).cuda() sent1_lens = ( Variable(torch.LongTensor(sorted_sent1_lens), requires_grad=False) .squeeze() .cuda() ) sent2_lens",
") ) \"\"\"If buffer isn't full after reading the contents of the file,",
"line in sorted_trg_lines ] # Cast lists to torch tensors input_lines_src = Variable(torch.LongTensor(input_lines_src)).cuda()",
"in sorted_trg_lines] max_src_len = max(sorted_src_lens) max_trg_len = max(sorted_trg_lens) input_lines_src = [ [src_word2id[w] if",
"sentences. charlevel(bool): If need to split the sentence with space. Returns: word2id(list): Word",
"task_idx) loss = criterion( decoder_logit.contiguous().view(-1, decoder_logit.size(2)), minibatch[\"output_trg\"].contiguous().view(-1), ) # losses.append(loss.data[0]) losses.append(loss.item()) return np.mean(losses)",
"sorted_word2id = sorted( vocab.items(), key=operator.itemgetter(1), reverse=True ) if vocab_size != -1: sorted_words =",
"Map words to indices input_lines_src = [ [ self.src[corpus_idx][\"word2id\"][w] if w in self.src[corpus_idx][\"word2id\"]",
"Variable(torch.LongTensor(output_lines_trg)).cuda() # sorted_src_lens = Variable( # torch.LongTensor(sorted_src_lens) # ).squeeze().cuda() sorted_src_lens = ( Variable(torch.LongTensor(sorted_src_lens))",
"input_lines_trg = Variable(torch.LongTensor(input_lines_trg)).cuda() output_lines_trg = Variable(torch.LongTensor(output_lines_trg)).cuda() sorted_src_lens = ( Variable(torch.LongTensor(sorted_src_lens), volatile=True) .squeeze() .cuda()",
"text to class mapping. self.text2label = {\"entailment\": 0, \"neutral\": 1, \"contradiction\": 2} self.shuffle_dataset()",
"for line in lines[index : index + batch_size] ] labels = [ self.text2label[line[2]]",
"self.test_lines sent1 = [ [\"<s>\"] + line[0].split() + [\"</s>\"] for line in lines[index",
"max(sorted_src_lens) max_trg_len = max(sorted_trg_lens) input_lines_src = [ [src_word2id[w] if w in src else",
"get_validation_minibatch( val_src, val_trg, j, batch_size, train_iterator.src[task_idx][\"word2id\"], train_iterator.trg[task_idx][\"word2id\"], ) decoder_logit = model(minibatch, task_idx) loss",
"shuffle( self.src[idx][\"data\"], self.trg[idx][\"data\"], random_state=self.seed, ) def get_parallel_minibatch( self, corpus_idx, index, batch_size, max_len_src, max_len_trg",
"files. self.f_src = [ open(fname, \"r\", encoding=\"utf-8\") for fname in self.fname_src ] self.f_trg",
"minibatch. Args: src(list): source data. trg(list): target data. index(int): index for the file.",
"for ind, word in enumerate(sorted_words): word2id[word] = ind + 4 for ind, word",
"import torch from sklearn.utils import shuffle from torch.autograd import Variable # Change to",
"input_lines_src = Variable(torch.LongTensor(input_lines_src)).cuda() input_lines_trg = Variable(torch.LongTensor(input_lines_trg)).cuda() output_lines_trg = Variable(torch.LongTensor(output_lines_trg)).cuda() # sorted_src_lens = Variable(",
"of source vocab. trg_vocab_size(int): The size of target vocab. tasknames(list): The list of",
"open(val_src, \"r\", encoding=\"utf-8\") ] val_trg = [ line.strip().split() for line in open(val_trg, \"r\",",
"the file into the buffer. Args: idx(int): Index used to fetch the sentences.",
"Each of train/dev/test is a tab-separate file of the form premise \\t hypothesis",
"Task index. lowercase(bool): If lowercase the data. Returns: float as the mean of",
"idx, reset=True): \"\"\"Fetch sentences from the file into the buffer. Args: idx(int): Index",
"[ trg_word2id[w] if w in trg_word2id else trg_word2id[\"<unk>\"] for w in line[1:] ]",
"[x[0] for x in self.train_lines] + [x[1] for x in self.train_lines], self.vocab_size, lowercase=self.lowercase,",
"- len(line)) for line in sorted_src_lines ] input_lines_trg = [ [ trg_word2id[w] if",
"id2word else: trg_vocab_dump = {} for idx, (corpus, fname) in enumerate(zip(self.trg, self.f_trg)): word2id,",
"] self.f_trg = [ open(fname, \"r\", encoding=\"utf-8\") for fname in self.fname_trg ] #",
"import zip class DataIterator(object): \"\"\"Data Iterator.\"\"\" @staticmethod def _trim_vocab(vocab, vocab_size): \"\"\"Discard start, end,",
"= [sent1[idx] for idx in sorted_sent1_indices] rev_sent1 = np.argsort(sorted_sent1_indices) sent2_lens = [len(line) for",
"\"\"\" self.f_src[idx] = open(self.fname_src[idx], \"r\", encoding=\"utf-8\") self.f_trg[idx] = open(self.fname_trg[idx], \"r\", encoding=\"utf-8\") def fetch_buffer(self,",
"For pytroch 0.4 with torch.no_grad(): input_lines_src = Variable(torch.LongTensor(input_lines_src)).cuda() input_lines_trg = Variable(torch.LongTensor(input_lines_trg)).cuda() output_lines_trg =",
"build vocabularies.\"\"\" for idx in range(len(self.src)): self._reset_filepointer(idx) for idx in range(len(self.src)): self.fetch_buffer(idx) def"
] |
[] |
[
"def before_request(): g.db = sqlite3.connect(app.config['DATABASE']) @app.teardown_request def teardown_request(exception): db = getattr(g, 'db', None)",
"methods=['POST', 'GET']) def login(): if request.method == 'POST': name = request.form['user'] password =",
"g.db.execute('select * from users where name=? and password=?', [name, password]) if cursor.fetchone(): session['user']",
"#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sqlite3 import config from flask",
"python3 # -*- coding: utf-8 -*- import sqlite3 import config from flask import",
"cursor = g.db.execute('select * from users where name=? and password=?', [name, password]) if",
"db = getattr(g, 'db', None) if db is not None: db.close() # URL",
"if db is not None: db.close() # URL 重定向 @app.route('/') def index(): if",
"sqlite3 import config from flask import * app = Flask(__name__) app.config.from_object('config') @app.before_request def",
"def index(): if 'user' in session: return render_template('hello.html', name=session['user']) else: return redirect(url_for('login'), 302)",
"is not None: db.close() # URL 重定向 @app.route('/') def index(): if 'user' in",
"import config from flask import * app = Flask(__name__) app.config.from_object('config') @app.before_request def before_request():",
"@app.before_request def before_request(): g.db = sqlite3.connect(app.config['DATABASE']) @app.teardown_request def teardown_request(exception): db = getattr(g, 'db',",
"db.close() # URL 重定向 @app.route('/') def index(): if 'user' in session: return render_template('hello.html',",
"not None: db.close() # URL 重定向 @app.route('/') def index(): if 'user' in session:",
"= Flask(__name__) app.config.from_object('config') @app.before_request def before_request(): g.db = sqlite3.connect(app.config['DATABASE']) @app.teardown_request def teardown_request(exception): db",
"URL 重定向 @app.route('/') def index(): if 'user' in session: return render_template('hello.html', name=session['user']) else:",
"successfully!') return redirect(url_for('index')) else: flash('No such user!', 'error') return redirect(url_for('login')) else: return render_template('login.html')",
"def login(): if request.method == 'POST': name = request.form['user'] password = request.form['password'] cursor",
"cursor.fetchone(): session['user'] = name flash('login successfully!') return redirect(url_for('index')) else: flash('No such user!', 'error')",
"from flask import * app = Flask(__name__) app.config.from_object('config') @app.before_request def before_request(): g.db =",
"name flash('login successfully!') return redirect(url_for('index')) else: flash('No such user!', 'error') return redirect(url_for('login')) else:",
"'GET']) def login(): if request.method == 'POST': name = request.form['user'] password = request.form['password']",
"重定向 @app.route('/') def index(): if 'user' in session: return render_template('hello.html', name=session['user']) else: return",
"<reponame>hyhplus/FlaskFirstDemo #!/usr/bin/env python3 # -*- coding: utf-8 -*- import sqlite3 import config from",
"@app.route('/') def index(): if 'user' in session: return render_template('hello.html', name=session['user']) else: return redirect(url_for('login'),",
"teardown_request(exception): db = getattr(g, 'db', None) if db is not None: db.close() #",
"= sqlite3.connect(app.config['DATABASE']) @app.teardown_request def teardown_request(exception): db = getattr(g, 'db', None) if db is",
"in session: return render_template('hello.html', name=session['user']) else: return redirect(url_for('login'), 302) @app.route('/login', methods=['POST', 'GET']) def",
"'POST': name = request.form['user'] password = request.form['password'] cursor = g.db.execute('select * from users",
"login(): if request.method == 'POST': name = request.form['user'] password = request.form['password'] cursor =",
"flask import * app = Flask(__name__) app.config.from_object('config') @app.before_request def before_request(): g.db = sqlite3.connect(app.config['DATABASE'])",
"index(): if 'user' in session: return render_template('hello.html', name=session['user']) else: return redirect(url_for('login'), 302) @app.route('/login',",
"None: db.close() # URL 重定向 @app.route('/') def index(): if 'user' in session: return",
"if request.method == 'POST': name = request.form['user'] password = request.form['password'] cursor = g.db.execute('select",
"password]) if cursor.fetchone(): session['user'] = name flash('login successfully!') return redirect(url_for('index')) else: flash('No such",
"* app = Flask(__name__) app.config.from_object('config') @app.before_request def before_request(): g.db = sqlite3.connect(app.config['DATABASE']) @app.teardown_request def",
"coding: utf-8 -*- import sqlite3 import config from flask import * app =",
"name=session['user']) else: return redirect(url_for('login'), 302) @app.route('/login', methods=['POST', 'GET']) def login(): if request.method ==",
"def teardown_request(exception): db = getattr(g, 'db', None) if db is not None: db.close()",
"users where name=? and password=?', [name, password]) if cursor.fetchone(): session['user'] = name flash('login",
"@app.route('/login', methods=['POST', 'GET']) def login(): if request.method == 'POST': name = request.form['user'] password",
"app = Flask(__name__) app.config.from_object('config') @app.before_request def before_request(): g.db = sqlite3.connect(app.config['DATABASE']) @app.teardown_request def teardown_request(exception):",
"302) @app.route('/login', methods=['POST', 'GET']) def login(): if request.method == 'POST': name = request.form['user']",
"render_template('hello.html', name=session['user']) else: return redirect(url_for('login'), 302) @app.route('/login', methods=['POST', 'GET']) def login(): if request.method",
"before_request(): g.db = sqlite3.connect(app.config['DATABASE']) @app.teardown_request def teardown_request(exception): db = getattr(g, 'db', None) if",
"request.method == 'POST': name = request.form['user'] password = request.form['password'] cursor = g.db.execute('select *",
"import sqlite3 import config from flask import * app = Flask(__name__) app.config.from_object('config') @app.before_request",
"and password=?', [name, password]) if cursor.fetchone(): session['user'] = name flash('login successfully!') return redirect(url_for('index'))",
"# -*- coding: utf-8 -*- import sqlite3 import config from flask import *",
"getattr(g, 'db', None) if db is not None: db.close() # URL 重定向 @app.route('/')",
"name = request.form['user'] password = request.form['password'] cursor = g.db.execute('select * from users where",
"-*- coding: utf-8 -*- import sqlite3 import config from flask import * app",
"return redirect(url_for('login'), 302) @app.route('/login', methods=['POST', 'GET']) def login(): if request.method == 'POST': name",
"if 'user' in session: return render_template('hello.html', name=session['user']) else: return redirect(url_for('login'), 302) @app.route('/login', methods=['POST',",
"[name, password]) if cursor.fetchone(): session['user'] = name flash('login successfully!') return redirect(url_for('index')) else: flash('No",
"else: return redirect(url_for('login'), 302) @app.route('/login', methods=['POST', 'GET']) def login(): if request.method == 'POST':",
"utf-8 -*- import sqlite3 import config from flask import * app = Flask(__name__)",
"config from flask import * app = Flask(__name__) app.config.from_object('config') @app.before_request def before_request(): g.db",
"session['user'] = name flash('login successfully!') return redirect(url_for('index')) else: flash('No such user!', 'error') return",
"password=?', [name, password]) if cursor.fetchone(): session['user'] = name flash('login successfully!') return redirect(url_for('index')) else:",
"flash('login successfully!') return redirect(url_for('index')) else: flash('No such user!', 'error') return redirect(url_for('login')) else: return",
"* from users where name=? and password=?', [name, password]) if cursor.fetchone(): session['user'] =",
"= name flash('login successfully!') return redirect(url_for('index')) else: flash('No such user!', 'error') return redirect(url_for('login'))",
"name=? and password=?', [name, password]) if cursor.fetchone(): session['user'] = name flash('login successfully!') return",
"db is not None: db.close() # URL 重定向 @app.route('/') def index(): if 'user'",
"= getattr(g, 'db', None) if db is not None: db.close() # URL 重定向",
"@app.teardown_request def teardown_request(exception): db = getattr(g, 'db', None) if db is not None:",
"g.db = sqlite3.connect(app.config['DATABASE']) @app.teardown_request def teardown_request(exception): db = getattr(g, 'db', None) if db",
"if cursor.fetchone(): session['user'] = name flash('login successfully!') return redirect(url_for('index')) else: flash('No such user!',",
"None) if db is not None: db.close() # URL 重定向 @app.route('/') def index():",
"import * app = Flask(__name__) app.config.from_object('config') @app.before_request def before_request(): g.db = sqlite3.connect(app.config['DATABASE']) @app.teardown_request",
"from users where name=? and password=?', [name, password]) if cursor.fetchone(): session['user'] = name",
"'db', None) if db is not None: db.close() # URL 重定向 @app.route('/') def",
"request.form['password'] cursor = g.db.execute('select * from users where name=? and password=?', [name, password])",
"# URL 重定向 @app.route('/') def index(): if 'user' in session: return render_template('hello.html', name=session['user'])",
"redirect(url_for('login'), 302) @app.route('/login', methods=['POST', 'GET']) def login(): if request.method == 'POST': name =",
"app.config.from_object('config') @app.before_request def before_request(): g.db = sqlite3.connect(app.config['DATABASE']) @app.teardown_request def teardown_request(exception): db = getattr(g,",
"-*- import sqlite3 import config from flask import * app = Flask(__name__) app.config.from_object('config')",
"= request.form['password'] cursor = g.db.execute('select * from users where name=? and password=?', [name,",
"= request.form['user'] password = request.form['password'] cursor = g.db.execute('select * from users where name=?",
"sqlite3.connect(app.config['DATABASE']) @app.teardown_request def teardown_request(exception): db = getattr(g, 'db', None) if db is not",
"'user' in session: return render_template('hello.html', name=session['user']) else: return redirect(url_for('login'), 302) @app.route('/login', methods=['POST', 'GET'])",
"request.form['user'] password = request.form['password'] cursor = g.db.execute('select * from users where name=? and",
"password = request.form['password'] cursor = g.db.execute('select * from users where name=? and password=?',",
"Flask(__name__) app.config.from_object('config') @app.before_request def before_request(): g.db = sqlite3.connect(app.config['DATABASE']) @app.teardown_request def teardown_request(exception): db =",
"session: return render_template('hello.html', name=session['user']) else: return redirect(url_for('login'), 302) @app.route('/login', methods=['POST', 'GET']) def login():",
"where name=? and password=?', [name, password]) if cursor.fetchone(): session['user'] = name flash('login successfully!')",
"= g.db.execute('select * from users where name=? and password=?', [name, password]) if cursor.fetchone():",
"== 'POST': name = request.form['user'] password = request.form['password'] cursor = g.db.execute('select * from",
"return render_template('hello.html', name=session['user']) else: return redirect(url_for('login'), 302) @app.route('/login', methods=['POST', 'GET']) def login(): if"
] |
[
"print('Invalid parts') return False if parts[0] != 'Bearer': print('No bearer') return False try:",
"<filename>backend/src/auth.py from flask import request import jwt import os JWT_SECRET = os.getenv('JWT_SECRET') JWT_AUDIENCE",
"authorization.split(' ') if len(parts) != 2: print('Invalid parts') return False if parts[0] !=",
"parts') return False if parts[0] != 'Bearer': print('No bearer') return False try: audience",
"authorization: print('No authorization') return False parts = authorization.split(' ') if len(parts) != 2:",
"Check if the request header includes a valid JWT def verify_jwt(): authorization =",
"header includes a valid JWT def verify_jwt(): authorization = request.headers.get('Authorization') if not authorization:",
"import jwt import os JWT_SECRET = os.getenv('JWT_SECRET') JWT_AUDIENCE = os.getenv('JWT_AUDIENCE') # Check if",
"os.getenv('JWT_SECRET') JWT_AUDIENCE = os.getenv('JWT_AUDIENCE') # Check if the request header includes a valid",
"request import jwt import os JWT_SECRET = os.getenv('JWT_SECRET') JWT_AUDIENCE = os.getenv('JWT_AUDIENCE') # Check",
"parts[0] != 'Bearer': print('No bearer') return False try: audience = [JWT_AUDIENCE] decoded =",
"import request import jwt import os JWT_SECRET = os.getenv('JWT_SECRET') JWT_AUDIENCE = os.getenv('JWT_AUDIENCE') #",
"!= 2: print('Invalid parts') return False if parts[0] != 'Bearer': print('No bearer') return",
"parts = authorization.split(' ') if len(parts) != 2: print('Invalid parts') return False if",
"') if len(parts) != 2: print('Invalid parts') return False if parts[0] != 'Bearer':",
"[JWT_AUDIENCE] decoded = jwt.decode(parts[1], JWT_SECRET, audience=audience, algorithms=['HS256']) return decoded except Exception: print('Invalid JWT')",
"False if parts[0] != 'Bearer': print('No bearer') return False try: audience = [JWT_AUDIENCE]",
"jwt import os JWT_SECRET = os.getenv('JWT_SECRET') JWT_AUDIENCE = os.getenv('JWT_AUDIENCE') # Check if the",
"flask import request import jwt import os JWT_SECRET = os.getenv('JWT_SECRET') JWT_AUDIENCE = os.getenv('JWT_AUDIENCE')",
"# Check if the request header includes a valid JWT def verify_jwt(): authorization",
"valid JWT def verify_jwt(): authorization = request.headers.get('Authorization') if not authorization: print('No authorization') return",
"len(parts) != 2: print('Invalid parts') return False if parts[0] != 'Bearer': print('No bearer')",
"False try: audience = [JWT_AUDIENCE] decoded = jwt.decode(parts[1], JWT_SECRET, audience=audience, algorithms=['HS256']) return decoded",
"a valid JWT def verify_jwt(): authorization = request.headers.get('Authorization') if not authorization: print('No authorization')",
"try: audience = [JWT_AUDIENCE] decoded = jwt.decode(parts[1], JWT_SECRET, audience=audience, algorithms=['HS256']) return decoded except",
"= [JWT_AUDIENCE] decoded = jwt.decode(parts[1], JWT_SECRET, audience=audience, algorithms=['HS256']) return decoded except Exception: print('Invalid",
"False parts = authorization.split(' ') if len(parts) != 2: print('Invalid parts') return False",
"authorization = request.headers.get('Authorization') if not authorization: print('No authorization') return False parts = authorization.split('",
"if not authorization: print('No authorization') return False parts = authorization.split(' ') if len(parts)",
"bearer') return False try: audience = [JWT_AUDIENCE] decoded = jwt.decode(parts[1], JWT_SECRET, audience=audience, algorithms=['HS256'])",
"from flask import request import jwt import os JWT_SECRET = os.getenv('JWT_SECRET') JWT_AUDIENCE =",
"os JWT_SECRET = os.getenv('JWT_SECRET') JWT_AUDIENCE = os.getenv('JWT_AUDIENCE') # Check if the request header",
"= os.getenv('JWT_AUDIENCE') # Check if the request header includes a valid JWT def",
"= authorization.split(' ') if len(parts) != 2: print('Invalid parts') return False if parts[0]",
"if len(parts) != 2: print('Invalid parts') return False if parts[0] != 'Bearer': print('No",
"def verify_jwt(): authorization = request.headers.get('Authorization') if not authorization: print('No authorization') return False parts",
"JWT_SECRET = os.getenv('JWT_SECRET') JWT_AUDIENCE = os.getenv('JWT_AUDIENCE') # Check if the request header includes",
"authorization') return False parts = authorization.split(' ') if len(parts) != 2: print('Invalid parts')",
"audience = [JWT_AUDIENCE] decoded = jwt.decode(parts[1], JWT_SECRET, audience=audience, algorithms=['HS256']) return decoded except Exception:",
"if parts[0] != 'Bearer': print('No bearer') return False try: audience = [JWT_AUDIENCE] decoded",
"!= 'Bearer': print('No bearer') return False try: audience = [JWT_AUDIENCE] decoded = jwt.decode(parts[1],",
"decoded = jwt.decode(parts[1], JWT_SECRET, audience=audience, algorithms=['HS256']) return decoded except Exception: print('Invalid JWT') return",
"return False try: audience = [JWT_AUDIENCE] decoded = jwt.decode(parts[1], JWT_SECRET, audience=audience, algorithms=['HS256']) return",
"if the request header includes a valid JWT def verify_jwt(): authorization = request.headers.get('Authorization')",
"verify_jwt(): authorization = request.headers.get('Authorization') if not authorization: print('No authorization') return False parts =",
"return False parts = authorization.split(' ') if len(parts) != 2: print('Invalid parts') return",
"'Bearer': print('No bearer') return False try: audience = [JWT_AUDIENCE] decoded = jwt.decode(parts[1], JWT_SECRET,",
"= request.headers.get('Authorization') if not authorization: print('No authorization') return False parts = authorization.split(' ')",
"print('No authorization') return False parts = authorization.split(' ') if len(parts) != 2: print('Invalid",
"JWT def verify_jwt(): authorization = request.headers.get('Authorization') if not authorization: print('No authorization') return False",
"print('No bearer') return False try: audience = [JWT_AUDIENCE] decoded = jwt.decode(parts[1], JWT_SECRET, audience=audience,",
"= jwt.decode(parts[1], JWT_SECRET, audience=audience, algorithms=['HS256']) return decoded except Exception: print('Invalid JWT') return False",
"JWT_AUDIENCE = os.getenv('JWT_AUDIENCE') # Check if the request header includes a valid JWT",
"2: print('Invalid parts') return False if parts[0] != 'Bearer': print('No bearer') return False",
"return False if parts[0] != 'Bearer': print('No bearer') return False try: audience =",
"the request header includes a valid JWT def verify_jwt(): authorization = request.headers.get('Authorization') if",
"includes a valid JWT def verify_jwt(): authorization = request.headers.get('Authorization') if not authorization: print('No",
"os.getenv('JWT_AUDIENCE') # Check if the request header includes a valid JWT def verify_jwt():",
"not authorization: print('No authorization') return False parts = authorization.split(' ') if len(parts) !=",
"= os.getenv('JWT_SECRET') JWT_AUDIENCE = os.getenv('JWT_AUDIENCE') # Check if the request header includes a",
"request header includes a valid JWT def verify_jwt(): authorization = request.headers.get('Authorization') if not",
"import os JWT_SECRET = os.getenv('JWT_SECRET') JWT_AUDIENCE = os.getenv('JWT_AUDIENCE') # Check if the request",
"request.headers.get('Authorization') if not authorization: print('No authorization') return False parts = authorization.split(' ') if"
] |
[
"License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"# under the License. from tempest.common import utils from tempest.lib import decorators from",
"Unless required by applicable law or agreed to in writing, software # distributed",
"See the # License for the specific language governing permissions and limitations #",
"\"License\"); you may # not use this file except in compliance with the",
"rbac_base as base class AvailabilityZoneExtRbacTest(base.BaseNetworkExtRbacTest): @classmethod def skip_checks(cls): super(AvailabilityZoneExtRbacTest, cls).skip_checks() if not utils.is_extension_enabled('availability_zone',",
"Apache License, Version 2.0 (the \"License\"); you may # not use this file",
"the License. You may obtain # a copy of the License at #",
"not enabled.\" raise cls.skipException(msg) @rbac_rule_validation.action(service=\"neutron\", rules=[\"get_availability_zone\"]) @decorators.idempotent_id('3c521be8-c32e-11e8-a611-080027758b73') def test_list_availability_zone_rbac(self): \"\"\"List all available zones.",
"law or agreed to in writing, software # distributed under the License is",
"Reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\"); you",
"may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"the Apache License, Version 2.0 (the \"License\"); you may # not use this",
"from patrole_tempest_plugin import rbac_rule_validation from patrole_tempest_plugin.tests.api.network import rbac_base as base class AvailabilityZoneExtRbacTest(base.BaseNetworkExtRbacTest): @classmethod",
"permissions and limitations # under the License. from tempest.common import utils from tempest.lib",
"express or implied. See the # License for the specific language governing permissions",
"if not utils.is_extension_enabled('availability_zone', 'network'): msg = \"network_availability_zone extension not enabled.\" raise cls.skipException(msg) @rbac_rule_validation.action(service=\"neutron\",",
"governing permissions and limitations # under the License. from tempest.common import utils from",
"an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either",
"# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"CONDITIONS OF ANY KIND, either express or implied. See the # License for",
"not use this file except in compliance with the License. You may obtain",
"rules=[\"get_availability_zone\"]) @decorators.idempotent_id('3c521be8-c32e-11e8-a611-080027758b73') def test_list_availability_zone_rbac(self): \"\"\"List all available zones. RBAC test for the neutron",
"utils from tempest.lib import decorators from patrole_tempest_plugin import rbac_rule_validation from patrole_tempest_plugin.tests.api.network import rbac_base",
"admin_resources = (self.ntp_client.list_availability_zones() [\"availability_zones\"]) with self.override_role_and_validate_list( admin_resources=admin_resources) as ctx: ctx.resources = (self.ntp_client.list_availability_zones() ['availability_zones'])",
"patrole_tempest_plugin.tests.api.network import rbac_base as base class AvailabilityZoneExtRbacTest(base.BaseNetworkExtRbacTest): @classmethod def skip_checks(cls): super(AvailabilityZoneExtRbacTest, cls).skip_checks() if",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"with the License. You may obtain # a copy of the License at",
"from tempest.common import utils from tempest.lib import decorators from patrole_tempest_plugin import rbac_rule_validation from",
"import rbac_base as base class AvailabilityZoneExtRbacTest(base.BaseNetworkExtRbacTest): @classmethod def skip_checks(cls): super(AvailabilityZoneExtRbacTest, cls).skip_checks() if not",
"all available zones. RBAC test for the neutron ``list_availability_zones`` function and the ``get_availability_zone``",
"Licensed under the Apache License, Version 2.0 (the \"License\"); you may # not",
"License for the specific language governing permissions and limitations # under the License.",
"= \"network_availability_zone extension not enabled.\" raise cls.skipException(msg) @rbac_rule_validation.action(service=\"neutron\", rules=[\"get_availability_zone\"]) @decorators.idempotent_id('3c521be8-c32e-11e8-a611-080027758b73') def test_list_availability_zone_rbac(self): \"\"\"List",
"2.0 (the \"License\"); you may # not use this file except in compliance",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"the License. from tempest.common import utils from tempest.lib import decorators from patrole_tempest_plugin import",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"use this file except in compliance with the License. You may obtain #",
"# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT",
"Corporation. # All Rights Reserved. # # Licensed under the Apache License, Version",
"AvailabilityZoneExtRbacTest(base.BaseNetworkExtRbacTest): @classmethod def skip_checks(cls): super(AvailabilityZoneExtRbacTest, cls).skip_checks() if not utils.is_extension_enabled('availability_zone', 'network'): msg = \"network_availability_zone",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the #",
"compliance with the License. You may obtain # a copy of the License",
"License, Version 2.0 (the \"License\"); you may # not use this file except",
"BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"neutron ``list_availability_zones`` function and the ``get_availability_zone`` policy \"\"\" admin_resources = (self.ntp_client.list_availability_zones() [\"availability_zones\"]) with",
"is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF",
"zones. RBAC test for the neutron ``list_availability_zones`` function and the ``get_availability_zone`` policy \"\"\"",
"the ``get_availability_zone`` policy \"\"\" admin_resources = (self.ntp_client.list_availability_zones() [\"availability_zones\"]) with self.override_role_and_validate_list( admin_resources=admin_resources) as ctx:",
"from patrole_tempest_plugin.tests.api.network import rbac_base as base class AvailabilityZoneExtRbacTest(base.BaseNetworkExtRbacTest): @classmethod def skip_checks(cls): super(AvailabilityZoneExtRbacTest, cls).skip_checks()",
"IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"implied. See the # License for the specific language governing permissions and limitations",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"OF ANY KIND, either express or implied. See the # License for the",
"test for the neutron ``list_availability_zones`` function and the ``get_availability_zone`` policy \"\"\" admin_resources =",
"available zones. RBAC test for the neutron ``list_availability_zones`` function and the ``get_availability_zone`` policy",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"\"\"\"List all available zones. RBAC test for the neutron ``list_availability_zones`` function and the",
"\"network_availability_zone extension not enabled.\" raise cls.skipException(msg) @rbac_rule_validation.action(service=\"neutron\", rules=[\"get_availability_zone\"]) @decorators.idempotent_id('3c521be8-c32e-11e8-a611-080027758b73') def test_list_availability_zone_rbac(self): \"\"\"List all",
"import decorators from patrole_tempest_plugin import rbac_rule_validation from patrole_tempest_plugin.tests.api.network import rbac_base as base class",
"'network'): msg = \"network_availability_zone extension not enabled.\" raise cls.skipException(msg) @rbac_rule_validation.action(service=\"neutron\", rules=[\"get_availability_zone\"]) @decorators.idempotent_id('3c521be8-c32e-11e8-a611-080027758b73') def",
"# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the",
"super(AvailabilityZoneExtRbacTest, cls).skip_checks() if not utils.is_extension_enabled('availability_zone', 'network'): msg = \"network_availability_zone extension not enabled.\" raise",
"def test_list_availability_zone_rbac(self): \"\"\"List all available zones. RBAC test for the neutron ``list_availability_zones`` function",
"import rbac_rule_validation from patrole_tempest_plugin.tests.api.network import rbac_base as base class AvailabilityZoneExtRbacTest(base.BaseNetworkExtRbacTest): @classmethod def skip_checks(cls):",
"you may # not use this file except in compliance with the License.",
"``get_availability_zone`` policy \"\"\" admin_resources = (self.ntp_client.list_availability_zones() [\"availability_zones\"]) with self.override_role_and_validate_list( admin_resources=admin_resources) as ctx: ctx.resources",
"agreed to in writing, software # distributed under the License is distributed on",
"@classmethod def skip_checks(cls): super(AvailabilityZoneExtRbacTest, cls).skip_checks() if not utils.is_extension_enabled('availability_zone', 'network'): msg = \"network_availability_zone extension",
"\"\"\" admin_resources = (self.ntp_client.list_availability_zones() [\"availability_zones\"]) with self.override_role_and_validate_list( admin_resources=admin_resources) as ctx: ctx.resources = (self.ntp_client.list_availability_zones()",
"(the \"License\"); you may # not use this file except in compliance with",
"enabled.\" raise cls.skipException(msg) @rbac_rule_validation.action(service=\"neutron\", rules=[\"get_availability_zone\"]) @decorators.idempotent_id('3c521be8-c32e-11e8-a611-080027758b73') def test_list_availability_zone_rbac(self): \"\"\"List all available zones. RBAC",
"may # not use this file except in compliance with the License. You",
"# Copyright 2018 AT&T Corporation. # All Rights Reserved. # # Licensed under",
"KIND, either express or implied. See the # License for the specific language",
"msg = \"network_availability_zone extension not enabled.\" raise cls.skipException(msg) @rbac_rule_validation.action(service=\"neutron\", rules=[\"get_availability_zone\"]) @decorators.idempotent_id('3c521be8-c32e-11e8-a611-080027758b73') def test_list_availability_zone_rbac(self):",
"the neutron ``list_availability_zones`` function and the ``get_availability_zone`` policy \"\"\" admin_resources = (self.ntp_client.list_availability_zones() [\"availability_zones\"])",
"AT&T Corporation. # All Rights Reserved. # # Licensed under the Apache License,",
"either express or implied. See the # License for the specific language governing",
"# # Unless required by applicable law or agreed to in writing, software",
"file except in compliance with the License. You may obtain # a copy",
"this file except in compliance with the License. You may obtain # a",
"extension not enabled.\" raise cls.skipException(msg) @rbac_rule_validation.action(service=\"neutron\", rules=[\"get_availability_zone\"]) @decorators.idempotent_id('3c521be8-c32e-11e8-a611-080027758b73') def test_list_availability_zone_rbac(self): \"\"\"List all available",
"# Unless required by applicable law or agreed to in writing, software #",
"License. from tempest.common import utils from tempest.lib import decorators from patrole_tempest_plugin import rbac_rule_validation",
"decorators from patrole_tempest_plugin import rbac_rule_validation from patrole_tempest_plugin.tests.api.network import rbac_base as base class AvailabilityZoneExtRbacTest(base.BaseNetworkExtRbacTest):",
"as base class AvailabilityZoneExtRbacTest(base.BaseNetworkExtRbacTest): @classmethod def skip_checks(cls): super(AvailabilityZoneExtRbacTest, cls).skip_checks() if not utils.is_extension_enabled('availability_zone', 'network'):",
"Copyright 2018 AT&T Corporation. # All Rights Reserved. # # Licensed under the",
"by applicable law or agreed to in writing, software # distributed under the",
"All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the",
"\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"class AvailabilityZoneExtRbacTest(base.BaseNetworkExtRbacTest): @classmethod def skip_checks(cls): super(AvailabilityZoneExtRbacTest, cls).skip_checks() if not utils.is_extension_enabled('availability_zone', 'network'): msg =",
"under the License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"or implied. See the # License for the specific language governing permissions and",
"utils.is_extension_enabled('availability_zone', 'network'): msg = \"network_availability_zone extension not enabled.\" raise cls.skipException(msg) @rbac_rule_validation.action(service=\"neutron\", rules=[\"get_availability_zone\"]) @decorators.idempotent_id('3c521be8-c32e-11e8-a611-080027758b73')",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"skip_checks(cls): super(AvailabilityZoneExtRbacTest, cls).skip_checks() if not utils.is_extension_enabled('availability_zone', 'network'): msg = \"network_availability_zone extension not enabled.\"",
"raise cls.skipException(msg) @rbac_rule_validation.action(service=\"neutron\", rules=[\"get_availability_zone\"]) @decorators.idempotent_id('3c521be8-c32e-11e8-a611-080027758b73') def test_list_availability_zone_rbac(self): \"\"\"List all available zones. RBAC test",
"@rbac_rule_validation.action(service=\"neutron\", rules=[\"get_availability_zone\"]) @decorators.idempotent_id('3c521be8-c32e-11e8-a611-080027758b73') def test_list_availability_zone_rbac(self): \"\"\"List all available zones. RBAC test for the",
"License. You may obtain # a copy of the License at # #",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"the License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR",
"test_list_availability_zone_rbac(self): \"\"\"List all available zones. RBAC test for the neutron ``list_availability_zones`` function and",
"for the specific language governing permissions and limitations # under the License. from",
"distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY",
"def skip_checks(cls): super(AvailabilityZoneExtRbacTest, cls).skip_checks() if not utils.is_extension_enabled('availability_zone', 'network'): msg = \"network_availability_zone extension not",
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); you may",
"language governing permissions and limitations # under the License. from tempest.common import utils",
"on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,",
"limitations # under the License. from tempest.common import utils from tempest.lib import decorators",
"rbac_rule_validation from patrole_tempest_plugin.tests.api.network import rbac_base as base class AvailabilityZoneExtRbacTest(base.BaseNetworkExtRbacTest): @classmethod def skip_checks(cls): super(AvailabilityZoneExtRbacTest,",
"base class AvailabilityZoneExtRbacTest(base.BaseNetworkExtRbacTest): @classmethod def skip_checks(cls): super(AvailabilityZoneExtRbacTest, cls).skip_checks() if not utils.is_extension_enabled('availability_zone', 'network'): msg",
"tempest.common import utils from tempest.lib import decorators from patrole_tempest_plugin import rbac_rule_validation from patrole_tempest_plugin.tests.api.network",
"the specific language governing permissions and limitations # under the License. from tempest.common",
"ANY KIND, either express or implied. See the # License for the specific",
"the # License for the specific language governing permissions and limitations # under",
"except in compliance with the License. You may obtain # a copy of",
"and limitations # under the License. from tempest.common import utils from tempest.lib import",
"and the ``get_availability_zone`` policy \"\"\" admin_resources = (self.ntp_client.list_availability_zones() [\"availability_zones\"]) with self.override_role_and_validate_list( admin_resources=admin_resources) as",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"policy \"\"\" admin_resources = (self.ntp_client.list_availability_zones() [\"availability_zones\"]) with self.override_role_and_validate_list( admin_resources=admin_resources) as ctx: ctx.resources =",
"for the neutron ``list_availability_zones`` function and the ``get_availability_zone`` policy \"\"\" admin_resources = (self.ntp_client.list_availability_zones()",
"tempest.lib import decorators from patrole_tempest_plugin import rbac_rule_validation from patrole_tempest_plugin.tests.api.network import rbac_base as base",
"under the License. from tempest.common import utils from tempest.lib import decorators from patrole_tempest_plugin",
"to in writing, software # distributed under the License is distributed on an",
"You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"required by applicable law or agreed to in writing, software # distributed under",
"patrole_tempest_plugin import rbac_rule_validation from patrole_tempest_plugin.tests.api.network import rbac_base as base class AvailabilityZoneExtRbacTest(base.BaseNetworkExtRbacTest): @classmethod def",
"2018 AT&T Corporation. # All Rights Reserved. # # Licensed under the Apache",
"applicable law or agreed to in writing, software # distributed under the License",
"not utils.is_extension_enabled('availability_zone', 'network'): msg = \"network_availability_zone extension not enabled.\" raise cls.skipException(msg) @rbac_rule_validation.action(service=\"neutron\", rules=[\"get_availability_zone\"])",
"distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT #",
"OR CONDITIONS OF ANY KIND, either express or implied. See the # License",
"obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may #",
"in compliance with the License. You may obtain # a copy of the",
"RBAC test for the neutron ``list_availability_zones`` function and the ``get_availability_zone`` policy \"\"\" admin_resources",
"# not use this file except in compliance with the License. You may",
"or agreed to in writing, software # distributed under the License is distributed",
"# License for the specific language governing permissions and limitations # under the",
"@decorators.idempotent_id('3c521be8-c32e-11e8-a611-080027758b73') def test_list_availability_zone_rbac(self): \"\"\"List all available zones. RBAC test for the neutron ``list_availability_zones``",
"cls).skip_checks() if not utils.is_extension_enabled('availability_zone', 'network'): msg = \"network_availability_zone extension not enabled.\" raise cls.skipException(msg)",
"# All Rights Reserved. # # Licensed under the Apache License, Version 2.0",
"from tempest.lib import decorators from patrole_tempest_plugin import rbac_rule_validation from patrole_tempest_plugin.tests.api.network import rbac_base as",
"under the Apache License, Version 2.0 (the \"License\"); you may # not use",
"specific language governing permissions and limitations # under the License. from tempest.common import",
"WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See",
"import utils from tempest.lib import decorators from patrole_tempest_plugin import rbac_rule_validation from patrole_tempest_plugin.tests.api.network import",
"``list_availability_zones`` function and the ``get_availability_zone`` policy \"\"\" admin_resources = (self.ntp_client.list_availability_zones() [\"availability_zones\"]) with self.override_role_and_validate_list(",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"in writing, software # distributed under the License is distributed on an \"AS",
"Version 2.0 (the \"License\"); you may # not use this file except in",
"function and the ``get_availability_zone`` policy \"\"\" admin_resources = (self.ntp_client.list_availability_zones() [\"availability_zones\"]) with self.override_role_and_validate_list( admin_resources=admin_resources)",
"cls.skipException(msg) @rbac_rule_validation.action(service=\"neutron\", rules=[\"get_availability_zone\"]) @decorators.idempotent_id('3c521be8-c32e-11e8-a611-080027758b73') def test_list_availability_zone_rbac(self): \"\"\"List all available zones. RBAC test for"
] |
[
"no # digit is exceeded by the digit to its right it is",
"to its left # it is called an increasing number; for example, 134468.",
"by the digit to its left # it is called an increasing number;",
"http://github.com/lcsm29/project-euler import timed def dummy(n): pass if __name__ == '__main__': n = 1000",
"for example, 134468. Similarly if no # digit is exceeded by the digit",
"# digit is exceeded by the digit to its right it is called",
"# (10100) are not bouncy? # # by lcsm29 http://github.com/lcsm29/project-euler import timed def",
"example, 134468. Similarly if no # digit is exceeded by the digit to",
"right it is called a decreasing # number; for example, 66420. We shall",
"== '__main__': n = 1000 i = 10000 prob_id = 113 timed.caller(dummy, n,",
"Working from left-to-right if no digit is exceeded by the digit to its",
"numbers below a googol # (10100) are not bouncy? # # by lcsm29",
"are only 12951 numbers below one-million that are not bouncy and only #",
"a googol # (10100) are not bouncy? # # by lcsm29 http://github.com/lcsm29/project-euler import",
"the proportion of bouncy numbers below n increases such that # there are",
"# # Working from left-to-right if no digit is exceeded by the digit",
"that is neither # increasing nor decreasing a \"bouncy\" number; for example, 155349.",
"numbers below 1010. How many numbers below a googol # (10100) are not",
"that # there are only 12951 numbers below one-million that are not bouncy",
"are not bouncy? # # by lcsm29 http://github.com/lcsm29/project-euler import timed def dummy(n): pass",
"the digit to its right it is called a decreasing # number; for",
"# increasing nor decreasing a \"bouncy\" number; for example, 155349. As n #",
"digit is exceeded by the digit to its left # it is called",
"66420. We shall call a positive integer that is neither # increasing nor",
"for example, 155349. As n # increases, the proportion of bouncy numbers below",
"As n # increases, the proportion of bouncy numbers below n increases such",
"below 1010. How many numbers below a googol # (10100) are not bouncy?",
"lcsm29 http://github.com/lcsm29/project-euler import timed def dummy(n): pass if __name__ == '__main__': n =",
"not bouncy? # # by lcsm29 http://github.com/lcsm29/project-euler import timed def dummy(n): pass if",
"that are not bouncy and only # 277032 non-bouncy numbers below 1010. How",
"How many numbers below a googol # (10100) are not bouncy? # #",
"such that # there are only 12951 numbers below one-million that are not",
"if no digit is exceeded by the digit to its left # it",
"numbers below n increases such that # there are only 12951 numbers below",
"is called an increasing number; for example, 134468. Similarly if no # digit",
"Similarly if no # digit is exceeded by the digit to its right",
"below a googol # (10100) are not bouncy? # # by lcsm29 http://github.com/lcsm29/project-euler",
"for example, 66420. We shall call a positive integer that is neither #",
"non-bouncy numbers below 1010. How many numbers below a googol # (10100) are",
"is neither # increasing nor decreasing a \"bouncy\" number; for example, 155349. As",
"import timed def dummy(n): pass if __name__ == '__main__': n = 1000 i",
"if __name__ == '__main__': n = 1000 i = 10000 prob_id = 113",
"n increases such that # there are only 12951 numbers below one-million that",
"below one-million that are not bouncy and only # 277032 non-bouncy numbers below",
"increasing nor decreasing a \"bouncy\" number; for example, 155349. As n # increases,",
"only # 277032 non-bouncy numbers below 1010. How many numbers below a googol",
"12951 numbers below one-million that are not bouncy and only # 277032 non-bouncy",
"# Solution of; # Project Euler Problem 113: Non-bouncy numbers # https://projecteuler.net/problem=113 #",
"one-million that are not bouncy and only # 277032 non-bouncy numbers below 1010.",
"# # by lcsm29 http://github.com/lcsm29/project-euler import timed def dummy(n): pass if __name__ ==",
"digit is exceeded by the digit to its right it is called a",
"not bouncy and only # 277032 non-bouncy numbers below 1010. How many numbers",
"it is called a decreasing # number; for example, 66420. We shall call",
"called an increasing number; for example, 134468. Similarly if no # digit is",
"Non-bouncy numbers # https://projecteuler.net/problem=113 # # Working from left-to-right if no digit is",
"many numbers below a googol # (10100) are not bouncy? # # by",
"timed def dummy(n): pass if __name__ == '__main__': n = 1000 i =",
"integer that is neither # increasing nor decreasing a \"bouncy\" number; for example,",
"there are only 12951 numbers below one-million that are not bouncy and only",
"Solution of; # Project Euler Problem 113: Non-bouncy numbers # https://projecteuler.net/problem=113 # #",
"dummy(n): pass if __name__ == '__main__': n = 1000 i = 10000 prob_id",
"increasing number; for example, 134468. Similarly if no # digit is exceeded by",
"it is called an increasing number; for example, 134468. Similarly if no #",
"below n increases such that # there are only 12951 numbers below one-million",
"1010. How many numbers below a googol # (10100) are not bouncy? #",
"a positive integer that is neither # increasing nor decreasing a \"bouncy\" number;",
"the digit to its left # it is called an increasing number; for",
"example, 155349. As n # increases, the proportion of bouncy numbers below n",
"exceeded by the digit to its left # it is called an increasing",
"number; for example, 134468. Similarly if no # digit is exceeded by the",
"# it is called an increasing number; for example, 134468. Similarly if no",
"decreasing a \"bouncy\" number; for example, 155349. As n # increases, the proportion",
"call a positive integer that is neither # increasing nor decreasing a \"bouncy\"",
"if no # digit is exceeded by the digit to its right it",
"Project Euler Problem 113: Non-bouncy numbers # https://projecteuler.net/problem=113 # # Working from left-to-right",
"its right it is called a decreasing # number; for example, 66420. We",
"nor decreasing a \"bouncy\" number; for example, 155349. As n # increases, the",
"bouncy and only # 277032 non-bouncy numbers below 1010. How many numbers below",
"'__main__': n = 1000 i = 10000 prob_id = 113 timed.caller(dummy, n, i,",
"left # it is called an increasing number; for example, 134468. Similarly if",
"googol # (10100) are not bouncy? # # by lcsm29 http://github.com/lcsm29/project-euler import timed",
"by the digit to its right it is called a decreasing # number;",
"(10100) are not bouncy? # # by lcsm29 http://github.com/lcsm29/project-euler import timed def dummy(n):",
"155349. As n # increases, the proportion of bouncy numbers below n increases",
"exceeded by the digit to its right it is called a decreasing #",
"n = 1000 i = 10000 prob_id = 113 timed.caller(dummy, n, i, prob_id)",
"by lcsm29 http://github.com/lcsm29/project-euler import timed def dummy(n): pass if __name__ == '__main__': n",
"of; # Project Euler Problem 113: Non-bouncy numbers # https://projecteuler.net/problem=113 # # Working",
"# number; for example, 66420. We shall call a positive integer that is",
"of bouncy numbers below n increases such that # there are only 12951",
"no digit is exceeded by the digit to its left # it is",
"# https://projecteuler.net/problem=113 # # Working from left-to-right if no digit is exceeded by",
"Problem 113: Non-bouncy numbers # https://projecteuler.net/problem=113 # # Working from left-to-right if no",
"Euler Problem 113: Non-bouncy numbers # https://projecteuler.net/problem=113 # # Working from left-to-right if",
"from left-to-right if no digit is exceeded by the digit to its left",
"a decreasing # number; for example, 66420. We shall call a positive integer",
"# 277032 non-bouncy numbers below 1010. How many numbers below a googol #",
"We shall call a positive integer that is neither # increasing nor decreasing",
"positive integer that is neither # increasing nor decreasing a \"bouncy\" number; for",
"is exceeded by the digit to its right it is called a decreasing",
"# Working from left-to-right if no digit is exceeded by the digit to",
"number; for example, 66420. We shall call a positive integer that is neither",
"increases, the proportion of bouncy numbers below n increases such that # there",
"pass if __name__ == '__main__': n = 1000 i = 10000 prob_id =",
"digit to its left # it is called an increasing number; for example,",
"numbers # https://projecteuler.net/problem=113 # # Working from left-to-right if no digit is exceeded",
"proportion of bouncy numbers below n increases such that # there are only",
"are not bouncy and only # 277032 non-bouncy numbers below 1010. How many",
"increases such that # there are only 12951 numbers below one-million that are",
"to its right it is called a decreasing # number; for example, 66420.",
"is exceeded by the digit to its left # it is called an",
"# Project Euler Problem 113: Non-bouncy numbers # https://projecteuler.net/problem=113 # # Working from",
"134468. Similarly if no # digit is exceeded by the digit to its",
"def dummy(n): pass if __name__ == '__main__': n = 1000 i = 10000",
"https://projecteuler.net/problem=113 # # Working from left-to-right if no digit is exceeded by the",
"its left # it is called an increasing number; for example, 134468. Similarly",
"n # increases, the proportion of bouncy numbers below n increases such that",
"called a decreasing # number; for example, 66420. We shall call a positive",
"and only # 277032 non-bouncy numbers below 1010. How many numbers below a",
"# by lcsm29 http://github.com/lcsm29/project-euler import timed def dummy(n): pass if __name__ == '__main__':",
"shall call a positive integer that is neither # increasing nor decreasing a",
"__name__ == '__main__': n = 1000 i = 10000 prob_id = 113 timed.caller(dummy,",
"digit to its right it is called a decreasing # number; for example,",
"bouncy? # # by lcsm29 http://github.com/lcsm29/project-euler import timed def dummy(n): pass if __name__",
"113: Non-bouncy numbers # https://projecteuler.net/problem=113 # # Working from left-to-right if no digit",
"only 12951 numbers below one-million that are not bouncy and only # 277032",
"277032 non-bouncy numbers below 1010. How many numbers below a googol # (10100)",
"numbers below one-million that are not bouncy and only # 277032 non-bouncy numbers",
"is called a decreasing # number; for example, 66420. We shall call a",
"# there are only 12951 numbers below one-million that are not bouncy and",
"example, 66420. We shall call a positive integer that is neither # increasing",
"# increases, the proportion of bouncy numbers below n increases such that #",
"\"bouncy\" number; for example, 155349. As n # increases, the proportion of bouncy",
"neither # increasing nor decreasing a \"bouncy\" number; for example, 155349. As n",
"an increasing number; for example, 134468. Similarly if no # digit is exceeded",
"decreasing # number; for example, 66420. We shall call a positive integer that",
"number; for example, 155349. As n # increases, the proportion of bouncy numbers",
"a \"bouncy\" number; for example, 155349. As n # increases, the proportion of",
"left-to-right if no digit is exceeded by the digit to its left #",
"bouncy numbers below n increases such that # there are only 12951 numbers"
] |
[
"= await get_firebolt_tables(connection) logger.info(f\"Found {len(tables)} available tables.\") return await gather(*[get_table_stream(connection, table) for table",
"logger: Logging object to display debug/info/error to the logs (logs will not be",
"\"\"\" try: with establish_connection(config, logger) as connection: # We can only verify correctness",
"connection.cursor() as cursor: cursor.execute(\"SELECT 1\") return AirbyteConnectionStatus(status=Status.SUCCEEDED) except Exception as e: return AirbyteConnectionStatus(status=Status.FAILED,",
"logger.info(f\"Reading data from {len(catalog.streams)} Firebolt tables.\") with establish_connection(config, logger) as connection: with connection.cursor()",
"in cursor.fetchall(): message = airbyte_message_from_data(result, columns, table_name) if message: yield message logger.info(\"Data read",
"logger) as connection: with connection.cursor() as cursor: for c_stream in catalog.streams: table_name =",
"specified in the properties of the spec.json file :return: AirbyteCatalog is an object",
"= get_event_loop() streams = loop.run_until_complete(get_streams()) logger.info(f\"Provided {len(streams)} streams to the Aribyte Catalog.\") return",
"the Stripe API. :param logger: Logging object to display debug/info/error to the logs",
"table name in the case of Postgres) - json_schema providing the specifications of",
"rows from table {table_name}.\") for result in cursor.fetchall(): message = airbyte_message_from_data(result, columns, table_name)",
"connection.cursor() await cursor.execute(f\"SHOW COLUMNS {table}\") for t_name, c_name, c_type, nullable in await cursor.fetchall():",
"AirbyteRecordMessage contained in AirbyteMessage object. \"\"\" logger.info(f\"Reading data from {len(catalog.streams)} Firebolt tables.\") with",
"logs (logs will not be accessible via airbyte UI if they are not",
"types) \"\"\" async def get_streams(): async with await establish_async_connection(config, logger) as connection: tables",
"\" to avoid reserved keywords e.g. id escaped_columns = ['\"{}\"'.format(col) for col in",
"from {len(catalog.streams)} Firebolt tables.\") with establish_connection(config, logger) as connection: with connection.cursor() as cursor:",
"nullable) column_mapping[c_name] = airbyte_type cursor.close() json_schema = { \"type\": \"object\", \"properties\": column_mapping, }",
"spec.json file :param catalog: The input catalog is a ConfiguredAirbyteCatalog which is almost",
"is almost the same as AirbyteCatalog returned by discover(), but in addition, it's",
"to avoid reserved keywords e.g. id escaped_columns = ['\"{}\"'.format(col) for col in columns]",
"streams and fields in this integration. For example, given valid credentials to a",
"in the properties of the spec.json file :return: AirbyteCatalog is an object describing",
"str) -> AirbyteStream: \"\"\" Get AirbyteStream for a particular table with table structure",
"import airbyte_message_from_data, convert_type SUPPORTED_SYNC_MODES = [SyncMode.full_refresh] async def get_table_stream(connection: AsyncConnection, table: str) ->",
"config: json) -> AirbyteConnectionStatus: \"\"\" Tests if the input configuration can be used",
"and fields in this integration. For example, given valid credentials to a Postgres",
"[SyncMode.full_refresh] async def get_table_stream(connection: AsyncConnection, table: str) -> AirbyteStream: \"\"\" Get AirbyteStream for",
"input configuration can be used to successfully connect to the integration e.g: if",
"each table column is a field. :param logger: Logging object to display debug/info/error",
"a generator of the AirbyteMessages generated by reading the source with the given",
"a list of all available streams in this source. A stream is an",
"connection: with connection.cursor() as cursor: for c_stream in catalog.streams: table_name = c_stream.stream.name table_properties",
"in addition, it's been configured in the UI! For each particular stream and",
"import establish_async_connection, establish_connection, get_firebolt_tables from .utils import airbyte_message_from_data, convert_type SUPPORTED_SYNC_MODES = [SyncMode.full_refresh] async",
"stream, and each table column is a field. :param logger: Logging object to",
"Postgres) - json_schema providing the specifications of expected schema for this stream (a",
"col in columns] query = \"SELECT {columns} FROM {table}\".format(columns=\",\".join(escaped_columns), table=table_name) cursor.execute(query) logger.info(f\"Fetched {cursor.rowcount}",
"a provided Stripe API token can be used to connect to the Stripe",
"have been provided with extra modifications such as: filtering streams and/or columns out,",
"the same as AirbyteCatalog returned by discover(), but in addition, it's been configured",
"{cursor.rowcount} rows from table {table_name}.\") for result in cursor.fetchall(): message = airbyte_message_from_data(result, columns,",
"json) -> AirbyteConnectionStatus: \"\"\" Tests if the input configuration can be used to",
"of this source, content of this json is as specified in the properties",
"to this logger) :param config: Json object containing the configuration of this source,",
"case of Postgres) - json_schema providing the specifications of expected schema for this",
"A generator that produces a stream of AirbyteRecordMessage contained in AirbyteMessage object. \"\"\"",
"e.g. id escaped_columns = ['\"{}\"'.format(col) for col in columns] query = \"SELECT {columns}",
"field. :param logger: Logging object to display debug/info/error to the logs (logs will",
"AsyncConnection from .database import establish_async_connection, establish_connection, get_firebolt_tables from .utils import airbyte_message_from_data, convert_type SUPPORTED_SYNC_MODES",
"gather(*[get_table_stream(connection, table) for table in tables]) loop = get_event_loop() streams = loop.run_until_complete(get_streams()) logger.info(f\"Provided",
"as AirbyteCatalog returned by discover(), but in addition, it's been configured in the",
"get_firebolt_tables(connection) logger.info(f\"Found {len(tables)} available tables.\") return await gather(*[get_table_stream(connection, table) for table in tables])",
"from typing import Dict, Generator from airbyte_cdk.logger import AirbyteLogger from airbyte_cdk.models import (",
"list(table_properties.keys()) # Escape columns with \" to avoid reserved keywords e.g. id escaped_columns",
"properties of the spec.json file :return: AirbyteConnectionStatus indicating a Success or Failure \"\"\"",
"structure defined. :param connection: Connection object connected to a database :return: AirbyteStream object",
"async def get_streams(): async with await establish_async_connection(config, logger) as connection: tables = await",
"Exception as e: return AirbyteConnectionStatus(status=Status.FAILED, message=f\"An exception occurred: {str(e)}\") def discover(self, logger: AirbyteLogger,",
"A stream is an AirbyteStream object that includes: - its stream name (or",
"['\"{}\"'.format(col) for col in columns] query = \"SELECT {columns} FROM {table}\".format(columns=\",\".join(escaped_columns), table=table_name) cursor.execute(query)",
"the available streams and fields in this integration. For example, given valid credentials",
"debug/info/error to the logs (logs will not be accessible via airbyte UI if",
"Postgres database, returns an Airbyte catalog where each postgres table is a stream,",
"Firebolt tables.\") with establish_connection(config, logger) as connection: with connection.cursor() as cursor: for c_stream",
"columns with \" to avoid reserved keywords e.g. id escaped_columns = ['\"{}\"'.format(col) for",
"AirbyteCatalog, AirbyteConnectionStatus, AirbyteMessage, AirbyteStream, ConfiguredAirbyteCatalog, Status, SyncMode, ) from airbyte_cdk.sources import Source from",
"checkpoint cursor to resume replication in the future from that saved checkpoint. This",
"{table_name}.\") for result in cursor.fetchall(): message = airbyte_message_from_data(result, columns, table_name) if message: yield",
"an Airbyte catalog where each postgres table is a stream, and each table",
"AirbyteCatalog returned by discover(), but in addition, it's been configured in the UI!",
"a ConfiguredAirbyteCatalog which is almost the same as AirbyteCatalog returned by discover(), but",
"as connection: with connection.cursor() as cursor: for c_stream in catalog.streams: table_name = c_stream.stream.name",
"class SourceFirebolt(Source): def check(self, logger: AirbyteLogger, config: json) -> AirbyteConnectionStatus: \"\"\" Tests if",
"and types) \"\"\" async def get_streams(): async with await establish_async_connection(config, logger) as connection:",
"import json from asyncio import gather, get_event_loop from typing import Dict, Generator from",
"specified in the properties of the spec.json file :param catalog: The input catalog",
"if the input configuration can be used to successfully connect to the integration",
"AirbyteCatalog representing the available streams and fields in this integration. For example, given",
"table) for table in tables]) loop = get_event_loop() streams = loop.run_until_complete(get_streams()) logger.info(f\"Provided {len(streams)}",
"each particular stream and field, there may have been provided with extra modifications",
"be accessible via airbyte UI if they are not passed to this logger)",
"configured in the UI! For each particular stream and field, there may have",
"in columns] query = \"SELECT {columns} FROM {table}\".format(columns=\",\".join(escaped_columns), table=table_name) cursor.execute(query) logger.info(f\"Fetched {cursor.rowcount} rows",
"cursor to resume replication in the future from that saved checkpoint. This is",
"with establish_connection(config, logger) as connection: with connection.cursor() as cursor: for c_stream in catalog.streams:",
"structure \"\"\" column_mapping = {} cursor = connection.cursor() await cursor.execute(f\"SHOW COLUMNS {table}\") for",
"schema for this stream (a list of columns described by their names and",
"resume replication in the future from that saved checkpoint. This is the object",
"verify correctness of connection parameters on execution with connection.cursor() as cursor: cursor.execute(\"SELECT 1\")",
"config: json) -> AirbyteCatalog: \"\"\" Returns an AirbyteCatalog representing the available streams and",
"} return AirbyteStream(name=table, json_schema=json_schema, supported_sync_modes=SUPPORTED_SYNC_MODES) class SourceFirebolt(Source): def check(self, logger: AirbyteLogger, config: json)",
"is a stream, and each table column is a field. :param logger: Logging",
"Inc., all rights reserved. # import json from asyncio import gather, get_event_loop from",
"indicating a Success or Failure \"\"\" try: with establish_connection(config, logger) as connection: #",
"integration. For example, given valid credentials to a Postgres database, returns an Airbyte",
"for this stream (a list of columns described by their names and types)",
"it might need to keep a checkpoint cursor to resume replication in the",
"keywords e.g. id escaped_columns = ['\"{}\"'.format(col) for col in columns] query = \"SELECT",
"logger) as connection: tables = await get_firebolt_tables(connection) logger.info(f\"Found {len(tables)} available tables.\") return await",
"in the properties of the spec.json file :param catalog: The input catalog is",
"occurred: {str(e)}\") def discover(self, logger: AirbyteLogger, config: json) -> AirbyteCatalog: \"\"\" Returns an",
"from asyncio import gather, get_event_loop from typing import Dict, Generator from airbyte_cdk.logger import",
"as connection: tables = await get_firebolt_tables(connection) logger.info(f\"Found {len(tables)} available tables.\") return await gather(*[get_table_stream(connection,",
"catalog: ConfiguredAirbyteCatalog, state: Dict[str, any], ) -> Generator[AirbyteMessage, None, None]: \"\"\" Returns a",
"object containing the table structure \"\"\" column_mapping = {} cursor = connection.cursor() await",
"as cursor: cursor.execute(\"SELECT 1\") return AirbyteConnectionStatus(status=Status.SUCCEEDED) except Exception as e: return AirbyteConnectionStatus(status=Status.FAILED, message=f\"An",
"in the UI! For each particular stream and field, there may have been",
"read( self, logger: AirbyteLogger, config: json, catalog: ConfiguredAirbyteCatalog, state: Dict[str, any], ) ->",
"credentials to a Postgres database, returns an Airbyte catalog where each postgres table",
"table is a stream, and each table column is a field. :param logger:",
"asyncio import gather, get_event_loop from typing import Dict, Generator from airbyte_cdk.logger import AirbyteLogger",
"\"\"\" Returns a generator of the AirbyteMessages generated by reading the source with",
"generated by reading the source with the given configuration, catalog, and state. :param",
"to connect to the Stripe API. :param logger: Logging object to display debug/info/error",
"Returns an AirbyteCatalog representing the available streams and fields in this integration. For",
"typing import Dict, Generator from airbyte_cdk.logger import AirbyteLogger from airbyte_cdk.models import ( AirbyteCatalog,",
"def get_table_stream(connection: AsyncConnection, table: str) -> AirbyteStream: \"\"\" Get AirbyteStream for a particular",
"by discover(), but in addition, it's been configured in the UI! For each",
"{str(e)}\") def discover(self, logger: AirbyteLogger, config: json) -> AirbyteCatalog: \"\"\" Returns an AirbyteCatalog",
"which is almost the same as AirbyteCatalog returned by discover(), but in addition,",
"this stream (a list of columns described by their names and types) \"\"\"",
"try: with establish_connection(config, logger) as connection: # We can only verify correctness of",
"{len(streams)} streams to the Aribyte Catalog.\") return AirbyteCatalog(streams=streams) def read( self, logger: AirbyteLogger,",
"def check(self, logger: AirbyteLogger, config: json) -> AirbyteConnectionStatus: \"\"\" Tests if the input",
"None, None]: \"\"\" Returns a generator of the AirbyteMessages generated by reading the",
"When a Airbyte reads data from a source, it might need to keep",
"configuration can be used to successfully connect to the integration e.g: if a",
"a database :return: AirbyteStream object containing the table structure \"\"\" column_mapping = {}",
"used to successfully connect to the integration e.g: if a provided Stripe API",
"may have been provided with extra modifications such as: filtering streams and/or columns",
"a source, it might need to keep a checkpoint cursor to resume replication",
"json is as specified in the properties of the spec.json file :param catalog:",
"table: str) -> AirbyteStream: \"\"\" Get AirbyteStream for a particular table with table",
"this integration. For example, given valid credentials to a Postgres database, returns an",
"data everytime. :return: A generator that produces a stream of AirbyteRecordMessage contained in",
":param state: When a Airbyte reads data from a source, it might need",
"\"SELECT {columns} FROM {table}\".format(columns=\",\".join(escaped_columns), table=table_name) cursor.execute(query) logger.info(f\"Fetched {cursor.rowcount} rows from table {table_name}.\") for",
"column_mapping, } return AirbyteStream(name=table, json_schema=json_schema, supported_sync_modes=SUPPORTED_SYNC_MODES) class SourceFirebolt(Source): def check(self, logger: AirbyteLogger, config:",
"ConfiguredAirbyteCatalog, Status, SyncMode, ) from airbyte_cdk.sources import Source from firebolt.async_db import Connection as",
"containing the configuration of this source, content of this json is as specified",
"specifications of expected schema for this stream (a list of columns described by",
"state. :param logger: Logging object to display debug/info/error to the logs (logs will",
":param logger: Logging object to display debug/info/error to the logs (logs will not",
"reading the source with the given configuration, catalog, and state. :param logger: Logging",
"defined. :param connection: Connection object connected to a database :return: AirbyteStream object containing",
"get_event_loop from typing import Dict, Generator from airbyte_cdk.logger import AirbyteLogger from airbyte_cdk.models import",
"not be accessible via airbyte UI if they are not passed to this",
"set of data everytime. :return: A generator that produces a stream of AirbyteRecordMessage",
"fields in this integration. For example, given valid credentials to a Postgres database,",
"execution with connection.cursor() as cursor: cursor.execute(\"SELECT 1\") return AirbyteConnectionStatus(status=Status.SUCCEEDED) except Exception as e:",
"runs and avoid replicating the entire set of data everytime. :return: A generator",
"if a provided Stripe API token can be used to connect to the",
"object connected to a database :return: AirbyteStream object containing the table structure \"\"\"",
"correctness of connection parameters on execution with connection.cursor() as cursor: cursor.execute(\"SELECT 1\") return",
"in AirbyteMessage object. \"\"\" logger.info(f\"Reading data from {len(catalog.streams)} Firebolt tables.\") with establish_connection(config, logger)",
"import Source from firebolt.async_db import Connection as AsyncConnection from .database import establish_async_connection, establish_connection,",
"all available streams in this source. A stream is an AirbyteStream object that",
"await get_firebolt_tables(connection) logger.info(f\"Found {len(tables)} available tables.\") return await gather(*[get_table_stream(connection, table) for table in",
"= convert_type(c_type, nullable) column_mapping[c_name] = airbyte_type cursor.close() json_schema = { \"type\": \"object\", \"properties\":",
"cursor: for c_stream in catalog.streams: table_name = c_stream.stream.name table_properties = c_stream.stream.json_schema[\"properties\"] columns =",
"cursor.fetchall(): airbyte_type = convert_type(c_type, nullable) column_mapping[c_name] = airbyte_type cursor.close() json_schema = { \"type\":",
"of connection parameters on execution with connection.cursor() as cursor: cursor.execute(\"SELECT 1\") return AirbyteConnectionStatus(status=Status.SUCCEEDED)",
"\"\"\" column_mapping = {} cursor = connection.cursor() await cursor.execute(f\"SHOW COLUMNS {table}\") for t_name,",
":param catalog: The input catalog is a ConfiguredAirbyteCatalog which is almost the same",
"import Dict, Generator from airbyte_cdk.logger import AirbyteLogger from airbyte_cdk.models import ( AirbyteCatalog, AirbyteConnectionStatus,",
"out, renaming some entities, etc :param state: When a Airbyte reads data from",
":return: A generator that produces a stream of AirbyteRecordMessage contained in AirbyteMessage object.",
"check(self, logger: AirbyteLogger, config: json) -> AirbyteConnectionStatus: \"\"\" Tests if the input configuration",
"AirbyteConnectionStatus, AirbyteMessage, AirbyteStream, ConfiguredAirbyteCatalog, Status, SyncMode, ) from airbyte_cdk.sources import Source from firebolt.async_db",
"UI if they are not passed to this logger) :param config: Json object",
"# # Copyright (c) 2022 Airbyte, Inc., all rights reserved. # import json",
"in the future from that saved checkpoint. This is the object that is",
"{ \"type\": \"object\", \"properties\": column_mapping, } return AirbyteStream(name=table, json_schema=json_schema, supported_sync_modes=SUPPORTED_SYNC_MODES) class SourceFirebolt(Source): def",
"Get AirbyteStream for a particular table with table structure defined. :param connection: Connection",
"await cursor.fetchall(): airbyte_type = convert_type(c_type, nullable) column_mapping[c_name] = airbyte_type cursor.close() json_schema = {",
"Copyright (c) 2022 Airbyte, Inc., all rights reserved. # import json from asyncio",
"addition, it's been configured in the UI! For each particular stream and field,",
"the properties of the spec.json file :param catalog: The input catalog is a",
"None]: \"\"\" Returns a generator of the AirbyteMessages generated by reading the source",
"with await establish_async_connection(config, logger) as connection: tables = await get_firebolt_tables(connection) logger.info(f\"Found {len(tables)} available",
"in catalog.streams: table_name = c_stream.stream.name table_properties = c_stream.stream.json_schema[\"properties\"] columns = list(table_properties.keys()) # Escape",
"this json is as specified in the properties of the spec.json file :return:",
":param connection: Connection object connected to a database :return: AirbyteStream object containing the",
"Airbyte catalog where each postgres table is a stream, and each table column",
"reserved keywords e.g. id escaped_columns = ['\"{}\"'.format(col) for col in columns] query =",
"only verify correctness of connection parameters on execution with connection.cursor() as cursor: cursor.execute(\"SELECT",
"escaped_columns = ['\"{}\"'.format(col) for col in columns] query = \"SELECT {columns} FROM {table}\".format(columns=\",\".join(escaped_columns),",
"json is as specified in the properties of the spec.json file :return: AirbyteConnectionStatus",
"or Failure \"\"\" try: with establish_connection(config, logger) as connection: # We can only",
"= [SyncMode.full_refresh] async def get_table_stream(connection: AsyncConnection, table: str) -> AirbyteStream: \"\"\" Get AirbyteStream",
"# Escape columns with \" to avoid reserved keywords e.g. id escaped_columns =",
"contained in AirbyteMessage object. \"\"\" logger.info(f\"Reading data from {len(catalog.streams)} Firebolt tables.\") with establish_connection(config,",
"the configuration of this source, content of this json is as specified in",
"AirbyteStream, ConfiguredAirbyteCatalog, Status, SyncMode, ) from airbyte_cdk.sources import Source from firebolt.async_db import Connection",
"available streams and fields in this integration. For example, given valid credentials to",
"input catalog is a ConfiguredAirbyteCatalog which is almost the same as AirbyteCatalog returned",
"result in cursor.fetchall(): message = airbyte_message_from_data(result, columns, table_name) if message: yield message logger.info(\"Data",
"-> AirbyteCatalog: \"\"\" Returns an AirbyteCatalog representing the available streams and fields in",
"the object that is provided with state from previous runs and avoid replicating",
"table=table_name) cursor.execute(query) logger.info(f\"Fetched {cursor.rowcount} rows from table {table_name}.\") for result in cursor.fetchall(): message",
"the properties of the spec.json file :return: AirbyteCatalog is an object describing a",
"airbyte_type cursor.close() json_schema = { \"type\": \"object\", \"properties\": column_mapping, } return AirbyteStream(name=table, json_schema=json_schema,",
"a Postgres database, returns an Airbyte catalog where each postgres table is a",
"used to connect to the Stripe API. :param logger: Logging object to display",
"and avoid replicating the entire set of data everytime. :return: A generator that",
"where each postgres table is a stream, and each table column is a",
"Airbyte reads data from a source, it might need to keep a checkpoint",
"almost the same as AirbyteCatalog returned by discover(), but in addition, it's been",
"is an object describing a list of all available streams in this source.",
"We can only verify correctness of connection parameters on execution with connection.cursor() as",
"such as: filtering streams and/or columns out, renaming some entities, etc :param state:",
"for result in cursor.fetchall(): message = airbyte_message_from_data(result, columns, table_name) if message: yield message",
"API. :param logger: Logging object to display debug/info/error to the logs (logs will",
"For each particular stream and field, there may have been provided with extra",
"modifications such as: filtering streams and/or columns out, renaming some entities, etc :param",
"that produces a stream of AirbyteRecordMessage contained in AirbyteMessage object. \"\"\" logger.info(f\"Reading data",
"message=f\"An exception occurred: {str(e)}\") def discover(self, logger: AirbyteLogger, config: json) -> AirbyteCatalog: \"\"\"",
"c_type, nullable in await cursor.fetchall(): airbyte_type = convert_type(c_type, nullable) column_mapping[c_name] = airbyte_type cursor.close()",
"a checkpoint cursor to resume replication in the future from that saved checkpoint.",
"from table {table_name}.\") for result in cursor.fetchall(): message = airbyte_message_from_data(result, columns, table_name) if",
"the spec.json file :return: AirbyteConnectionStatus indicating a Success or Failure \"\"\" try: with",
"entities, etc :param state: When a Airbyte reads data from a source, it",
"json_schema = { \"type\": \"object\", \"properties\": column_mapping, } return AirbyteStream(name=table, json_schema=json_schema, supported_sync_modes=SUPPORTED_SYNC_MODES) class",
"The input catalog is a ConfiguredAirbyteCatalog which is almost the same as AirbyteCatalog",
"- its stream name (or table name in the case of Postgres) -",
"name (or table name in the case of Postgres) - json_schema providing the",
":return: AirbyteCatalog is an object describing a list of all available streams in",
"name in the case of Postgres) - json_schema providing the specifications of expected",
"the case of Postgres) - json_schema providing the specifications of expected schema for",
"a Airbyte reads data from a source, it might need to keep a",
"available tables.\") return await gather(*[get_table_stream(connection, table) for table in tables]) loop = get_event_loop()",
"is a field. :param logger: Logging object to display debug/info/error to the logs",
"file :param catalog: The input catalog is a ConfiguredAirbyteCatalog which is almost the",
"connection: # We can only verify correctness of connection parameters on execution with",
"of columns described by their names and types) \"\"\" async def get_streams(): async",
"data from a source, it might need to keep a checkpoint cursor to",
"\"\"\" logger.info(f\"Reading data from {len(catalog.streams)} Firebolt tables.\") with establish_connection(config, logger) as connection: with",
"by their names and types) \"\"\" async def get_streams(): async with await establish_async_connection(config,",
"particular table with table structure defined. :param connection: Connection object connected to a",
"properties of the spec.json file :param catalog: The input catalog is a ConfiguredAirbyteCatalog",
"in this integration. For example, given valid credentials to a Postgres database, returns",
"file :return: AirbyteConnectionStatus indicating a Success or Failure \"\"\" try: with establish_connection(config, logger)",
"source. A stream is an AirbyteStream object that includes: - its stream name",
"the AirbyteMessages generated by reading the source with the given configuration, catalog, and",
"async def get_table_stream(connection: AsyncConnection, table: str) -> AirbyteStream: \"\"\" Get AirbyteStream for a",
"= loop.run_until_complete(get_streams()) logger.info(f\"Provided {len(streams)} streams to the Aribyte Catalog.\") return AirbyteCatalog(streams=streams) def read(",
"streams to the Aribyte Catalog.\") return AirbyteCatalog(streams=streams) def read( self, logger: AirbyteLogger, config:",
"\"object\", \"properties\": column_mapping, } return AirbyteStream(name=table, json_schema=json_schema, supported_sync_modes=SUPPORTED_SYNC_MODES) class SourceFirebolt(Source): def check(self, logger:",
"entire set of data everytime. :return: A generator that produces a stream of",
"connect to the integration e.g: if a provided Stripe API token can be",
"= { \"type\": \"object\", \"properties\": column_mapping, } return AirbyteStream(name=table, json_schema=json_schema, supported_sync_modes=SUPPORTED_SYNC_MODES) class SourceFirebolt(Source):",
"with connection.cursor() as cursor: for c_stream in catalog.streams: table_name = c_stream.stream.name table_properties =",
"the entire set of data everytime. :return: A generator that produces a stream",
"\"\"\" async def get_streams(): async with await establish_async_connection(config, logger) as connection: tables =",
"is as specified in the properties of the spec.json file :param catalog: The",
"connection.cursor() as cursor: for c_stream in catalog.streams: table_name = c_stream.stream.name table_properties = c_stream.stream.json_schema[\"properties\"]",
"stream name (or table name in the case of Postgres) - json_schema providing",
"\"type\": \"object\", \"properties\": column_mapping, } return AirbyteStream(name=table, json_schema=json_schema, supported_sync_modes=SUPPORTED_SYNC_MODES) class SourceFirebolt(Source): def check(self,",
"cursor.close() json_schema = { \"type\": \"object\", \"properties\": column_mapping, } return AirbyteStream(name=table, json_schema=json_schema, supported_sync_modes=SUPPORTED_SYNC_MODES)",
"{} cursor = connection.cursor() await cursor.execute(f\"SHOW COLUMNS {table}\") for t_name, c_name, c_type, nullable",
"get_event_loop() streams = loop.run_until_complete(get_streams()) logger.info(f\"Provided {len(streams)} streams to the Aribyte Catalog.\") return AirbyteCatalog(streams=streams)",
"streams = loop.run_until_complete(get_streams()) logger.info(f\"Provided {len(streams)} streams to the Aribyte Catalog.\") return AirbyteCatalog(streams=streams) def",
"as: filtering streams and/or columns out, renaming some entities, etc :param state: When",
"can be used to successfully connect to the integration e.g: if a provided",
".utils import airbyte_message_from_data, convert_type SUPPORTED_SYNC_MODES = [SyncMode.full_refresh] async def get_table_stream(connection: AsyncConnection, table: str)",
"with table structure defined. :param connection: Connection object connected to a database :return:",
"a field. :param logger: Logging object to display debug/info/error to the logs (logs",
"avoid reserved keywords e.g. id escaped_columns = ['\"{}\"'.format(col) for col in columns] query",
"is as specified in the properties of the spec.json file :return: AirbyteCatalog is",
"c_stream in catalog.streams: table_name = c_stream.stream.name table_properties = c_stream.stream.json_schema[\"properties\"] columns = list(table_properties.keys()) #",
"for col in columns] query = \"SELECT {columns} FROM {table}\".format(columns=\",\".join(escaped_columns), table=table_name) cursor.execute(query) logger.info(f\"Fetched",
"columns = list(table_properties.keys()) # Escape columns with \" to avoid reserved keywords e.g.",
"streams and/or columns out, renaming some entities, etc :param state: When a Airbyte",
"of all available streams in this source. A stream is an AirbyteStream object",
"# We can only verify correctness of connection parameters on execution with connection.cursor()",
"tables.\") with establish_connection(config, logger) as connection: with connection.cursor() as cursor: for c_stream in",
"AsyncConnection, table: str) -> AirbyteStream: \"\"\" Get AirbyteStream for a particular table with",
"the input configuration can be used to successfully connect to the integration e.g:",
"from previous runs and avoid replicating the entire set of data everytime. :return:",
"to keep a checkpoint cursor to resume replication in the future from that",
"Generator[AirbyteMessage, None, None]: \"\"\" Returns a generator of the AirbyteMessages generated by reading",
"database, returns an Airbyte catalog where each postgres table is a stream, and",
"get_firebolt_tables from .utils import airbyte_message_from_data, convert_type SUPPORTED_SYNC_MODES = [SyncMode.full_refresh] async def get_table_stream(connection: AsyncConnection,",
"1\") return AirbyteConnectionStatus(status=Status.SUCCEEDED) except Exception as e: return AirbyteConnectionStatus(status=Status.FAILED, message=f\"An exception occurred: {str(e)}\")",
"establish_connection(config, logger) as connection: # We can only verify correctness of connection parameters",
"state: When a Airbyte reads data from a source, it might need to",
"and field, there may have been provided with extra modifications such as: filtering",
"is a ConfiguredAirbyteCatalog which is almost the same as AirbyteCatalog returned by discover(),",
"establish_connection, get_firebolt_tables from .utils import airbyte_message_from_data, convert_type SUPPORTED_SYNC_MODES = [SyncMode.full_refresh] async def get_table_stream(connection:",
"stream (a list of columns described by their names and types) \"\"\" async",
"of the AirbyteMessages generated by reading the source with the given configuration, catalog,",
"filtering streams and/or columns out, renaming some entities, etc :param state: When a",
"cursor: cursor.execute(\"SELECT 1\") return AirbyteConnectionStatus(status=Status.SUCCEEDED) except Exception as e: return AirbyteConnectionStatus(status=Status.FAILED, message=f\"An exception",
"stream is an AirbyteStream object that includes: - its stream name (or table",
"available streams in this source. A stream is an AirbyteStream object that includes:",
"spec.json file :return: AirbyteConnectionStatus indicating a Success or Failure \"\"\" try: with establish_connection(config,",
"as connection: # We can only verify correctness of connection parameters on execution",
"same as AirbyteCatalog returned by discover(), but in addition, it's been configured in",
"\"\"\" Returns an AirbyteCatalog representing the available streams and fields in this integration.",
"generator that produces a stream of AirbyteRecordMessage contained in AirbyteMessage object. \"\"\" logger.info(f\"Reading",
"self, logger: AirbyteLogger, config: json, catalog: ConfiguredAirbyteCatalog, state: Dict[str, any], ) -> Generator[AirbyteMessage,",
"-> AirbyteStream: \"\"\" Get AirbyteStream for a particular table with table structure defined.",
"passed to this logger) :param config: Json object containing the configuration of this",
"names and types) \"\"\" async def get_streams(): async with await establish_async_connection(config, logger) as",
"return AirbyteCatalog(streams=streams) def read( self, logger: AirbyteLogger, config: json, catalog: ConfiguredAirbyteCatalog, state: Dict[str,",
"catalog: The input catalog is a ConfiguredAirbyteCatalog which is almost the same as",
"airbyte UI if they are not passed to this logger) :param config: Json",
"of this json is as specified in the properties of the spec.json file",
"for c_stream in catalog.streams: table_name = c_stream.stream.name table_properties = c_stream.stream.json_schema[\"properties\"] columns = list(table_properties.keys())",
"in the case of Postgres) - json_schema providing the specifications of expected schema",
"config: json, catalog: ConfiguredAirbyteCatalog, state: Dict[str, any], ) -> Generator[AirbyteMessage, None, None]: \"\"\"",
"await establish_async_connection(config, logger) as connection: tables = await get_firebolt_tables(connection) logger.info(f\"Found {len(tables)} available tables.\")",
"Returns a generator of the AirbyteMessages generated by reading the source with the",
"a Success or Failure \"\"\" try: with establish_connection(config, logger) as connection: # We",
"logger.info(f\"Fetched {cursor.rowcount} rows from table {table_name}.\") for result in cursor.fetchall(): message = airbyte_message_from_data(result,",
"from airbyte_cdk.models import ( AirbyteCatalog, AirbyteConnectionStatus, AirbyteMessage, AirbyteStream, ConfiguredAirbyteCatalog, Status, SyncMode, ) from",
"logger: AirbyteLogger, config: json, catalog: ConfiguredAirbyteCatalog, state: Dict[str, any], ) -> Generator[AirbyteMessage, None,",
"SUPPORTED_SYNC_MODES = [SyncMode.full_refresh] async def get_table_stream(connection: AsyncConnection, table: str) -> AirbyteStream: \"\"\" Get",
"AirbyteCatalog is an object describing a list of all available streams in this",
"rights reserved. # import json from asyncio import gather, get_event_loop from typing import",
"cursor.execute(f\"SHOW COLUMNS {table}\") for t_name, c_name, c_type, nullable in await cursor.fetchall(): airbyte_type =",
"as e: return AirbyteConnectionStatus(status=Status.FAILED, message=f\"An exception occurred: {str(e)}\") def discover(self, logger: AirbyteLogger, config:",
"establish_async_connection(config, logger) as connection: tables = await get_firebolt_tables(connection) logger.info(f\"Found {len(tables)} available tables.\") return",
"Dict[str, any], ) -> Generator[AirbyteMessage, None, None]: \"\"\" Returns a generator of the",
"avoid replicating the entire set of data everytime. :return: A generator that produces",
"state from previous runs and avoid replicating the entire set of data everytime.",
"await cursor.execute(f\"SHOW COLUMNS {table}\") for t_name, c_name, c_type, nullable in await cursor.fetchall(): airbyte_type",
"be used to connect to the Stripe API. :param logger: Logging object to",
"loop.run_until_complete(get_streams()) logger.info(f\"Provided {len(streams)} streams to the Aribyte Catalog.\") return AirbyteCatalog(streams=streams) def read( self,",
"provided with extra modifications such as: filtering streams and/or columns out, renaming some",
"json) -> AirbyteCatalog: \"\"\" Returns an AirbyteCatalog representing the available streams and fields",
"{table}\") for t_name, c_name, c_type, nullable in await cursor.fetchall(): airbyte_type = convert_type(c_type, nullable)",
"connection: tables = await get_firebolt_tables(connection) logger.info(f\"Found {len(tables)} available tables.\") return await gather(*[get_table_stream(connection, table)",
"object that is provided with state from previous runs and avoid replicating the",
"list of all available streams in this source. A stream is an AirbyteStream",
"Airbyte, Inc., all rights reserved. # import json from asyncio import gather, get_event_loop",
"Failure \"\"\" try: with establish_connection(config, logger) as connection: # We can only verify",
"AirbyteStream for a particular table with table structure defined. :param connection: Connection object",
"import gather, get_event_loop from typing import Dict, Generator from airbyte_cdk.logger import AirbyteLogger from",
"produces a stream of AirbyteRecordMessage contained in AirbyteMessage object. \"\"\" logger.info(f\"Reading data from",
"containing the table structure \"\"\" column_mapping = {} cursor = connection.cursor() await cursor.execute(f\"SHOW",
"to the Aribyte Catalog.\") return AirbyteCatalog(streams=streams) def read( self, logger: AirbyteLogger, config: json,",
"the specifications of expected schema for this stream (a list of columns described",
"discover(), but in addition, it's been configured in the UI! For each particular",
"with establish_connection(config, logger) as connection: # We can only verify correctness of connection",
"AirbyteConnectionStatus(status=Status.FAILED, message=f\"An exception occurred: {str(e)}\") def discover(self, logger: AirbyteLogger, config: json) -> AirbyteCatalog:",
"object to display debug/info/error to the logs (logs will not be accessible via",
"are not passed to this logger) :param config: Json object containing the configuration",
"representing the available streams and fields in this integration. For example, given valid",
"file :return: AirbyteCatalog is an object describing a list of all available streams",
"logger) as connection: # We can only verify correctness of connection parameters on",
"returns an Airbyte catalog where each postgres table is a stream, and each",
"catalog.streams: table_name = c_stream.stream.name table_properties = c_stream.stream.json_schema[\"properties\"] columns = list(table_properties.keys()) # Escape columns",
"not passed to this logger) :param config: Json object containing the configuration of",
"configuration, catalog, and state. :param logger: Logging object to display debug/info/error to the",
"cursor.execute(\"SELECT 1\") return AirbyteConnectionStatus(status=Status.SUCCEEDED) except Exception as e: return AirbyteConnectionStatus(status=Status.FAILED, message=f\"An exception occurred:",
"describing a list of all available streams in this source. A stream is",
"streams in this source. A stream is an AirbyteStream object that includes: -",
"but in addition, it's been configured in the UI! For each particular stream",
"Aribyte Catalog.\") return AirbyteCatalog(streams=streams) def read( self, logger: AirbyteLogger, config: json, catalog: ConfiguredAirbyteCatalog,",
"is an AirbyteStream object that includes: - its stream name (or table name",
") from airbyte_cdk.sources import Source from firebolt.async_db import Connection as AsyncConnection from .database",
"connect to the Stripe API. :param logger: Logging object to display debug/info/error to",
"returned by discover(), but in addition, it's been configured in the UI! For",
"source, it might need to keep a checkpoint cursor to resume replication in",
"display debug/info/error to the logs (logs will not be accessible via airbyte UI",
"for t_name, c_name, c_type, nullable in await cursor.fetchall(): airbyte_type = convert_type(c_type, nullable) column_mapping[c_name]",
"return await gather(*[get_table_stream(connection, table) for table in tables]) loop = get_event_loop() streams =",
"in await cursor.fetchall(): airbyte_type = convert_type(c_type, nullable) column_mapping[c_name] = airbyte_type cursor.close() json_schema =",
"catalog where each postgres table is a stream, and each table column is",
"from airbyte_cdk.sources import Source from firebolt.async_db import Connection as AsyncConnection from .database import",
"each postgres table is a stream, and each table column is a field.",
"the spec.json file :param catalog: The input catalog is a ConfiguredAirbyteCatalog which is",
"that includes: - its stream name (or table name in the case of",
"\"\"\" Get AirbyteStream for a particular table with table structure defined. :param connection:",
"# Copyright (c) 2022 Airbyte, Inc., all rights reserved. # import json from",
"this source. A stream is an AirbyteStream object that includes: - its stream",
"etc :param state: When a Airbyte reads data from a source, it might",
"the source with the given configuration, catalog, and state. :param logger: Logging object",
"convert_type SUPPORTED_SYNC_MODES = [SyncMode.full_refresh] async def get_table_stream(connection: AsyncConnection, table: str) -> AirbyteStream: \"\"\"",
"their names and types) \"\"\" async def get_streams(): async with await establish_async_connection(config, logger)",
"catalog, and state. :param logger: Logging object to display debug/info/error to the logs",
"Connection as AsyncConnection from .database import establish_async_connection, establish_connection, get_firebolt_tables from .utils import airbyte_message_from_data,",
"from that saved checkpoint. This is the object that is provided with state",
"from .utils import airbyte_message_from_data, convert_type SUPPORTED_SYNC_MODES = [SyncMode.full_refresh] async def get_table_stream(connection: AsyncConnection, table:",
"need to keep a checkpoint cursor to resume replication in the future from",
"specified in the properties of the spec.json file :return: AirbyteConnectionStatus indicating a Success",
"( AirbyteCatalog, AirbyteConnectionStatus, AirbyteMessage, AirbyteStream, ConfiguredAirbyteCatalog, Status, SyncMode, ) from airbyte_cdk.sources import Source",
"object describing a list of all available streams in this source. A stream",
"SourceFirebolt(Source): def check(self, logger: AirbyteLogger, config: json) -> AirbyteConnectionStatus: \"\"\" Tests if the",
"object that includes: - its stream name (or table name in the case",
"loop = get_event_loop() streams = loop.run_until_complete(get_streams()) logger.info(f\"Provided {len(streams)} streams to the Aribyte Catalog.\")",
"integration e.g: if a provided Stripe API token can be used to connect",
"an AirbyteCatalog representing the available streams and fields in this integration. For example,",
"from .database import establish_async_connection, establish_connection, get_firebolt_tables from .utils import airbyte_message_from_data, convert_type SUPPORTED_SYNC_MODES =",
"reads data from a source, it might need to keep a checkpoint cursor",
"can only verify correctness of connection parameters on execution with connection.cursor() as cursor:",
"source, content of this json is as specified in the properties of the",
"the UI! For each particular stream and field, there may have been provided",
"airbyte_cdk.models import ( AirbyteCatalog, AirbyteConnectionStatus, AirbyteMessage, AirbyteStream, ConfiguredAirbyteCatalog, Status, SyncMode, ) from airbyte_cdk.sources",
"connected to a database :return: AirbyteStream object containing the table structure \"\"\" column_mapping",
"cursor = connection.cursor() await cursor.execute(f\"SHOW COLUMNS {table}\") for t_name, c_name, c_type, nullable in",
"return AirbyteConnectionStatus(status=Status.SUCCEEDED) except Exception as e: return AirbyteConnectionStatus(status=Status.FAILED, message=f\"An exception occurred: {str(e)}\") def",
"= list(table_properties.keys()) # Escape columns with \" to avoid reserved keywords e.g. id",
"to the Stripe API. :param logger: Logging object to display debug/info/error to the",
"an object describing a list of all available streams in this source. A",
"the logs (logs will not be accessible via airbyte UI if they are",
"(a list of columns described by their names and types) \"\"\" async def",
"= \"SELECT {columns} FROM {table}\".format(columns=\",\".join(escaped_columns), table=table_name) cursor.execute(query) logger.info(f\"Fetched {cursor.rowcount} rows from table {table_name}.\")",
"and/or columns out, renaming some entities, etc :param state: When a Airbyte reads",
"postgres table is a stream, and each table column is a field. :param",
"stream of AirbyteRecordMessage contained in AirbyteMessage object. \"\"\" logger.info(f\"Reading data from {len(catalog.streams)} Firebolt",
"AirbyteStream object containing the table structure \"\"\" column_mapping = {} cursor = connection.cursor()",
"with state from previous runs and avoid replicating the entire set of data",
"reserved. # import json from asyncio import gather, get_event_loop from typing import Dict,",
"logger: AirbyteLogger, config: json) -> AirbyteConnectionStatus: \"\"\" Tests if the input configuration can",
"checkpoint. This is the object that is provided with state from previous runs",
"SyncMode, ) from airbyte_cdk.sources import Source from firebolt.async_db import Connection as AsyncConnection from",
"of the spec.json file :param catalog: The input catalog is a ConfiguredAirbyteCatalog which",
"json_schema providing the specifications of expected schema for this stream (a list of",
"object. \"\"\" logger.info(f\"Reading data from {len(catalog.streams)} Firebolt tables.\") with establish_connection(config, logger) as connection:",
"keep a checkpoint cursor to resume replication in the future from that saved",
"of Postgres) - json_schema providing the specifications of expected schema for this stream",
"this source, content of this json is as specified in the properties of",
"import AirbyteLogger from airbyte_cdk.models import ( AirbyteCatalog, AirbyteConnectionStatus, AirbyteMessage, AirbyteStream, ConfiguredAirbyteCatalog, Status, SyncMode,",
"as specified in the properties of the spec.json file :return: AirbyteConnectionStatus indicating a",
"for table in tables]) loop = get_event_loop() streams = loop.run_until_complete(get_streams()) logger.info(f\"Provided {len(streams)} streams",
"Json object containing the configuration of this source, content of this json is",
"future from that saved checkpoint. This is the object that is provided with",
"been configured in the UI! For each particular stream and field, there may",
"table structure \"\"\" column_mapping = {} cursor = connection.cursor() await cursor.execute(f\"SHOW COLUMNS {table}\")",
"column_mapping[c_name] = airbyte_type cursor.close() json_schema = { \"type\": \"object\", \"properties\": column_mapping, } return",
"Success or Failure \"\"\" try: with establish_connection(config, logger) as connection: # We can",
".database import establish_async_connection, establish_connection, get_firebolt_tables from .utils import airbyte_message_from_data, convert_type SUPPORTED_SYNC_MODES = [SyncMode.full_refresh]",
"will not be accessible via airbyte UI if they are not passed to",
"exception occurred: {str(e)}\") def discover(self, logger: AirbyteLogger, config: json) -> AirbyteCatalog: \"\"\" Returns",
"t_name, c_name, c_type, nullable in await cursor.fetchall(): airbyte_type = convert_type(c_type, nullable) column_mapping[c_name] =",
"AirbyteStream: \"\"\" Get AirbyteStream for a particular table with table structure defined. :param",
"been provided with extra modifications such as: filtering streams and/or columns out, renaming",
"{table}\".format(columns=\",\".join(escaped_columns), table=table_name) cursor.execute(query) logger.info(f\"Fetched {cursor.rowcount} rows from table {table_name}.\") for result in cursor.fetchall():",
"AirbyteLogger, config: json) -> AirbyteConnectionStatus: \"\"\" Tests if the input configuration can be",
"AirbyteStream object that includes: - its stream name (or table name in the",
"establish_async_connection, establish_connection, get_firebolt_tables from .utils import airbyte_message_from_data, convert_type SUPPORTED_SYNC_MODES = [SyncMode.full_refresh] async def",
"list of columns described by their names and types) \"\"\" async def get_streams():",
"Stripe API. :param logger: Logging object to display debug/info/error to the logs (logs",
"AirbyteConnectionStatus(status=Status.SUCCEEDED) except Exception as e: return AirbyteConnectionStatus(status=Status.FAILED, message=f\"An exception occurred: {str(e)}\") def discover(self,",
"{len(catalog.streams)} Firebolt tables.\") with establish_connection(config, logger) as connection: with connection.cursor() as cursor: for",
"await gather(*[get_table_stream(connection, table) for table in tables]) loop = get_event_loop() streams = loop.run_until_complete(get_streams())",
"database :return: AirbyteStream object containing the table structure \"\"\" column_mapping = {} cursor",
"- json_schema providing the specifications of expected schema for this stream (a list",
"described by their names and types) \"\"\" async def get_streams(): async with await",
"2022 Airbyte, Inc., all rights reserved. # import json from asyncio import gather,",
"Source from firebolt.async_db import Connection as AsyncConnection from .database import establish_async_connection, establish_connection, get_firebolt_tables",
"configuration of this source, content of this json is as specified in the",
"of the spec.json file :return: AirbyteConnectionStatus indicating a Success or Failure \"\"\" try:",
"it's been configured in the UI! For each particular stream and field, there",
"COLUMNS {table}\") for t_name, c_name, c_type, nullable in await cursor.fetchall(): airbyte_type = convert_type(c_type,",
"For example, given valid credentials to a Postgres database, returns an Airbyte catalog",
"logger: AirbyteLogger, config: json) -> AirbyteCatalog: \"\"\" Returns an AirbyteCatalog representing the available",
"table column is a field. :param logger: Logging object to display debug/info/error to",
"the table structure \"\"\" column_mapping = {} cursor = connection.cursor() await cursor.execute(f\"SHOW COLUMNS",
"e: return AirbyteConnectionStatus(status=Status.FAILED, message=f\"An exception occurred: {str(e)}\") def discover(self, logger: AirbyteLogger, config: json)",
"= connection.cursor() await cursor.execute(f\"SHOW COLUMNS {table}\") for t_name, c_name, c_type, nullable in await",
"UI! For each particular stream and field, there may have been provided with",
"import Connection as AsyncConnection from .database import establish_async_connection, establish_connection, get_firebolt_tables from .utils import",
"everytime. :return: A generator that produces a stream of AirbyteRecordMessage contained in AirbyteMessage",
"id escaped_columns = ['\"{}\"'.format(col) for col in columns] query = \"SELECT {columns} FROM",
"an AirbyteStream object that includes: - its stream name (or table name in",
"of AirbyteRecordMessage contained in AirbyteMessage object. \"\"\" logger.info(f\"Reading data from {len(catalog.streams)} Firebolt tables.\")",
"Logging object to display debug/info/error to the logs (logs will not be accessible",
"that is provided with state from previous runs and avoid replicating the entire",
"parameters on execution with connection.cursor() as cursor: cursor.execute(\"SELECT 1\") return AirbyteConnectionStatus(status=Status.SUCCEEDED) except Exception",
"table structure defined. :param connection: Connection object connected to a database :return: AirbyteStream",
"of expected schema for this stream (a list of columns described by their",
") -> Generator[AirbyteMessage, None, None]: \"\"\" Returns a generator of the AirbyteMessages generated",
"gather, get_event_loop from typing import Dict, Generator from airbyte_cdk.logger import AirbyteLogger from airbyte_cdk.models",
"table_properties = c_stream.stream.json_schema[\"properties\"] columns = list(table_properties.keys()) # Escape columns with \" to avoid",
"properties of the spec.json file :return: AirbyteCatalog is an object describing a list",
"connection parameters on execution with connection.cursor() as cursor: cursor.execute(\"SELECT 1\") return AirbyteConnectionStatus(status=Status.SUCCEEDED) except",
"is provided with state from previous runs and avoid replicating the entire set",
"Escape columns with \" to avoid reserved keywords e.g. id escaped_columns = ['\"{}\"'.format(col)",
"source with the given configuration, catalog, and state. :param logger: Logging object to",
"async with await establish_async_connection(config, logger) as connection: tables = await get_firebolt_tables(connection) logger.info(f\"Found {len(tables)}",
"successfully connect to the integration e.g: if a provided Stripe API token can",
"from airbyte_cdk.logger import AirbyteLogger from airbyte_cdk.models import ( AirbyteCatalog, AirbyteConnectionStatus, AirbyteMessage, AirbyteStream, ConfiguredAirbyteCatalog,",
"def get_streams(): async with await establish_async_connection(config, logger) as connection: tables = await get_firebolt_tables(connection)",
"airbyte_cdk.sources import Source from firebolt.async_db import Connection as AsyncConnection from .database import establish_async_connection,",
"AirbyteMessages generated by reading the source with the given configuration, catalog, and state.",
"column is a field. :param logger: Logging object to display debug/info/error to the",
"FROM {table}\".format(columns=\",\".join(escaped_columns), table=table_name) cursor.execute(query) logger.info(f\"Fetched {cursor.rowcount} rows from table {table_name}.\") for result in",
"tables]) loop = get_event_loop() streams = loop.run_until_complete(get_streams()) logger.info(f\"Provided {len(streams)} streams to the Aribyte",
"AirbyteCatalog: \"\"\" Returns an AirbyteCatalog representing the available streams and fields in this",
"<reponame>faros-ai/airbyte # # Copyright (c) 2022 Airbyte, Inc., all rights reserved. # import",
"can be used to connect to the Stripe API. :param logger: Logging object",
"data from {len(catalog.streams)} Firebolt tables.\") with establish_connection(config, logger) as connection: with connection.cursor() as",
"with connection.cursor() as cursor: cursor.execute(\"SELECT 1\") return AirbyteConnectionStatus(status=Status.SUCCEEDED) except Exception as e: return",
"the properties of the spec.json file :return: AirbyteConnectionStatus indicating a Success or Failure",
"to the logs (logs will not be accessible via airbyte UI if they",
"convert_type(c_type, nullable) column_mapping[c_name] = airbyte_type cursor.close() json_schema = { \"type\": \"object\", \"properties\": column_mapping,",
"return AirbyteConnectionStatus(status=Status.FAILED, message=f\"An exception occurred: {str(e)}\") def discover(self, logger: AirbyteLogger, config: json) ->",
"a stream of AirbyteRecordMessage contained in AirbyteMessage object. \"\"\" logger.info(f\"Reading data from {len(catalog.streams)}",
"table in tables]) loop = get_event_loop() streams = loop.run_until_complete(get_streams()) logger.info(f\"Provided {len(streams)} streams to",
"def discover(self, logger: AirbyteLogger, config: json) -> AirbyteCatalog: \"\"\" Returns an AirbyteCatalog representing",
"AirbyteConnectionStatus indicating a Success or Failure \"\"\" try: with establish_connection(config, logger) as connection:",
"logger.info(f\"Provided {len(streams)} streams to the Aribyte Catalog.\") return AirbyteCatalog(streams=streams) def read( self, logger:",
"any], ) -> Generator[AirbyteMessage, None, None]: \"\"\" Returns a generator of the AirbyteMessages",
"field, there may have been provided with extra modifications such as: filtering streams",
"some entities, etc :param state: When a Airbyte reads data from a source,",
"# import json from asyncio import gather, get_event_loop from typing import Dict, Generator",
"its stream name (or table name in the case of Postgres) - json_schema",
"ConfiguredAirbyteCatalog, state: Dict[str, any], ) -> Generator[AirbyteMessage, None, None]: \"\"\" Returns a generator",
"table {table_name}.\") for result in cursor.fetchall(): message = airbyte_message_from_data(result, columns, table_name) if message:",
"to resume replication in the future from that saved checkpoint. This is the",
"This is the object that is provided with state from previous runs and",
"= ['\"{}\"'.format(col) for col in columns] query = \"SELECT {columns} FROM {table}\".format(columns=\",\".join(escaped_columns), table=table_name)",
"if they are not passed to this logger) :param config: Json object containing",
"might need to keep a checkpoint cursor to resume replication in the future",
"(logs will not be accessible via airbyte UI if they are not passed",
"includes: - its stream name (or table name in the case of Postgres)",
"import ( AirbyteCatalog, AirbyteConnectionStatus, AirbyteMessage, AirbyteStream, ConfiguredAirbyteCatalog, Status, SyncMode, ) from airbyte_cdk.sources import",
"this json is as specified in the properties of the spec.json file :param",
"c_stream.stream.name table_properties = c_stream.stream.json_schema[\"properties\"] columns = list(table_properties.keys()) # Escape columns with \" to",
"of data everytime. :return: A generator that produces a stream of AirbyteRecordMessage contained",
"airbyte_type = convert_type(c_type, nullable) column_mapping[c_name] = airbyte_type cursor.close() json_schema = { \"type\": \"object\",",
"is the object that is provided with state from previous runs and avoid",
"json, catalog: ConfiguredAirbyteCatalog, state: Dict[str, any], ) -> Generator[AirbyteMessage, None, None]: \"\"\" Returns",
"tables = await get_firebolt_tables(connection) logger.info(f\"Found {len(tables)} available tables.\") return await gather(*[get_table_stream(connection, table) for",
"get_table_stream(connection: AsyncConnection, table: str) -> AirbyteStream: \"\"\" Get AirbyteStream for a particular table",
"to successfully connect to the integration e.g: if a provided Stripe API token",
"columns described by their names and types) \"\"\" async def get_streams(): async with",
"from a source, it might need to keep a checkpoint cursor to resume",
"json_schema=json_schema, supported_sync_modes=SUPPORTED_SYNC_MODES) class SourceFirebolt(Source): def check(self, logger: AirbyteLogger, config: json) -> AirbyteConnectionStatus: \"\"\"",
"(or table name in the case of Postgres) - json_schema providing the specifications",
"with \" to avoid reserved keywords e.g. id escaped_columns = ['\"{}\"'.format(col) for col",
"e.g: if a provided Stripe API token can be used to connect to",
"token can be used to connect to the Stripe API. :param logger: Logging",
"= {} cursor = connection.cursor() await cursor.execute(f\"SHOW COLUMNS {table}\") for t_name, c_name, c_type,",
"extra modifications such as: filtering streams and/or columns out, renaming some entities, etc",
"the given configuration, catalog, and state. :param logger: Logging object to display debug/info/error",
"they are not passed to this logger) :param config: Json object containing the",
"(c) 2022 Airbyte, Inc., all rights reserved. # import json from asyncio import",
"= airbyte_type cursor.close() json_schema = { \"type\": \"object\", \"properties\": column_mapping, } return AirbyteStream(name=table,",
"query = \"SELECT {columns} FROM {table}\".format(columns=\",\".join(escaped_columns), table=table_name) cursor.execute(query) logger.info(f\"Fetched {cursor.rowcount} rows from table",
"providing the specifications of expected schema for this stream (a list of columns",
"table with table structure defined. :param connection: Connection object connected to a database",
"for a particular table with table structure defined. :param connection: Connection object connected",
"the future from that saved checkpoint. This is the object that is provided",
"in the properties of the spec.json file :return: AirbyteConnectionStatus indicating a Success or",
"{len(tables)} available tables.\") return await gather(*[get_table_stream(connection, table) for table in tables]) loop =",
"ConfiguredAirbyteCatalog which is almost the same as AirbyteCatalog returned by discover(), but in",
"the spec.json file :return: AirbyteCatalog is an object describing a list of all",
"there may have been provided with extra modifications such as: filtering streams and/or",
"c_name, c_type, nullable in await cursor.fetchall(): airbyte_type = convert_type(c_type, nullable) column_mapping[c_name] = airbyte_type",
"and state. :param logger: Logging object to display debug/info/error to the logs (logs",
"API token can be used to connect to the Stripe API. :param logger:",
"as AsyncConnection from .database import establish_async_connection, establish_connection, get_firebolt_tables from .utils import airbyte_message_from_data, convert_type",
"expected schema for this stream (a list of columns described by their names",
"example, given valid credentials to a Postgres database, returns an Airbyte catalog where",
"replication in the future from that saved checkpoint. This is the object that",
"to the integration e.g: if a provided Stripe API token can be used",
"given valid credentials to a Postgres database, returns an Airbyte catalog where each",
"with the given configuration, catalog, and state. :param logger: Logging object to display",
"be used to successfully connect to the integration e.g: if a provided Stripe",
"provided with state from previous runs and avoid replicating the entire set of",
"particular stream and field, there may have been provided with extra modifications such",
"is as specified in the properties of the spec.json file :return: AirbyteConnectionStatus indicating",
"with extra modifications such as: filtering streams and/or columns out, renaming some entities,",
"establish_connection(config, logger) as connection: with connection.cursor() as cursor: for c_stream in catalog.streams: table_name",
"nullable in await cursor.fetchall(): airbyte_type = convert_type(c_type, nullable) column_mapping[c_name] = airbyte_type cursor.close() json_schema",
"airbyte_cdk.logger import AirbyteLogger from airbyte_cdk.models import ( AirbyteCatalog, AirbyteConnectionStatus, AirbyteMessage, AirbyteStream, ConfiguredAirbyteCatalog, Status,",
"c_stream.stream.json_schema[\"properties\"] columns = list(table_properties.keys()) # Escape columns with \" to avoid reserved keywords",
"columns] query = \"SELECT {columns} FROM {table}\".format(columns=\",\".join(escaped_columns), table=table_name) cursor.execute(query) logger.info(f\"Fetched {cursor.rowcount} rows from",
"logger) :param config: Json object containing the configuration of this source, content of",
"renaming some entities, etc :param state: When a Airbyte reads data from a",
"of the spec.json file :return: AirbyteCatalog is an object describing a list of",
"the Aribyte Catalog.\") return AirbyteCatalog(streams=streams) def read( self, logger: AirbyteLogger, config: json, catalog:",
"column_mapping = {} cursor = connection.cursor() await cursor.execute(f\"SHOW COLUMNS {table}\") for t_name, c_name,",
"and each table column is a field. :param logger: Logging object to display",
"to a Postgres database, returns an Airbyte catalog where each postgres table is",
"Tests if the input configuration can be used to successfully connect to the",
"-> Generator[AirbyteMessage, None, None]: \"\"\" Returns a generator of the AirbyteMessages generated by",
"supported_sync_modes=SUPPORTED_SYNC_MODES) class SourceFirebolt(Source): def check(self, logger: AirbyteLogger, config: json) -> AirbyteConnectionStatus: \"\"\" Tests",
"on execution with connection.cursor() as cursor: cursor.execute(\"SELECT 1\") return AirbyteConnectionStatus(status=Status.SUCCEEDED) except Exception as",
"tables.\") return await gather(*[get_table_stream(connection, table) for table in tables]) loop = get_event_loop() streams",
"by reading the source with the given configuration, catalog, and state. :param logger:",
"Generator from airbyte_cdk.logger import AirbyteLogger from airbyte_cdk.models import ( AirbyteCatalog, AirbyteConnectionStatus, AirbyteMessage, AirbyteStream,",
"a particular table with table structure defined. :param connection: Connection object connected to",
"provided Stripe API token can be used to connect to the Stripe API.",
"AirbyteLogger, config: json) -> AirbyteCatalog: \"\"\" Returns an AirbyteCatalog representing the available streams",
"def read( self, logger: AirbyteLogger, config: json, catalog: ConfiguredAirbyteCatalog, state: Dict[str, any], )",
"AirbyteStream(name=table, json_schema=json_schema, supported_sync_modes=SUPPORTED_SYNC_MODES) class SourceFirebolt(Source): def check(self, logger: AirbyteLogger, config: json) -> AirbyteConnectionStatus:",
"spec.json file :return: AirbyteCatalog is an object describing a list of all available",
"except Exception as e: return AirbyteConnectionStatus(status=Status.FAILED, message=f\"An exception occurred: {str(e)}\") def discover(self, logger:",
"valid credentials to a Postgres database, returns an Airbyte catalog where each postgres",
"Catalog.\") return AirbyteCatalog(streams=streams) def read( self, logger: AirbyteLogger, config: json, catalog: ConfiguredAirbyteCatalog, state:",
"= c_stream.stream.name table_properties = c_stream.stream.json_schema[\"properties\"] columns = list(table_properties.keys()) # Escape columns with \"",
"all rights reserved. # import json from asyncio import gather, get_event_loop from typing",
"Connection object connected to a database :return: AirbyteStream object containing the table structure",
"that saved checkpoint. This is the object that is provided with state from",
"catalog is a ConfiguredAirbyteCatalog which is almost the same as AirbyteCatalog returned by",
"to a database :return: AirbyteStream object containing the table structure \"\"\" column_mapping =",
"connection: Connection object connected to a database :return: AirbyteStream object containing the table",
"a stream, and each table column is a field. :param logger: Logging object",
"this logger) :param config: Json object containing the configuration of this source, content",
"logger.info(f\"Found {len(tables)} available tables.\") return await gather(*[get_table_stream(connection, table) for table in tables]) loop",
"\"properties\": column_mapping, } return AirbyteStream(name=table, json_schema=json_schema, supported_sync_modes=SUPPORTED_SYNC_MODES) class SourceFirebolt(Source): def check(self, logger: AirbyteLogger,",
"json is as specified in the properties of the spec.json file :return: AirbyteCatalog",
"previous runs and avoid replicating the entire set of data everytime. :return: A",
"given configuration, catalog, and state. :param logger: Logging object to display debug/info/error to",
"firebolt.async_db import Connection as AsyncConnection from .database import establish_async_connection, establish_connection, get_firebolt_tables from .utils",
"AirbyteMessage, AirbyteStream, ConfiguredAirbyteCatalog, Status, SyncMode, ) from airbyte_cdk.sources import Source from firebolt.async_db import",
"-> AirbyteConnectionStatus: \"\"\" Tests if the input configuration can be used to successfully",
"AirbyteLogger from airbyte_cdk.models import ( AirbyteCatalog, AirbyteConnectionStatus, AirbyteMessage, AirbyteStream, ConfiguredAirbyteCatalog, Status, SyncMode, )",
"\"\"\" Tests if the input configuration can be used to successfully connect to",
"the integration e.g: if a provided Stripe API token can be used to",
":param config: Json object containing the configuration of this source, content of this",
"via airbyte UI if they are not passed to this logger) :param config:",
"stream and field, there may have been provided with extra modifications such as:",
"object containing the configuration of this source, content of this json is as",
"Dict, Generator from airbyte_cdk.logger import AirbyteLogger from airbyte_cdk.models import ( AirbyteCatalog, AirbyteConnectionStatus, AirbyteMessage,",
":return: AirbyteConnectionStatus indicating a Success or Failure \"\"\" try: with establish_connection(config, logger) as",
"replicating the entire set of data everytime. :return: A generator that produces a",
"as cursor: for c_stream in catalog.streams: table_name = c_stream.stream.name table_properties = c_stream.stream.json_schema[\"properties\"] columns",
"= c_stream.stream.json_schema[\"properties\"] columns = list(table_properties.keys()) # Escape columns with \" to avoid reserved",
"cursor.execute(query) logger.info(f\"Fetched {cursor.rowcount} rows from table {table_name}.\") for result in cursor.fetchall(): message =",
":return: AirbyteStream object containing the table structure \"\"\" column_mapping = {} cursor =",
"table_name = c_stream.stream.name table_properties = c_stream.stream.json_schema[\"properties\"] columns = list(table_properties.keys()) # Escape columns with",
"return AirbyteStream(name=table, json_schema=json_schema, supported_sync_modes=SUPPORTED_SYNC_MODES) class SourceFirebolt(Source): def check(self, logger: AirbyteLogger, config: json) ->",
"AirbyteConnectionStatus: \"\"\" Tests if the input configuration can be used to successfully connect",
"get_streams(): async with await establish_async_connection(config, logger) as connection: tables = await get_firebolt_tables(connection) logger.info(f\"Found",
"json from asyncio import gather, get_event_loop from typing import Dict, Generator from airbyte_cdk.logger",
"cursor.fetchall(): message = airbyte_message_from_data(result, columns, table_name) if message: yield message logger.info(\"Data read complete.\")",
"airbyte_message_from_data, convert_type SUPPORTED_SYNC_MODES = [SyncMode.full_refresh] async def get_table_stream(connection: AsyncConnection, table: str) -> AirbyteStream:",
"AirbyteMessage object. \"\"\" logger.info(f\"Reading data from {len(catalog.streams)} Firebolt tables.\") with establish_connection(config, logger) as",
"AirbyteLogger, config: json, catalog: ConfiguredAirbyteCatalog, state: Dict[str, any], ) -> Generator[AirbyteMessage, None, None]:",
"saved checkpoint. This is the object that is provided with state from previous",
"to display debug/info/error to the logs (logs will not be accessible via airbyte",
"AirbyteCatalog(streams=streams) def read( self, logger: AirbyteLogger, config: json, catalog: ConfiguredAirbyteCatalog, state: Dict[str, any],",
"state: Dict[str, any], ) -> Generator[AirbyteMessage, None, None]: \"\"\" Returns a generator of",
"discover(self, logger: AirbyteLogger, config: json) -> AirbyteCatalog: \"\"\" Returns an AirbyteCatalog representing the",
"config: Json object containing the configuration of this source, content of this json",
"content of this json is as specified in the properties of the spec.json",
"in tables]) loop = get_event_loop() streams = loop.run_until_complete(get_streams()) logger.info(f\"Provided {len(streams)} streams to the",
"as specified in the properties of the spec.json file :param catalog: The input",
"Stripe API token can be used to connect to the Stripe API. :param",
"generator of the AirbyteMessages generated by reading the source with the given configuration,",
"as specified in the properties of the spec.json file :return: AirbyteCatalog is an",
"from firebolt.async_db import Connection as AsyncConnection from .database import establish_async_connection, establish_connection, get_firebolt_tables from",
"Status, SyncMode, ) from airbyte_cdk.sources import Source from firebolt.async_db import Connection as AsyncConnection",
"columns out, renaming some entities, etc :param state: When a Airbyte reads data",
"accessible via airbyte UI if they are not passed to this logger) :param",
"{columns} FROM {table}\".format(columns=\",\".join(escaped_columns), table=table_name) cursor.execute(query) logger.info(f\"Fetched {cursor.rowcount} rows from table {table_name}.\") for result",
"in this source. A stream is an AirbyteStream object that includes: - its"
] |
[
"self.translate_collection if not word: return word for write in translate_list: if isinstance(write, dict)",
"value in v.items(): return cast(value_type, value) fdict = {} for key in thsort:",
"for i, value in enumerate(search_obj): new_d_path = None if d_path: new_d_path = f'{d_path}[{i}]'",
"import os import logging import json import copy from benedict import benedict from",
"self.translate_collection[word] return word # Если не найдено перевода - оставляем как есть @staticmethod",
"value_path @staticmethod def __clean_format_tpl(data): \"\"\" Очистка щаполненного шаблона от пустых блоков\"\"\" def is_rows_null(section):",
"респондера \"\"\" normalize_incident = copy.deepcopy(data) normalize_incident.update({\"customFields\": self.__sort_thive_list(normalize_incident['customFields'])}) return normalize_incident def __get_value_of_the_path(self, value_bank: benedict,",
"[] for k, v in self.normal_thive_incident['customFields'].items(): rows.append({\"left\": self.get_translate_of_word(word=k, position='left'), \"right\": self.get_translate_of_word(word=v, position='right')}) return",
"not word: return word for write in translate_list: if isinstance(write, dict) and write['word']",
"key in thsort: v = get_value(thdict[key]) fdict.update({key: v}) return fdict def __normalize_thive_dict(self, data):",
"value): from datetime import datetime if not value: return None if value_type ==",
"position: # position может быть обязательным для сравнения if write['position'] == position: return",
"tpl: logger.debug('Имя шаблона не задано, будет использован default') return self.__load_tpl(\"default\") logger.debug(f'Будет использован шаблон",
"def __clean_format_tpl(data): \"\"\" Очистка щаполненного шаблона от пустых блоков\"\"\" def is_rows_null(section): \"\"\" тут",
"def build(self, data: dict, tpl: dict) -> dict: if not data: logger.warning('No data')",
"= self.__clean_format_tpl(format_tpl) return final_format_tpl def translate_other_items(self, data: dict): \"\"\" Перевод дополнительных полей \"\"\"",
"not d_path: paths_to_fields.update({key: value}) if d_path: paths_to_fields.update({f'{d_path}.{key}': value}) elif isinstance(value, dict): if d_path:",
"isinstance(value, dict): if d_path: key = d_path + '.' + key results =",
"value_type, value in v.items(): return cast(value_type, value) fdict = {} for key in",
"\"\"\" Получаем список объектов, которые нужно заменить \"\"\" paths_to_fields = {} if isinstance(search_obj,",
"in value_path: \"\"\" soc_inc>{что взять из инцидента} \"\"\" v = value_path.replace(\"soc_inc>\", '') data_value",
"getting setting. Check your settings file in {tpl_path}') raise TemplateFileNotExist(f\"File {tpl_path} doesn't exist\")",
"'.' + key results = self.__get_recursively(value, field, key) paths_to_fields = {**paths_to_fields, **results} return",
"как есть @staticmethod def __sort_thive_list(thdict: dict): \"\"\" Сортируем словарь-список thive \"\"\" thsort =",
"word # Если не найдено перевода - оставляем как есть @staticmethod def __sort_thive_list(thdict:",
"not value: return None if value_type == 'date': return datetime.fromtimestamp(value / 1e3).isoformat() if",
"= None) -> dict: \"\"\" Получаем список объектов, которые нужно заменить \"\"\" paths_to_fields",
"'string': return str(value) if value_type == 'numder': return int(value) return value def get_value(v:",
"value_path: \"\"\"Отрисовать список\"\"\" v = value_path.replace(\"soc_inc_rows>\", '') rows_data = get_value(_value_bank, v) rows =",
"dict: \"\"\" Получаем список объектов, которые нужно заменить \"\"\" paths_to_fields = {} if",
"if d_path: key = d_path + '.' + key results = self.__get_recursively(value, field,",
"value_path: str) -> object: \"\"\" Получение значения по пути через точку \"\"\" _value_bank",
"__get_tpl(self, tpl: str = None) -> dict: if not tpl: logger.debug('Имя шаблона не",
"не задано, будет использован default') return self.__load_tpl(\"default\") logger.debug(f'Будет использован шаблон {tpl}') return self.__load_tpl(tpl_name=tpl)",
"d_path: str = None) -> dict: \"\"\" Получаем список объектов, которые нужно заменить",
"from datetime import datetime if not value: return None if value_type == 'date':",
"задано, будет использован default') return self.__load_tpl(\"default\") logger.debug(f'Будет использован шаблон {tpl}') return self.__load_tpl(tpl_name=tpl) def",
"'.' + key results = self.__get_recursively(value, field, key) paths_to_fields = {**paths_to_fields, **results} elif",
"-> dict: tpl_path = os.path.join(os.getcwd(), f'templates/{tpl_name}.json') if not os.path.exists(tpl_path): logger.error(f'Error getting setting. Check",
"= {**paths_to_fields, **results} elif isinstance(value, list): if d_path: key = d_path + '.'",
"return None if value_type == 'date': return datetime.fromtimestamp(value / 1e3).isoformat() if value_type ==",
"value def get_value(v: dict): v.pop('order') for value_type, value in v.items(): return cast(value_type, value)",
"дополнительных полей \"\"\" if not data: return None translate_result = {} for k,",
"if isinstance(search_obj, dict): for key, value in search_obj.items(): if field in value: if",
"= self.__get_recursively(benedict(copy.deepcopy(tpl)), 'soc_static_field') for repl_key, repl_value in replacement_list.items(): format_tpl.set(repl_key, self.__get_value_of_the_path(self.translate_collection, repl_value)) final_format_tpl =",
"format_tpl.set(repl_key, self.__get_value_of_the_path(format_data, repl_value)) replacement_list = self.__get_recursively(benedict(copy.deepcopy(tpl)), 'soc_static_field') for repl_key, repl_value in replacement_list.items(): format_tpl.set(repl_key,",
"final_format_tpl def translate_other_items(self, data: dict): \"\"\" Перевод дополнительных полей \"\"\" if not data:",
"word: return word for write in translate_list: if isinstance(write, dict) and write['word'] ==",
"None if d_path: new_d_path = f'{d_path}[{i}]' results = self.__get_recursively(value, field, new_d_path) paths_to_fields =",
"return {} self.normal_thive_incident = self.__normalize_thive_dict(data) format_data = benedict(self.normal_thive_incident) format_tpl = benedict(copy.deepcopy(tpl)) replacement_list =",
"translate_path[0] == \"items_translate\": return self.get_translate_of_word(word=translate_path[1]) if len(translate_path) == 1: return self.get_translate_of_word(word=v) if \"soc_inc_rows>\"",
"def __get_recursively(self, search_obj: object, field: str, d_path: str = None) -> dict: \"\"\"",
"return self.__load_tpl(\"default\") logger.debug(f'Будет использован шаблон {tpl}') return self.__load_tpl(tpl_name=tpl) def __get_recursively(self, search_obj: object, field:",
"cast(value_type, value) fdict = {} for key in thsort: v = get_value(thdict[key]) fdict.update({key:",
"data: logger.warning('No data') return {} self.normal_thive_incident = self.__normalize_thive_dict(data) format_data = benedict(self.normal_thive_incident) format_tpl =",
"\"soc_inc_rows>\" in value_path: \"\"\"Отрисовать список\"\"\" v = value_path.replace(\"soc_inc_rows>\", '') rows_data = get_value(_value_bank, v)",
"elif isinstance(value, list): if d_path: key = d_path + '.' + key results",
"isinstance(search_obj, dict): for key, value in search_obj.items(): if field in value: if not",
"benedict(copy.deepcopy(tpl)) replacement_list = self.__get_recursively(benedict(copy.deepcopy(tpl)), 'soc_inc') for repl_key, repl_value in replacement_list.items(): format_tpl.set(repl_key, self.__get_value_of_the_path(format_data, repl_value))",
"return True from copy import deepcopy final_format_tpl = deepcopy(data) for i in data['categories'][0]['sections']:",
"final_format_tpl = deepcopy(data) for i in data['categories'][0]['sections']: if is_rows_null(i): final_format_tpl['categories'][0]['sections'].remove(i) return final_format_tpl def",
"and write in self.translate_collection: return self.translate_collection[word] return word # Если не найдено перевода",
"deepcopy(data) for i in data['categories'][0]['sections']: if is_rows_null(i): final_format_tpl['categories'][0]['sections'].remove(i) return final_format_tpl def build(self, data:",
"in replacement_list.items(): format_tpl.set(repl_key, self.__get_value_of_the_path(self.translate_collection, repl_value)) final_format_tpl = self.__clean_format_tpl(format_tpl) return final_format_tpl def translate_other_items(self, data:",
"key results = self.__get_recursively(value, field, key) paths_to_fields = {**paths_to_fields, **results} elif isinstance(value, list):",
"dict): if d_path: key = d_path + '.' + key results = self.__get_recursively(value,",
"\"\"\" Получение значения по пути через точку \"\"\" _value_bank = copy.deepcopy(value_bank) def get_value(_data,",
"_v): _data = _data.get(_v) return _data if \"soc_inc>\" in value_path: \"\"\" soc_inc>{что взять",
"fdict.update({key: v}) return fdict def __normalize_thive_dict(self, data): \"\"\" Нормализуем инцидент для респондера \"\"\"",
"какому word взять translate}\"\"\" v = value_path.replace(\"soc_static_field>\", '') translate_path = v.split('.') if translate_path[0]",
"{tpl}') return self.__load_tpl(tpl_name=tpl) def __get_recursively(self, search_obj: object, field: str, d_path: str = None)",
"not None: return False return True from copy import deepcopy final_format_tpl = deepcopy(data)",
"= benedict(copy.deepcopy(tpl)) replacement_list = self.__get_recursively(benedict(copy.deepcopy(tpl)), 'soc_inc') for repl_key, repl_value in replacement_list.items(): format_tpl.set(repl_key, self.__get_value_of_the_path(format_data,",
"{} @staticmethod def __load_tpl(tpl_name: str) -> dict: tpl_path = os.path.join(os.getcwd(), f'templates/{tpl_name}.json') if not",
"= 'default' self.normal_thive_incident = {} @staticmethod def __load_tpl(tpl_name: str) -> dict: tpl_path =",
"position='right')}) return rows return value_path @staticmethod def __clean_format_tpl(data): \"\"\" Очистка щаполненного шаблона от",
"not data: return None translate_result = {} for k, v in data.items(): translate_result[k]",
"__get_recursively(self, search_obj: object, field: str, d_path: str = None) -> dict: \"\"\" Получаем",
"paths_to_fields def get_translate_of_word(self, word: str = None, position: str = None): translate_list =",
"dict, tpl: dict) -> dict: if not data: logger.warning('No data') return {} self.normal_thive_incident",
"не найдено перевода - оставляем как есть @staticmethod def __sort_thive_list(thdict: dict): \"\"\" Сортируем",
"value_path.replace(\"soc_inc_rows>\", '') rows_data = get_value(_value_bank, v) rows = [] for k, v in",
"= get_value(_value_bank, v) rows = [] for k, v in self.normal_thive_incident['customFields'].items(): rows.append({\"left\": self.get_translate_of_word(word=k,",
"value_type == 'numder': return int(value) return value def get_value(v: dict): v.pop('order') for value_type,",
"def is_rows_null(section): \"\"\" тут проверяем, пустой блок или нет\"\"\" for item in section['blocks'][0]['rows']:",
"field, key) paths_to_fields = {**paths_to_fields, **results} return paths_to_fields def get_translate_of_word(self, word: str =",
"write['translate'] if isinstance(write, str) and write in self.translate_collection: return self.translate_collection[word] return word #",
"section['blocks'][0]['rows']: if item['right'] is not None: return False return True from copy import",
"'date': return datetime.fromtimestamp(value / 1e3).isoformat() if value_type == 'string': return str(value) if value_type",
"== position: return write['translate'] else: return write['translate'] if isinstance(write, str) and write in",
"+ key results = self.__get_recursively(value, field, key) paths_to_fields = {**paths_to_fields, **results} elif isinstance(value,",
"== 1: return self.get_translate_of_word(word=v) if \"soc_inc_rows>\" in value_path: \"\"\"Отрисовать список\"\"\" v = value_path.replace(\"soc_inc_rows>\",",
"= value_path.replace(\"soc_inc_rows>\", '') rows_data = get_value(_value_bank, v) rows = [] for k, v",
"= f'{d_path}[{i}]' results = self.__get_recursively(value, field, new_d_path) paths_to_fields = {**paths_to_fields, **results} if isinstance(search_obj,",
"is_rows_null(section): \"\"\" тут проверяем, пустой блок или нет\"\"\" for item in section['blocks'][0]['rows']: if",
"value_path: \"\"\" soc_inc>{что взять из инцидента} \"\"\" v = value_path.replace(\"soc_inc>\", '') data_value =",
"repl_value in replacement_list.items(): format_tpl.set(repl_key, self.__get_value_of_the_path(format_data, repl_value)) replacement_list = self.__get_recursively(benedict(copy.deepcopy(tpl)), 'soc_static_field') for repl_key, repl_value",
"translate_result = {} for k, v in data.items(): translate_result[k] = self.get_translate_of_word(word=v, position=k) return",
"return self.translate_collection[word] return word # Если не найдено перевода - оставляем как есть",
"тут проверяем, пустой блок или нет\"\"\" for item in section['blocks'][0]['rows']: if item['right'] is",
"if not value: return None if value_type == 'date': return datetime.fromtimestamp(value / 1e3).isoformat()",
"{tpl_path}') raise TemplateFileNotExist(f\"File {tpl_path} doesn't exist\") with open(tpl_path, encoding='utf-8') as f: tpl =",
"<filename>responder_commons/report_builder.py import os import logging import json import copy from benedict import benedict",
"as f: tpl = json.load(f) return tpl def __get_tpl(self, tpl: str = None)",
"else: return write['translate'] if isinstance(write, str) and write in self.translate_collection: return self.translate_collection[word] return",
"in section['blocks'][0]['rows']: if item['right'] is not None: return False return True from copy",
"\"\"\" _value_bank = copy.deepcopy(value_bank) def get_value(_data, _v): _data = _data.get(_v) return _data if",
"logger.debug(f'Будет использован шаблон {tpl}') return self.__load_tpl(tpl_name=tpl) def __get_recursively(self, search_obj: object, field: str, d_path:",
"len(translate_path) == 1: return self.get_translate_of_word(word=v) if \"soc_inc_rows>\" in value_path: \"\"\"Отрисовать список\"\"\" v =",
"TemplateFileNotExist(f\"File {tpl_path} doesn't exist\") with open(tpl_path, encoding='utf-8') as f: tpl = json.load(f) return",
"logging import json import copy from benedict import benedict from responder_commons.exc import TemplateFileNotExist",
"v}) return fdict def __normalize_thive_dict(self, data): \"\"\" Нормализуем инцидент для респондера \"\"\" normalize_incident",
"sorted(thdict, key=lambda x: thdict[x]['order']) def cast(value_type, value): from datetime import datetime if not",
"= None) -> dict: if not tpl: logger.debug('Имя шаблона не задано, будет использован",
"\"\"\" if not data: return None translate_result = {} for k, v in",
"return fdict def __normalize_thive_dict(self, data): \"\"\" Нормализуем инцидент для респондера \"\"\" normalize_incident =",
"from copy import deepcopy final_format_tpl = deepcopy(data) for i in data['categories'][0]['sections']: if is_rows_null(i):",
"x: thdict[x]['order']) def cast(value_type, value): from datetime import datetime if not value: return",
"write in self.translate_collection: return self.translate_collection[word] return word # Если не найдено перевода -",
"_value_bank = copy.deepcopy(value_bank) def get_value(_data, _v): _data = _data.get(_v) return _data if \"soc_inc>\"",
"\"\"\" v = value_path.replace(\"soc_inc>\", '') data_value = get_value(_value_bank, v) return data_value if \"soc_static_field>\"",
"item['right'] is not None: return False return True from copy import deepcopy final_format_tpl",
"return self.__load_tpl(tpl_name=tpl) def __get_recursively(self, search_obj: object, field: str, d_path: str = None) ->",
"value_path.replace(\"soc_static_field>\", '') translate_path = v.split('.') if translate_path[0] == \"items_translate\": return self.get_translate_of_word(word=translate_path[1]) if len(translate_path)",
"{} self.normal_thive_incident = self.__normalize_thive_dict(data) format_data = benedict(self.normal_thive_incident) format_tpl = benedict(copy.deepcopy(tpl)) replacement_list = self.__get_recursively(benedict(copy.deepcopy(tpl)),",
"not tpl: logger.debug('Имя шаблона не задано, будет использован default') return self.__load_tpl(\"default\") logger.debug(f'Будет использован",
"str) -> object: \"\"\" Получение значения по пути через точку \"\"\" _value_bank =",
"from benedict import benedict from responder_commons.exc import TemplateFileNotExist logger = logging.getLogger('responder_commons') class Builder:",
"benedict from responder_commons.exc import TemplateFileNotExist logger = logging.getLogger('responder_commons') class Builder: def __init__(self, translate_params):",
"def __get_value_of_the_path(self, value_bank: benedict, value_path: str) -> object: \"\"\" Получение значения по пути",
"Очистка щаполненного шаблона от пустых блоков\"\"\" def is_rows_null(section): \"\"\" тут проверяем, пустой блок",
"in {tpl_path}') raise TemplateFileNotExist(f\"File {tpl_path} doesn't exist\") with open(tpl_path, encoding='utf-8') as f: tpl",
"@staticmethod def __sort_thive_list(thdict: dict): \"\"\" Сортируем словарь-список thive \"\"\" thsort = sorted(thdict, key=lambda",
"- оставляем как есть @staticmethod def __sort_thive_list(thdict: dict): \"\"\" Сортируем словарь-список thive \"\"\"",
"datetime.fromtimestamp(value / 1e3).isoformat() if value_type == 'string': return str(value) if value_type == 'numder':",
"self.translate_collection = benedict(translate_params) self.translate_collection = translate_params self.tpl_name = 'default' self.normal_thive_incident = {} @staticmethod",
"repl_key, repl_value in replacement_list.items(): format_tpl.set(repl_key, self.__get_value_of_the_path(format_data, repl_value)) replacement_list = self.__get_recursively(benedict(copy.deepcopy(tpl)), 'soc_static_field') for repl_key,",
"{**paths_to_fields, **results} if isinstance(search_obj, dict): for key, value in search_obj.items(): if field in",
"def __sort_thive_list(thdict: dict): \"\"\" Сортируем словарь-список thive \"\"\" thsort = sorted(thdict, key=lambda x:",
"из инцидента} \"\"\" v = value_path.replace(\"soc_inc>\", '') data_value = get_value(_value_bank, v) return data_value",
"is_rows_null(i): final_format_tpl['categories'][0]['sections'].remove(i) return final_format_tpl def build(self, data: dict, tpl: dict) -> dict: if",
"= {} if isinstance(search_obj, list): for i, value in enumerate(search_obj): new_d_path = None",
"tpl_path = os.path.join(os.getcwd(), f'templates/{tpl_name}.json') if not os.path.exists(tpl_path): logger.error(f'Error getting setting. Check your settings",
"if not data: return None translate_result = {} for k, v in data.items():",
"object: \"\"\" Получение значения по пути через точку \"\"\" _value_bank = copy.deepcopy(value_bank) def",
"if \"soc_static_field>\" in value_path: \"\"\" soc_static_field>{где}.{по какому word взять translate}\"\"\" v = value_path.replace(\"soc_static_field>\",",
"**results} return paths_to_fields def get_translate_of_word(self, word: str = None, position: str = None):",
"data: dict, tpl: dict) -> dict: if not data: logger.warning('No data') return {}",
"item in section['blocks'][0]['rows']: if item['right'] is not None: return False return True from",
"d_path + '.' + key results = self.__get_recursively(value, field, key) paths_to_fields = {**paths_to_fields,",
"tpl def __get_tpl(self, tpl: str = None) -> dict: if not tpl: logger.debug('Имя",
"обязательным для сравнения if write['position'] == position: return write['translate'] else: return write['translate'] if",
"in self.translate_collection: return self.translate_collection[word] return word # Если не найдено перевода - оставляем",
"= get_value(_value_bank, v) return data_value if \"soc_static_field>\" in value_path: \"\"\" soc_static_field>{где}.{по какому word",
"\"right\": self.get_translate_of_word(word=v, position='right')}) return rows return value_path @staticmethod def __clean_format_tpl(data): \"\"\" Очистка щаполненного",
"soc_static_field>{где}.{по какому word взять translate}\"\"\" v = value_path.replace(\"soc_static_field>\", '') translate_path = v.split('.') if",
"with open(tpl_path, encoding='utf-8') as f: tpl = json.load(f) return tpl def __get_tpl(self, tpl:",
"rows.append({\"left\": self.get_translate_of_word(word=k, position='left'), \"right\": self.get_translate_of_word(word=v, position='right')}) return rows return value_path @staticmethod def __clean_format_tpl(data):",
"self.__get_value_of_the_path(self.translate_collection, repl_value)) final_format_tpl = self.__clean_format_tpl(format_tpl) return final_format_tpl def translate_other_items(self, data: dict): \"\"\" Перевод",
"if translate_path[0] == \"items_translate\": return self.get_translate_of_word(word=translate_path[1]) if len(translate_path) == 1: return self.get_translate_of_word(word=v) if",
"translate_list: if isinstance(write, dict) and write['word'] == word: if position: # position может",
"copy from benedict import benedict from responder_commons.exc import TemplateFileNotExist logger = logging.getLogger('responder_commons') class",
"word for write in translate_list: if isinstance(write, dict) and write['word'] == word: if",
"= deepcopy(data) for i in data['categories'][0]['sections']: if is_rows_null(i): final_format_tpl['categories'][0]['sections'].remove(i) return final_format_tpl def build(self,",
"\"\"\"Отрисовать список\"\"\" v = value_path.replace(\"soc_inc_rows>\", '') rows_data = get_value(_value_bank, v) rows = []",
"щаполненного шаблона от пустых блоков\"\"\" def is_rows_null(section): \"\"\" тут проверяем, пустой блок или",
"def get_value(_data, _v): _data = _data.get(_v) return _data if \"soc_inc>\" in value_path: \"\"\"",
"return data_value if \"soc_static_field>\" in value_path: \"\"\" soc_static_field>{где}.{по какому word взять translate}\"\"\" v",
"list): for i, value in enumerate(search_obj): new_d_path = None if d_path: new_d_path =",
"-> object: \"\"\" Получение значения по пути через точку \"\"\" _value_bank = copy.deepcopy(value_bank)",
"tpl = json.load(f) return tpl def __get_tpl(self, tpl: str = None) -> dict:",
"key = d_path + '.' + key results = self.__get_recursively(value, field, key) paths_to_fields",
"пути через точку \"\"\" _value_bank = copy.deepcopy(value_bank) def get_value(_data, _v): _data = _data.get(_v)",
"in translate_list: if isinstance(write, dict) and write['word'] == word: if position: # position",
"thive \"\"\" thsort = sorted(thdict, key=lambda x: thdict[x]['order']) def cast(value_type, value): from datetime",
"= {} for k, v in data.items(): translate_result[k] = self.get_translate_of_word(word=v, position=k) return translate_result",
"'') translate_path = v.split('.') if translate_path[0] == \"items_translate\": return self.get_translate_of_word(word=translate_path[1]) if len(translate_path) ==",
"isinstance(write, str) and write in self.translate_collection: return self.translate_collection[word] return word # Если не",
"= benedict(self.normal_thive_incident) format_tpl = benedict(copy.deepcopy(tpl)) replacement_list = self.__get_recursively(benedict(copy.deepcopy(tpl)), 'soc_inc') for repl_key, repl_value in",
"get_value(_value_bank, v) return data_value if \"soc_static_field>\" in value_path: \"\"\" soc_static_field>{где}.{по какому word взять",
"от пустых блоков\"\"\" def is_rows_null(section): \"\"\" тут проверяем, пустой блок или нет\"\"\" for",
"= value_path.replace(\"soc_static_field>\", '') translate_path = v.split('.') if translate_path[0] == \"items_translate\": return self.get_translate_of_word(word=translate_path[1]) if",
"final_format_tpl['categories'][0]['sections'].remove(i) return final_format_tpl def build(self, data: dict, tpl: dict) -> dict: if not",
"paths_to_fields.update({key: value}) if d_path: paths_to_fields.update({f'{d_path}.{key}': value}) elif isinstance(value, dict): if d_path: key =",
"== word: if position: # position может быть обязательным для сравнения if write['position']",
"value in enumerate(search_obj): new_d_path = None if d_path: new_d_path = f'{d_path}[{i}]' results =",
"== 'date': return datetime.fromtimestamp(value / 1e3).isoformat() if value_type == 'string': return str(value) if",
"key) paths_to_fields = {**paths_to_fields, **results} return paths_to_fields def get_translate_of_word(self, word: str = None,",
"_data = _data.get(_v) return _data if \"soc_inc>\" in value_path: \"\"\" soc_inc>{что взять из",
"-> dict: if not tpl: logger.debug('Имя шаблона не задано, будет использован default') return",
"for i in data['categories'][0]['sections']: if is_rows_null(i): final_format_tpl['categories'][0]['sections'].remove(i) return final_format_tpl def build(self, data: dict,",
"os.path.join(os.getcwd(), f'templates/{tpl_name}.json') if not os.path.exists(tpl_path): logger.error(f'Error getting setting. Check your settings file in",
"return int(value) return value def get_value(v: dict): v.pop('order') for value_type, value in v.items():",
"def cast(value_type, value): from datetime import datetime if not value: return None if",
"rows = [] for k, v in self.normal_thive_incident['customFields'].items(): rows.append({\"left\": self.get_translate_of_word(word=k, position='left'), \"right\": self.get_translate_of_word(word=v,",
"return tpl def __get_tpl(self, tpl: str = None) -> dict: if not tpl:",
"datetime if not value: return None if value_type == 'date': return datetime.fromtimestamp(value /",
"v) rows = [] for k, v in self.normal_thive_incident['customFields'].items(): rows.append({\"left\": self.get_translate_of_word(word=k, position='left'), \"right\":",
"f'{d_path}[{i}]' results = self.__get_recursively(value, field, new_d_path) paths_to_fields = {**paths_to_fields, **results} if isinstance(search_obj, dict):",
"settings file in {tpl_path}') raise TemplateFileNotExist(f\"File {tpl_path} doesn't exist\") with open(tpl_path, encoding='utf-8') as",
"results = self.__get_recursively(value, field, key) paths_to_fields = {**paths_to_fields, **results} elif isinstance(value, list): if",
"build(self, data: dict, tpl: dict) -> dict: if not data: logger.warning('No data') return",
"word: str = None, position: str = None): translate_list = self.translate_collection if not",
"write['word'] == word: if position: # position может быть обязательным для сравнения if",
"+ '.' + key results = self.__get_recursively(value, field, key) paths_to_fields = {**paths_to_fields, **results}",
"= self.__get_recursively(value, field, key) paths_to_fields = {**paths_to_fields, **results} return paths_to_fields def get_translate_of_word(self, word:",
"import json import copy from benedict import benedict from responder_commons.exc import TemplateFileNotExist logger",
"def get_value(v: dict): v.pop('order') for value_type, value in v.items(): return cast(value_type, value) fdict",
"= self.__get_recursively(benedict(copy.deepcopy(tpl)), 'soc_inc') for repl_key, repl_value in replacement_list.items(): format_tpl.set(repl_key, self.__get_value_of_the_path(format_data, repl_value)) replacement_list =",
"v) return data_value if \"soc_static_field>\" in value_path: \"\"\" soc_static_field>{где}.{по какому word взять translate}\"\"\"",
"if isinstance(write, str) and write in self.translate_collection: return self.translate_collection[word] return word # Если",
"заменить \"\"\" paths_to_fields = {} if isinstance(search_obj, list): for i, value in enumerate(search_obj):",
"True from copy import deepcopy final_format_tpl = deepcopy(data) for i in data['categories'][0]['sections']: if",
"enumerate(search_obj): new_d_path = None if d_path: new_d_path = f'{d_path}[{i}]' results = self.__get_recursively(value, field,",
"{} for key in thsort: v = get_value(thdict[key]) fdict.update({key: v}) return fdict def",
"False return True from copy import deepcopy final_format_tpl = deepcopy(data) for i in",
"return rows return value_path @staticmethod def __clean_format_tpl(data): \"\"\" Очистка щаполненного шаблона от пустых",
"= self.translate_collection if not word: return word for write in translate_list: if isinstance(write,",
"{**paths_to_fields, **results} elif isinstance(value, list): if d_path: key = d_path + '.' +",
"return self.get_translate_of_word(word=translate_path[1]) if len(translate_path) == 1: return self.get_translate_of_word(word=v) if \"soc_inc_rows>\" in value_path: \"\"\"Отрисовать",
"benedict import benedict from responder_commons.exc import TemplateFileNotExist logger = logging.getLogger('responder_commons') class Builder: def",
"dict): \"\"\" Перевод дополнительных полей \"\"\" if not data: return None translate_result =",
"word: if position: # position может быть обязательным для сравнения if write['position'] ==",
"= {} for key in thsort: v = get_value(thdict[key]) fdict.update({key: v}) return fdict",
"replacement_list = self.__get_recursively(benedict(copy.deepcopy(tpl)), 'soc_inc') for repl_key, repl_value in replacement_list.items(): format_tpl.set(repl_key, self.__get_value_of_the_path(format_data, repl_value)) replacement_list",
"setting. Check your settings file in {tpl_path}') raise TemplateFileNotExist(f\"File {tpl_path} doesn't exist\") with",
"data_value = get_value(_value_bank, v) return data_value if \"soc_static_field>\" in value_path: \"\"\" soc_static_field>{где}.{по какому",
"\"items_translate\": return self.get_translate_of_word(word=translate_path[1]) if len(translate_path) == 1: return self.get_translate_of_word(word=v) if \"soc_inc_rows>\" in value_path:",
"and write['word'] == word: if position: # position может быть обязательным для сравнения",
"return write['translate'] if isinstance(write, str) and write in self.translate_collection: return self.translate_collection[word] return word",
"найдено перевода - оставляем как есть @staticmethod def __sort_thive_list(thdict: dict): \"\"\" Сортируем словарь-список",
"= translate_params self.tpl_name = 'default' self.normal_thive_incident = {} @staticmethod def __load_tpl(tpl_name: str) ->",
"== 'string': return str(value) if value_type == 'numder': return int(value) return value def",
"repl_key, repl_value in replacement_list.items(): format_tpl.set(repl_key, self.__get_value_of_the_path(self.translate_collection, repl_value)) final_format_tpl = self.__clean_format_tpl(format_tpl) return final_format_tpl def",
"for key, value in search_obj.items(): if field in value: if not d_path: paths_to_fields.update({key:",
"dict: if not data: logger.warning('No data') return {} self.normal_thive_incident = self.__normalize_thive_dict(data) format_data =",
"инцидент для респондера \"\"\" normalize_incident = copy.deepcopy(data) normalize_incident.update({\"customFields\": self.__sort_thive_list(normalize_incident['customFields'])}) return normalize_incident def __get_value_of_the_path(self,",
"self.__get_recursively(value, field, key) paths_to_fields = {**paths_to_fields, **results} return paths_to_fields def get_translate_of_word(self, word: str",
"**results} if isinstance(search_obj, dict): for key, value in search_obj.items(): if field in value:",
"self.tpl_name = 'default' self.normal_thive_incident = {} @staticmethod def __load_tpl(tpl_name: str) -> dict: tpl_path",
"if field in value: if not d_path: paths_to_fields.update({key: value}) if d_path: paths_to_fields.update({f'{d_path}.{key}': value})",
"in value_path: \"\"\"Отрисовать список\"\"\" v = value_path.replace(\"soc_inc_rows>\", '') rows_data = get_value(_value_bank, v) rows",
"None if value_type == 'date': return datetime.fromtimestamp(value / 1e3).isoformat() if value_type == 'string':",
"thdict[x]['order']) def cast(value_type, value): from datetime import datetime if not value: return None",
"@staticmethod def __clean_format_tpl(data): \"\"\" Очистка щаполненного шаблона от пустых блоков\"\"\" def is_rows_null(section): \"\"\"",
"self.get_translate_of_word(word=translate_path[1]) if len(translate_path) == 1: return self.get_translate_of_word(word=v) if \"soc_inc_rows>\" in value_path: \"\"\"Отрисовать список\"\"\"",
"class Builder: def __init__(self, translate_params): # self.translate_collection = benedict(translate_params) self.translate_collection = translate_params self.tpl_name",
"not data: logger.warning('No data') return {} self.normal_thive_incident = self.__normalize_thive_dict(data) format_data = benedict(self.normal_thive_incident) format_tpl",
"cast(value_type, value): from datetime import datetime if not value: return None if value_type",
"import logging import json import copy from benedict import benedict from responder_commons.exc import",
"self.__get_recursively(benedict(copy.deepcopy(tpl)), 'soc_inc') for repl_key, repl_value in replacement_list.items(): format_tpl.set(repl_key, self.__get_value_of_the_path(format_data, repl_value)) replacement_list = self.__get_recursively(benedict(copy.deepcopy(tpl)),",
"format_tpl = benedict(copy.deepcopy(tpl)) replacement_list = self.__get_recursively(benedict(copy.deepcopy(tpl)), 'soc_inc') for repl_key, repl_value in replacement_list.items(): format_tpl.set(repl_key,",
"field in value: if not d_path: paths_to_fields.update({key: value}) if d_path: paths_to_fields.update({f'{d_path}.{key}': value}) elif",
"for write in translate_list: if isinstance(write, dict) and write['word'] == word: if position:",
"translate_other_items(self, data: dict): \"\"\" Перевод дополнительных полей \"\"\" if not data: return None",
"\"\"\" soc_static_field>{где}.{по какому word взять translate}\"\"\" v = value_path.replace(\"soc_static_field>\", '') translate_path = v.split('.')",
"data: dict): \"\"\" Перевод дополнительных полей \"\"\" if not data: return None translate_result",
"dict) -> dict: if not data: logger.warning('No data') return {} self.normal_thive_incident = self.__normalize_thive_dict(data)",
"{} if isinstance(search_obj, list): for i, value in enumerate(search_obj): new_d_path = None if",
"position='left'), \"right\": self.get_translate_of_word(word=v, position='right')}) return rows return value_path @staticmethod def __clean_format_tpl(data): \"\"\" Очистка",
"_data if \"soc_inc>\" in value_path: \"\"\" soc_inc>{что взять из инцидента} \"\"\" v =",
"словарь-список thive \"\"\" thsort = sorted(thdict, key=lambda x: thdict[x]['order']) def cast(value_type, value): from",
"которые нужно заменить \"\"\" paths_to_fields = {} if isinstance(search_obj, list): for i, value",
"final_format_tpl = self.__clean_format_tpl(format_tpl) return final_format_tpl def translate_other_items(self, data: dict): \"\"\" Перевод дополнительных полей",
"translate}\"\"\" v = value_path.replace(\"soc_static_field>\", '') translate_path = v.split('.') if translate_path[0] == \"items_translate\": return",
"if not word: return word for write in translate_list: if isinstance(write, dict) and",
"def translate_other_items(self, data: dict): \"\"\" Перевод дополнительных полей \"\"\" if not data: return",
"= None, position: str = None): translate_list = self.translate_collection if not word: return",
"для сравнения if write['position'] == position: return write['translate'] else: return write['translate'] if isinstance(write,",
"get_translate_of_word(self, word: str = None, position: str = None): translate_list = self.translate_collection if",
"шаблон {tpl}') return self.__load_tpl(tpl_name=tpl) def __get_recursively(self, search_obj: object, field: str, d_path: str =",
"if len(translate_path) == 1: return self.get_translate_of_word(word=v) if \"soc_inc_rows>\" in value_path: \"\"\"Отрисовать список\"\"\" v",
"= None): translate_list = self.translate_collection if not word: return word for write in",
"results = self.__get_recursively(value, field, new_d_path) paths_to_fields = {**paths_to_fields, **results} if isinstance(search_obj, dict): for",
"v in self.normal_thive_incident['customFields'].items(): rows.append({\"left\": self.get_translate_of_word(word=k, position='left'), \"right\": self.get_translate_of_word(word=v, position='right')}) return rows return value_path",
"return write['translate'] else: return write['translate'] if isinstance(write, str) and write in self.translate_collection: return",
"fdict = {} for key in thsort: v = get_value(thdict[key]) fdict.update({key: v}) return",
"\"soc_static_field>\" in value_path: \"\"\" soc_static_field>{где}.{по какому word взять translate}\"\"\" v = value_path.replace(\"soc_static_field>\", '')",
"write['translate'] else: return write['translate'] if isinstance(write, str) and write in self.translate_collection: return self.translate_collection[word]",
"normalize_incident.update({\"customFields\": self.__sort_thive_list(normalize_incident['customFields'])}) return normalize_incident def __get_value_of_the_path(self, value_bank: benedict, value_path: str) -> object: \"\"\"",
"new_d_path = f'{d_path}[{i}]' results = self.__get_recursively(value, field, new_d_path) paths_to_fields = {**paths_to_fields, **results} if",
"data['categories'][0]['sections']: if is_rows_null(i): final_format_tpl['categories'][0]['sections'].remove(i) return final_format_tpl def build(self, data: dict, tpl: dict) ->",
"def __get_tpl(self, tpl: str = None) -> dict: if not tpl: logger.debug('Имя шаблона",
"значения по пути через точку \"\"\" _value_bank = copy.deepcopy(value_bank) def get_value(_data, _v): _data",
"= json.load(f) return tpl def __get_tpl(self, tpl: str = None) -> dict: if",
"value}) elif isinstance(value, dict): if d_path: key = d_path + '.' + key",
"in v.items(): return cast(value_type, value) fdict = {} for key in thsort: v",
"logging.getLogger('responder_commons') class Builder: def __init__(self, translate_params): # self.translate_collection = benedict(translate_params) self.translate_collection = translate_params",
"return word # Если не найдено перевода - оставляем как есть @staticmethod def",
"paths_to_fields = {**paths_to_fields, **results} elif isinstance(value, list): if d_path: key = d_path +",
"field, new_d_path) paths_to_fields = {**paths_to_fields, **results} if isinstance(search_obj, dict): for key, value in",
"блок или нет\"\"\" for item in section['blocks'][0]['rows']: if item['right'] is not None: return",
"responder_commons.exc import TemplateFileNotExist logger = logging.getLogger('responder_commons') class Builder: def __init__(self, translate_params): # self.translate_collection",
"benedict(self.normal_thive_incident) format_tpl = benedict(copy.deepcopy(tpl)) replacement_list = self.__get_recursively(benedict(copy.deepcopy(tpl)), 'soc_inc') for repl_key, repl_value in replacement_list.items():",
"translate_params self.tpl_name = 'default' self.normal_thive_incident = {} @staticmethod def __load_tpl(tpl_name: str) -> dict:",
"def __init__(self, translate_params): # self.translate_collection = benedict(translate_params) self.translate_collection = translate_params self.tpl_name = 'default'",
"logger.warning('No data') return {} self.normal_thive_incident = self.__normalize_thive_dict(data) format_data = benedict(self.normal_thive_incident) format_tpl = benedict(copy.deepcopy(tpl))",
"return _data if \"soc_inc>\" in value_path: \"\"\" soc_inc>{что взять из инцидента} \"\"\" v",
"Builder: def __init__(self, translate_params): # self.translate_collection = benedict(translate_params) self.translate_collection = translate_params self.tpl_name =",
"инцидента} \"\"\" v = value_path.replace(\"soc_inc>\", '') data_value = get_value(_value_bank, v) return data_value if",
"if not os.path.exists(tpl_path): logger.error(f'Error getting setting. Check your settings file in {tpl_path}') raise",
"None, position: str = None): translate_list = self.translate_collection if not word: return word",
"v.split('.') if translate_path[0] == \"items_translate\": return self.get_translate_of_word(word=translate_path[1]) if len(translate_path) == 1: return self.get_translate_of_word(word=v)",
"1e3).isoformat() if value_type == 'string': return str(value) if value_type == 'numder': return int(value)",
"key) paths_to_fields = {**paths_to_fields, **results} elif isinstance(value, list): if d_path: key = d_path",
"isinstance(value, list): if d_path: key = d_path + '.' + key results =",
"import benedict from responder_commons.exc import TemplateFileNotExist logger = logging.getLogger('responder_commons') class Builder: def __init__(self,",
"benedict(translate_params) self.translate_collection = translate_params self.tpl_name = 'default' self.normal_thive_incident = {} @staticmethod def __load_tpl(tpl_name:",
"self.__sort_thive_list(normalize_incident['customFields'])}) return normalize_incident def __get_value_of_the_path(self, value_bank: benedict, value_path: str) -> object: \"\"\" Получение",
"default') return self.__load_tpl(\"default\") logger.debug(f'Будет использован шаблон {tpl}') return self.__load_tpl(tpl_name=tpl) def __get_recursively(self, search_obj: object,",
"или нет\"\"\" for item in section['blocks'][0]['rows']: if item['right'] is not None: return False",
"return str(value) if value_type == 'numder': return int(value) return value def get_value(v: dict):",
"d_path: key = d_path + '.' + key results = self.__get_recursively(value, field, key)",
"@staticmethod def __load_tpl(tpl_name: str) -> dict: tpl_path = os.path.join(os.getcwd(), f'templates/{tpl_name}.json') if not os.path.exists(tpl_path):",
"'') rows_data = get_value(_value_bank, v) rows = [] for k, v in self.normal_thive_incident['customFields'].items():",
"**results} elif isinstance(value, list): if d_path: key = d_path + '.' + key",
"шаблона не задано, будет использован default') return self.__load_tpl(\"default\") logger.debug(f'Будет использован шаблон {tpl}') return",
"import TemplateFileNotExist logger = logging.getLogger('responder_commons') class Builder: def __init__(self, translate_params): # self.translate_collection =",
"write['position'] == position: return write['translate'] else: return write['translate'] if isinstance(write, str) and write",
"= v.split('.') if translate_path[0] == \"items_translate\": return self.get_translate_of_word(word=translate_path[1]) if len(translate_path) == 1: return",
"if value_type == 'numder': return int(value) return value def get_value(v: dict): v.pop('order') for",
"paths_to_fields = {} if isinstance(search_obj, list): for i, value in enumerate(search_obj): new_d_path =",
"if value_type == 'date': return datetime.fromtimestamp(value / 1e3).isoformat() if value_type == 'string': return",
"d_path: new_d_path = f'{d_path}[{i}]' results = self.__get_recursively(value, field, new_d_path) paths_to_fields = {**paths_to_fields, **results}",
"in value_path: \"\"\" soc_static_field>{где}.{по какому word взять translate}\"\"\" v = value_path.replace(\"soc_static_field>\", '') translate_path",
"return value_path @staticmethod def __clean_format_tpl(data): \"\"\" Очистка щаполненного шаблона от пустых блоков\"\"\" def",
"= self.__get_recursively(value, field, key) paths_to_fields = {**paths_to_fields, **results} elif isinstance(value, list): if d_path:",
"def get_translate_of_word(self, word: str = None, position: str = None): translate_list = self.translate_collection",
"import copy from benedict import benedict from responder_commons.exc import TemplateFileNotExist logger = logging.getLogger('responder_commons')",
"dict): for key, value in search_obj.items(): if field in value: if not d_path:",
"== 'numder': return int(value) return value def get_value(v: dict): v.pop('order') for value_type, value",
"использован шаблон {tpl}') return self.__load_tpl(tpl_name=tpl) def __get_recursively(self, search_obj: object, field: str, d_path: str",
"paths_to_fields.update({f'{d_path}.{key}': value}) elif isinstance(value, dict): if d_path: key = d_path + '.' +",
"def __normalize_thive_dict(self, data): \"\"\" Нормализуем инцидент для респондера \"\"\" normalize_incident = copy.deepcopy(data) normalize_incident.update({\"customFields\":",
"self.normal_thive_incident['customFields'].items(): rows.append({\"left\": self.get_translate_of_word(word=k, position='left'), \"right\": self.get_translate_of_word(word=v, position='right')}) return rows return value_path @staticmethod def",
"doesn't exist\") with open(tpl_path, encoding='utf-8') as f: tpl = json.load(f) return tpl def",
"if not d_path: paths_to_fields.update({key: value}) if d_path: paths_to_fields.update({f'{d_path}.{key}': value}) elif isinstance(value, dict): if",
"шаблона от пустых блоков\"\"\" def is_rows_null(section): \"\"\" тут проверяем, пустой блок или нет\"\"\"",
"isinstance(write, dict) and write['word'] == word: if position: # position может быть обязательным",
"d_path: paths_to_fields.update({f'{d_path}.{key}': value}) elif isinstance(value, dict): if d_path: key = d_path + '.'",
"translate_path = v.split('.') if translate_path[0] == \"items_translate\": return self.get_translate_of_word(word=translate_path[1]) if len(translate_path) == 1:",
"new_d_path = None if d_path: new_d_path = f'{d_path}[{i}]' results = self.__get_recursively(value, field, new_d_path)",
"= [] for k, v in self.normal_thive_incident['customFields'].items(): rows.append({\"left\": self.get_translate_of_word(word=k, position='left'), \"right\": self.get_translate_of_word(word=v, position='right')})",
"deepcopy final_format_tpl = deepcopy(data) for i in data['categories'][0]['sections']: if is_rows_null(i): final_format_tpl['categories'][0]['sections'].remove(i) return final_format_tpl",
"проверяем, пустой блок или нет\"\"\" for item in section['blocks'][0]['rows']: if item['right'] is not",
"{**paths_to_fields, **results} return paths_to_fields def get_translate_of_word(self, word: str = None, position: str =",
"список объектов, которые нужно заменить \"\"\" paths_to_fields = {} if isinstance(search_obj, list): for",
"return final_format_tpl def build(self, data: dict, tpl: dict) -> dict: if not data:",
"is not None: return False return True from copy import deepcopy final_format_tpl =",
"\"\"\" Очистка щаполненного шаблона от пустых блоков\"\"\" def is_rows_null(section): \"\"\" тут проверяем, пустой",
"k, v in self.normal_thive_incident['customFields'].items(): rows.append({\"left\": self.get_translate_of_word(word=k, position='left'), \"right\": self.get_translate_of_word(word=v, position='right')}) return rows return",
"key, value in search_obj.items(): if field in value: if not d_path: paths_to_fields.update({key: value})",
"v.items(): return cast(value_type, value) fdict = {} for key in thsort: v =",
"in self.normal_thive_incident['customFields'].items(): rows.append({\"left\": self.get_translate_of_word(word=k, position='left'), \"right\": self.get_translate_of_word(word=v, position='right')}) return rows return value_path @staticmethod",
"\"\"\" normalize_incident = copy.deepcopy(data) normalize_incident.update({\"customFields\": self.__sort_thive_list(normalize_incident['customFields'])}) return normalize_incident def __get_value_of_the_path(self, value_bank: benedict, value_path:",
"'') data_value = get_value(_value_bank, v) return data_value if \"soc_static_field>\" in value_path: \"\"\" soc_static_field>{где}.{по",
"Получение значения по пути через точку \"\"\" _value_bank = copy.deepcopy(value_bank) def get_value(_data, _v):",
"None) -> dict: if not tpl: logger.debug('Имя шаблона не задано, будет использован default')",
"value_type == 'date': return datetime.fromtimestamp(value / 1e3).isoformat() if value_type == 'string': return str(value)",
"position может быть обязательным для сравнения if write['position'] == position: return write['translate'] else:",
"field, key) paths_to_fields = {**paths_to_fields, **results} elif isinstance(value, list): if d_path: key =",
"new_d_path) paths_to_fields = {**paths_to_fields, **results} if isinstance(search_obj, dict): for key, value in search_obj.items():",
"v = get_value(thdict[key]) fdict.update({key: v}) return fdict def __normalize_thive_dict(self, data): \"\"\" Нормализуем инцидент",
"logger = logging.getLogger('responder_commons') class Builder: def __init__(self, translate_params): # self.translate_collection = benedict(translate_params) self.translate_collection",
"value_path: \"\"\" soc_static_field>{где}.{по какому word взять translate}\"\"\" v = value_path.replace(\"soc_static_field>\", '') translate_path =",
"str = None): translate_list = self.translate_collection if not word: return word for write",
"return paths_to_fields def get_translate_of_word(self, word: str = None, position: str = None): translate_list",
"position: return write['translate'] else: return write['translate'] if isinstance(write, str) and write in self.translate_collection:",
"str, d_path: str = None) -> dict: \"\"\" Получаем список объектов, которые нужно",
"= _data.get(_v) return _data if \"soc_inc>\" in value_path: \"\"\" soc_inc>{что взять из инцидента}",
"\"\"\" тут проверяем, пустой блок или нет\"\"\" for item in section['blocks'][0]['rows']: if item['right']",
"self.normal_thive_incident = self.__normalize_thive_dict(data) format_data = benedict(self.normal_thive_incident) format_tpl = benedict(copy.deepcopy(tpl)) replacement_list = self.__get_recursively(benedict(copy.deepcopy(tpl)), 'soc_inc')",
"v.pop('order') for value_type, value in v.items(): return cast(value_type, value) fdict = {} for",
"v = value_path.replace(\"soc_inc_rows>\", '') rows_data = get_value(_value_bank, v) rows = [] for k,",
"оставляем как есть @staticmethod def __sort_thive_list(thdict: dict): \"\"\" Сортируем словарь-список thive \"\"\" thsort",
"= sorted(thdict, key=lambda x: thdict[x]['order']) def cast(value_type, value): from datetime import datetime if",
"for repl_key, repl_value in replacement_list.items(): format_tpl.set(repl_key, self.__get_value_of_the_path(self.translate_collection, repl_value)) final_format_tpl = self.__clean_format_tpl(format_tpl) return final_format_tpl",
"_data.get(_v) return _data if \"soc_inc>\" in value_path: \"\"\" soc_inc>{что взять из инцидента} \"\"\"",
"нет\"\"\" for item in section['blocks'][0]['rows']: if item['right'] is not None: return False return",
"= copy.deepcopy(data) normalize_incident.update({\"customFields\": self.__sort_thive_list(normalize_incident['customFields'])}) return normalize_incident def __get_value_of_the_path(self, value_bank: benedict, value_path: str) ->",
"repl_value)) replacement_list = self.__get_recursively(benedict(copy.deepcopy(tpl)), 'soc_static_field') for repl_key, repl_value in replacement_list.items(): format_tpl.set(repl_key, self.__get_value_of_the_path(self.translate_collection, repl_value))",
"return None translate_result = {} for k, v in data.items(): translate_result[k] = self.get_translate_of_word(word=v,",
"v = value_path.replace(\"soc_static_field>\", '') translate_path = v.split('.') if translate_path[0] == \"items_translate\": return self.get_translate_of_word(word=translate_path[1])",
"Check your settings file in {tpl_path}') raise TemplateFileNotExist(f\"File {tpl_path} doesn't exist\") with open(tpl_path,",
"== \"items_translate\": return self.get_translate_of_word(word=translate_path[1]) if len(translate_path) == 1: return self.get_translate_of_word(word=v) if \"soc_inc_rows>\" in",
"i, value in enumerate(search_obj): new_d_path = None if d_path: new_d_path = f'{d_path}[{i}]' results",
"self.__get_recursively(benedict(copy.deepcopy(tpl)), 'soc_static_field') for repl_key, repl_value in replacement_list.items(): format_tpl.set(repl_key, self.__get_value_of_the_path(self.translate_collection, repl_value)) final_format_tpl = self.__clean_format_tpl(format_tpl)",
"str = None, position: str = None): translate_list = self.translate_collection if not word:",
"сравнения if write['position'] == position: return write['translate'] else: return write['translate'] if isinstance(write, str)",
"if d_path: paths_to_fields.update({f'{d_path}.{key}': value}) elif isinstance(value, dict): if d_path: key = d_path +",
"rows return value_path @staticmethod def __clean_format_tpl(data): \"\"\" Очистка щаполненного шаблона от пустых блоков\"\"\"",
"i in data['categories'][0]['sections']: if is_rows_null(i): final_format_tpl['categories'][0]['sections'].remove(i) return final_format_tpl def build(self, data: dict, tpl:",
"search_obj.items(): if field in value: if not d_path: paths_to_fields.update({key: value}) if d_path: paths_to_fields.update({f'{d_path}.{key}':",
"# Если не найдено перевода - оставляем как есть @staticmethod def __sort_thive_list(thdict: dict):",
"быть обязательным для сравнения if write['position'] == position: return write['translate'] else: return write['translate']",
"\"\"\" Перевод дополнительных полей \"\"\" if not data: return None translate_result = {}",
"key results = self.__get_recursively(value, field, key) paths_to_fields = {**paths_to_fields, **results} return paths_to_fields def",
"int(value) return value def get_value(v: dict): v.pop('order') for value_type, value in v.items(): return",
"взять translate}\"\"\" v = value_path.replace(\"soc_static_field>\", '') translate_path = v.split('.') if translate_path[0] == \"items_translate\":",
"= value_path.replace(\"soc_inc>\", '') data_value = get_value(_value_bank, v) return data_value if \"soc_static_field>\" in value_path:",
"self.normal_thive_incident = {} @staticmethod def __load_tpl(tpl_name: str) -> dict: tpl_path = os.path.join(os.getcwd(), f'templates/{tpl_name}.json')",
"value: if not d_path: paths_to_fields.update({key: value}) if d_path: paths_to_fields.update({f'{d_path}.{key}': value}) elif isinstance(value, dict):",
"есть @staticmethod def __sort_thive_list(thdict: dict): \"\"\" Сортируем словарь-список thive \"\"\" thsort = sorted(thdict,",
"field: str, d_path: str = None) -> dict: \"\"\" Получаем список объектов, которые",
"return value def get_value(v: dict): v.pop('order') for value_type, value in v.items(): return cast(value_type,",
"file in {tpl_path}') raise TemplateFileNotExist(f\"File {tpl_path} doesn't exist\") with open(tpl_path, encoding='utf-8') as f:",
"raise TemplateFileNotExist(f\"File {tpl_path} doesn't exist\") with open(tpl_path, encoding='utf-8') as f: tpl = json.load(f)",
"if position: # position может быть обязательным для сравнения if write['position'] == position:",
"будет использован default') return self.__load_tpl(\"default\") logger.debug(f'Будет использован шаблон {tpl}') return self.__load_tpl(tpl_name=tpl) def __get_recursively(self,",
"fdict def __normalize_thive_dict(self, data): \"\"\" Нормализуем инцидент для респондера \"\"\" normalize_incident = copy.deepcopy(data)",
"value}) if d_path: paths_to_fields.update({f'{d_path}.{key}': value}) elif isinstance(value, dict): if d_path: key = d_path",
"\"\"\" Нормализуем инцидент для респондера \"\"\" normalize_incident = copy.deepcopy(data) normalize_incident.update({\"customFields\": self.__sort_thive_list(normalize_incident['customFields'])}) return normalize_incident",
"encoding='utf-8') as f: tpl = json.load(f) return tpl def __get_tpl(self, tpl: str =",
"self.__get_value_of_the_path(format_data, repl_value)) replacement_list = self.__get_recursively(benedict(copy.deepcopy(tpl)), 'soc_static_field') for repl_key, repl_value in replacement_list.items(): format_tpl.set(repl_key, self.__get_value_of_the_path(self.translate_collection,",
"TemplateFileNotExist logger = logging.getLogger('responder_commons') class Builder: def __init__(self, translate_params): # self.translate_collection = benedict(translate_params)",
"f: tpl = json.load(f) return tpl def __get_tpl(self, tpl: str = None) ->",
"rows_data = get_value(_value_bank, v) rows = [] for k, v in self.normal_thive_incident['customFields'].items(): rows.append({\"left\":",
"= None if d_path: new_d_path = f'{d_path}[{i}]' results = self.__get_recursively(value, field, new_d_path) paths_to_fields",
"copy.deepcopy(data) normalize_incident.update({\"customFields\": self.__sort_thive_list(normalize_incident['customFields'])}) return normalize_incident def __get_value_of_the_path(self, value_bank: benedict, value_path: str) -> object:",
"= {**paths_to_fields, **results} return paths_to_fields def get_translate_of_word(self, word: str = None, position: str",
"logger.debug('Имя шаблона не задано, будет использован default') return self.__load_tpl(\"default\") logger.debug(f'Будет использован шаблон {tpl}')",
"self.__get_recursively(value, field, key) paths_to_fields = {**paths_to_fields, **results} elif isinstance(value, list): if d_path: key",
"None translate_result = {} for k, v in data.items(): translate_result[k] = self.get_translate_of_word(word=v, position=k)",
"\"\"\" thsort = sorted(thdict, key=lambda x: thdict[x]['order']) def cast(value_type, value): from datetime import",
"{tpl_path} doesn't exist\") with open(tpl_path, encoding='utf-8') as f: tpl = json.load(f) return tpl",
"dict: if not tpl: logger.debug('Имя шаблона не задано, будет использован default') return self.__load_tpl(\"default\")",
"__normalize_thive_dict(self, data): \"\"\" Нормализуем инцидент для респондера \"\"\" normalize_incident = copy.deepcopy(data) normalize_incident.update({\"customFields\": self.__sort_thive_list(normalize_incident['customFields'])})",
"get_value(_data, _v): _data = _data.get(_v) return _data if \"soc_inc>\" in value_path: \"\"\" soc_inc>{что",
"self.translate_collection: return self.translate_collection[word] return word # Если не найдено перевода - оставляем как",
"data: return None translate_result = {} for k, v in data.items(): translate_result[k] =",
"__load_tpl(tpl_name: str) -> dict: tpl_path = os.path.join(os.getcwd(), f'templates/{tpl_name}.json') if not os.path.exists(tpl_path): logger.error(f'Error getting",
"'numder': return int(value) return value def get_value(v: dict): v.pop('order') for value_type, value in",
"if write['position'] == position: return write['translate'] else: return write['translate'] if isinstance(write, str) and",
"self.__load_tpl(tpl_name=tpl) def __get_recursively(self, search_obj: object, field: str, d_path: str = None) -> dict:",
"self.get_translate_of_word(word=v, position='right')}) return rows return value_path @staticmethod def __clean_format_tpl(data): \"\"\" Очистка щаполненного шаблона",
"пустых блоков\"\"\" def is_rows_null(section): \"\"\" тут проверяем, пустой блок или нет\"\"\" for item",
"'soc_static_field') for repl_key, repl_value in replacement_list.items(): format_tpl.set(repl_key, self.__get_value_of_the_path(self.translate_collection, repl_value)) final_format_tpl = self.__clean_format_tpl(format_tpl) return",
"= {**paths_to_fields, **results} if isinstance(search_obj, dict): for key, value in search_obj.items(): if field",
"in value: if not d_path: paths_to_fields.update({key: value}) if d_path: paths_to_fields.update({f'{d_path}.{key}': value}) elif isinstance(value,",
"None: return False return True from copy import deepcopy final_format_tpl = deepcopy(data) for",
"self.__get_recursively(value, field, new_d_path) paths_to_fields = {**paths_to_fields, **results} if isinstance(search_obj, dict): for key, value",
"list): if d_path: key = d_path + '.' + key results = self.__get_recursively(value,",
"if value_type == 'string': return str(value) if value_type == 'numder': return int(value) return",
"if \"soc_inc_rows>\" in value_path: \"\"\"Отрисовать список\"\"\" v = value_path.replace(\"soc_inc_rows>\", '') rows_data = get_value(_value_bank,",
"value in search_obj.items(): if field in value: if not d_path: paths_to_fields.update({key: value}) if",
"__sort_thive_list(thdict: dict): \"\"\" Сортируем словарь-список thive \"\"\" thsort = sorted(thdict, key=lambda x: thdict[x]['order'])",
"soc_inc>{что взять из инцидента} \"\"\" v = value_path.replace(\"soc_inc>\", '') data_value = get_value(_value_bank, v)",
"dict) and write['word'] == word: if position: # position может быть обязательным для",
"для респондера \"\"\" normalize_incident = copy.deepcopy(data) normalize_incident.update({\"customFields\": self.__sort_thive_list(normalize_incident['customFields'])}) return normalize_incident def __get_value_of_the_path(self, value_bank:",
"for item in section['blocks'][0]['rows']: if item['right'] is not None: return False return True",
"пустой блок или нет\"\"\" for item in section['blocks'][0]['rows']: if item['right'] is not None:",
"return word for write in translate_list: if isinstance(write, dict) and write['word'] == word:",
"f'templates/{tpl_name}.json') if not os.path.exists(tpl_path): logger.error(f'Error getting setting. Check your settings file in {tpl_path}')",
"thsort: v = get_value(thdict[key]) fdict.update({key: v}) return fdict def __normalize_thive_dict(self, data): \"\"\" Нормализуем",
"\"\"\" Сортируем словарь-список thive \"\"\" thsort = sorted(thdict, key=lambda x: thdict[x]['order']) def cast(value_type,",
"data_value if \"soc_static_field>\" in value_path: \"\"\" soc_static_field>{где}.{по какому word взять translate}\"\"\" v =",
"final_format_tpl def build(self, data: dict, tpl: dict) -> dict: if not data: logger.warning('No",
"return final_format_tpl def translate_other_items(self, data: dict): \"\"\" Перевод дополнительных полей \"\"\" if not",
"-> dict: \"\"\" Получаем список объектов, которые нужно заменить \"\"\" paths_to_fields = {}",
"key=lambda x: thdict[x]['order']) def cast(value_type, value): from datetime import datetime if not value:",
"# position может быть обязательным для сравнения if write['position'] == position: return write['translate']",
"in replacement_list.items(): format_tpl.set(repl_key, self.__get_value_of_the_path(format_data, repl_value)) replacement_list = self.__get_recursively(benedict(copy.deepcopy(tpl)), 'soc_static_field') for repl_key, repl_value in",
"value) fdict = {} for key in thsort: v = get_value(thdict[key]) fdict.update({key: v})",
"v = value_path.replace(\"soc_inc>\", '') data_value = get_value(_value_bank, v) return data_value if \"soc_static_field>\" in",
"нужно заменить \"\"\" paths_to_fields = {} if isinstance(search_obj, list): for i, value in",
"get_value(thdict[key]) fdict.update({key: v}) return fdict def __normalize_thive_dict(self, data): \"\"\" Нормализуем инцидент для респондера",
"in enumerate(search_obj): new_d_path = None if d_path: new_d_path = f'{d_path}[{i}]' results = self.__get_recursively(value,",
"может быть обязательным для сравнения if write['position'] == position: return write['translate'] else: return",
"if isinstance(search_obj, list): for i, value in enumerate(search_obj): new_d_path = None if d_path:",
"get_value(_value_bank, v) rows = [] for k, v in self.normal_thive_incident['customFields'].items(): rows.append({\"left\": self.get_translate_of_word(word=k, position='left'),",
"word взять translate}\"\"\" v = value_path.replace(\"soc_static_field>\", '') translate_path = v.split('.') if translate_path[0] ==",
"return self.get_translate_of_word(word=v) if \"soc_inc_rows>\" in value_path: \"\"\"Отрисовать список\"\"\" v = value_path.replace(\"soc_inc_rows>\", '') rows_data",
"+ key results = self.__get_recursively(value, field, key) paths_to_fields = {**paths_to_fields, **results} return paths_to_fields",
"взять из инцидента} \"\"\" v = value_path.replace(\"soc_inc>\", '') data_value = get_value(_value_bank, v) return",
"dict): \"\"\" Сортируем словарь-список thive \"\"\" thsort = sorted(thdict, key=lambda x: thdict[x]['order']) def",
"# self.translate_collection = benedict(translate_params) self.translate_collection = translate_params self.tpl_name = 'default' self.normal_thive_incident = {}",
"через точку \"\"\" _value_bank = copy.deepcopy(value_bank) def get_value(_data, _v): _data = _data.get(_v) return",
"benedict, value_path: str) -> object: \"\"\" Получение значения по пути через точку \"\"\"",
"полей \"\"\" if not data: return None translate_result = {} for k, v",
"replacement_list.items(): format_tpl.set(repl_key, self.__get_value_of_the_path(format_data, repl_value)) replacement_list = self.__get_recursively(benedict(copy.deepcopy(tpl)), 'soc_static_field') for repl_key, repl_value in replacement_list.items():",
"self.translate_collection = translate_params self.tpl_name = 'default' self.normal_thive_incident = {} @staticmethod def __load_tpl(tpl_name: str)",
"if \"soc_inc>\" in value_path: \"\"\" soc_inc>{что взять из инцидента} \"\"\" v = value_path.replace(\"soc_inc>\",",
"os.path.exists(tpl_path): logger.error(f'Error getting setting. Check your settings file in {tpl_path}') raise TemplateFileNotExist(f\"File {tpl_path}",
"d_path: paths_to_fields.update({key: value}) if d_path: paths_to_fields.update({f'{d_path}.{key}': value}) elif isinstance(value, dict): if d_path: key",
"replacement_list = self.__get_recursively(benedict(copy.deepcopy(tpl)), 'soc_static_field') for repl_key, repl_value in replacement_list.items(): format_tpl.set(repl_key, self.__get_value_of_the_path(self.translate_collection, repl_value)) final_format_tpl",
"Получаем список объектов, которые нужно заменить \"\"\" paths_to_fields = {} if isinstance(search_obj, list):",
"exist\") with open(tpl_path, encoding='utf-8') as f: tpl = json.load(f) return tpl def __get_tpl(self,",
"replacement_list.items(): format_tpl.set(repl_key, self.__get_value_of_the_path(self.translate_collection, repl_value)) final_format_tpl = self.__clean_format_tpl(format_tpl) return final_format_tpl def translate_other_items(self, data: dict):",
"__get_value_of_the_path(self, value_bank: benedict, value_path: str) -> object: \"\"\" Получение значения по пути через",
"if is_rows_null(i): final_format_tpl['categories'][0]['sections'].remove(i) return final_format_tpl def build(self, data: dict, tpl: dict) -> dict:",
"elif isinstance(value, dict): if d_path: key = d_path + '.' + key results",
"in thsort: v = get_value(thdict[key]) fdict.update({key: v}) return fdict def __normalize_thive_dict(self, data): \"\"\"",
"self.get_translate_of_word(word=k, position='left'), \"right\": self.get_translate_of_word(word=v, position='right')}) return rows return value_path @staticmethod def __clean_format_tpl(data): \"\"\"",
"= logging.getLogger('responder_commons') class Builder: def __init__(self, translate_params): # self.translate_collection = benedict(translate_params) self.translate_collection =",
"value_type == 'string': return str(value) if value_type == 'numder': return int(value) return value",
"точку \"\"\" _value_bank = copy.deepcopy(value_bank) def get_value(_data, _v): _data = _data.get(_v) return _data",
"__init__(self, translate_params): # self.translate_collection = benedict(translate_params) self.translate_collection = translate_params self.tpl_name = 'default' self.normal_thive_incident",
"по пути через точку \"\"\" _value_bank = copy.deepcopy(value_bank) def get_value(_data, _v): _data =",
"str) -> dict: tpl_path = os.path.join(os.getcwd(), f'templates/{tpl_name}.json') if not os.path.exists(tpl_path): logger.error(f'Error getting setting.",
"dict): v.pop('order') for value_type, value in v.items(): return cast(value_type, value) fdict = {}",
"= d_path + '.' + key results = self.__get_recursively(value, field, key) paths_to_fields =",
"return normalize_incident def __get_value_of_the_path(self, value_bank: benedict, value_path: str) -> object: \"\"\" Получение значения",
"Если не найдено перевода - оставляем как есть @staticmethod def __sort_thive_list(thdict: dict): \"\"\"",
"перевода - оставляем как есть @staticmethod def __sort_thive_list(thdict: dict): \"\"\" Сортируем словарь-список thive",
"def __load_tpl(tpl_name: str) -> dict: tpl_path = os.path.join(os.getcwd(), f'templates/{tpl_name}.json') if not os.path.exists(tpl_path): logger.error(f'Error",
"Нормализуем инцидент для респондера \"\"\" normalize_incident = copy.deepcopy(data) normalize_incident.update({\"customFields\": self.__sort_thive_list(normalize_incident['customFields'])}) return normalize_incident def",
"import deepcopy final_format_tpl = deepcopy(data) for i in data['categories'][0]['sections']: if is_rows_null(i): final_format_tpl['categories'][0]['sections'].remove(i) return",
"json import copy from benedict import benedict from responder_commons.exc import TemplateFileNotExist logger =",
"return cast(value_type, value) fdict = {} for key in thsort: v = get_value(thdict[key])",
"None) -> dict: \"\"\" Получаем список объектов, которые нужно заменить \"\"\" paths_to_fields =",
"1: return self.get_translate_of_word(word=v) if \"soc_inc_rows>\" in value_path: \"\"\"Отрисовать список\"\"\" v = value_path.replace(\"soc_inc_rows>\", '')",
"return False return True from copy import deepcopy final_format_tpl = deepcopy(data) for i",
"self.__load_tpl(\"default\") logger.debug(f'Будет использован шаблон {tpl}') return self.__load_tpl(tpl_name=tpl) def __get_recursively(self, search_obj: object, field: str,",
"for value_type, value in v.items(): return cast(value_type, value) fdict = {} for key",
"str(value) if value_type == 'numder': return int(value) return value def get_value(v: dict): v.pop('order')",
"repl_value in replacement_list.items(): format_tpl.set(repl_key, self.__get_value_of_the_path(self.translate_collection, repl_value)) final_format_tpl = self.__clean_format_tpl(format_tpl) return final_format_tpl def translate_other_items(self,",
"open(tpl_path, encoding='utf-8') as f: tpl = json.load(f) return tpl def __get_tpl(self, tpl: str",
"value_path.replace(\"soc_inc>\", '') data_value = get_value(_value_bank, v) return data_value if \"soc_static_field>\" in value_path: \"\"\"",
"\"\"\" paths_to_fields = {} if isinstance(search_obj, list): for i, value in enumerate(search_obj): new_d_path",
"data') return {} self.normal_thive_incident = self.__normalize_thive_dict(data) format_data = benedict(self.normal_thive_incident) format_tpl = benedict(copy.deepcopy(tpl)) replacement_list",
"in search_obj.items(): if field in value: if not d_path: paths_to_fields.update({key: value}) if d_path:",
"if d_path: new_d_path = f'{d_path}[{i}]' results = self.__get_recursively(value, field, new_d_path) paths_to_fields = {**paths_to_fields,",
"__clean_format_tpl(data): \"\"\" Очистка щаполненного шаблона от пустых блоков\"\"\" def is_rows_null(section): \"\"\" тут проверяем,",
"your settings file in {tpl_path}') raise TemplateFileNotExist(f\"File {tpl_path} doesn't exist\") with open(tpl_path, encoding='utf-8')",
"datetime import datetime if not value: return None if value_type == 'date': return",
"translate_params): # self.translate_collection = benedict(translate_params) self.translate_collection = translate_params self.tpl_name = 'default' self.normal_thive_incident =",
"translate_list = self.translate_collection if not word: return word for write in translate_list: if",
"results = self.__get_recursively(value, field, key) paths_to_fields = {**paths_to_fields, **results} return paths_to_fields def get_translate_of_word(self,",
"thsort = sorted(thdict, key=lambda x: thdict[x]['order']) def cast(value_type, value): from datetime import datetime",
"str = None) -> dict: if not tpl: logger.debug('Имя шаблона не задано, будет",
"paths_to_fields = {**paths_to_fields, **results} return paths_to_fields def get_translate_of_word(self, word: str = None, position:",
"write in translate_list: if isinstance(write, dict) and write['word'] == word: if position: #",
"return datetime.fromtimestamp(value / 1e3).isoformat() if value_type == 'string': return str(value) if value_type ==",
"position: str = None): translate_list = self.translate_collection if not word: return word for",
"str) and write in self.translate_collection: return self.translate_collection[word] return word # Если не найдено",
"for k, v in self.normal_thive_incident['customFields'].items(): rows.append({\"left\": self.get_translate_of_word(word=k, position='left'), \"right\": self.get_translate_of_word(word=v, position='right')}) return rows",
"\"\"\" soc_inc>{что взять из инцидента} \"\"\" v = value_path.replace(\"soc_inc>\", '') data_value = get_value(_value_bank,",
"not os.path.exists(tpl_path): logger.error(f'Error getting setting. Check your settings file in {tpl_path}') raise TemplateFileNotExist(f\"File",
"объектов, которые нужно заменить \"\"\" paths_to_fields = {} if isinstance(search_obj, list): for i,",
"in data['categories'][0]['sections']: if is_rows_null(i): final_format_tpl['categories'][0]['sections'].remove(i) return final_format_tpl def build(self, data: dict, tpl: dict)",
"if isinstance(write, dict) and write['word'] == word: if position: # position может быть",
"tpl: dict) -> dict: if not data: logger.warning('No data') return {} self.normal_thive_incident =",
"= copy.deepcopy(value_bank) def get_value(_data, _v): _data = _data.get(_v) return _data if \"soc_inc>\" in",
"= get_value(thdict[key]) fdict.update({key: v}) return fdict def __normalize_thive_dict(self, data): \"\"\" Нормализуем инцидент для",
"search_obj: object, field: str, d_path: str = None) -> dict: \"\"\" Получаем список",
"-> dict: if not data: logger.warning('No data') return {} self.normal_thive_incident = self.__normalize_thive_dict(data) format_data",
"Перевод дополнительных полей \"\"\" if not data: return None translate_result = {} for",
"self.__normalize_thive_dict(data) format_data = benedict(self.normal_thive_incident) format_tpl = benedict(copy.deepcopy(tpl)) replacement_list = self.__get_recursively(benedict(copy.deepcopy(tpl)), 'soc_inc') for repl_key,",
"logger.error(f'Error getting setting. Check your settings file in {tpl_path}') raise TemplateFileNotExist(f\"File {tpl_path} doesn't",
"object, field: str, d_path: str = None) -> dict: \"\"\" Получаем список объектов,",
"format_data = benedict(self.normal_thive_incident) format_tpl = benedict(copy.deepcopy(tpl)) replacement_list = self.__get_recursively(benedict(copy.deepcopy(tpl)), 'soc_inc') for repl_key, repl_value",
"get_value(v: dict): v.pop('order') for value_type, value in v.items(): return cast(value_type, value) fdict =",
"normalize_incident = copy.deepcopy(data) normalize_incident.update({\"customFields\": self.__sort_thive_list(normalize_incident['customFields'])}) return normalize_incident def __get_value_of_the_path(self, value_bank: benedict, value_path: str)",
"= {} @staticmethod def __load_tpl(tpl_name: str) -> dict: tpl_path = os.path.join(os.getcwd(), f'templates/{tpl_name}.json') if",
"format_tpl.set(repl_key, self.__get_value_of_the_path(self.translate_collection, repl_value)) final_format_tpl = self.__clean_format_tpl(format_tpl) return final_format_tpl def translate_other_items(self, data: dict): \"\"\"",
"value: return None if value_type == 'date': return datetime.fromtimestamp(value / 1e3).isoformat() if value_type",
"if not data: logger.warning('No data') return {} self.normal_thive_incident = self.__normalize_thive_dict(data) format_data = benedict(self.normal_thive_incident)",
"= os.path.join(os.getcwd(), f'templates/{tpl_name}.json') if not os.path.exists(tpl_path): logger.error(f'Error getting setting. Check your settings file",
"None): translate_list = self.translate_collection if not word: return word for write in translate_list:",
"Сортируем словарь-список thive \"\"\" thsort = sorted(thdict, key=lambda x: thdict[x]['order']) def cast(value_type, value):",
"copy import deepcopy final_format_tpl = deepcopy(data) for i in data['categories'][0]['sections']: if is_rows_null(i): final_format_tpl['categories'][0]['sections'].remove(i)",
"isinstance(search_obj, list): for i, value in enumerate(search_obj): new_d_path = None if d_path: new_d_path",
"value_bank: benedict, value_path: str) -> object: \"\"\" Получение значения по пути через точку",
"data): \"\"\" Нормализуем инцидент для респондера \"\"\" normalize_incident = copy.deepcopy(data) normalize_incident.update({\"customFields\": self.__sort_thive_list(normalize_incident['customFields'])}) return",
"if not tpl: logger.debug('Имя шаблона не задано, будет использован default') return self.__load_tpl(\"default\") logger.debug(f'Будет",
"dict: tpl_path = os.path.join(os.getcwd(), f'templates/{tpl_name}.json') if not os.path.exists(tpl_path): logger.error(f'Error getting setting. Check your",
"= benedict(translate_params) self.translate_collection = translate_params self.tpl_name = 'default' self.normal_thive_incident = {} @staticmethod def",
"paths_to_fields = {**paths_to_fields, **results} if isinstance(search_obj, dict): for key, value in search_obj.items(): if",
"normalize_incident def __get_value_of_the_path(self, value_bank: benedict, value_path: str) -> object: \"\"\" Получение значения по",
"= self.__normalize_thive_dict(data) format_data = benedict(self.normal_thive_incident) format_tpl = benedict(copy.deepcopy(tpl)) replacement_list = self.__get_recursively(benedict(copy.deepcopy(tpl)), 'soc_inc') for",
"= self.__get_recursively(value, field, new_d_path) paths_to_fields = {**paths_to_fields, **results} if isinstance(search_obj, dict): for key,",
"json.load(f) return tpl def __get_tpl(self, tpl: str = None) -> dict: if not",
"if item['right'] is not None: return False return True from copy import deepcopy",
"self.get_translate_of_word(word=v) if \"soc_inc_rows>\" in value_path: \"\"\"Отрисовать список\"\"\" v = value_path.replace(\"soc_inc_rows>\", '') rows_data =",
"os import logging import json import copy from benedict import benedict from responder_commons.exc",
"блоков\"\"\" def is_rows_null(section): \"\"\" тут проверяем, пустой блок или нет\"\"\" for item in",
"repl_value)) final_format_tpl = self.__clean_format_tpl(format_tpl) return final_format_tpl def translate_other_items(self, data: dict): \"\"\" Перевод дополнительных",
"'soc_inc') for repl_key, repl_value in replacement_list.items(): format_tpl.set(repl_key, self.__get_value_of_the_path(format_data, repl_value)) replacement_list = self.__get_recursively(benedict(copy.deepcopy(tpl)), 'soc_static_field')",
"for repl_key, repl_value in replacement_list.items(): format_tpl.set(repl_key, self.__get_value_of_the_path(format_data, repl_value)) replacement_list = self.__get_recursively(benedict(copy.deepcopy(tpl)), 'soc_static_field') for",
"tpl: str = None) -> dict: if not tpl: logger.debug('Имя шаблона не задано,",
"copy.deepcopy(value_bank) def get_value(_data, _v): _data = _data.get(_v) return _data if \"soc_inc>\" in value_path:",
"список\"\"\" v = value_path.replace(\"soc_inc_rows>\", '') rows_data = get_value(_value_bank, v) rows = [] for",
"for key in thsort: v = get_value(thdict[key]) fdict.update({key: v}) return fdict def __normalize_thive_dict(self,",
"str = None) -> dict: \"\"\" Получаем список объектов, которые нужно заменить \"\"\"",
"\"soc_inc>\" in value_path: \"\"\" soc_inc>{что взять из инцидента} \"\"\" v = value_path.replace(\"soc_inc>\", '')",
"'default' self.normal_thive_incident = {} @staticmethod def __load_tpl(tpl_name: str) -> dict: tpl_path = os.path.join(os.getcwd(),",
"использован default') return self.__load_tpl(\"default\") logger.debug(f'Будет использован шаблон {tpl}') return self.__load_tpl(tpl_name=tpl) def __get_recursively(self, search_obj:",
"/ 1e3).isoformat() if value_type == 'string': return str(value) if value_type == 'numder': return",
"self.__clean_format_tpl(format_tpl) return final_format_tpl def translate_other_items(self, data: dict): \"\"\" Перевод дополнительных полей \"\"\" if",
"from responder_commons.exc import TemplateFileNotExist logger = logging.getLogger('responder_commons') class Builder: def __init__(self, translate_params): #",
"import datetime if not value: return None if value_type == 'date': return datetime.fromtimestamp(value"
] |
[
"import bot if __name__ == '__main__': zonbot = bot.Bot('!', pm_help = True) zonbot.run(zonbot.token)"
] |
[
"= { 'type': 'intention', 'function': eq2, } yaml_dict['constraints'] = constraints # agents agents",
"as f: yaml.dump(scenarios, f) print(f'Simulation scenario file saved: {yaml_file}') if __name__ == '__main__':",
"}) exported_file = args.file.split('/')[-1] + '-scenario.yaml' yaml_file = os.path.join('./yaml-files', exported_file) with open(yaml_file, 'w')",
"for agent_id in agent_ids] yaml_dict['agents'] = agents # export to yaml exported_file =",
"yaml_dict = { 'name': args.name, 'objective': 'min', } # domains domains = {}",
"1, }] scenarios = {'events': events} for i, cmd in enumerate(lines_4_config['commands'].split(' ')): cmd,",
"'agent': f'a{agent}' } }) events.append({ 'id': 'w', 'delay': 1, }) exported_file = args.file.split('/')[-1]",
"f'{c} * var{y}^2 + {b} * var{y} * var{x} + {a} * var{x}^2'",
"{a} * var{x}^2' return c1, c2 def main(args): lines_4_config = {} with open(args.file,",
"* var{y}^2' c2 = f'{c} * var{y}^2 + {b} * var{y} * var{x}",
"var{x}^2 + {b} * var{x} * var{y} + {c} * var{y}^2' c2 =",
"# domains domains = {} domain_info = lines_4_config['domains'].split(' ') agent_ids = [] for",
"+ {a} * var{x}^2' return c1, c2 def main(args): lines_4_config = {} with",
"domain_info: agent_id, dvals = domain_str.split(':') domains[f'd{agent_id}'] = { 'values': [int(v) for v in",
"{ 'type': cmd, 'agent': f'a{agent}' } }) events.append({ 'id': 'w', 'delay': 1, })",
"agent_ids.append(agent_id) yaml_dict['domains'] = domains # variables variables = {} for agent in agent_ids:",
"events = [{ 'id': 'w', 'delay': 1, }] scenarios = {'events': events} for",
"* var{y}^2 + {b} * var{y} * var{x} + {a} * var{x}^2' return",
"'').split(',') c1 = f'{a} * var{x}^2 + {b} * var{x} * var{y} +",
"coefficients_str.replace('(', '').replace(')', '').split(',') c1 = f'{a} * var{x}^2 + {b} * var{x} *",
"yaml exported_file = args.file.split('/')[-1] + '.yaml' yaml_file = os.path.join('./yaml-files', exported_file) with open(yaml_file, 'w')",
"* var{y} * var{x} + {a} * var{x}^2' return c1, c2 def main(args):",
"'delay': 1, }] scenarios = {'events': events} for i, cmd in enumerate(lines_4_config['commands'].split(' ')):",
"= os.path.join('./yaml-files', exported_file) with open(yaml_file, 'w') as f: yaml.dump(yaml_dict, f) print(f'Simulation config file",
"}) events.append({ 'id': 'w', 'delay': 1, }) exported_file = args.file.split('/')[-1] + '-scenario.yaml' yaml_file",
"os.path import oyaml as yaml def parse_constraint(con_str): # sample: (0,1):(1,1,1) agents_str, coefficients_str =",
"f: yaml.dump(scenarios, f) print(f'Simulation scenario file saved: {yaml_file}') if __name__ == '__main__': parser",
"import argparse import os.path import oyaml as yaml def parse_constraint(con_str): # sample: (0,1):(1,1,1)",
"= {} for con in lines_4_config['cons'].split('>'): eq1, eq2 = parse_constraint(con) constraints[f'c{len(constraints)}'] = {",
"= agents_str.replace('(', '').replace(')', '').split(',') a, b, c = coefficients_str.replace('(', '').replace(')', '').split(',') c1 =",
"variables variables = {} for agent in agent_ids: variables[f'var{agent}'] = { 'domain': f'd{agent}',",
"var{x} * var{y} + {c} * var{y}^2' c2 = f'{c} * var{y}^2 +",
"if cmd == 'remove_agent': # only agent removal is supported by pydcop events.append({",
"yaml_dict['variables'] = variables # constraints constraints = {} for con in lines_4_config['cons'].split('>'): eq1,",
"= { 'domain': f'd{agent}', } yaml_dict['variables'] = variables # constraints constraints = {}",
"f: line = f.readline() while line: kv = line.split('=') lines_4_config[kv[0]] = kv[1].strip() line",
"var{y} * var{x} + {a} * var{x}^2' return c1, c2 def main(args): lines_4_config",
"in agent_ids: variables[f'var{agent}'] = { 'domain': f'd{agent}', } yaml_dict['variables'] = variables # constraints",
"'r') as f: line = f.readline() while line: kv = line.split('=') lines_4_config[kv[0]] =",
"var{y}^2 + {b} * var{y} * var{x} + {a} * var{x}^2' return c1,",
"variables[f'var{agent}'] = { 'domain': f'd{agent}', } yaml_dict['variables'] = variables # constraints constraints =",
"{ 'domain': f'd{agent}', } yaml_dict['variables'] = variables # constraints constraints = {} for",
"'.yaml' yaml_file = os.path.join('./yaml-files', exported_file) with open(yaml_file, 'w') as f: yaml.dump(yaml_dict, f) print(f'Simulation",
"lines_4_config['domains'].split(' ') agent_ids = [] for domain_str in domain_info: agent_id, dvals = domain_str.split(':')",
"} }) events.append({ 'id': 'w', 'delay': 1, }) exported_file = args.file.split('/')[-1] + '-scenario.yaml'",
"import oyaml as yaml def parse_constraint(con_str): # sample: (0,1):(1,1,1) agents_str, coefficients_str = con_str.split(':')",
"saved: {yaml_file}') # create scenario file events = [{ 'id': 'w', 'delay': 1,",
"line: kv = line.split('=') lines_4_config[kv[0]] = kv[1].strip() line = f.readline() yaml_dict = {",
"with open(args.file, 'r') as f: line = f.readline() while line: kv = line.split('=')",
"= f'{c} * var{y}^2 + {b} * var{y} * var{x} + {a} *",
"exported_file) with open(yaml_file, 'w') as f: yaml.dump(yaml_dict, f) print(f'Simulation config file saved: {yaml_file}')",
"= [{ 'id': 'w', 'delay': 1, }] scenarios = {'events': events} for i,",
"eq1, eq2 = parse_constraint(con) constraints[f'c{len(constraints)}'] = { 'type': 'intention', 'function': eq1, } constraints[f'c{len(constraints)}']",
"}] scenarios = {'events': events} for i, cmd in enumerate(lines_4_config['commands'].split(' ')): cmd, agent",
"+ {b} * var{x} * var{y} + {c} * var{y}^2' c2 = f'{c}",
"file saved: {yaml_file}') # create scenario file events = [{ 'id': 'w', 'delay':",
"+ {c} * var{y}^2' c2 = f'{c} * var{y}^2 + {b} * var{y}",
"for domain_str in domain_info: agent_id, dvals = domain_str.split(':') domains[f'd{agent_id}'] = { 'values': [int(v)",
"def main(args): lines_4_config = {} with open(args.file, 'r') as f: line = f.readline()",
"f'a{agent}' } }) events.append({ 'id': 'w', 'delay': 1, }) exported_file = args.file.split('/')[-1] +",
"{b} * var{y} * var{x} + {a} * var{x}^2' return c1, c2 def",
"* var{y} + {c} * var{y}^2' c2 = f'{c} * var{y}^2 + {b}",
"'min', } # domains domains = {} domain_info = lines_4_config['domains'].split(' ') agent_ids =",
"+ '.yaml' yaml_file = os.path.join('./yaml-files', exported_file) with open(yaml_file, 'w') as f: yaml.dump(yaml_dict, f)",
"f.readline() yaml_dict = { 'name': args.name, 'objective': 'min', } # domains domains =",
"in agent_ids] yaml_dict['agents'] = agents # export to yaml exported_file = args.file.split('/')[-1] +",
"args.file.split('/')[-1] + '.yaml' yaml_file = os.path.join('./yaml-files', exported_file) with open(yaml_file, 'w') as f: yaml.dump(yaml_dict,",
"if __name__ == '__main__': parser = argparse.ArgumentParser(description='Convert DynaGraph sim file to pyDCOP compatible",
"'w', 'delay': 1, }) exported_file = args.file.split('/')[-1] + '-scenario.yaml' yaml_file = os.path.join('./yaml-files', exported_file)",
"lines_4_config = {} with open(args.file, 'r') as f: line = f.readline() while line:",
"= { 'values': [int(v) for v in dvals.split(',')], } agent_ids.append(agent_id) yaml_dict['domains'] = domains",
"f'{a} * var{x}^2 + {b} * var{x} * var{y} + {c} * var{y}^2'",
"parse_constraint(con_str): # sample: (0,1):(1,1,1) agents_str, coefficients_str = con_str.split(':') x, y = agents_str.replace('(', '').replace(')',",
"in dvals.split(',')], } agent_ids.append(agent_id) yaml_dict['domains'] = domains # variables variables = {} for",
"= {} domain_info = lines_4_config['domains'].split(' ') agent_ids = [] for domain_str in domain_info:",
"* var{x} * var{y} + {c} * var{y}^2' c2 = f'{c} * var{y}^2",
"__name__ == '__main__': parser = argparse.ArgumentParser(description='Convert DynaGraph sim file to pyDCOP compatible yaml",
"scenarios = {'events': events} for i, cmd in enumerate(lines_4_config['commands'].split(' ')): cmd, agent =",
"cmd in enumerate(lines_4_config['commands'].split(' ')): cmd, agent = cmd.split(':') if cmd == 'remove_agent': #",
"* var{x} + {a} * var{x}^2' return c1, c2 def main(args): lines_4_config =",
"# agents agents = [f'a{agent_id}' for agent_id in agent_ids] yaml_dict['agents'] = agents #",
"argparse import os.path import oyaml as yaml def parse_constraint(con_str): # sample: (0,1):(1,1,1) agents_str,",
"create scenario file events = [{ 'id': 'w', 'delay': 1, }] scenarios =",
"+ '-scenario.yaml' yaml_file = os.path.join('./yaml-files', exported_file) with open(yaml_file, 'w') as f: yaml.dump(scenarios, f)",
"a, b, c = coefficients_str.replace('(', '').replace(')', '').split(',') c1 = f'{a} * var{x}^2 +",
"= line.split('=') lines_4_config[kv[0]] = kv[1].strip() line = f.readline() yaml_dict = { 'name': args.name,",
"= f'{a} * var{x}^2 + {b} * var{x} * var{y} + {c} *",
"saved: {yaml_file}') if __name__ == '__main__': parser = argparse.ArgumentParser(description='Convert DynaGraph sim file to",
"parser = argparse.ArgumentParser(description='Convert DynaGraph sim file to pyDCOP compatible yaml config') parser.add_argument('-f', '--file',",
"= domain_str.split(':') domains[f'd{agent_id}'] = { 'values': [int(v) for v in dvals.split(',')], } agent_ids.append(agent_id)",
"scenario file saved: {yaml_file}') if __name__ == '__main__': parser = argparse.ArgumentParser(description='Convert DynaGraph sim",
"required=True, help='sim file path') parser.add_argument('-n', '--name', type=str, required=True, help='DCOP name') args = parser.parse_args()",
"for i, cmd in enumerate(lines_4_config['commands'].split(' ')): cmd, agent = cmd.split(':') if cmd ==",
"c1, c2 def main(args): lines_4_config = {} with open(args.file, 'r') as f: line",
"'').replace(')', '').split(',') c1 = f'{a} * var{x}^2 + {b} * var{x} * var{y}",
"args.name, 'objective': 'min', } # domains domains = {} domain_info = lines_4_config['domains'].split(' ')",
"constraints[f'c{len(constraints)}'] = { 'type': 'intention', 'function': eq2, } yaml_dict['constraints'] = constraints # agents",
"args.file.split('/')[-1] + '-scenario.yaml' yaml_file = os.path.join('./yaml-files', exported_file) with open(yaml_file, 'w') as f: yaml.dump(scenarios,",
"c2 def main(args): lines_4_config = {} with open(args.file, 'r') as f: line =",
"= { 'type': 'intention', 'function': eq1, } constraints[f'c{len(constraints)}'] = { 'type': 'intention', 'function':",
"f.readline() while line: kv = line.split('=') lines_4_config[kv[0]] = kv[1].strip() line = f.readline() yaml_dict",
"for con in lines_4_config['cons'].split('>'): eq1, eq2 = parse_constraint(con) constraints[f'c{len(constraints)}'] = { 'type': 'intention',",
"{ 'type': 'intention', 'function': eq2, } yaml_dict['constraints'] = constraints # agents agents =",
"def parse_constraint(con_str): # sample: (0,1):(1,1,1) agents_str, coefficients_str = con_str.split(':') x, y = agents_str.replace('(',",
"line.split('=') lines_4_config[kv[0]] = kv[1].strip() line = f.readline() yaml_dict = { 'name': args.name, 'objective':",
"events.append({ 'id': 'w', 'delay': 1, }) exported_file = args.file.split('/')[-1] + '-scenario.yaml' yaml_file =",
"'id': 'w', 'delay': 1, }] scenarios = {'events': events} for i, cmd in",
"con_str.split(':') x, y = agents_str.replace('(', '').replace(')', '').split(',') a, b, c = coefficients_str.replace('(', '').replace(')',",
"help='sim file path') parser.add_argument('-n', '--name', type=str, required=True, help='DCOP name') args = parser.parse_args() main(args)",
"= variables # constraints constraints = {} for con in lines_4_config['cons'].split('>'): eq1, eq2",
"agent_ids = [] for domain_str in domain_info: agent_id, dvals = domain_str.split(':') domains[f'd{agent_id}'] =",
"= {} for agent in agent_ids: variables[f'var{agent}'] = { 'domain': f'd{agent}', } yaml_dict['variables']",
"exported_file) with open(yaml_file, 'w') as f: yaml.dump(scenarios, f) print(f'Simulation scenario file saved: {yaml_file}')",
"open(yaml_file, 'w') as f: yaml.dump(scenarios, f) print(f'Simulation scenario file saved: {yaml_file}') if __name__",
"} constraints[f'c{len(constraints)}'] = { 'type': 'intention', 'function': eq2, } yaml_dict['constraints'] = constraints #",
"in enumerate(lines_4_config['commands'].split(' ')): cmd, agent = cmd.split(':') if cmd == 'remove_agent': # only",
"'function': eq1, } constraints[f'c{len(constraints)}'] = { 'type': 'intention', 'function': eq2, } yaml_dict['constraints'] =",
"') agent_ids = [] for domain_str in domain_info: agent_id, dvals = domain_str.split(':') domains[f'd{agent_id}']",
"f) print(f'Simulation scenario file saved: {yaml_file}') if __name__ == '__main__': parser = argparse.ArgumentParser(description='Convert",
"removal is supported by pydcop events.append({ 'id': f'e{i}', 'actions': { 'type': cmd, 'agent':",
"v in dvals.split(',')], } agent_ids.append(agent_id) yaml_dict['domains'] = domains # variables variables = {}",
"'function': eq2, } yaml_dict['constraints'] = constraints # agents agents = [f'a{agent_id}' for agent_id",
"config') parser.add_argument('-f', '--file', type=str, required=True, help='sim file path') parser.add_argument('-n', '--name', type=str, required=True, help='DCOP",
"'type': 'intention', 'function': eq1, } constraints[f'c{len(constraints)}'] = { 'type': 'intention', 'function': eq2, }",
"variables # constraints constraints = {} for con in lines_4_config['cons'].split('>'): eq1, eq2 =",
"= parse_constraint(con) constraints[f'c{len(constraints)}'] = { 'type': 'intention', 'function': eq1, } constraints[f'c{len(constraints)}'] = {",
"yaml config') parser.add_argument('-f', '--file', type=str, required=True, help='sim file path') parser.add_argument('-n', '--name', type=str, required=True,",
"yaml_file = os.path.join('./yaml-files', exported_file) with open(yaml_file, 'w') as f: yaml.dump(yaml_dict, f) print(f'Simulation config",
"scenario file events = [{ 'id': 'w', 'delay': 1, }] scenarios = {'events':",
"sample: (0,1):(1,1,1) agents_str, coefficients_str = con_str.split(':') x, y = agents_str.replace('(', '').replace(')', '').split(',') a,",
"# constraints constraints = {} for con in lines_4_config['cons'].split('>'): eq1, eq2 = parse_constraint(con)",
"as f: line = f.readline() while line: kv = line.split('=') lines_4_config[kv[0]] = kv[1].strip()",
"# only agent removal is supported by pydcop events.append({ 'id': f'e{i}', 'actions': {",
"= coefficients_str.replace('(', '').replace(')', '').split(',') c1 = f'{a} * var{x}^2 + {b} * var{x}",
"eq2, } yaml_dict['constraints'] = constraints # agents agents = [f'a{agent_id}' for agent_id in",
"eq2 = parse_constraint(con) constraints[f'c{len(constraints)}'] = { 'type': 'intention', 'function': eq1, } constraints[f'c{len(constraints)}'] =",
"{} domain_info = lines_4_config['domains'].split(' ') agent_ids = [] for domain_str in domain_info: agent_id,",
"to pyDCOP compatible yaml config') parser.add_argument('-f', '--file', type=str, required=True, help='sim file path') parser.add_argument('-n',",
"parse_constraint(con) constraints[f'c{len(constraints)}'] = { 'type': 'intention', 'function': eq1, } constraints[f'c{len(constraints)}'] = { 'type':",
"'intention', 'function': eq1, } constraints[f'c{len(constraints)}'] = { 'type': 'intention', 'function': eq2, } yaml_dict['constraints']",
"by pydcop events.append({ 'id': f'e{i}', 'actions': { 'type': cmd, 'agent': f'a{agent}' } })",
"'actions': { 'type': cmd, 'agent': f'a{agent}' } }) events.append({ 'id': 'w', 'delay': 1,",
"= {} with open(args.file, 'r') as f: line = f.readline() while line: kv",
"'delay': 1, }) exported_file = args.file.split('/')[-1] + '-scenario.yaml' yaml_file = os.path.join('./yaml-files', exported_file) with",
"'type': 'intention', 'function': eq2, } yaml_dict['constraints'] = constraints # agents agents = [f'a{agent_id}'",
"'name': args.name, 'objective': 'min', } # domains domains = {} domain_info = lines_4_config['domains'].split('",
"events} for i, cmd in enumerate(lines_4_config['commands'].split(' ')): cmd, agent = cmd.split(':') if cmd",
"x, y = agents_str.replace('(', '').replace(')', '').split(',') a, b, c = coefficients_str.replace('(', '').replace(')', '').split(',')",
"domains # variables variables = {} for agent in agent_ids: variables[f'var{agent}'] = {",
"= lines_4_config['domains'].split(' ') agent_ids = [] for domain_str in domain_info: agent_id, dvals =",
"# variables variables = {} for agent in agent_ids: variables[f'var{agent}'] = { 'domain':",
"'id': f'e{i}', 'actions': { 'type': cmd, 'agent': f'a{agent}' } }) events.append({ 'id': 'w',",
"print(f'Simulation config file saved: {yaml_file}') # create scenario file events = [{ 'id':",
"cmd == 'remove_agent': # only agent removal is supported by pydcop events.append({ 'id':",
"'id': 'w', 'delay': 1, }) exported_file = args.file.split('/')[-1] + '-scenario.yaml' yaml_file = os.path.join('./yaml-files',",
"print(f'Simulation scenario file saved: {yaml_file}') if __name__ == '__main__': parser = argparse.ArgumentParser(description='Convert DynaGraph",
"agent_id, dvals = domain_str.split(':') domains[f'd{agent_id}'] = { 'values': [int(v) for v in dvals.split(',')],",
"type=str, required=True, help='sim file path') parser.add_argument('-n', '--name', type=str, required=True, help='DCOP name') args =",
"lines_4_config[kv[0]] = kv[1].strip() line = f.readline() yaml_dict = { 'name': args.name, 'objective': 'min',",
"'objective': 'min', } # domains domains = {} domain_info = lines_4_config['domains'].split(' ') agent_ids",
"'').split(',') a, b, c = coefficients_str.replace('(', '').replace(')', '').split(',') c1 = f'{a} * var{x}^2",
"exported_file = args.file.split('/')[-1] + '-scenario.yaml' yaml_file = os.path.join('./yaml-files', exported_file) with open(yaml_file, 'w') as",
"= [f'a{agent_id}' for agent_id in agent_ids] yaml_dict['agents'] = agents # export to yaml",
"with open(yaml_file, 'w') as f: yaml.dump(scenarios, f) print(f'Simulation scenario file saved: {yaml_file}') if",
"{b} * var{x} * var{y} + {c} * var{y}^2' c2 = f'{c} *",
"var{y} + {c} * var{y}^2' c2 = f'{c} * var{y}^2 + {b} *",
"'values': [int(v) for v in dvals.split(',')], } agent_ids.append(agent_id) yaml_dict['domains'] = domains # variables",
"agents # export to yaml exported_file = args.file.split('/')[-1] + '.yaml' yaml_file = os.path.join('./yaml-files',",
"{ 'type': 'intention', 'function': eq1, } constraints[f'c{len(constraints)}'] = { 'type': 'intention', 'function': eq2,",
"to yaml exported_file = args.file.split('/')[-1] + '.yaml' yaml_file = os.path.join('./yaml-files', exported_file) with open(yaml_file,",
"agent removal is supported by pydcop events.append({ 'id': f'e{i}', 'actions': { 'type': cmd,",
"agents agents = [f'a{agent_id}' for agent_id in agent_ids] yaml_dict['agents'] = agents # export",
"} yaml_dict['variables'] = variables # constraints constraints = {} for con in lines_4_config['cons'].split('>'):",
"} yaml_dict['constraints'] = constraints # agents agents = [f'a{agent_id}' for agent_id in agent_ids]",
"agents = [f'a{agent_id}' for agent_id in agent_ids] yaml_dict['agents'] = agents # export to",
"constraints[f'c{len(constraints)}'] = { 'type': 'intention', 'function': eq1, } constraints[f'c{len(constraints)}'] = { 'type': 'intention',",
"'-scenario.yaml' yaml_file = os.path.join('./yaml-files', exported_file) with open(yaml_file, 'w') as f: yaml.dump(scenarios, f) print(f'Simulation",
"main(args): lines_4_config = {} with open(args.file, 'r') as f: line = f.readline() while",
"var{x}^2' return c1, c2 def main(args): lines_4_config = {} with open(args.file, 'r') as",
"cmd, 'agent': f'a{agent}' } }) events.append({ 'id': 'w', 'delay': 1, }) exported_file =",
"oyaml as yaml def parse_constraint(con_str): # sample: (0,1):(1,1,1) agents_str, coefficients_str = con_str.split(':') x,",
"= argparse.ArgumentParser(description='Convert DynaGraph sim file to pyDCOP compatible yaml config') parser.add_argument('-f', '--file', type=str,",
"sim file to pyDCOP compatible yaml config') parser.add_argument('-f', '--file', type=str, required=True, help='sim file",
"'__main__': parser = argparse.ArgumentParser(description='Convert DynaGraph sim file to pyDCOP compatible yaml config') parser.add_argument('-f',",
"f) print(f'Simulation config file saved: {yaml_file}') # create scenario file events = [{",
"dvals = domain_str.split(':') domains[f'd{agent_id}'] = { 'values': [int(v) for v in dvals.split(',')], }",
"c2 = f'{c} * var{y}^2 + {b} * var{y} * var{x} + {a}",
"'--file', type=str, required=True, help='sim file path') parser.add_argument('-n', '--name', type=str, required=True, help='DCOP name') args",
"in lines_4_config['cons'].split('>'): eq1, eq2 = parse_constraint(con) constraints[f'c{len(constraints)}'] = { 'type': 'intention', 'function': eq1,",
"line = f.readline() while line: kv = line.split('=') lines_4_config[kv[0]] = kv[1].strip() line =",
"file to pyDCOP compatible yaml config') parser.add_argument('-f', '--file', type=str, required=True, help='sim file path')",
"[{ 'id': 'w', 'delay': 1, }] scenarios = {'events': events} for i, cmd",
"only agent removal is supported by pydcop events.append({ 'id': f'e{i}', 'actions': { 'type':",
"b, c = coefficients_str.replace('(', '').replace(')', '').split(',') c1 = f'{a} * var{x}^2 + {b}",
"} agent_ids.append(agent_id) yaml_dict['domains'] = domains # variables variables = {} for agent in",
"f'e{i}', 'actions': { 'type': cmd, 'agent': f'a{agent}' } }) events.append({ 'id': 'w', 'delay':",
"= f.readline() yaml_dict = { 'name': args.name, 'objective': 'min', } # domains domains",
"# export to yaml exported_file = args.file.split('/')[-1] + '.yaml' yaml_file = os.path.join('./yaml-files', exported_file)",
"i, cmd in enumerate(lines_4_config['commands'].split(' ')): cmd, agent = cmd.split(':') if cmd == 'remove_agent':",
"'type': cmd, 'agent': f'a{agent}' } }) events.append({ 'id': 'w', 'delay': 1, }) exported_file",
"for v in dvals.split(',')], } agent_ids.append(agent_id) yaml_dict['domains'] = domains # variables variables =",
"{} with open(args.file, 'r') as f: line = f.readline() while line: kv =",
"agent_ids: variables[f'var{agent}'] = { 'domain': f'd{agent}', } yaml_dict['variables'] = variables # constraints constraints",
"[int(v) for v in dvals.split(',')], } agent_ids.append(agent_id) yaml_dict['domains'] = domains # variables variables",
"for agent in agent_ids: variables[f'var{agent}'] = { 'domain': f'd{agent}', } yaml_dict['variables'] = variables",
"'remove_agent': # only agent removal is supported by pydcop events.append({ 'id': f'e{i}', 'actions':",
"line = f.readline() yaml_dict = { 'name': args.name, 'objective': 'min', } # domains",
"[f'a{agent_id}' for agent_id in agent_ids] yaml_dict['agents'] = agents # export to yaml exported_file",
"'w') as f: yaml.dump(scenarios, f) print(f'Simulation scenario file saved: {yaml_file}') if __name__ ==",
"= cmd.split(':') if cmd == 'remove_agent': # only agent removal is supported by",
"agent_id in agent_ids] yaml_dict['agents'] = agents # export to yaml exported_file = args.file.split('/')[-1]",
"os.path.join('./yaml-files', exported_file) with open(yaml_file, 'w') as f: yaml.dump(scenarios, f) print(f'Simulation scenario file saved:",
"== '__main__': parser = argparse.ArgumentParser(description='Convert DynaGraph sim file to pyDCOP compatible yaml config')",
"agent in agent_ids: variables[f'var{agent}'] = { 'domain': f'd{agent}', } yaml_dict['variables'] = variables #",
"yaml_dict['domains'] = domains # variables variables = {} for agent in agent_ids: variables[f'var{agent}']",
"= kv[1].strip() line = f.readline() yaml_dict = { 'name': args.name, 'objective': 'min', }",
"constraints constraints = {} for con in lines_4_config['cons'].split('>'): eq1, eq2 = parse_constraint(con) constraints[f'c{len(constraints)}']",
"export to yaml exported_file = args.file.split('/')[-1] + '.yaml' yaml_file = os.path.join('./yaml-files', exported_file) with",
"= { 'name': args.name, 'objective': 'min', } # domains domains = {} domain_info",
"{'events': events} for i, cmd in enumerate(lines_4_config['commands'].split(' ')): cmd, agent = cmd.split(':') if",
"in domain_info: agent_id, dvals = domain_str.split(':') domains[f'd{agent_id}'] = { 'values': [int(v) for v",
"')): cmd, agent = cmd.split(':') if cmd == 'remove_agent': # only agent removal",
"= constraints # agents agents = [f'a{agent_id}' for agent_id in agent_ids] yaml_dict['agents'] =",
"yaml.dump(scenarios, f) print(f'Simulation scenario file saved: {yaml_file}') if __name__ == '__main__': parser =",
"'w') as f: yaml.dump(yaml_dict, f) print(f'Simulation config file saved: {yaml_file}') # create scenario",
"parser.add_argument('-f', '--file', type=str, required=True, help='sim file path') parser.add_argument('-n', '--name', type=str, required=True, help='DCOP name')",
"{ 'values': [int(v) for v in dvals.split(',')], } agent_ids.append(agent_id) yaml_dict['domains'] = domains #",
"== 'remove_agent': # only agent removal is supported by pydcop events.append({ 'id': f'e{i}',",
"domain_info = lines_4_config['domains'].split(' ') agent_ids = [] for domain_str in domain_info: agent_id, dvals",
"yaml def parse_constraint(con_str): # sample: (0,1):(1,1,1) agents_str, coefficients_str = con_str.split(':') x, y =",
"} # domains domains = {} domain_info = lines_4_config['domains'].split(' ') agent_ids = []",
"'intention', 'function': eq2, } yaml_dict['constraints'] = constraints # agents agents = [f'a{agent_id}' for",
"[] for domain_str in domain_info: agent_id, dvals = domain_str.split(':') domains[f'd{agent_id}'] = { 'values':",
"domain_str in domain_info: agent_id, dvals = domain_str.split(':') domains[f'd{agent_id}'] = { 'values': [int(v) for",
"supported by pydcop events.append({ 'id': f'e{i}', 'actions': { 'type': cmd, 'agent': f'a{agent}' }",
"lines_4_config['cons'].split('>'): eq1, eq2 = parse_constraint(con) constraints[f'c{len(constraints)}'] = { 'type': 'intention', 'function': eq1, }",
"cmd, agent = cmd.split(':') if cmd == 'remove_agent': # only agent removal is",
"agents_str, coefficients_str = con_str.split(':') x, y = agents_str.replace('(', '').replace(')', '').split(',') a, b, c",
"agents_str.replace('(', '').replace(')', '').split(',') a, b, c = coefficients_str.replace('(', '').replace(')', '').split(',') c1 = f'{a}",
"domains = {} domain_info = lines_4_config['domains'].split(' ') agent_ids = [] for domain_str in",
"agent_ids] yaml_dict['agents'] = agents # export to yaml exported_file = args.file.split('/')[-1] + '.yaml'",
"{c} * var{y}^2' c2 = f'{c} * var{y}^2 + {b} * var{y} *",
"dvals.split(',')], } agent_ids.append(agent_id) yaml_dict['domains'] = domains # variables variables = {} for agent",
"yaml.dump(yaml_dict, f) print(f'Simulation config file saved: {yaml_file}') # create scenario file events =",
"= {'events': events} for i, cmd in enumerate(lines_4_config['commands'].split(' ')): cmd, agent = cmd.split(':')",
"pyDCOP compatible yaml config') parser.add_argument('-f', '--file', type=str, required=True, help='sim file path') parser.add_argument('-n', '--name',",
"= os.path.join('./yaml-files', exported_file) with open(yaml_file, 'w') as f: yaml.dump(scenarios, f) print(f'Simulation scenario file",
"return c1, c2 def main(args): lines_4_config = {} with open(args.file, 'r') as f:",
"DynaGraph sim file to pyDCOP compatible yaml config') parser.add_argument('-f', '--file', type=str, required=True, help='sim",
"(0,1):(1,1,1) agents_str, coefficients_str = con_str.split(':') x, y = agents_str.replace('(', '').replace(')', '').split(',') a, b,",
"pydcop events.append({ 'id': f'e{i}', 'actions': { 'type': cmd, 'agent': f'a{agent}' } }) events.append({",
"'').replace(')', '').split(',') a, b, c = coefficients_str.replace('(', '').replace(')', '').split(',') c1 = f'{a} *",
"{} for con in lines_4_config['cons'].split('>'): eq1, eq2 = parse_constraint(con) constraints[f'c{len(constraints)}'] = { 'type':",
"var{x} + {a} * var{x}^2' return c1, c2 def main(args): lines_4_config = {}",
"yaml_file = os.path.join('./yaml-files', exported_file) with open(yaml_file, 'w') as f: yaml.dump(scenarios, f) print(f'Simulation scenario",
"= f.readline() while line: kv = line.split('=') lines_4_config[kv[0]] = kv[1].strip() line = f.readline()",
"c1 = f'{a} * var{x}^2 + {b} * var{x} * var{y} + {c}",
"exported_file = args.file.split('/')[-1] + '.yaml' yaml_file = os.path.join('./yaml-files', exported_file) with open(yaml_file, 'w') as",
"f: yaml.dump(yaml_dict, f) print(f'Simulation config file saved: {yaml_file}') # create scenario file events",
"'domain': f'd{agent}', } yaml_dict['variables'] = variables # constraints constraints = {} for con",
"= domains # variables variables = {} for agent in agent_ids: variables[f'var{agent}'] =",
"kv = line.split('=') lines_4_config[kv[0]] = kv[1].strip() line = f.readline() yaml_dict = { 'name':",
"c = coefficients_str.replace('(', '').replace(')', '').split(',') c1 = f'{a} * var{x}^2 + {b} *",
"* var{x}^2' return c1, c2 def main(args): lines_4_config = {} with open(args.file, 'r')",
"compatible yaml config') parser.add_argument('-f', '--file', type=str, required=True, help='sim file path') parser.add_argument('-n', '--name', type=str,",
"y = agents_str.replace('(', '').replace(')', '').split(',') a, b, c = coefficients_str.replace('(', '').replace(')', '').split(',') c1",
"is supported by pydcop events.append({ 'id': f'e{i}', 'actions': { 'type': cmd, 'agent': f'a{agent}'",
"= args.file.split('/')[-1] + '.yaml' yaml_file = os.path.join('./yaml-files', exported_file) with open(yaml_file, 'w') as f:",
"coefficients_str = con_str.split(':') x, y = agents_str.replace('(', '').replace(')', '').split(',') a, b, c =",
"events.append({ 'id': f'e{i}', 'actions': { 'type': cmd, 'agent': f'a{agent}' } }) events.append({ 'id':",
"+ {b} * var{y} * var{x} + {a} * var{x}^2' return c1, c2",
"variables = {} for agent in agent_ids: variables[f'var{agent}'] = { 'domain': f'd{agent}', }",
"constraints # agents agents = [f'a{agent_id}' for agent_id in agent_ids] yaml_dict['agents'] = agents",
"{yaml_file}') # create scenario file events = [{ 'id': 'w', 'delay': 1, }]",
"os.path.join('./yaml-files', exported_file) with open(yaml_file, 'w') as f: yaml.dump(yaml_dict, f) print(f'Simulation config file saved:",
"# create scenario file events = [{ 'id': 'w', 'delay': 1, }] scenarios",
"var{y}^2' c2 = f'{c} * var{y}^2 + {b} * var{y} * var{x} +",
"domain_str.split(':') domains[f'd{agent_id}'] = { 'values': [int(v) for v in dvals.split(',')], } agent_ids.append(agent_id) yaml_dict['domains']",
"con in lines_4_config['cons'].split('>'): eq1, eq2 = parse_constraint(con) constraints[f'c{len(constraints)}'] = { 'type': 'intention', 'function':",
"file saved: {yaml_file}') if __name__ == '__main__': parser = argparse.ArgumentParser(description='Convert DynaGraph sim file",
"# sample: (0,1):(1,1,1) agents_str, coefficients_str = con_str.split(':') x, y = agents_str.replace('(', '').replace(')', '').split(',')",
"yaml_dict['constraints'] = constraints # agents agents = [f'a{agent_id}' for agent_id in agent_ids] yaml_dict['agents']",
"{} for agent in agent_ids: variables[f'var{agent}'] = { 'domain': f'd{agent}', } yaml_dict['variables'] =",
"file events = [{ 'id': 'w', 'delay': 1, }] scenarios = {'events': events}",
"f'd{agent}', } yaml_dict['variables'] = variables # constraints constraints = {} for con in",
"as yaml def parse_constraint(con_str): # sample: (0,1):(1,1,1) agents_str, coefficients_str = con_str.split(':') x, y",
"enumerate(lines_4_config['commands'].split(' ')): cmd, agent = cmd.split(':') if cmd == 'remove_agent': # only agent",
"open(yaml_file, 'w') as f: yaml.dump(yaml_dict, f) print(f'Simulation config file saved: {yaml_file}') # create",
"= [] for domain_str in domain_info: agent_id, dvals = domain_str.split(':') domains[f'd{agent_id}'] = {",
"domains domains = {} domain_info = lines_4_config['domains'].split(' ') agent_ids = [] for domain_str",
"eq1, } constraints[f'c{len(constraints)}'] = { 'type': 'intention', 'function': eq2, } yaml_dict['constraints'] = constraints",
"argparse.ArgumentParser(description='Convert DynaGraph sim file to pyDCOP compatible yaml config') parser.add_argument('-f', '--file', type=str, required=True,",
"{yaml_file}') if __name__ == '__main__': parser = argparse.ArgumentParser(description='Convert DynaGraph sim file to pyDCOP",
"open(args.file, 'r') as f: line = f.readline() while line: kv = line.split('=') lines_4_config[kv[0]]",
"* var{x}^2 + {b} * var{x} * var{y} + {c} * var{y}^2' c2",
"with open(yaml_file, 'w') as f: yaml.dump(yaml_dict, f) print(f'Simulation config file saved: {yaml_file}') #",
"1, }) exported_file = args.file.split('/')[-1] + '-scenario.yaml' yaml_file = os.path.join('./yaml-files', exported_file) with open(yaml_file,",
"{ 'name': args.name, 'objective': 'min', } # domains domains = {} domain_info =",
"config file saved: {yaml_file}') # create scenario file events = [{ 'id': 'w',",
"= args.file.split('/')[-1] + '-scenario.yaml' yaml_file = os.path.join('./yaml-files', exported_file) with open(yaml_file, 'w') as f:",
"domains[f'd{agent_id}'] = { 'values': [int(v) for v in dvals.split(',')], } agent_ids.append(agent_id) yaml_dict['domains'] =",
"= con_str.split(':') x, y = agents_str.replace('(', '').replace(')', '').split(',') a, b, c = coefficients_str.replace('(',",
"constraints = {} for con in lines_4_config['cons'].split('>'): eq1, eq2 = parse_constraint(con) constraints[f'c{len(constraints)}'] =",
"as f: yaml.dump(yaml_dict, f) print(f'Simulation config file saved: {yaml_file}') # create scenario file",
"'w', 'delay': 1, }] scenarios = {'events': events} for i, cmd in enumerate(lines_4_config['commands'].split('",
"agent = cmd.split(':') if cmd == 'remove_agent': # only agent removal is supported",
"kv[1].strip() line = f.readline() yaml_dict = { 'name': args.name, 'objective': 'min', } #",
"import os.path import oyaml as yaml def parse_constraint(con_str): # sample: (0,1):(1,1,1) agents_str, coefficients_str",
"= agents # export to yaml exported_file = args.file.split('/')[-1] + '.yaml' yaml_file =",
"yaml_dict['agents'] = agents # export to yaml exported_file = args.file.split('/')[-1] + '.yaml' yaml_file",
"cmd.split(':') if cmd == 'remove_agent': # only agent removal is supported by pydcop",
"while line: kv = line.split('=') lines_4_config[kv[0]] = kv[1].strip() line = f.readline() yaml_dict ="
] |
[
"'_gdp'].sum() dec_base[perc] = dec_gdp_tot/dec_pop_tot ind_ctry = dec.index imtrx_dec = imtrx_gdp[:,ind_ctry,:] imtrx_dec_sum = dec_gdp_tot-(imtrx_dec.data).sum(axis=1)",
"_env.mkdirs(odir_summary) for scen in scens: writer = pd.ExcelWriter(odir_summary + 'Deciles_and_Quintile_ratio_changes_'+ds+'_'+scen+'_Burke.xls') otbls_ctry_GDP_stat = {}",
"otbls_ctry_GDP_stat = {} otbls = {} otbl_ineq = pd.DataFrame(index = boot_methods,columns = ['median_ratio','5_ratio','95_ratio','10_ratio','90_ratio','probability_reduced'])",
"itbl_gdp_baseline[sgdp_year + '_popsum']/tot_pop #deciles (<=10% and >=90%) deciles = {} ind10 = np.where(itbl_gdp_baseline[sgdp_year",
"'_gdpsum'] = 0 #itbl_gdp_baseline['2010_popw_gdp'] = 0 itbl_gdp_baseline[sgdp_year + '_popsum'] = 0 #itbl_gdp_baseline['2010_pop_ratio_sum'] =",
"dec_base = {} for perc in [10,20,80,90]: dec = deciles[perc].copy() dec_pop_tot = dec[sgdp_year",
"itbl_gdp_baseline.loc[row,sgdp_year + '_gdpsum'] = itbl_gdp_baseline[sgdp_year + '_gdpsum'].iloc[irow-1] + itbl_gdp_baseline.loc[row,sgdp_year + '_gdp'] itbl_gdp_baseline.loc[row, sgdp_year",
"np.percentile(quin_diff,5) otbls['quintiles'].loc[b_m,'95_ratio'] = np.percentile(quin_diff,95) otbls['quintiles'].loc[b_m,'10_ratio'] = np.percentile(quin_diff,10) otbls['quintiles'].loc[b_m,'90_ratio'] = np.percentile(quin_diff,90) otbls['quintiles'].loc[b_m,'probability_reduced'] = len(quin_diff[quin_diff<0])/np.size(quin_diff)",
"+ '_pop'].sum() #itbl_gdp_baseline['2010_pop_ratio'] = itbl_gdp_baseline['2010_pop']/tot_pop itbl_gdp_baseline[sgdp_year + '_gdpsum'] = 0 #itbl_gdp_baseline['2010_popw_gdp'] = 0",
"as np from netCDF4 import Dataset import _env datasets = _env.datasets scenarios =",
"['country-lag0','country-lag1','country-lag5','year','year-blocks'] itbl_gdp_baseline = pd.read_csv(_env.odir_root + 'basic_stats' + '/Country_Basic_Stats.csv') itbl_gdp_baseline.sort_values([sgdp_year + '_gdpcap'],inplace=True) tot_pop =",
"itbl_gdp_baseline.loc[row,sgdp_year + '_gdp'] itbl_gdp_baseline.loc[row, sgdp_year + '_popsum'] = itbl_gdp_baseline.loc[row,sgdp_year + '_pop'] else: itbl_gdp_baseline.loc[row,sgdp_year",
"idir_temp = _env.odir_root + '/sim_temperature/' ####summarize global and regional GDP changes#### gdp_year =",
"_env datasets = _env.datasets scenarios = _env.scenarios gdp_year = 2010 sgdp_year = str(gdp_year)",
"+ '/gdp_' + ds + '/' odir_summary = _env.odir_root + '/summary_' + ds",
"This code calculates changes in the ratio between different population-weighted GDP deciles and",
"pd.ExcelWriter(odir_summary + 'Deciles_and_Quintile_ratio_changes_'+ds+'_'+scen+'_Burke.xls') otbls_ctry_GDP_stat = {} otbls = {} otbl_ineq = pd.DataFrame(index =",
"'_gdp'] itbl_gdp_baseline.loc[row, sgdp_year + '_popsum'] = itbl_gdp_baseline.loc[row,sgdp_year + '_pop'] else: itbl_gdp_baseline.loc[row,sgdp_year + '_gdpsum']",
"#itbl_gdp_baseline['2010_pop_ratio_sum'] = 0 for irow, row in enumerate(itbl_gdp_baseline.index): if irow == 0: itbl_gdp_baseline.loc[row,sgdp_year",
"2010 sgdp_year = str(gdp_year) idir_temp = _env.odir_root + '/sim_temperature/' ####summarize global and regional",
"= 0 itbl_gdp_baseline[sgdp_year + '_popsum'] = 0 #itbl_gdp_baseline['2010_pop_ratio_sum'] = 0 for irow, row",
"#itbl_gdp_baseline['2010_pop_ratio'] = itbl_gdp_baseline['2010_pop']/tot_pop itbl_gdp_baseline[sgdp_year + '_gdpsum'] = 0 #itbl_gdp_baseline['2010_popw_gdp'] = 0 itbl_gdp_baseline[sgdp_year +",
"otbls['deciles'].loc[b_m,'median_ratio'] = np.median(dec_diff) otbls['deciles'].loc[b_m,'5_ratio'] = np.percentile(dec_diff,5) otbls['deciles'].loc[b_m,'95_ratio'] = np.percentile(dec_diff,95) otbls['deciles'].loc[b_m,'10_ratio'] = np.percentile(dec_diff,10) otbls['deciles'].loc[b_m,'90_ratio']",
"inc_gdp['GDP'][:] dec_var = {} dec_base = {} for perc in [10,20,80,90]: dec =",
"= 0 for irow, row in enumerate(itbl_gdp_baseline.index): if irow == 0: itbl_gdp_baseline.loc[row,sgdp_year +",
"= dec_gdpcap.copy() dec_diff = (dec_var[90]/dec_var[10]-dec_base[90]/dec_base[10])/(dec_base[90]/dec_base[10])*100 quin_diff = (dec_var[80]/dec_var[20] - dec_base[80]/dec_base[20])/(dec_base[80]/dec_base[20])*100 otbls['deciles'].loc[b_m,'median_ratio'] = np.median(dec_diff)",
"(<=10% and >=90%) deciles = {} ind10 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']<=0.1)[0] deciles[10] =",
"= imtrx_gdp[:,ind_ctry,:] imtrx_dec_sum = dec_gdp_tot-(imtrx_dec.data).sum(axis=1) # print(perc, np.median(imtrx_dec_sum),dec_gdp_tot,np.median(imtrx_dec_sum)/dec_gdp_tot) dec_gdpcap = imtrx_dec_sum/dec_pop_tot dec_var[perc] =",
"= _env.odir_root + '/gdp_' + ds + '/' odir_summary = _env.odir_root + '/summary_'",
"itbl_gdp_baseline.iloc[ind80].copy() for ds in datasets: scens = ['No-Aerosol'] if ds == 'ERA-Interim': scens",
"= pd.DataFrame(index = boot_methods,columns = ['median_ratio','5_ratio','95_ratio','10_ratio','90_ratio','probability_reduced']) otbls['deciles'] = otbl_ineq.copy() otbls['quintiles'] = otbl_ineq.copy() for",
"+ '_popsum'] = 0 #itbl_gdp_baseline['2010_pop_ratio_sum'] = 0 for irow, row in enumerate(itbl_gdp_baseline.index): if",
"== 0: itbl_gdp_baseline.loc[row,sgdp_year + '_gdpsum'] = itbl_gdp_baseline.loc[row,sgdp_year + '_gdp'] itbl_gdp_baseline.loc[row, sgdp_year + '_popsum']",
"and regional GDP changes#### gdp_year = 2010 sgdp_year = str(gdp_year) boot_methods = ['country-lag0','country-lag1','country-lag5','year','year-blocks']",
"otbls['deciles'].loc[b_m,'5_ratio'] = np.percentile(dec_diff,5) otbls['deciles'].loc[b_m,'95_ratio'] = np.percentile(dec_diff,95) otbls['deciles'].loc[b_m,'10_ratio'] = np.percentile(dec_diff,10) otbls['deciles'].loc[b_m,'90_ratio'] = np.percentile(dec_diff,90) otbls['deciles'].loc[b_m,'probability_reduced']",
"np.percentile(quin_diff,95) otbls['quintiles'].loc[b_m,'10_ratio'] = np.percentile(quin_diff,10) otbls['quintiles'].loc[b_m,'90_ratio'] = np.percentile(quin_diff,90) otbls['quintiles'].loc[b_m,'probability_reduced'] = len(quin_diff[quin_diff<0])/np.size(quin_diff) otbls['deciles'].to_excel(writer,'deciles') otbls['quintiles'].to_excel(writer,'quintiles') writer.save()",
"idir_gdp = _env.odir_root + '/gdp_' + ds + '/' odir_summary = _env.odir_root +",
"= _env.datasets scenarios = _env.scenarios gdp_year = 2010 sgdp_year = str(gdp_year) idir_temp =",
"= {} dec_base = {} for perc in [10,20,80,90]: dec = deciles[perc].copy() dec_pop_tot",
"len(dec_diff[dec_diff<0])/np.size(dec_diff) otbls['quintiles'].loc[b_m,'median_ratio'] = np.median(quin_diff) otbls['quintiles'].loc[b_m,'5_ratio'] = np.percentile(quin_diff,5) otbls['quintiles'].loc[b_m,'95_ratio'] = np.percentile(quin_diff,95) otbls['quintiles'].loc[b_m,'10_ratio'] = np.percentile(quin_diff,10)",
"= pd.read_csv(_env.odir_root + 'basic_stats' + '/Country_Basic_Stats.csv') itbl_gdp_baseline.sort_values([sgdp_year + '_gdpcap'],inplace=True) tot_pop = itbl_gdp_baseline[sgdp_year +",
"row in enumerate(itbl_gdp_baseline.index): if irow == 0: itbl_gdp_baseline.loc[row,sgdp_year + '_gdpsum'] = itbl_gdp_baseline.loc[row,sgdp_year +",
"'/' _env.mkdirs(odir_summary) for scen in scens: writer = pd.ExcelWriter(odir_summary + 'Deciles_and_Quintile_ratio_changes_'+ds+'_'+scen+'_Burke.xls') otbls_ctry_GDP_stat =",
"datasets: scens = ['No-Aerosol'] if ds == 'ERA-Interim': scens = ['No-Aerosol','No-Sulfate'] idir_gdp =",
"otbls['deciles'].loc[b_m,'10_ratio'] = np.percentile(dec_diff,10) otbls['deciles'].loc[b_m,'90_ratio'] = np.percentile(dec_diff,90) otbls['deciles'].loc[b_m,'probability_reduced'] = len(dec_diff[dec_diff<0])/np.size(dec_diff) otbls['quintiles'].loc[b_m,'median_ratio'] = np.median(quin_diff) otbls['quintiles'].loc[b_m,'5_ratio']",
"deciles[90] = itbl_gdp_baseline.iloc[ind90].copy() #quintiles (<=20% and >=80%) ind20 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']<=0.2)[0] deciles[20]",
"_env.odir_root + '/sim_temperature/' ####summarize global and regional GDP changes#### gdp_year = 2010 sgdp_year",
">=90%) deciles = {} ind10 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']<=0.1)[0] deciles[10] = itbl_gdp_baseline.iloc[ind10].copy() ind90",
"'_pop'] itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum'] = itbl_gdp_baseline[sgdp_year + '_popsum']/tot_pop #deciles (<=10% and >=90%) deciles",
"itbl_gdp_baseline.iloc[ind20].copy() ind80 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']>=0.8)[0] deciles[80] = itbl_gdp_baseline.iloc[ind80].copy() for ds in datasets:",
"= otbl_ineq.copy() otbls['quintiles'] = otbl_ineq.copy() for b_m in boot_methods: inc_gdp = Dataset(idir_gdp +",
"= _env.odir_root + '/sim_temperature/' ####summarize global and regional GDP changes#### gdp_year = 2010",
"_env.scenarios gdp_year = 2010 sgdp_year = str(gdp_year) idir_temp = _env.odir_root + '/sim_temperature/' ####summarize",
"+ '_popsum'].iloc[irow-1] + itbl_gdp_baseline.loc[row,sgdp_year + '_pop'] itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum'] = itbl_gdp_baseline[sgdp_year + '_popsum']/tot_pop",
"ind90 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']>=0.9)[0] deciles[90] = itbl_gdp_baseline.iloc[ind90].copy() #quintiles (<=20% and >=80%) ind20",
"= dec[sgdp_year + '_gdp'].sum() dec_base[perc] = dec_gdp_tot/dec_pop_tot ind_ctry = dec.index imtrx_dec = imtrx_gdp[:,ind_ctry,:]",
"sgdp_year + '_popsum'] = itbl_gdp_baseline.loc[row,sgdp_year + '_pop'] else: itbl_gdp_baseline.loc[row,sgdp_year + '_gdpsum'] = itbl_gdp_baseline[sgdp_year",
"'/Country_Basic_Stats.csv') itbl_gdp_baseline.sort_values([sgdp_year + '_gdpcap'],inplace=True) tot_pop = itbl_gdp_baseline[sgdp_year + '_pop'].sum() #itbl_gdp_baseline['2010_pop_ratio'] = itbl_gdp_baseline['2010_pop']/tot_pop itbl_gdp_baseline[sgdp_year",
"+ '_pop_ratio_sum']>=0.9)[0] deciles[90] = itbl_gdp_baseline.iloc[ind90].copy() #quintiles (<=20% and >=80%) ind20 = np.where(itbl_gdp_baseline[sgdp_year +",
"= deciles[perc].copy() dec_pop_tot = dec[sgdp_year + '_pop'].sum() dec_gdp_tot = dec[sgdp_year + '_gdp'].sum() dec_base[perc]",
"in the ratio between different population-weighted GDP deciles and quintiles by <NAME> (<EMAIL>)",
"itbl_gdp_baseline.loc[row,sgdp_year + '_gdpsum'] = itbl_gdp_baseline.loc[row,sgdp_year + '_gdp'] itbl_gdp_baseline.loc[row, sgdp_year + '_popsum'] = itbl_gdp_baseline.loc[row,sgdp_year",
"_env.odir_root + '/summary_' + ds + '/' _env.mkdirs(odir_summary) for scen in scens: writer",
"= itbl_gdp_baseline.iloc[ind90].copy() #quintiles (<=20% and >=80%) ind20 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']<=0.2)[0] deciles[20] =",
"(dec_var[80]/dec_var[20] - dec_base[80]/dec_base[20])/(dec_base[80]/dec_base[20])*100 otbls['deciles'].loc[b_m,'median_ratio'] = np.median(dec_diff) otbls['deciles'].loc[b_m,'5_ratio'] = np.percentile(dec_diff,5) otbls['deciles'].loc[b_m,'95_ratio'] = np.percentile(dec_diff,95) otbls['deciles'].loc[b_m,'10_ratio']",
"= itbl_gdp_baseline[sgdp_year + '_popsum'].iloc[irow-1] + itbl_gdp_baseline.loc[row,sgdp_year + '_pop'] itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum'] = itbl_gdp_baseline[sgdp_year",
"+ '_pop_ratio_sum']>=0.8)[0] deciles[80] = itbl_gdp_baseline.iloc[ind80].copy() for ds in datasets: scens = ['No-Aerosol'] if",
"#itbl_gdp_baseline['2010_popw_gdp'] = 0 itbl_gdp_baseline[sgdp_year + '_popsum'] = 0 #itbl_gdp_baseline['2010_pop_ratio_sum'] = 0 for irow,",
"str(gdp_year) + '_'+ds+'_'+scen+'.nc') imtrx_gdp = inc_gdp['GDP'][:] dec_var = {} dec_base = {} for",
"sgdp_year = str(gdp_year) boot_methods = ['country-lag0','country-lag1','country-lag5','year','year-blocks'] itbl_gdp_baseline = pd.read_csv(_env.odir_root + 'basic_stats' + '/Country_Basic_Stats.csv')",
"quintiles by <NAME> (<EMAIL>) ''' import pandas as pd import numpy as np",
"in boot_methods: inc_gdp = Dataset(idir_gdp + 'GDP_Changes_Burke_' + b_m + '_' + str(gdp_year)",
"= dec_gdp_tot/dec_pop_tot ind_ctry = dec.index imtrx_dec = imtrx_gdp[:,ind_ctry,:] imtrx_dec_sum = dec_gdp_tot-(imtrx_dec.data).sum(axis=1) # print(perc,",
"0 itbl_gdp_baseline[sgdp_year + '_popsum'] = 0 #itbl_gdp_baseline['2010_pop_ratio_sum'] = 0 for irow, row in",
"np.percentile(dec_diff,95) otbls['deciles'].loc[b_m,'10_ratio'] = np.percentile(dec_diff,10) otbls['deciles'].loc[b_m,'90_ratio'] = np.percentile(dec_diff,90) otbls['deciles'].loc[b_m,'probability_reduced'] = len(dec_diff[dec_diff<0])/np.size(dec_diff) otbls['quintiles'].loc[b_m,'median_ratio'] = np.median(quin_diff)",
"'_popsum'] = itbl_gdp_baseline[sgdp_year + '_popsum'].iloc[irow-1] + itbl_gdp_baseline.loc[row,sgdp_year + '_pop'] itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum'] =",
"dec_base[perc] = dec_gdp_tot/dec_pop_tot ind_ctry = dec.index imtrx_dec = imtrx_gdp[:,ind_ctry,:] imtrx_dec_sum = dec_gdp_tot-(imtrx_dec.data).sum(axis=1) #",
"itbl_gdp_baseline.iloc[ind10].copy() ind90 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']>=0.9)[0] deciles[90] = itbl_gdp_baseline.iloc[ind90].copy() #quintiles (<=20% and >=80%)",
"= itbl_gdp_baseline.iloc[ind20].copy() ind80 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']>=0.8)[0] deciles[80] = itbl_gdp_baseline.iloc[ind80].copy() for ds in",
"0 #itbl_gdp_baseline['2010_popw_gdp'] = 0 itbl_gdp_baseline[sgdp_year + '_popsum'] = 0 #itbl_gdp_baseline['2010_pop_ratio_sum'] = 0 for",
"= np.percentile(dec_diff,10) otbls['deciles'].loc[b_m,'90_ratio'] = np.percentile(dec_diff,90) otbls['deciles'].loc[b_m,'probability_reduced'] = len(dec_diff[dec_diff<0])/np.size(dec_diff) otbls['quintiles'].loc[b_m,'median_ratio'] = np.median(quin_diff) otbls['quintiles'].loc[b_m,'5_ratio'] =",
"utf-8 -*- ''' This code calculates changes in the ratio between different population-weighted",
"['No-Aerosol'] if ds == 'ERA-Interim': scens = ['No-Aerosol','No-Sulfate'] idir_gdp = _env.odir_root + '/gdp_'",
"dec_gdpcap.copy() dec_diff = (dec_var[90]/dec_var[10]-dec_base[90]/dec_base[10])/(dec_base[90]/dec_base[10])*100 quin_diff = (dec_var[80]/dec_var[20] - dec_base[80]/dec_base[20])/(dec_base[80]/dec_base[20])*100 otbls['deciles'].loc[b_m,'median_ratio'] = np.median(dec_diff) otbls['deciles'].loc[b_m,'5_ratio']",
"'_pop_ratio_sum']>=0.8)[0] deciles[80] = itbl_gdp_baseline.iloc[ind80].copy() for ds in datasets: scens = ['No-Aerosol'] if ds",
"= np.median(dec_diff) otbls['deciles'].loc[b_m,'5_ratio'] = np.percentile(dec_diff,5) otbls['deciles'].loc[b_m,'95_ratio'] = np.percentile(dec_diff,95) otbls['deciles'].loc[b_m,'10_ratio'] = np.percentile(dec_diff,10) otbls['deciles'].loc[b_m,'90_ratio'] =",
"deciles[perc].copy() dec_pop_tot = dec[sgdp_year + '_pop'].sum() dec_gdp_tot = dec[sgdp_year + '_gdp'].sum() dec_base[perc] =",
"= itbl_gdp_baseline[sgdp_year + '_popsum']/tot_pop #deciles (<=10% and >=90%) deciles = {} ind10 =",
"and >=80%) ind20 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']<=0.2)[0] deciles[20] = itbl_gdp_baseline.iloc[ind20].copy() ind80 = np.where(itbl_gdp_baseline[sgdp_year",
"in enumerate(itbl_gdp_baseline.index): if irow == 0: itbl_gdp_baseline.loc[row,sgdp_year + '_gdpsum'] = itbl_gdp_baseline.loc[row,sgdp_year + '_gdp']",
"<NAME> (<EMAIL>) ''' import pandas as pd import numpy as np from netCDF4",
"'_gdp'] itbl_gdp_baseline.loc[row, sgdp_year + '_popsum'] = itbl_gdp_baseline[sgdp_year + '_popsum'].iloc[irow-1] + itbl_gdp_baseline.loc[row,sgdp_year + '_pop']",
"scen in scens: writer = pd.ExcelWriter(odir_summary + 'Deciles_and_Quintile_ratio_changes_'+ds+'_'+scen+'_Burke.xls') otbls_ctry_GDP_stat = {} otbls =",
"dec.index imtrx_dec = imtrx_gdp[:,ind_ctry,:] imtrx_dec_sum = dec_gdp_tot-(imtrx_dec.data).sum(axis=1) # print(perc, np.median(imtrx_dec_sum),dec_gdp_tot,np.median(imtrx_dec_sum)/dec_gdp_tot) dec_gdpcap = imtrx_dec_sum/dec_pop_tot",
"= 0 #itbl_gdp_baseline['2010_pop_ratio_sum'] = 0 for irow, row in enumerate(itbl_gdp_baseline.index): if irow ==",
"''' import pandas as pd import numpy as np from netCDF4 import Dataset",
"(dec_var[90]/dec_var[10]-dec_base[90]/dec_base[10])/(dec_base[90]/dec_base[10])*100 quin_diff = (dec_var[80]/dec_var[20] - dec_base[80]/dec_base[20])/(dec_base[80]/dec_base[20])*100 otbls['deciles'].loc[b_m,'median_ratio'] = np.median(dec_diff) otbls['deciles'].loc[b_m,'5_ratio'] = np.percentile(dec_diff,5) otbls['deciles'].loc[b_m,'95_ratio']",
"+ '/' odir_summary = _env.odir_root + '/summary_' + ds + '/' _env.mkdirs(odir_summary) for",
"'_gdpsum'] = itbl_gdp_baseline.loc[row,sgdp_year + '_gdp'] itbl_gdp_baseline.loc[row, sgdp_year + '_popsum'] = itbl_gdp_baseline.loc[row,sgdp_year + '_pop']",
"itbl_gdp_baseline[sgdp_year + '_popsum'].iloc[irow-1] + itbl_gdp_baseline.loc[row,sgdp_year + '_pop'] itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum'] = itbl_gdp_baseline[sgdp_year +",
"{} otbls = {} otbl_ineq = pd.DataFrame(index = boot_methods,columns = ['median_ratio','5_ratio','95_ratio','10_ratio','90_ratio','probability_reduced']) otbls['deciles'] =",
"boot_methods: inc_gdp = Dataset(idir_gdp + 'GDP_Changes_Burke_' + b_m + '_' + str(gdp_year) +",
"2010 sgdp_year = str(gdp_year) boot_methods = ['country-lag0','country-lag1','country-lag5','year','year-blocks'] itbl_gdp_baseline = pd.read_csv(_env.odir_root + 'basic_stats' +",
"otbls['deciles'].loc[b_m,'probability_reduced'] = len(dec_diff[dec_diff<0])/np.size(dec_diff) otbls['quintiles'].loc[b_m,'median_ratio'] = np.median(quin_diff) otbls['quintiles'].loc[b_m,'5_ratio'] = np.percentile(quin_diff,5) otbls['quintiles'].loc[b_m,'95_ratio'] = np.percentile(quin_diff,95) otbls['quintiles'].loc[b_m,'10_ratio']",
"inc_gdp = Dataset(idir_gdp + 'GDP_Changes_Burke_' + b_m + '_' + str(gdp_year) + '_'+ds+'_'+scen+'.nc')",
"imtrx_dec_sum = dec_gdp_tot-(imtrx_dec.data).sum(axis=1) # print(perc, np.median(imtrx_dec_sum),dec_gdp_tot,np.median(imtrx_dec_sum)/dec_gdp_tot) dec_gdpcap = imtrx_dec_sum/dec_pop_tot dec_var[perc] = dec_gdpcap.copy() dec_diff",
"dec_gdpcap = imtrx_dec_sum/dec_pop_tot dec_var[perc] = dec_gdpcap.copy() dec_diff = (dec_var[90]/dec_var[10]-dec_base[90]/dec_base[10])/(dec_base[90]/dec_base[10])*100 quin_diff = (dec_var[80]/dec_var[20] -",
"= np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']<=0.1)[0] deciles[10] = itbl_gdp_baseline.iloc[ind10].copy() ind90 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']>=0.9)[0] deciles[90]",
"= np.percentile(dec_diff,90) otbls['deciles'].loc[b_m,'probability_reduced'] = len(dec_diff[dec_diff<0])/np.size(dec_diff) otbls['quintiles'].loc[b_m,'median_ratio'] = np.median(quin_diff) otbls['quintiles'].loc[b_m,'5_ratio'] = np.percentile(quin_diff,5) otbls['quintiles'].loc[b_m,'95_ratio'] =",
"otbls['deciles'] = otbl_ineq.copy() otbls['quintiles'] = otbl_ineq.copy() for b_m in boot_methods: inc_gdp = Dataset(idir_gdp",
"+ '_popsum']/tot_pop #deciles (<=10% and >=90%) deciles = {} ind10 = np.where(itbl_gdp_baseline[sgdp_year +",
"itbl_gdp_baseline.loc[row,sgdp_year + '_gdp'] itbl_gdp_baseline.loc[row, sgdp_year + '_popsum'] = itbl_gdp_baseline[sgdp_year + '_popsum'].iloc[irow-1] + itbl_gdp_baseline.loc[row,sgdp_year",
"= ['country-lag0','country-lag1','country-lag5','year','year-blocks'] itbl_gdp_baseline = pd.read_csv(_env.odir_root + 'basic_stats' + '/Country_Basic_Stats.csv') itbl_gdp_baseline.sort_values([sgdp_year + '_gdpcap'],inplace=True) tot_pop",
"+ '_pop_ratio_sum']<=0.1)[0] deciles[10] = itbl_gdp_baseline.iloc[ind10].copy() ind90 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']>=0.9)[0] deciles[90] = itbl_gdp_baseline.iloc[ind90].copy()",
"= itbl_gdp_baseline[sgdp_year + '_pop'].sum() #itbl_gdp_baseline['2010_pop_ratio'] = itbl_gdp_baseline['2010_pop']/tot_pop itbl_gdp_baseline[sgdp_year + '_gdpsum'] = 0 #itbl_gdp_baseline['2010_popw_gdp']",
"+ ds + '/' _env.mkdirs(odir_summary) for scen in scens: writer = pd.ExcelWriter(odir_summary +",
"# print(perc, np.median(imtrx_dec_sum),dec_gdp_tot,np.median(imtrx_dec_sum)/dec_gdp_tot) dec_gdpcap = imtrx_dec_sum/dec_pop_tot dec_var[perc] = dec_gdpcap.copy() dec_diff = (dec_var[90]/dec_var[10]-dec_base[90]/dec_base[10])/(dec_base[90]/dec_base[10])*100 quin_diff",
"itbl_gdp_baseline['2010_pop']/tot_pop itbl_gdp_baseline[sgdp_year + '_gdpsum'] = 0 #itbl_gdp_baseline['2010_popw_gdp'] = 0 itbl_gdp_baseline[sgdp_year + '_popsum'] =",
"{} otbl_ineq = pd.DataFrame(index = boot_methods,columns = ['median_ratio','5_ratio','95_ratio','10_ratio','90_ratio','probability_reduced']) otbls['deciles'] = otbl_ineq.copy() otbls['quintiles'] =",
"+ '_gdp'] itbl_gdp_baseline.loc[row, sgdp_year + '_popsum'] = itbl_gdp_baseline.loc[row,sgdp_year + '_pop'] else: itbl_gdp_baseline.loc[row,sgdp_year +",
"irow, row in enumerate(itbl_gdp_baseline.index): if irow == 0: itbl_gdp_baseline.loc[row,sgdp_year + '_gdpsum'] = itbl_gdp_baseline.loc[row,sgdp_year",
"global and regional GDP changes#### gdp_year = 2010 sgdp_year = str(gdp_year) boot_methods =",
"scens = ['No-Aerosol'] if ds == 'ERA-Interim': scens = ['No-Aerosol','No-Sulfate'] idir_gdp = _env.odir_root",
"for irow, row in enumerate(itbl_gdp_baseline.index): if irow == 0: itbl_gdp_baseline.loc[row,sgdp_year + '_gdpsum'] =",
"{} for perc in [10,20,80,90]: dec = deciles[perc].copy() dec_pop_tot = dec[sgdp_year + '_pop'].sum()",
"code calculates changes in the ratio between different population-weighted GDP deciles and quintiles",
"regional GDP changes#### gdp_year = 2010 sgdp_year = str(gdp_year) boot_methods = ['country-lag0','country-lag1','country-lag5','year','year-blocks'] itbl_gdp_baseline",
"0 #itbl_gdp_baseline['2010_pop_ratio_sum'] = 0 for irow, row in enumerate(itbl_gdp_baseline.index): if irow == 0:",
"'_gdpsum'] = itbl_gdp_baseline[sgdp_year + '_gdpsum'].iloc[irow-1] + itbl_gdp_baseline.loc[row,sgdp_year + '_gdp'] itbl_gdp_baseline.loc[row, sgdp_year + '_popsum']",
"_env.odir_root + '/gdp_' + ds + '/' odir_summary = _env.odir_root + '/summary_' +",
"itbl_gdp_baseline[sgdp_year + '_popsum'] = 0 #itbl_gdp_baseline['2010_pop_ratio_sum'] = 0 for irow, row in enumerate(itbl_gdp_baseline.index):",
"= itbl_gdp_baseline.iloc[ind10].copy() ind90 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']>=0.9)[0] deciles[90] = itbl_gdp_baseline.iloc[ind90].copy() #quintiles (<=20% and",
"= ['No-Aerosol','No-Sulfate'] idir_gdp = _env.odir_root + '/gdp_' + ds + '/' odir_summary =",
"'_popsum'] = 0 #itbl_gdp_baseline['2010_pop_ratio_sum'] = 0 for irow, row in enumerate(itbl_gdp_baseline.index): if irow",
"'_pop'].sum() #itbl_gdp_baseline['2010_pop_ratio'] = itbl_gdp_baseline['2010_pop']/tot_pop itbl_gdp_baseline[sgdp_year + '_gdpsum'] = 0 #itbl_gdp_baseline['2010_popw_gdp'] = 0 itbl_gdp_baseline[sgdp_year",
"= itbl_gdp_baseline.loc[row,sgdp_year + '_pop'] else: itbl_gdp_baseline.loc[row,sgdp_year + '_gdpsum'] = itbl_gdp_baseline[sgdp_year + '_gdpsum'].iloc[irow-1] +",
"+ '_pop_ratio_sum'] = itbl_gdp_baseline[sgdp_year + '_popsum']/tot_pop #deciles (<=10% and >=90%) deciles = {}",
"if ds == 'ERA-Interim': scens = ['No-Aerosol','No-Sulfate'] idir_gdp = _env.odir_root + '/gdp_' +",
"'_pop_ratio_sum']<=0.2)[0] deciles[20] = itbl_gdp_baseline.iloc[ind20].copy() ind80 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']>=0.8)[0] deciles[80] = itbl_gdp_baseline.iloc[ind80].copy() for",
"scens = ['No-Aerosol','No-Sulfate'] idir_gdp = _env.odir_root + '/gdp_' + ds + '/' odir_summary",
"calculates changes in the ratio between different population-weighted GDP deciles and quintiles by",
"dec[sgdp_year + '_gdp'].sum() dec_base[perc] = dec_gdp_tot/dec_pop_tot ind_ctry = dec.index imtrx_dec = imtrx_gdp[:,ind_ctry,:] imtrx_dec_sum",
"'_pop'] else: itbl_gdp_baseline.loc[row,sgdp_year + '_gdpsum'] = itbl_gdp_baseline[sgdp_year + '_gdpsum'].iloc[irow-1] + itbl_gdp_baseline.loc[row,sgdp_year + '_gdp']",
"as pd import numpy as np from netCDF4 import Dataset import _env datasets",
"+ '_popsum'] = itbl_gdp_baseline.loc[row,sgdp_year + '_pop'] else: itbl_gdp_baseline.loc[row,sgdp_year + '_gdpsum'] = itbl_gdp_baseline[sgdp_year +",
"= {} otbls = {} otbl_ineq = pd.DataFrame(index = boot_methods,columns = ['median_ratio','5_ratio','95_ratio','10_ratio','90_ratio','probability_reduced']) otbls['deciles']",
"'_pop_ratio_sum'] = itbl_gdp_baseline[sgdp_year + '_popsum']/tot_pop #deciles (<=10% and >=90%) deciles = {} ind10",
"dec_diff = (dec_var[90]/dec_var[10]-dec_base[90]/dec_base[10])/(dec_base[90]/dec_base[10])*100 quin_diff = (dec_var[80]/dec_var[20] - dec_base[80]/dec_base[20])/(dec_base[80]/dec_base[20])*100 otbls['deciles'].loc[b_m,'median_ratio'] = np.median(dec_diff) otbls['deciles'].loc[b_m,'5_ratio'] =",
"pandas as pd import numpy as np from netCDF4 import Dataset import _env",
"otbl_ineq.copy() for b_m in boot_methods: inc_gdp = Dataset(idir_gdp + 'GDP_Changes_Burke_' + b_m +",
"ind80 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']>=0.8)[0] deciles[80] = itbl_gdp_baseline.iloc[ind80].copy() for ds in datasets: scens",
"= 0 #itbl_gdp_baseline['2010_popw_gdp'] = 0 itbl_gdp_baseline[sgdp_year + '_popsum'] = 0 #itbl_gdp_baseline['2010_pop_ratio_sum'] = 0",
"changes#### gdp_year = 2010 sgdp_year = str(gdp_year) boot_methods = ['country-lag0','country-lag1','country-lag5','year','year-blocks'] itbl_gdp_baseline = pd.read_csv(_env.odir_root",
"imtrx_gdp = inc_gdp['GDP'][:] dec_var = {} dec_base = {} for perc in [10,20,80,90]:",
"imtrx_dec_sum/dec_pop_tot dec_var[perc] = dec_gdpcap.copy() dec_diff = (dec_var[90]/dec_var[10]-dec_base[90]/dec_base[10])/(dec_base[90]/dec_base[10])*100 quin_diff = (dec_var[80]/dec_var[20] - dec_base[80]/dec_base[20])/(dec_base[80]/dec_base[20])*100 otbls['deciles'].loc[b_m,'median_ratio']",
"[10,20,80,90]: dec = deciles[perc].copy() dec_pop_tot = dec[sgdp_year + '_pop'].sum() dec_gdp_tot = dec[sgdp_year +",
"pd.read_csv(_env.odir_root + 'basic_stats' + '/Country_Basic_Stats.csv') itbl_gdp_baseline.sort_values([sgdp_year + '_gdpcap'],inplace=True) tot_pop = itbl_gdp_baseline[sgdp_year + '_pop'].sum()",
"= np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']<=0.2)[0] deciles[20] = itbl_gdp_baseline.iloc[ind20].copy() ind80 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']>=0.8)[0] deciles[80]",
"= itbl_gdp_baseline.loc[row,sgdp_year + '_gdp'] itbl_gdp_baseline.loc[row, sgdp_year + '_popsum'] = itbl_gdp_baseline.loc[row,sgdp_year + '_pop'] else:",
"= otbl_ineq.copy() for b_m in boot_methods: inc_gdp = Dataset(idir_gdp + 'GDP_Changes_Burke_' + b_m",
"= Dataset(idir_gdp + 'GDP_Changes_Burke_' + b_m + '_' + str(gdp_year) + '_'+ds+'_'+scen+'.nc') imtrx_gdp",
"dec[sgdp_year + '_pop'].sum() dec_gdp_tot = dec[sgdp_year + '_gdp'].sum() dec_base[perc] = dec_gdp_tot/dec_pop_tot ind_ctry =",
"pd import numpy as np from netCDF4 import Dataset import _env datasets =",
"+ '_gdpsum'] = itbl_gdp_baseline.loc[row,sgdp_year + '_gdp'] itbl_gdp_baseline.loc[row, sgdp_year + '_popsum'] = itbl_gdp_baseline.loc[row,sgdp_year +",
"= str(gdp_year) boot_methods = ['country-lag0','country-lag1','country-lag5','year','year-blocks'] itbl_gdp_baseline = pd.read_csv(_env.odir_root + 'basic_stats' + '/Country_Basic_Stats.csv') itbl_gdp_baseline.sort_values([sgdp_year",
"'_pop_ratio_sum']>=0.9)[0] deciles[90] = itbl_gdp_baseline.iloc[ind90].copy() #quintiles (<=20% and >=80%) ind20 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']<=0.2)[0]",
"'Deciles_and_Quintile_ratio_changes_'+ds+'_'+scen+'_Burke.xls') otbls_ctry_GDP_stat = {} otbls = {} otbl_ineq = pd.DataFrame(index = boot_methods,columns =",
"= boot_methods,columns = ['median_ratio','5_ratio','95_ratio','10_ratio','90_ratio','probability_reduced']) otbls['deciles'] = otbl_ineq.copy() otbls['quintiles'] = otbl_ineq.copy() for b_m in",
"in scens: writer = pd.ExcelWriter(odir_summary + 'Deciles_and_Quintile_ratio_changes_'+ds+'_'+scen+'_Burke.xls') otbls_ctry_GDP_stat = {} otbls = {}",
"= itbl_gdp_baseline.iloc[ind80].copy() for ds in datasets: scens = ['No-Aerosol'] if ds == 'ERA-Interim':",
"dec_var = {} dec_base = {} for perc in [10,20,80,90]: dec = deciles[perc].copy()",
"'basic_stats' + '/Country_Basic_Stats.csv') itbl_gdp_baseline.sort_values([sgdp_year + '_gdpcap'],inplace=True) tot_pop = itbl_gdp_baseline[sgdp_year + '_pop'].sum() #itbl_gdp_baseline['2010_pop_ratio'] =",
"import _env datasets = _env.datasets scenarios = _env.scenarios gdp_year = 2010 sgdp_year =",
"np.median(imtrx_dec_sum),dec_gdp_tot,np.median(imtrx_dec_sum)/dec_gdp_tot) dec_gdpcap = imtrx_dec_sum/dec_pop_tot dec_var[perc] = dec_gdpcap.copy() dec_diff = (dec_var[90]/dec_var[10]-dec_base[90]/dec_base[10])/(dec_base[90]/dec_base[10])*100 quin_diff = (dec_var[80]/dec_var[20]",
"np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']<=0.1)[0] deciles[10] = itbl_gdp_baseline.iloc[ind10].copy() ind90 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']>=0.9)[0] deciles[90] =",
"0: itbl_gdp_baseline.loc[row,sgdp_year + '_gdpsum'] = itbl_gdp_baseline.loc[row,sgdp_year + '_gdp'] itbl_gdp_baseline.loc[row, sgdp_year + '_popsum'] =",
"sgdp_year = str(gdp_year) idir_temp = _env.odir_root + '/sim_temperature/' ####summarize global and regional GDP",
"+ '_gdpsum'].iloc[irow-1] + itbl_gdp_baseline.loc[row,sgdp_year + '_gdp'] itbl_gdp_baseline.loc[row, sgdp_year + '_popsum'] = itbl_gdp_baseline[sgdp_year +",
"= {} ind10 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']<=0.1)[0] deciles[10] = itbl_gdp_baseline.iloc[ind10].copy() ind90 = np.where(itbl_gdp_baseline[sgdp_year",
"if irow == 0: itbl_gdp_baseline.loc[row,sgdp_year + '_gdpsum'] = itbl_gdp_baseline.loc[row,sgdp_year + '_gdp'] itbl_gdp_baseline.loc[row, sgdp_year",
"deciles[80] = itbl_gdp_baseline.iloc[ind80].copy() for ds in datasets: scens = ['No-Aerosol'] if ds ==",
"+ '_'+ds+'_'+scen+'.nc') imtrx_gdp = inc_gdp['GDP'][:] dec_var = {} dec_base = {} for perc",
"imtrx_gdp[:,ind_ctry,:] imtrx_dec_sum = dec_gdp_tot-(imtrx_dec.data).sum(axis=1) # print(perc, np.median(imtrx_dec_sum),dec_gdp_tot,np.median(imtrx_dec_sum)/dec_gdp_tot) dec_gdpcap = imtrx_dec_sum/dec_pop_tot dec_var[perc] = dec_gdpcap.copy()",
"coding: utf-8 -*- ''' This code calculates changes in the ratio between different",
"= itbl_gdp_baseline['2010_pop']/tot_pop itbl_gdp_baseline[sgdp_year + '_gdpsum'] = 0 #itbl_gdp_baseline['2010_popw_gdp'] = 0 itbl_gdp_baseline[sgdp_year + '_popsum']",
"+ ds + '/' odir_summary = _env.odir_root + '/summary_' + ds + '/'",
"np.percentile(dec_diff,90) otbls['deciles'].loc[b_m,'probability_reduced'] = len(dec_diff[dec_diff<0])/np.size(dec_diff) otbls['quintiles'].loc[b_m,'median_ratio'] = np.median(quin_diff) otbls['quintiles'].loc[b_m,'5_ratio'] = np.percentile(quin_diff,5) otbls['quintiles'].loc[b_m,'95_ratio'] = np.percentile(quin_diff,95)",
"quin_diff = (dec_var[80]/dec_var[20] - dec_base[80]/dec_base[20])/(dec_base[80]/dec_base[20])*100 otbls['deciles'].loc[b_m,'median_ratio'] = np.median(dec_diff) otbls['deciles'].loc[b_m,'5_ratio'] = np.percentile(dec_diff,5) otbls['deciles'].loc[b_m,'95_ratio'] =",
"itbl_gdp_baseline.sort_values([sgdp_year + '_gdpcap'],inplace=True) tot_pop = itbl_gdp_baseline[sgdp_year + '_pop'].sum() #itbl_gdp_baseline['2010_pop_ratio'] = itbl_gdp_baseline['2010_pop']/tot_pop itbl_gdp_baseline[sgdp_year +",
"ds in datasets: scens = ['No-Aerosol'] if ds == 'ERA-Interim': scens = ['No-Aerosol','No-Sulfate']",
"sgdp_year + '_popsum'] = itbl_gdp_baseline[sgdp_year + '_popsum'].iloc[irow-1] + itbl_gdp_baseline.loc[row,sgdp_year + '_pop'] itbl_gdp_baseline[sgdp_year +",
"dec_gdp_tot-(imtrx_dec.data).sum(axis=1) # print(perc, np.median(imtrx_dec_sum),dec_gdp_tot,np.median(imtrx_dec_sum)/dec_gdp_tot) dec_gdpcap = imtrx_dec_sum/dec_pop_tot dec_var[perc] = dec_gdpcap.copy() dec_diff = (dec_var[90]/dec_var[10]-dec_base[90]/dec_base[10])/(dec_base[90]/dec_base[10])*100",
"boot_methods = ['country-lag0','country-lag1','country-lag5','year','year-blocks'] itbl_gdp_baseline = pd.read_csv(_env.odir_root + 'basic_stats' + '/Country_Basic_Stats.csv') itbl_gdp_baseline.sort_values([sgdp_year + '_gdpcap'],inplace=True)",
"ds + '/' odir_summary = _env.odir_root + '/summary_' + ds + '/' _env.mkdirs(odir_summary)",
"+ '_pop_ratio_sum']<=0.2)[0] deciles[20] = itbl_gdp_baseline.iloc[ind20].copy() ind80 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']>=0.8)[0] deciles[80] = itbl_gdp_baseline.iloc[ind80].copy()",
"np.median(dec_diff) otbls['deciles'].loc[b_m,'5_ratio'] = np.percentile(dec_diff,5) otbls['deciles'].loc[b_m,'95_ratio'] = np.percentile(dec_diff,95) otbls['deciles'].loc[b_m,'10_ratio'] = np.percentile(dec_diff,10) otbls['deciles'].loc[b_m,'90_ratio'] = np.percentile(dec_diff,90)",
"= {} for perc in [10,20,80,90]: dec = deciles[perc].copy() dec_pop_tot = dec[sgdp_year +",
"for ds in datasets: scens = ['No-Aerosol'] if ds == 'ERA-Interim': scens =",
"+ 'Deciles_and_Quintile_ratio_changes_'+ds+'_'+scen+'_Burke.xls') otbls_ctry_GDP_stat = {} otbls = {} otbl_ineq = pd.DataFrame(index = boot_methods,columns",
"ind10 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']<=0.1)[0] deciles[10] = itbl_gdp_baseline.iloc[ind10].copy() ind90 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']>=0.9)[0]",
"numpy as np from netCDF4 import Dataset import _env datasets = _env.datasets scenarios",
"'_popsum'] = itbl_gdp_baseline.loc[row,sgdp_year + '_pop'] else: itbl_gdp_baseline.loc[row,sgdp_year + '_gdpsum'] = itbl_gdp_baseline[sgdp_year + '_gdpsum'].iloc[irow-1]",
"otbls['deciles'].loc[b_m,'90_ratio'] = np.percentile(dec_diff,90) otbls['deciles'].loc[b_m,'probability_reduced'] = len(dec_diff[dec_diff<0])/np.size(dec_diff) otbls['quintiles'].loc[b_m,'median_ratio'] = np.median(quin_diff) otbls['quintiles'].loc[b_m,'5_ratio'] = np.percentile(quin_diff,5) otbls['quintiles'].loc[b_m,'95_ratio']",
"'ERA-Interim': scens = ['No-Aerosol','No-Sulfate'] idir_gdp = _env.odir_root + '/gdp_' + ds + '/'",
"gdp_year = 2010 sgdp_year = str(gdp_year) boot_methods = ['country-lag0','country-lag1','country-lag5','year','year-blocks'] itbl_gdp_baseline = pd.read_csv(_env.odir_root +",
"np.percentile(dec_diff,5) otbls['deciles'].loc[b_m,'95_ratio'] = np.percentile(dec_diff,95) otbls['deciles'].loc[b_m,'10_ratio'] = np.percentile(dec_diff,10) otbls['deciles'].loc[b_m,'90_ratio'] = np.percentile(dec_diff,90) otbls['deciles'].loc[b_m,'probability_reduced'] = len(dec_diff[dec_diff<0])/np.size(dec_diff)",
"'_popsum']/tot_pop #deciles (<=10% and >=90%) deciles = {} ind10 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']<=0.1)[0]",
"+ str(gdp_year) + '_'+ds+'_'+scen+'.nc') imtrx_gdp = inc_gdp['GDP'][:] dec_var = {} dec_base = {}",
"dec_var[perc] = dec_gdpcap.copy() dec_diff = (dec_var[90]/dec_var[10]-dec_base[90]/dec_base[10])/(dec_base[90]/dec_base[10])*100 quin_diff = (dec_var[80]/dec_var[20] - dec_base[80]/dec_base[20])/(dec_base[80]/dec_base[20])*100 otbls['deciles'].loc[b_m,'median_ratio'] =",
"changes in the ratio between different population-weighted GDP deciles and quintiles by <NAME>",
"otbls['deciles'].loc[b_m,'95_ratio'] = np.percentile(dec_diff,95) otbls['deciles'].loc[b_m,'10_ratio'] = np.percentile(dec_diff,10) otbls['deciles'].loc[b_m,'90_ratio'] = np.percentile(dec_diff,90) otbls['deciles'].loc[b_m,'probability_reduced'] = len(dec_diff[dec_diff<0])/np.size(dec_diff) otbls['quintiles'].loc[b_m,'median_ratio']",
"= np.percentile(quin_diff,5) otbls['quintiles'].loc[b_m,'95_ratio'] = np.percentile(quin_diff,95) otbls['quintiles'].loc[b_m,'10_ratio'] = np.percentile(quin_diff,10) otbls['quintiles'].loc[b_m,'90_ratio'] = np.percentile(quin_diff,90) otbls['quintiles'].loc[b_m,'probability_reduced'] =",
"+ '_pop'] itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum'] = itbl_gdp_baseline[sgdp_year + '_popsum']/tot_pop #deciles (<=10% and >=90%)",
"netCDF4 import Dataset import _env datasets = _env.datasets scenarios = _env.scenarios gdp_year =",
"otbls['quintiles'].loc[b_m,'95_ratio'] = np.percentile(quin_diff,95) otbls['quintiles'].loc[b_m,'10_ratio'] = np.percentile(quin_diff,10) otbls['quintiles'].loc[b_m,'90_ratio'] = np.percentile(quin_diff,90) otbls['quintiles'].loc[b_m,'probability_reduced'] = len(quin_diff[quin_diff<0])/np.size(quin_diff) otbls['deciles'].to_excel(writer,'deciles')",
"import numpy as np from netCDF4 import Dataset import _env datasets = _env.datasets",
"for b_m in boot_methods: inc_gdp = Dataset(idir_gdp + 'GDP_Changes_Burke_' + b_m + '_'",
"= 2010 sgdp_year = str(gdp_year) boot_methods = ['country-lag0','country-lag1','country-lag5','year','year-blocks'] itbl_gdp_baseline = pd.read_csv(_env.odir_root + 'basic_stats'",
"np from netCDF4 import Dataset import _env datasets = _env.datasets scenarios = _env.scenarios",
"= {} otbl_ineq = pd.DataFrame(index = boot_methods,columns = ['median_ratio','5_ratio','95_ratio','10_ratio','90_ratio','probability_reduced']) otbls['deciles'] = otbl_ineq.copy() otbls['quintiles']",
"b_m + '_' + str(gdp_year) + '_'+ds+'_'+scen+'.nc') imtrx_gdp = inc_gdp['GDP'][:] dec_var = {}",
"# -*- coding: utf-8 -*- ''' This code calculates changes in the ratio",
"= dec[sgdp_year + '_pop'].sum() dec_gdp_tot = dec[sgdp_year + '_gdp'].sum() dec_base[perc] = dec_gdp_tot/dec_pop_tot ind_ctry",
"print(perc, np.median(imtrx_dec_sum),dec_gdp_tot,np.median(imtrx_dec_sum)/dec_gdp_tot) dec_gdpcap = imtrx_dec_sum/dec_pop_tot dec_var[perc] = dec_gdpcap.copy() dec_diff = (dec_var[90]/dec_var[10]-dec_base[90]/dec_base[10])/(dec_base[90]/dec_base[10])*100 quin_diff =",
"irow == 0: itbl_gdp_baseline.loc[row,sgdp_year + '_gdpsum'] = itbl_gdp_baseline.loc[row,sgdp_year + '_gdp'] itbl_gdp_baseline.loc[row, sgdp_year +",
"'_gdpsum'].iloc[irow-1] + itbl_gdp_baseline.loc[row,sgdp_year + '_gdp'] itbl_gdp_baseline.loc[row, sgdp_year + '_popsum'] = itbl_gdp_baseline[sgdp_year + '_popsum'].iloc[irow-1]",
"ind20 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']<=0.2)[0] deciles[20] = itbl_gdp_baseline.iloc[ind20].copy() ind80 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']>=0.8)[0]",
"deciles and quintiles by <NAME> (<EMAIL>) ''' import pandas as pd import numpy",
"= np.median(quin_diff) otbls['quintiles'].loc[b_m,'5_ratio'] = np.percentile(quin_diff,5) otbls['quintiles'].loc[b_m,'95_ratio'] = np.percentile(quin_diff,95) otbls['quintiles'].loc[b_m,'10_ratio'] = np.percentile(quin_diff,10) otbls['quintiles'].loc[b_m,'90_ratio'] =",
"####summarize global and regional GDP changes#### gdp_year = 2010 sgdp_year = str(gdp_year) boot_methods",
"str(gdp_year) idir_temp = _env.odir_root + '/sim_temperature/' ####summarize global and regional GDP changes#### gdp_year",
"dec_pop_tot = dec[sgdp_year + '_pop'].sum() dec_gdp_tot = dec[sgdp_year + '_gdp'].sum() dec_base[perc] = dec_gdp_tot/dec_pop_tot",
"str(gdp_year) boot_methods = ['country-lag0','country-lag1','country-lag5','year','year-blocks'] itbl_gdp_baseline = pd.read_csv(_env.odir_root + 'basic_stats' + '/Country_Basic_Stats.csv') itbl_gdp_baseline.sort_values([sgdp_year +",
"+ '_gdp'].sum() dec_base[perc] = dec_gdp_tot/dec_pop_tot ind_ctry = dec.index imtrx_dec = imtrx_gdp[:,ind_ctry,:] imtrx_dec_sum =",
"otbl_ineq = pd.DataFrame(index = boot_methods,columns = ['median_ratio','5_ratio','95_ratio','10_ratio','90_ratio','probability_reduced']) otbls['deciles'] = otbl_ineq.copy() otbls['quintiles'] = otbl_ineq.copy()",
">=80%) ind20 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']<=0.2)[0] deciles[20] = itbl_gdp_baseline.iloc[ind20].copy() ind80 = np.where(itbl_gdp_baseline[sgdp_year +",
"GDP changes#### gdp_year = 2010 sgdp_year = str(gdp_year) boot_methods = ['country-lag0','country-lag1','country-lag5','year','year-blocks'] itbl_gdp_baseline =",
"= np.percentile(dec_diff,5) otbls['deciles'].loc[b_m,'95_ratio'] = np.percentile(dec_diff,95) otbls['deciles'].loc[b_m,'10_ratio'] = np.percentile(dec_diff,10) otbls['deciles'].loc[b_m,'90_ratio'] = np.percentile(dec_diff,90) otbls['deciles'].loc[b_m,'probability_reduced'] =",
"the ratio between different population-weighted GDP deciles and quintiles by <NAME> (<EMAIL>) '''",
"pd.DataFrame(index = boot_methods,columns = ['median_ratio','5_ratio','95_ratio','10_ratio','90_ratio','probability_reduced']) otbls['deciles'] = otbl_ineq.copy() otbls['quintiles'] = otbl_ineq.copy() for b_m",
"'/summary_' + ds + '/' _env.mkdirs(odir_summary) for scen in scens: writer = pd.ExcelWriter(odir_summary",
"+ '/' _env.mkdirs(odir_summary) for scen in scens: writer = pd.ExcelWriter(odir_summary + 'Deciles_and_Quintile_ratio_changes_'+ds+'_'+scen+'_Burke.xls') otbls_ctry_GDP_stat",
"tot_pop = itbl_gdp_baseline[sgdp_year + '_pop'].sum() #itbl_gdp_baseline['2010_pop_ratio'] = itbl_gdp_baseline['2010_pop']/tot_pop itbl_gdp_baseline[sgdp_year + '_gdpsum'] = 0",
"_env.datasets scenarios = _env.scenarios gdp_year = 2010 sgdp_year = str(gdp_year) idir_temp = _env.odir_root",
"= 2010 sgdp_year = str(gdp_year) idir_temp = _env.odir_root + '/sim_temperature/' ####summarize global and",
"= imtrx_dec_sum/dec_pop_tot dec_var[perc] = dec_gdpcap.copy() dec_diff = (dec_var[90]/dec_var[10]-dec_base[90]/dec_base[10])/(dec_base[90]/dec_base[10])*100 quin_diff = (dec_var[80]/dec_var[20] - dec_base[80]/dec_base[20])/(dec_base[80]/dec_base[20])*100",
"+ '/sim_temperature/' ####summarize global and regional GDP changes#### gdp_year = 2010 sgdp_year =",
"scenarios = _env.scenarios gdp_year = 2010 sgdp_year = str(gdp_year) idir_temp = _env.odir_root +",
"otbls['quintiles'].loc[b_m,'median_ratio'] = np.median(quin_diff) otbls['quintiles'].loc[b_m,'5_ratio'] = np.percentile(quin_diff,5) otbls['quintiles'].loc[b_m,'95_ratio'] = np.percentile(quin_diff,95) otbls['quintiles'].loc[b_m,'10_ratio'] = np.percentile(quin_diff,10) otbls['quintiles'].loc[b_m,'90_ratio']",
"== 'ERA-Interim': scens = ['No-Aerosol','No-Sulfate'] idir_gdp = _env.odir_root + '/gdp_' + ds +",
"= _env.odir_root + '/summary_' + ds + '/' _env.mkdirs(odir_summary) for scen in scens:",
"ds + '/' _env.mkdirs(odir_summary) for scen in scens: writer = pd.ExcelWriter(odir_summary + 'Deciles_and_Quintile_ratio_changes_'+ds+'_'+scen+'_Burke.xls')",
"otbls['quintiles'].loc[b_m,'5_ratio'] = np.percentile(quin_diff,5) otbls['quintiles'].loc[b_m,'95_ratio'] = np.percentile(quin_diff,95) otbls['quintiles'].loc[b_m,'10_ratio'] = np.percentile(quin_diff,10) otbls['quintiles'].loc[b_m,'90_ratio'] = np.percentile(quin_diff,90) otbls['quintiles'].loc[b_m,'probability_reduced']",
"= dec.index imtrx_dec = imtrx_gdp[:,ind_ctry,:] imtrx_dec_sum = dec_gdp_tot-(imtrx_dec.data).sum(axis=1) # print(perc, np.median(imtrx_dec_sum),dec_gdp_tot,np.median(imtrx_dec_sum)/dec_gdp_tot) dec_gdpcap =",
"(<=20% and >=80%) ind20 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']<=0.2)[0] deciles[20] = itbl_gdp_baseline.iloc[ind20].copy() ind80 =",
"otbl_ineq.copy() otbls['quintiles'] = otbl_ineq.copy() for b_m in boot_methods: inc_gdp = Dataset(idir_gdp + 'GDP_Changes_Burke_'",
"'_popsum'].iloc[irow-1] + itbl_gdp_baseline.loc[row,sgdp_year + '_pop'] itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum'] = itbl_gdp_baseline[sgdp_year + '_popsum']/tot_pop #deciles",
"+ '_gdpcap'],inplace=True) tot_pop = itbl_gdp_baseline[sgdp_year + '_pop'].sum() #itbl_gdp_baseline['2010_pop_ratio'] = itbl_gdp_baseline['2010_pop']/tot_pop itbl_gdp_baseline[sgdp_year + '_gdpsum']",
"itbl_gdp_baseline[sgdp_year + '_gdpsum'] = 0 #itbl_gdp_baseline['2010_popw_gdp'] = 0 itbl_gdp_baseline[sgdp_year + '_popsum'] = 0",
"itbl_gdp_baseline.loc[row, sgdp_year + '_popsum'] = itbl_gdp_baseline.loc[row,sgdp_year + '_pop'] else: itbl_gdp_baseline.loc[row,sgdp_year + '_gdpsum'] =",
"= (dec_var[90]/dec_var[10]-dec_base[90]/dec_base[10])/(dec_base[90]/dec_base[10])*100 quin_diff = (dec_var[80]/dec_var[20] - dec_base[80]/dec_base[20])/(dec_base[80]/dec_base[20])*100 otbls['deciles'].loc[b_m,'median_ratio'] = np.median(dec_diff) otbls['deciles'].loc[b_m,'5_ratio'] = np.percentile(dec_diff,5)",
"ds == 'ERA-Interim': scens = ['No-Aerosol','No-Sulfate'] idir_gdp = _env.odir_root + '/gdp_' + ds",
"'/gdp_' + ds + '/' odir_summary = _env.odir_root + '/summary_' + ds +",
"and >=90%) deciles = {} ind10 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']<=0.1)[0] deciles[10] = itbl_gdp_baseline.iloc[ind10].copy()",
"= ['median_ratio','5_ratio','95_ratio','10_ratio','90_ratio','probability_reduced']) otbls['deciles'] = otbl_ineq.copy() otbls['quintiles'] = otbl_ineq.copy() for b_m in boot_methods: inc_gdp",
"itbl_gdp_baseline = pd.read_csv(_env.odir_root + 'basic_stats' + '/Country_Basic_Stats.csv') itbl_gdp_baseline.sort_values([sgdp_year + '_gdpcap'],inplace=True) tot_pop = itbl_gdp_baseline[sgdp_year",
"dec = deciles[perc].copy() dec_pop_tot = dec[sgdp_year + '_pop'].sum() dec_gdp_tot = dec[sgdp_year + '_gdp'].sum()",
"+ 'GDP_Changes_Burke_' + b_m + '_' + str(gdp_year) + '_'+ds+'_'+scen+'.nc') imtrx_gdp = inc_gdp['GDP'][:]",
"= np.percentile(quin_diff,95) otbls['quintiles'].loc[b_m,'10_ratio'] = np.percentile(quin_diff,10) otbls['quintiles'].loc[b_m,'90_ratio'] = np.percentile(quin_diff,90) otbls['quintiles'].loc[b_m,'probability_reduced'] = len(quin_diff[quin_diff<0])/np.size(quin_diff) otbls['deciles'].to_excel(writer,'deciles') otbls['quintiles'].to_excel(writer,'quintiles')",
"else: itbl_gdp_baseline.loc[row,sgdp_year + '_gdpsum'] = itbl_gdp_baseline[sgdp_year + '_gdpsum'].iloc[irow-1] + itbl_gdp_baseline.loc[row,sgdp_year + '_gdp'] itbl_gdp_baseline.loc[row,",
"+ '_' + str(gdp_year) + '_'+ds+'_'+scen+'.nc') imtrx_gdp = inc_gdp['GDP'][:] dec_var = {} dec_base",
"= ['No-Aerosol'] if ds == 'ERA-Interim': scens = ['No-Aerosol','No-Sulfate'] idir_gdp = _env.odir_root +",
"0 for irow, row in enumerate(itbl_gdp_baseline.index): if irow == 0: itbl_gdp_baseline.loc[row,sgdp_year + '_gdpsum']",
"+ '_pop'] else: itbl_gdp_baseline.loc[row,sgdp_year + '_gdpsum'] = itbl_gdp_baseline[sgdp_year + '_gdpsum'].iloc[irow-1] + itbl_gdp_baseline.loc[row,sgdp_year +",
"itbl_gdp_baseline[sgdp_year + '_pop'].sum() #itbl_gdp_baseline['2010_pop_ratio'] = itbl_gdp_baseline['2010_pop']/tot_pop itbl_gdp_baseline[sgdp_year + '_gdpsum'] = 0 #itbl_gdp_baseline['2010_popw_gdp'] =",
"= pd.ExcelWriter(odir_summary + 'Deciles_and_Quintile_ratio_changes_'+ds+'_'+scen+'_Burke.xls') otbls_ctry_GDP_stat = {} otbls = {} otbl_ineq = pd.DataFrame(index",
"np.median(quin_diff) otbls['quintiles'].loc[b_m,'5_ratio'] = np.percentile(quin_diff,5) otbls['quintiles'].loc[b_m,'95_ratio'] = np.percentile(quin_diff,95) otbls['quintiles'].loc[b_m,'10_ratio'] = np.percentile(quin_diff,10) otbls['quintiles'].loc[b_m,'90_ratio'] = np.percentile(quin_diff,90)",
"(<EMAIL>) ''' import pandas as pd import numpy as np from netCDF4 import",
"itbl_gdp_baseline.loc[row, sgdp_year + '_popsum'] = itbl_gdp_baseline[sgdp_year + '_popsum'].iloc[irow-1] + itbl_gdp_baseline.loc[row,sgdp_year + '_pop'] itbl_gdp_baseline[sgdp_year",
"+ itbl_gdp_baseline.loc[row,sgdp_year + '_gdp'] itbl_gdp_baseline.loc[row, sgdp_year + '_popsum'] = itbl_gdp_baseline[sgdp_year + '_popsum'].iloc[irow-1] +",
"Dataset(idir_gdp + 'GDP_Changes_Burke_' + b_m + '_' + str(gdp_year) + '_'+ds+'_'+scen+'.nc') imtrx_gdp =",
"'_gdpcap'],inplace=True) tot_pop = itbl_gdp_baseline[sgdp_year + '_pop'].sum() #itbl_gdp_baseline['2010_pop_ratio'] = itbl_gdp_baseline['2010_pop']/tot_pop itbl_gdp_baseline[sgdp_year + '_gdpsum'] =",
"+ '_popsum'] = itbl_gdp_baseline[sgdp_year + '_popsum'].iloc[irow-1] + itbl_gdp_baseline.loc[row,sgdp_year + '_pop'] itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']",
"['No-Aerosol','No-Sulfate'] idir_gdp = _env.odir_root + '/gdp_' + ds + '/' odir_summary = _env.odir_root",
"perc in [10,20,80,90]: dec = deciles[perc].copy() dec_pop_tot = dec[sgdp_year + '_pop'].sum() dec_gdp_tot =",
"dec_gdp_tot = dec[sgdp_year + '_gdp'].sum() dec_base[perc] = dec_gdp_tot/dec_pop_tot ind_ctry = dec.index imtrx_dec =",
"deciles[20] = itbl_gdp_baseline.iloc[ind20].copy() ind80 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']>=0.8)[0] deciles[80] = itbl_gdp_baseline.iloc[ind80].copy() for ds",
"np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']<=0.2)[0] deciles[20] = itbl_gdp_baseline.iloc[ind20].copy() ind80 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']>=0.8)[0] deciles[80] =",
"datasets = _env.datasets scenarios = _env.scenarios gdp_year = 2010 sgdp_year = str(gdp_year) idir_temp",
"gdp_year = 2010 sgdp_year = str(gdp_year) idir_temp = _env.odir_root + '/sim_temperature/' ####summarize global",
"deciles = {} ind10 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']<=0.1)[0] deciles[10] = itbl_gdp_baseline.iloc[ind10].copy() ind90 =",
"itbl_gdp_baseline.loc[row,sgdp_year + '_pop'] else: itbl_gdp_baseline.loc[row,sgdp_year + '_gdpsum'] = itbl_gdp_baseline[sgdp_year + '_gdpsum'].iloc[irow-1] + itbl_gdp_baseline.loc[row,sgdp_year",
"deciles[10] = itbl_gdp_baseline.iloc[ind10].copy() ind90 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']>=0.9)[0] deciles[90] = itbl_gdp_baseline.iloc[ind90].copy() #quintiles (<=20%",
"['median_ratio','5_ratio','95_ratio','10_ratio','90_ratio','probability_reduced']) otbls['deciles'] = otbl_ineq.copy() otbls['quintiles'] = otbl_ineq.copy() for b_m in boot_methods: inc_gdp =",
"writer = pd.ExcelWriter(odir_summary + 'Deciles_and_Quintile_ratio_changes_'+ds+'_'+scen+'_Burke.xls') otbls_ctry_GDP_stat = {} otbls = {} otbl_ineq =",
"boot_methods,columns = ['median_ratio','5_ratio','95_ratio','10_ratio','90_ratio','probability_reduced']) otbls['deciles'] = otbl_ineq.copy() otbls['quintiles'] = otbl_ineq.copy() for b_m in boot_methods:",
"scens: writer = pd.ExcelWriter(odir_summary + 'Deciles_and_Quintile_ratio_changes_'+ds+'_'+scen+'_Burke.xls') otbls_ctry_GDP_stat = {} otbls = {} otbl_ineq",
"- dec_base[80]/dec_base[20])/(dec_base[80]/dec_base[20])*100 otbls['deciles'].loc[b_m,'median_ratio'] = np.median(dec_diff) otbls['deciles'].loc[b_m,'5_ratio'] = np.percentile(dec_diff,5) otbls['deciles'].loc[b_m,'95_ratio'] = np.percentile(dec_diff,95) otbls['deciles'].loc[b_m,'10_ratio'] =",
"= inc_gdp['GDP'][:] dec_var = {} dec_base = {} for perc in [10,20,80,90]: dec",
"+ '_gdpsum'] = itbl_gdp_baseline[sgdp_year + '_gdpsum'].iloc[irow-1] + itbl_gdp_baseline.loc[row,sgdp_year + '_gdp'] itbl_gdp_baseline.loc[row, sgdp_year +",
"= str(gdp_year) idir_temp = _env.odir_root + '/sim_temperature/' ####summarize global and regional GDP changes####",
"b_m in boot_methods: inc_gdp = Dataset(idir_gdp + 'GDP_Changes_Burke_' + b_m + '_' +",
"{} dec_base = {} for perc in [10,20,80,90]: dec = deciles[perc].copy() dec_pop_tot =",
"= dec_gdp_tot-(imtrx_dec.data).sum(axis=1) # print(perc, np.median(imtrx_dec_sum),dec_gdp_tot,np.median(imtrx_dec_sum)/dec_gdp_tot) dec_gdpcap = imtrx_dec_sum/dec_pop_tot dec_var[perc] = dec_gdpcap.copy() dec_diff =",
"from netCDF4 import Dataset import _env datasets = _env.datasets scenarios = _env.scenarios gdp_year",
"'_pop_ratio_sum']<=0.1)[0] deciles[10] = itbl_gdp_baseline.iloc[ind10].copy() ind90 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']>=0.9)[0] deciles[90] = itbl_gdp_baseline.iloc[ind90].copy() #quintiles",
"otbls['quintiles'] = otbl_ineq.copy() for b_m in boot_methods: inc_gdp = Dataset(idir_gdp + 'GDP_Changes_Burke_' +",
"-*- coding: utf-8 -*- ''' This code calculates changes in the ratio between",
"+ '_gdp'] itbl_gdp_baseline.loc[row, sgdp_year + '_popsum'] = itbl_gdp_baseline[sgdp_year + '_popsum'].iloc[irow-1] + itbl_gdp_baseline.loc[row,sgdp_year +",
"dec_gdp_tot/dec_pop_tot ind_ctry = dec.index imtrx_dec = imtrx_gdp[:,ind_ctry,:] imtrx_dec_sum = dec_gdp_tot-(imtrx_dec.data).sum(axis=1) # print(perc, np.median(imtrx_dec_sum),dec_gdp_tot,np.median(imtrx_dec_sum)/dec_gdp_tot)",
"ratio between different population-weighted GDP deciles and quintiles by <NAME> (<EMAIL>) ''' import",
"'_pop'].sum() dec_gdp_tot = dec[sgdp_year + '_gdp'].sum() dec_base[perc] = dec_gdp_tot/dec_pop_tot ind_ctry = dec.index imtrx_dec",
"GDP deciles and quintiles by <NAME> (<EMAIL>) ''' import pandas as pd import",
"= np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']>=0.8)[0] deciles[80] = itbl_gdp_baseline.iloc[ind80].copy() for ds in datasets: scens =",
"itbl_gdp_baseline[sgdp_year + '_gdpsum'].iloc[irow-1] + itbl_gdp_baseline.loc[row,sgdp_year + '_gdp'] itbl_gdp_baseline.loc[row, sgdp_year + '_popsum'] = itbl_gdp_baseline[sgdp_year",
"for scen in scens: writer = pd.ExcelWriter(odir_summary + 'Deciles_and_Quintile_ratio_changes_'+ds+'_'+scen+'_Burke.xls') otbls_ctry_GDP_stat = {} otbls",
"#deciles (<=10% and >=90%) deciles = {} ind10 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']<=0.1)[0] deciles[10]",
"'_'+ds+'_'+scen+'.nc') imtrx_gdp = inc_gdp['GDP'][:] dec_var = {} dec_base = {} for perc in",
"+ b_m + '_' + str(gdp_year) + '_'+ds+'_'+scen+'.nc') imtrx_gdp = inc_gdp['GDP'][:] dec_var =",
"= np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']>=0.9)[0] deciles[90] = itbl_gdp_baseline.iloc[ind90].copy() #quintiles (<=20% and >=80%) ind20 =",
"+ '_pop'].sum() dec_gdp_tot = dec[sgdp_year + '_gdp'].sum() dec_base[perc] = dec_gdp_tot/dec_pop_tot ind_ctry = dec.index",
"for perc in [10,20,80,90]: dec = deciles[perc].copy() dec_pop_tot = dec[sgdp_year + '_pop'].sum() dec_gdp_tot",
"imtrx_dec = imtrx_gdp[:,ind_ctry,:] imtrx_dec_sum = dec_gdp_tot-(imtrx_dec.data).sum(axis=1) # print(perc, np.median(imtrx_dec_sum),dec_gdp_tot,np.median(imtrx_dec_sum)/dec_gdp_tot) dec_gdpcap = imtrx_dec_sum/dec_pop_tot dec_var[perc]",
"+ itbl_gdp_baseline.loc[row,sgdp_year + '_pop'] itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum'] = itbl_gdp_baseline[sgdp_year + '_popsum']/tot_pop #deciles (<=10%",
"itbl_gdp_baseline.loc[row,sgdp_year + '_pop'] itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum'] = itbl_gdp_baseline[sgdp_year + '_popsum']/tot_pop #deciles (<=10% and",
"#quintiles (<=20% and >=80%) ind20 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']<=0.2)[0] deciles[20] = itbl_gdp_baseline.iloc[ind20].copy() ind80",
"''' This code calculates changes in the ratio between different population-weighted GDP deciles",
"and quintiles by <NAME> (<EMAIL>) ''' import pandas as pd import numpy as",
"np.percentile(dec_diff,10) otbls['deciles'].loc[b_m,'90_ratio'] = np.percentile(dec_diff,90) otbls['deciles'].loc[b_m,'probability_reduced'] = len(dec_diff[dec_diff<0])/np.size(dec_diff) otbls['quintiles'].loc[b_m,'median_ratio'] = np.median(quin_diff) otbls['quintiles'].loc[b_m,'5_ratio'] = np.percentile(quin_diff,5)",
"import Dataset import _env datasets = _env.datasets scenarios = _env.scenarios gdp_year = 2010",
"ind_ctry = dec.index imtrx_dec = imtrx_gdp[:,ind_ctry,:] imtrx_dec_sum = dec_gdp_tot-(imtrx_dec.data).sum(axis=1) # print(perc, np.median(imtrx_dec_sum),dec_gdp_tot,np.median(imtrx_dec_sum)/dec_gdp_tot) dec_gdpcap",
"+ 'basic_stats' + '/Country_Basic_Stats.csv') itbl_gdp_baseline.sort_values([sgdp_year + '_gdpcap'],inplace=True) tot_pop = itbl_gdp_baseline[sgdp_year + '_pop'].sum() #itbl_gdp_baseline['2010_pop_ratio']",
"= (dec_var[80]/dec_var[20] - dec_base[80]/dec_base[20])/(dec_base[80]/dec_base[20])*100 otbls['deciles'].loc[b_m,'median_ratio'] = np.median(dec_diff) otbls['deciles'].loc[b_m,'5_ratio'] = np.percentile(dec_diff,5) otbls['deciles'].loc[b_m,'95_ratio'] = np.percentile(dec_diff,95)",
"itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum'] = itbl_gdp_baseline[sgdp_year + '_popsum']/tot_pop #deciles (<=10% and >=90%) deciles =",
"= np.percentile(dec_diff,95) otbls['deciles'].loc[b_m,'10_ratio'] = np.percentile(dec_diff,10) otbls['deciles'].loc[b_m,'90_ratio'] = np.percentile(dec_diff,90) otbls['deciles'].loc[b_m,'probability_reduced'] = len(dec_diff[dec_diff<0])/np.size(dec_diff) otbls['quintiles'].loc[b_m,'median_ratio'] =",
"different population-weighted GDP deciles and quintiles by <NAME> (<EMAIL>) ''' import pandas as",
"dec_base[80]/dec_base[20])/(dec_base[80]/dec_base[20])*100 otbls['deciles'].loc[b_m,'median_ratio'] = np.median(dec_diff) otbls['deciles'].loc[b_m,'5_ratio'] = np.percentile(dec_diff,5) otbls['deciles'].loc[b_m,'95_ratio'] = np.percentile(dec_diff,95) otbls['deciles'].loc[b_m,'10_ratio'] = np.percentile(dec_diff,10)",
"+ '/Country_Basic_Stats.csv') itbl_gdp_baseline.sort_values([sgdp_year + '_gdpcap'],inplace=True) tot_pop = itbl_gdp_baseline[sgdp_year + '_pop'].sum() #itbl_gdp_baseline['2010_pop_ratio'] = itbl_gdp_baseline['2010_pop']/tot_pop",
"-*- ''' This code calculates changes in the ratio between different population-weighted GDP",
"in [10,20,80,90]: dec = deciles[perc].copy() dec_pop_tot = dec[sgdp_year + '_pop'].sum() dec_gdp_tot = dec[sgdp_year",
"= _env.scenarios gdp_year = 2010 sgdp_year = str(gdp_year) idir_temp = _env.odir_root + '/sim_temperature/'",
"import pandas as pd import numpy as np from netCDF4 import Dataset import",
"in datasets: scens = ['No-Aerosol'] if ds == 'ERA-Interim': scens = ['No-Aerosol','No-Sulfate'] idir_gdp",
"itbl_gdp_baseline.iloc[ind90].copy() #quintiles (<=20% and >=80%) ind20 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']<=0.2)[0] deciles[20] = itbl_gdp_baseline.iloc[ind20].copy()",
"'/' odir_summary = _env.odir_root + '/summary_' + ds + '/' _env.mkdirs(odir_summary) for scen",
"population-weighted GDP deciles and quintiles by <NAME> (<EMAIL>) ''' import pandas as pd",
"+ '_gdpsum'] = 0 #itbl_gdp_baseline['2010_popw_gdp'] = 0 itbl_gdp_baseline[sgdp_year + '_popsum'] = 0 #itbl_gdp_baseline['2010_pop_ratio_sum']",
"= itbl_gdp_baseline[sgdp_year + '_gdpsum'].iloc[irow-1] + itbl_gdp_baseline.loc[row,sgdp_year + '_gdp'] itbl_gdp_baseline.loc[row, sgdp_year + '_popsum'] =",
"enumerate(itbl_gdp_baseline.index): if irow == 0: itbl_gdp_baseline.loc[row,sgdp_year + '_gdpsum'] = itbl_gdp_baseline.loc[row,sgdp_year + '_gdp'] itbl_gdp_baseline.loc[row,",
"Dataset import _env datasets = _env.datasets scenarios = _env.scenarios gdp_year = 2010 sgdp_year",
"= len(dec_diff[dec_diff<0])/np.size(dec_diff) otbls['quintiles'].loc[b_m,'median_ratio'] = np.median(quin_diff) otbls['quintiles'].loc[b_m,'5_ratio'] = np.percentile(quin_diff,5) otbls['quintiles'].loc[b_m,'95_ratio'] = np.percentile(quin_diff,95) otbls['quintiles'].loc[b_m,'10_ratio'] =",
"np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']>=0.8)[0] deciles[80] = itbl_gdp_baseline.iloc[ind80].copy() for ds in datasets: scens = ['No-Aerosol']",
"odir_summary = _env.odir_root + '/summary_' + ds + '/' _env.mkdirs(odir_summary) for scen in",
"'_' + str(gdp_year) + '_'+ds+'_'+scen+'.nc') imtrx_gdp = inc_gdp['GDP'][:] dec_var = {} dec_base =",
"+ '/summary_' + ds + '/' _env.mkdirs(odir_summary) for scen in scens: writer =",
"np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']>=0.9)[0] deciles[90] = itbl_gdp_baseline.iloc[ind90].copy() #quintiles (<=20% and >=80%) ind20 = np.where(itbl_gdp_baseline[sgdp_year",
"{} ind10 = np.where(itbl_gdp_baseline[sgdp_year + '_pop_ratio_sum']<=0.1)[0] deciles[10] = itbl_gdp_baseline.iloc[ind10].copy() ind90 = np.where(itbl_gdp_baseline[sgdp_year +",
"'GDP_Changes_Burke_' + b_m + '_' + str(gdp_year) + '_'+ds+'_'+scen+'.nc') imtrx_gdp = inc_gdp['GDP'][:] dec_var",
"'/sim_temperature/' ####summarize global and regional GDP changes#### gdp_year = 2010 sgdp_year = str(gdp_year)",
"between different population-weighted GDP deciles and quintiles by <NAME> (<EMAIL>) ''' import pandas",
"otbls = {} otbl_ineq = pd.DataFrame(index = boot_methods,columns = ['median_ratio','5_ratio','95_ratio','10_ratio','90_ratio','probability_reduced']) otbls['deciles'] = otbl_ineq.copy()",
"by <NAME> (<EMAIL>) ''' import pandas as pd import numpy as np from"
] |
[
"from typing import List mylist: list[int] = [1, 2, 3, 4] print(mylist) mylist",
"# from typing import List mylist: list[int] = [1, 2, 3, 4] print(mylist)",
"import List mylist: list[int] = [1, 2, 3, 4] print(mylist) mylist = '1234'",
"typing import List mylist: list[int] = [1, 2, 3, 4] print(mylist) mylist =",
"List mylist: list[int] = [1, 2, 3, 4] print(mylist) mylist = '1234' print(mylist)"
] |
[
"self.terminal = self.protocol.terminal def do_help(self): public_methods = [function_name for function_name in dir( self)",
"class CommandsHandler: def __init__(self, protocol): self.protocol = protocol self.terminal = self.protocol.terminal def do_help(self):",
"'.join(commands)) def do_echo(self, *args): self.terminal.write(' '.join(args)) def do_whoami(self): self.terminal.write(self.user.username) def do_quit(self): self.terminal.write('Bye!') self.terminal.loseConnection()",
"= self.protocol.terminal def do_help(self): public_methods = [function_name for function_name in dir( self) if",
"protocol): self.protocol = protocol self.terminal = self.protocol.terminal def do_help(self): public_methods = [function_name for",
"commands = [cmd.replace('do_', '', 1) for cmd in public_methods] self.terminal.write('Commands: ' + '",
"cmd in public_methods] self.terminal.write('Commands: ' + ' '.join(commands)) def do_echo(self, *args): self.terminal.write(' '.join(args))",
"dir( self) if function_name.startswith('do_')] commands = [cmd.replace('do_', '', 1) for cmd in public_methods]",
"in public_methods] self.terminal.write('Commands: ' + ' '.join(commands)) def do_echo(self, *args): self.terminal.write(' '.join(args)) def",
"self.terminal.write('Commands: ' + ' '.join(commands)) def do_echo(self, *args): self.terminal.write(' '.join(args)) def do_whoami(self): self.terminal.write(self.user.username)",
"self) if function_name.startswith('do_')] commands = [cmd.replace('do_', '', 1) for cmd in public_methods] self.terminal.write('Commands:",
"= [cmd.replace('do_', '', 1) for cmd in public_methods] self.terminal.write('Commands: ' + ' '.join(commands))",
"' '.join(commands)) def do_echo(self, *args): self.terminal.write(' '.join(args)) def do_whoami(self): self.terminal.write(self.user.username) def do_quit(self): self.terminal.write('Bye!')",
"in dir( self) if function_name.startswith('do_')] commands = [cmd.replace('do_', '', 1) for cmd in",
"function_name.startswith('do_')] commands = [cmd.replace('do_', '', 1) for cmd in public_methods] self.terminal.write('Commands: ' +",
"public_methods] self.terminal.write('Commands: ' + ' '.join(commands)) def do_echo(self, *args): self.terminal.write(' '.join(args)) def do_whoami(self):",
"*args): self.terminal.write(' '.join(args)) def do_whoami(self): self.terminal.write(self.user.username) def do_quit(self): self.terminal.write('Bye!') self.terminal.loseConnection() def do_clear(self): self.terminal.reset()",
"CommandsHandler: def __init__(self, protocol): self.protocol = protocol self.terminal = self.protocol.terminal def do_help(self): public_methods",
"<filename>commands.py class CommandsHandler: def __init__(self, protocol): self.protocol = protocol self.terminal = self.protocol.terminal def",
"= protocol self.terminal = self.protocol.terminal def do_help(self): public_methods = [function_name for function_name in",
"public_methods = [function_name for function_name in dir( self) if function_name.startswith('do_')] commands = [cmd.replace('do_',",
"= [function_name for function_name in dir( self) if function_name.startswith('do_')] commands = [cmd.replace('do_', '',",
"[function_name for function_name in dir( self) if function_name.startswith('do_')] commands = [cmd.replace('do_', '', 1)",
"self.protocol = protocol self.terminal = self.protocol.terminal def do_help(self): public_methods = [function_name for function_name",
"def do_echo(self, *args): self.terminal.write(' '.join(args)) def do_whoami(self): self.terminal.write(self.user.username) def do_quit(self): self.terminal.write('Bye!') self.terminal.loseConnection() def",
"def do_help(self): public_methods = [function_name for function_name in dir( self) if function_name.startswith('do_')] commands",
"for function_name in dir( self) if function_name.startswith('do_')] commands = [cmd.replace('do_', '', 1) for",
"__init__(self, protocol): self.protocol = protocol self.terminal = self.protocol.terminal def do_help(self): public_methods = [function_name",
"1) for cmd in public_methods] self.terminal.write('Commands: ' + ' '.join(commands)) def do_echo(self, *args):",
"function_name in dir( self) if function_name.startswith('do_')] commands = [cmd.replace('do_', '', 1) for cmd",
"def __init__(self, protocol): self.protocol = protocol self.terminal = self.protocol.terminal def do_help(self): public_methods =",
"self.protocol.terminal def do_help(self): public_methods = [function_name for function_name in dir( self) if function_name.startswith('do_')]",
"' + ' '.join(commands)) def do_echo(self, *args): self.terminal.write(' '.join(args)) def do_whoami(self): self.terminal.write(self.user.username) def",
"protocol self.terminal = self.protocol.terminal def do_help(self): public_methods = [function_name for function_name in dir(",
"+ ' '.join(commands)) def do_echo(self, *args): self.terminal.write(' '.join(args)) def do_whoami(self): self.terminal.write(self.user.username) def do_quit(self):",
"do_help(self): public_methods = [function_name for function_name in dir( self) if function_name.startswith('do_')] commands =",
"do_echo(self, *args): self.terminal.write(' '.join(args)) def do_whoami(self): self.terminal.write(self.user.username) def do_quit(self): self.terminal.write('Bye!') self.terminal.loseConnection() def do_clear(self):",
"'', 1) for cmd in public_methods] self.terminal.write('Commands: ' + ' '.join(commands)) def do_echo(self,",
"if function_name.startswith('do_')] commands = [cmd.replace('do_', '', 1) for cmd in public_methods] self.terminal.write('Commands: '",
"[cmd.replace('do_', '', 1) for cmd in public_methods] self.terminal.write('Commands: ' + ' '.join(commands)) def",
"for cmd in public_methods] self.terminal.write('Commands: ' + ' '.join(commands)) def do_echo(self, *args): self.terminal.write('"
] |
[
"self.__relationships relationships[statistic] = dict() for row in ws.iter_rows(values_only=True): if row[0] in relationships[statistic]: for",
"not None and i not in relationships[statistic][row[0]]: relationships[statistic][row[0]].append(i) else: relationships[statistic][row[0]] = [i for",
"row in ws.iter_rows(values_only=True): if row[0] in relationships[statistic]: for ind, i in enumerate(row): if",
"and i is not None] def get_relationships(self): return self.__relationships def build(self, path): wb",
"return self.__relationships def build(self, path): wb = load_workbook(path) for sheet in wb.sheetnames: ws",
"in enumerate(row): if ind > 0 and i is not None and i",
"in enumerate(row) if ind > 0 and i is not None] def get_relationships(self):",
"is not None and i not in relationships[statistic][row[0]]: relationships[statistic][row[0]].append(i) else: relationships[statistic][row[0]] = [i",
"i is not None] def get_relationships(self): return self.__relationships def build(self, path): wb =",
"import load_workbook class ExcelImporter: def __init__(self): self.__relationships = dict() def set_relationships(self, ws, statistic):",
"0 and i is not None] def get_relationships(self): return self.__relationships def build(self, path):",
"not in relationships[statistic][row[0]]: relationships[statistic][row[0]].append(i) else: relationships[statistic][row[0]] = [i for ind, i in enumerate(row)",
"def __init__(self): self.__relationships = dict() def set_relationships(self, ws, statistic): relationships = self.__relationships relationships[statistic]",
"relationships[statistic][row[0]]: relationships[statistic][row[0]].append(i) else: relationships[statistic][row[0]] = [i for ind, i in enumerate(row) if ind",
"and i is not None and i not in relationships[statistic][row[0]]: relationships[statistic][row[0]].append(i) else: relationships[statistic][row[0]]",
"set_relationships(self, ws, statistic): relationships = self.__relationships relationships[statistic] = dict() for row in ws.iter_rows(values_only=True):",
"relationships[statistic]: for ind, i in enumerate(row): if ind > 0 and i is",
"i is not None and i not in relationships[statistic][row[0]]: relationships[statistic][row[0]].append(i) else: relationships[statistic][row[0]] =",
"and i not in relationships[statistic][row[0]]: relationships[statistic][row[0]].append(i) else: relationships[statistic][row[0]] = [i for ind, i",
"dict() for row in ws.iter_rows(values_only=True): if row[0] in relationships[statistic]: for ind, i in",
"openpyxl import load_workbook class ExcelImporter: def __init__(self): self.__relationships = dict() def set_relationships(self, ws,",
"= dict() for row in ws.iter_rows(values_only=True): if row[0] in relationships[statistic]: for ind, i",
"for ind, i in enumerate(row): if ind > 0 and i is not",
"in relationships[statistic][row[0]]: relationships[statistic][row[0]].append(i) else: relationships[statistic][row[0]] = [i for ind, i in enumerate(row) if",
"relationships[statistic] = dict() for row in ws.iter_rows(values_only=True): if row[0] in relationships[statistic]: for ind,",
"relationships[statistic][row[0]] = [i for ind, i in enumerate(row) if ind > 0 and",
"ws, statistic): relationships = self.__relationships relationships[statistic] = dict() for row in ws.iter_rows(values_only=True): if",
"for ind, i in enumerate(row) if ind > 0 and i is not",
"build(self, path): wb = load_workbook(path) for sheet in wb.sheetnames: ws = wb[sheet] self.set_relationships(ws=ws,",
"relationships = self.__relationships relationships[statistic] = dict() for row in ws.iter_rows(values_only=True): if row[0] in",
"__init__(self): self.__relationships = dict() def set_relationships(self, ws, statistic): relationships = self.__relationships relationships[statistic] =",
"in relationships[statistic]: for ind, i in enumerate(row): if ind > 0 and i",
"load_workbook class ExcelImporter: def __init__(self): self.__relationships = dict() def set_relationships(self, ws, statistic): relationships",
"for row in ws.iter_rows(values_only=True): if row[0] in relationships[statistic]: for ind, i in enumerate(row):",
"else: relationships[statistic][row[0]] = [i for ind, i in enumerate(row) if ind > 0",
"ind, i in enumerate(row) if ind > 0 and i is not None]",
"None] def get_relationships(self): return self.__relationships def build(self, path): wb = load_workbook(path) for sheet",
"ind > 0 and i is not None and i not in relationships[statistic][row[0]]:",
"= [i for ind, i in enumerate(row) if ind > 0 and i",
"> 0 and i is not None] def get_relationships(self): return self.__relationships def build(self,",
"= self.__relationships relationships[statistic] = dict() for row in ws.iter_rows(values_only=True): if row[0] in relationships[statistic]:",
"i not in relationships[statistic][row[0]]: relationships[statistic][row[0]].append(i) else: relationships[statistic][row[0]] = [i for ind, i in",
"= dict() def set_relationships(self, ws, statistic): relationships = self.__relationships relationships[statistic] = dict() for",
"if ind > 0 and i is not None and i not in",
"path): wb = load_workbook(path) for sheet in wb.sheetnames: ws = wb[sheet] self.set_relationships(ws=ws, statistic=sheet)",
"None and i not in relationships[statistic][row[0]]: relationships[statistic][row[0]].append(i) else: relationships[statistic][row[0]] = [i for ind,",
"ws.iter_rows(values_only=True): if row[0] in relationships[statistic]: for ind, i in enumerate(row): if ind >",
"def set_relationships(self, ws, statistic): relationships = self.__relationships relationships[statistic] = dict() for row in",
"self.__relationships = dict() def set_relationships(self, ws, statistic): relationships = self.__relationships relationships[statistic] = dict()",
"dict() def set_relationships(self, ws, statistic): relationships = self.__relationships relationships[statistic] = dict() for row",
"statistic): relationships = self.__relationships relationships[statistic] = dict() for row in ws.iter_rows(values_only=True): if row[0]",
"ExcelImporter: def __init__(self): self.__relationships = dict() def set_relationships(self, ws, statistic): relationships = self.__relationships",
"from openpyxl import load_workbook class ExcelImporter: def __init__(self): self.__relationships = dict() def set_relationships(self,",
"row[0] in relationships[statistic]: for ind, i in enumerate(row): if ind > 0 and",
"not None] def get_relationships(self): return self.__relationships def build(self, path): wb = load_workbook(path) for",
"get_relationships(self): return self.__relationships def build(self, path): wb = load_workbook(path) for sheet in wb.sheetnames:",
"class ExcelImporter: def __init__(self): self.__relationships = dict() def set_relationships(self, ws, statistic): relationships =",
"> 0 and i is not None and i not in relationships[statistic][row[0]]: relationships[statistic][row[0]].append(i)",
"self.__relationships def build(self, path): wb = load_workbook(path) for sheet in wb.sheetnames: ws =",
"if ind > 0 and i is not None] def get_relationships(self): return self.__relationships",
"if row[0] in relationships[statistic]: for ind, i in enumerate(row): if ind > 0",
"i in enumerate(row) if ind > 0 and i is not None] def",
"def get_relationships(self): return self.__relationships def build(self, path): wb = load_workbook(path) for sheet in",
"ind, i in enumerate(row): if ind > 0 and i is not None",
"[i for ind, i in enumerate(row) if ind > 0 and i is",
"relationships[statistic][row[0]].append(i) else: relationships[statistic][row[0]] = [i for ind, i in enumerate(row) if ind >",
"ind > 0 and i is not None] def get_relationships(self): return self.__relationships def",
"def build(self, path): wb = load_workbook(path) for sheet in wb.sheetnames: ws = wb[sheet]",
"is not None] def get_relationships(self): return self.__relationships def build(self, path): wb = load_workbook(path)",
"in ws.iter_rows(values_only=True): if row[0] in relationships[statistic]: for ind, i in enumerate(row): if ind",
"i in enumerate(row): if ind > 0 and i is not None and",
"enumerate(row) if ind > 0 and i is not None] def get_relationships(self): return",
"0 and i is not None and i not in relationships[statistic][row[0]]: relationships[statistic][row[0]].append(i) else:",
"<filename>dataspot-bokeh/dataspot/statistics/excel_importer.py<gh_stars>1-10 from openpyxl import load_workbook class ExcelImporter: def __init__(self): self.__relationships = dict() def",
"enumerate(row): if ind > 0 and i is not None and i not"
] |
[
"rect4, title='RectCent: [1,-0.5], W: [0.5,1.0]', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) # Show Unions savedict[\"savename\"]=\"sphere_union_2d.jpg\"",
"2D Value zero - set as cyan contour. Author: <NAME>, October 29, 2021",
"-2*np.ones((2, 1),dtype=np.float64) g2max = +2*np.ones((2, 1),dtype=np.float64) g2N = 51*np.ones((2, 1),dtype=np.int64) g2 = createGrid(g2min,",
"fig, rect3, title='RectCorner: [1,-0.5], W: [0.5,1.0]', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect4_2d.jpg\" plt.clf() ax",
"'-dl', type=float, default=3, help='pause time between successive updates of plots' ) args =",
"savedict[\"savename\"]=\"rect_union_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2,",
"shapeUnion(rect, rect3) rect_comp = shapeComplement(rect2) sph_rect_diff = shapeDifference(sphere, rect) fig = plt.figure(figsize=(16, 9))",
"[plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect, title='Unit Square@Origin', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect2_2d.jpg\" plt.clf()",
"levelset_viz(g2, ax, fig, rect_comp, title='Rect Complement', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"sph_rect_diff_2d.jpg\" plt.clf() ax",
"fig, sph_rect_diff, title='Sphere-Rect Diff', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) if __name__ == '__main__': savedict",
"fig) ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] savedict[\"savename\"] =",
"<NAME>, October 29, 2021 \"\"\" ax[0].plot_surface(g.xs[0], g.xs[1], mesh, rstride=1, cstride=1, cmap='viridis', edgecolor=ec, facecolor=fc)",
"import abspath, dirname, exists, join sys.path.append(dirname(dirname(abspath(__file__)))) from Grids import createGrid from InitialConditions import",
"for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect, title='Unit Square@Origin', savedict=savedict,",
"np.float64).T g2 = get_grid() # shapes generation axis_align, radius=2, 1 cylinder = shapeCylinder(g2,",
"savedict[\"save\"]: plt.savefig(join(savedict[\"savepath\"],savedict[\"savename\"]), bbox_inches='tight',facecolor='None') fig.canvas.draw() fig.canvas.flush_events() def get_grid(): g2min = -2*np.ones((2, 1),dtype=np.float64) g2max =",
"fontdict=fontdict) ax[0].set_ylabel('Y', fontdict=fontdict) ax[0].set_zlabel('Z', fontdict=fontdict) ax[0].set_title(f'{title}', fontdict=fontdict) ax[1].contourf(g.xs[0], g.xs[1], mesh, colors=fc) ax[1].set_xlabel('X', fontdict=fontdict)",
"2D Value function as colored contour levels Chart 133: 2D Value zero -",
"i in range(2)] + [plt.subplot(gs[2])] savedict[\"savename\"] = \"cylinder_2d.jpg\" levelset_viz(g2, ax, fig, cylinder, title='Cylinder',",
"savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) if __name__ == '__main__': savedict = dict(save=True, savename='cyl_2d.jpg',\\ savepath=join(\"..\",",
"133: 2D Value zero - set as cyan contour. Author: <NAME>, October 29,",
"i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sphere2, title='Sphere, C=(-.5, .5)', savedict=savedict,",
"'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"] = \"sphere_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in",
"of a value function on a 1X3 chart: Chart 131: 2D Value function",
"as plt import matplotlib.gridspec as gridspec \"\"\" Test Implicit Functions Lekan Molu, September",
"fontdict=fontdict) fig.tight_layout() if savedict[\"save\"]: plt.savefig(join(savedict[\"savepath\"],savedict[\"savename\"]), bbox_inches='tight',facecolor='None') fig.canvas.draw() fig.canvas.flush_events() def get_grid(): g2min = -2*np.ones((2,",
"savedict[\"savename\"]=\"sphere2_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2,",
"savedict=None, fontdict=None, fc='c', ec='k'): \"\"\" Simultaneously visualize the level sets of a value",
"g2max = +2*np.ones((2, 1),dtype=np.float64) g2N = 51*np.ones((2, 1),dtype=np.int64) g2 = createGrid(g2min, g2max, g2N,",
"title='Sphere-Rect Diff', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) if __name__ == '__main__': savedict = dict(save=True,",
"center, radius=1) sphere2 = shapeSphere(g2, center=np.array(([-0., 0.])).T, radius=1) rect = shapeRectangleByCorners(g2) rect2 =",
"= argparse.ArgumentParser(description='2D Plotter for Various Implicit Initial Conditions for the Value Function') parser.add_argument('--delay',",
"mesh, colors=fc) ax[1].set_xlabel('X', fontdict=fontdict) ax[1].set_title(f'Contours', fontdict=fontdict) ax[2].contour(g.xs[0], g.xs[1], mesh, levels=0, colors=fc) ax[2].set_xlabel('X', fontdict=fontdict)",
"chart: Chart 131: 2D Value function as a surface mesh Chart 132: 2D",
"ax, fig, sphere, title='Sphere', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"sphere2_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i],",
"131: 2D Value function as a surface mesh Chart 132: 2D Value function",
"g2 def main(savedict): # generate signed distance function for cylinder center = np.array(([[-.5,.5]]),",
"fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)]",
"= get_grid() # shapes generation axis_align, radius=2, 1 cylinder = shapeCylinder(g2, axis_align, center,",
"projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sphere, title='Sphere', savedict=savedict,",
"g.xs[1], mesh, colors=fc) ax[1].set_xlabel('X', fontdict=fontdict) ax[1].set_title(f'Contours', fontdict=fontdict) ax[2].contour(g.xs[0], g.xs[1], mesh, levels=0, colors=fc) ax[2].set_xlabel('X',",
"savedict[\"savename\"]=\"sphere_union_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2,",
"plt.pause(args.delay) savedict[\"savename\"]=\"sphere2_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])]",
"successive updates of plots' ) args = parser.parse_args() def levelset_viz(g, ax, fig, mesh,",
"ax, fig, mesh, title='', savedict=None, fontdict=None, fc='c', ec='k'): \"\"\" Simultaneously visualize the level",
"Implicit Initial Conditions for the Value Function') parser.add_argument('--delay', '-dl', type=float, default=3, help='pause time",
"__status__ = \"Completed\" import argparse from mpl_toolkits.mplot3d import Axes3D import numpy as np",
"Hamilton-Jacobi Analysis in Python\" __license__ = \"Molux Licence\" __maintainer__ = \"<NAME>\" __email__ =",
"for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect3, title='RectCorner: [1,-0.5], W:",
"shapeRectangleByCorners(g2, np.array([[ -1.0, -0.5, ]]).T, np.array([[ .5, 1.0 ]]).T) rect4 = shapeRectangleByCenter(g2, np.array([[",
"Chart 133: 2D Value zero - set as cyan contour. Author: <NAME>, October",
"]]).T) rect4 = shapeRectangleByCenter(g2, np.array([[ -1.0, -0.5, ]]).T, np.array([[ .5, 1.0 ]]).T) #",
"+ [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect_union, title='Union of 2 Rects', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'})",
"September 07, 2021 \"\"\" parser = argparse.ArgumentParser(description='2D Plotter for Various Implicit Initial Conditions",
"[plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect3, title='RectCorner: [1,-0.5], W: [0.5,1.0]', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay)",
"= plt.figure(figsize=(16, 9)) gs = gridspec.GridSpec(1, 3, fig) ax = [plt.subplot(gs[i], projection='3d') for",
"Chart 132: 2D Value function as colored contour levels Chart 133: 2D Value",
"title='RectCorner: [1,-0.5], W: [0.5,1.0]', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect4_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i],",
"generate signed distance function for cylinder center = np.array(([[-.5,.5]]), np.float64).T g2 = get_grid()",
"join sys.path.append(dirname(dirname(abspath(__file__)))) from Grids import createGrid from InitialConditions import * from Visualization import",
"np.array([[ .5, 1.0 ]]).T) rect4 = shapeRectangleByCenter(g2, np.array([[ -1.0, -0.5, ]]).T, np.array([[ .5,",
"[plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect, title='Unit",
"savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"sphere2_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in",
"+ [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sphere_union, title='Spheres+Sphere', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_union_2d.jpg\" plt.clf()",
"rect, title='Unit Square@Origin', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect2_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d')",
"np import os, sys from os.path import abspath, dirname, exists, join sys.path.append(dirname(dirname(abspath(__file__)))) from",
"-1.0, -0.5, ]]).T, np.array([[ .5, 1.0 ]]).T) # Set Ops sphere_union = shapeUnion(sphere,",
"levelset_viz(g2, ax, fig, rect4, title='RectCent: [1,-0.5], W: [0.5,1.0]', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) #",
"fontdict=fontdict) ax[2].set_ylabel('Y', fontdict=fontdict) ax[2].grid('on') ax[2].set_title(f'2D Zero level set', fontdict=fontdict) fig.tight_layout() if savedict[\"save\"]: plt.savefig(join(savedict[\"savepath\"],savedict[\"savename\"]),",
"__license__ = \"Molux Licence\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" __status__ = \"Completed\"",
"ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] savedict[\"savename\"] = \"cylinder_2d.jpg\"",
"projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect_union, title='Union of",
"ax, fig, sphere2, title='Sphere, C=(-.5, .5)', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_2d.jpg\" plt.clf() ax",
"a 1X3 chart: Chart 131: 2D Value function as a surface mesh Chart",
"Show Unions savedict[\"savename\"]=\"sphere_union_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] +",
"sets of a value function on a 1X3 chart: Chart 131: 2D Value",
"on a 1X3 chart: Chart 131: 2D Value function as a surface mesh",
"[plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sphere, title='Sphere',",
"for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sphere2, title='Sphere, C=(-.5, .5)',",
"rect_comp = shapeComplement(rect2) sph_rect_diff = shapeDifference(sphere, rect) fig = plt.figure(figsize=(16, 9)) gs =",
"function on a 1X3 chart: Chart 131: 2D Value function as a surface",
"'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect3_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] +",
"Value function as a surface mesh Chart 132: 2D Value function as colored",
"Functions Lekan Molu, September 07, 2021 \"\"\" parser = argparse.ArgumentParser(description='2D Plotter for Various",
"1.0 ]]).T) rect4 = shapeRectangleByCenter(g2, np.array([[ -1.0, -0.5, ]]).T, np.array([[ .5, 1.0 ]]).T)",
"title='Rect Complement', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"sph_rect_diff_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for",
"set', fontdict=fontdict) fig.tight_layout() if savedict[\"save\"]: plt.savefig(join(savedict[\"savepath\"],savedict[\"savename\"]), bbox_inches='tight',facecolor='None') fig.canvas.draw() fig.canvas.flush_events() def get_grid(): g2min =",
"[plt.subplot(gs[2])] savedict[\"savename\"] = \"cylinder_2d.jpg\" levelset_viz(g2, ax, fig, cylinder, title='Cylinder', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay)",
"Author: <NAME>, October 29, 2021 \"\"\" ax[0].plot_surface(g.xs[0], g.xs[1], mesh, rstride=1, cstride=1, cmap='viridis', edgecolor=ec,",
"colors=fc) ax[1].set_xlabel('X', fontdict=fontdict) ax[1].set_title(f'Contours', fontdict=fontdict) ax[2].contour(g.xs[0], g.xs[1], mesh, levels=0, colors=fc) ax[2].set_xlabel('X', fontdict=fontdict) ax[2].set_ylabel('Y',",
"radius); sphere = shapeSphere(g2, center, radius=1) sphere2 = shapeSphere(g2, center=np.array(([-0., 0.])).T, radius=1) rect",
"'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect2_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] +",
"__email__ = \"<EMAIL>\" __status__ = \"Completed\" import argparse from mpl_toolkits.mplot3d import Axes3D import",
"savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"] = \"sphere_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for",
"ax[0].set_xlabel('X', fontdict=fontdict) ax[0].set_ylabel('Y', fontdict=fontdict) ax[0].set_zlabel('Z', fontdict=fontdict) ax[0].set_title(f'{title}', fontdict=fontdict) ax[1].contourf(g.xs[0], g.xs[1], mesh, colors=fc) ax[1].set_xlabel('X',",
"savedict[\"savename\"]=\"rect3_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2,",
"np.array([[ -1.0, -np.inf, ]]).T, np.array([[ np.inf, -1.0 ]]).T, ) rect3 = shapeRectangleByCorners(g2, np.array([[",
"levelset_viz(g2, ax, fig, rect_union, title='Union of 2 Rects', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_comp_2d.jpg\"",
"projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect2, title='Rect by",
"import createGrid from InitialConditions import * from Visualization import * import matplotlib.pyplot as",
"[plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sph_rect_diff, title='Sphere-Rect Diff', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) if __name__",
"\"<NAME>\" __email__ = \"<EMAIL>\" __status__ = \"Completed\" import argparse from mpl_toolkits.mplot3d import Axes3D",
"np.array([[ -1.0, -0.5, ]]).T, np.array([[ .5, 1.0 ]]).T) # Set Ops sphere_union =",
"[plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect4, title='RectCent: [1,-0.5], W: [0.5,1.0]', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay)",
"savedict[\"savename\"]=\"sph_rect_diff_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2,",
"for Various Implicit Initial Conditions for the Value Function') parser.add_argument('--delay', '-dl', type=float, default=3,",
"fig, rect4, title='RectCent: [1,-0.5], W: [0.5,1.0]', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) # Show Unions",
"-1.0, -0.5, ]]).T, np.array([[ .5, 1.0 ]]).T) rect4 = shapeRectangleByCenter(g2, np.array([[ -1.0, -0.5,",
"a value function on a 1X3 chart: Chart 131: 2D Value function as",
"* import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec \"\"\" Test Implicit Functions",
"Implicit Functions Lekan Molu, September 07, 2021 \"\"\" parser = argparse.ArgumentParser(description='2D Plotter for",
"ax, fig, rect, title='Unit Square@Origin', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect2_2d.jpg\" plt.clf() ax =",
"= [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sph_rect_diff,",
"contour. Author: <NAME>, October 29, 2021 \"\"\" ax[0].plot_surface(g.xs[0], g.xs[1], mesh, rstride=1, cstride=1, cmap='viridis',",
"np.array(([[-.5,.5]]), np.float64).T g2 = get_grid() # shapes generation axis_align, radius=2, 1 cylinder =",
"ax[1].contourf(g.xs[0], g.xs[1], mesh, colors=fc) ax[1].set_xlabel('X', fontdict=fontdict) ax[1].set_title(f'Contours', fontdict=fontdict) ax[2].contour(g.xs[0], g.xs[1], mesh, levels=0, colors=fc)",
"rect3 = shapeRectangleByCorners(g2, np.array([[ -1.0, -0.5, ]]).T, np.array([[ .5, 1.0 ]]).T) rect4 =",
"\"cylinder_2d.jpg\" levelset_viz(g2, ax, fig, cylinder, title='Cylinder', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"] = \"sphere_2d.jpg\"",
"radius=1) rect = shapeRectangleByCorners(g2) rect2 = shapeRectangleByCorners(g2, np.array([[ -1.0, -np.inf, ]]).T, np.array([[ np.inf,",
"Plotter for Various Implicit Initial Conditions for the Value Function') parser.add_argument('--delay', '-dl', type=float,",
"= [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect2,",
"fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_union_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)]",
".5)', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i",
"title='', savedict=None, fontdict=None, fc='c', ec='k'): \"\"\" Simultaneously visualize the level sets of a",
"W: [0.5,1.0]', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect4_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for",
"2D Value function as a surface mesh Chart 132: 2D Value function as",
"plt.pause(args.delay) savedict[\"savename\"] = \"sphere_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)]",
"= \"cylinder_2d.jpg\" levelset_viz(g2, ax, fig, cylinder, title='Cylinder', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"] =",
"as np import os, sys from os.path import abspath, dirname, exists, join sys.path.append(dirname(dirname(abspath(__file__))))",
"fig, sphere2, title='Sphere, C=(-.5, .5)', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_2d.jpg\" plt.clf() ax =",
"levelset_viz(g2, ax, fig, rect2, title='Rect by Corners', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect3_2d.jpg\" plt.clf()",
"from Grids import createGrid from InitialConditions import * from Visualization import * import",
"shapeRectangleByCorners(g2) rect2 = shapeRectangleByCorners(g2, np.array([[ -1.0, -np.inf, ]]).T, np.array([[ np.inf, -1.0 ]]).T, )",
"Axes3D import numpy as np import os, sys from os.path import abspath, dirname,",
"ax[2].set_ylabel('Y', fontdict=fontdict) ax[2].grid('on') ax[2].set_title(f'2D Zero level set', fontdict=fontdict) fig.tight_layout() if savedict[\"save\"]: plt.savefig(join(savedict[\"savepath\"],savedict[\"savename\"]), bbox_inches='tight',facecolor='None')",
"fontdict=fontdict) ax[0].set_title(f'{title}', fontdict=fontdict) ax[1].contourf(g.xs[0], g.xs[1], mesh, colors=fc) ax[1].set_xlabel('X', fontdict=fontdict) ax[1].set_title(f'Contours', fontdict=fontdict) ax[2].contour(g.xs[0], g.xs[1],",
"shapeRectangleByCorners(g2, np.array([[ -1.0, -np.inf, ]]).T, np.array([[ np.inf, -1.0 ]]).T, ) rect3 = shapeRectangleByCorners(g2,",
"-0.5, ]]).T, np.array([[ .5, 1.0 ]]).T) rect4 = shapeRectangleByCenter(g2, np.array([[ -1.0, -0.5, ]]).T,",
"fig, rect2, title='Rect by Corners', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect3_2d.jpg\" plt.clf() ax =",
"levelset_viz(g2, ax, fig, cylinder, title='Cylinder', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"] = \"sphere_2d.jpg\" plt.clf()",
"[plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] savedict[\"savename\"] = \"cylinder_2d.jpg\" levelset_viz(g2, ax,",
"fc='c', ec='k'): \"\"\" Simultaneously visualize the level sets of a value function on",
"levels=0, colors=fc) ax[2].set_xlabel('X', fontdict=fontdict) ax[2].set_ylabel('Y', fontdict=fontdict) ax[2].grid('on') ax[2].set_title(f'2D Zero level set', fontdict=fontdict) fig.tight_layout()",
"fig, mesh, title='', savedict=None, fontdict=None, fc='c', ec='k'): \"\"\" Simultaneously visualize the level sets",
"fig.tight_layout() if savedict[\"save\"]: plt.savefig(join(savedict[\"savepath\"],savedict[\"savename\"]), bbox_inches='tight',facecolor='None') fig.canvas.draw() fig.canvas.flush_events() def get_grid(): g2min = -2*np.ones((2, 1),dtype=np.float64)",
"fig, rect, title='Unit Square@Origin', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect2_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i],",
"sphere, title='Sphere', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"sphere2_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for",
"[plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect_comp, title='Rect",
"'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect4_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] +",
"from mpl_toolkits.mplot3d import Axes3D import numpy as np import os, sys from os.path",
"mesh Chart 132: 2D Value function as colored contour levels Chart 133: 2D",
"+ [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect_comp, title='Rect Complement', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"sph_rect_diff_2d.jpg\"",
"distance function for cylinder center = np.array(([[-.5,.5]]), np.float64).T g2 = get_grid() # shapes",
"savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect4_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in",
"sphere_union = shapeUnion(sphere, sphere2) rect_union = shapeUnion(rect, rect3) rect_comp = shapeComplement(rect2) sph_rect_diff =",
"07, 2021 \"\"\" parser = argparse.ArgumentParser(description='2D Plotter for Various Implicit Initial Conditions for",
"Corners', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect3_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i",
"levelset_viz(g2, ax, fig, sphere, title='Sphere', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"sphere2_2d.jpg\" plt.clf() ax =",
"fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) if __name__ == '__main__': savedict = dict(save=True, savename='cyl_2d.jpg',\\ savepath=join(\"..\", \"jpeg_dumps\"))",
"Value zero - set as cyan contour. Author: <NAME>, October 29, 2021 \"\"\"",
"levelset_viz(g2, ax, fig, sphere2, title='Sphere, C=(-.5, .5)', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_2d.jpg\" plt.clf()",
"import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec \"\"\" Test Implicit Functions Lekan",
"from Visualization import * import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec \"\"\"",
".5, 1.0 ]]).T) rect4 = shapeRectangleByCenter(g2, np.array([[ -1.0, -0.5, ]]).T, np.array([[ .5, 1.0",
"Complement', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"sph_rect_diff_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i",
"+ [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect4, title='RectCent: [1,-0.5], W: [0.5,1.0]', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'})",
"+ [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect3, title='RectCorner: [1,-0.5], W: [0.5,1.0]', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'})",
"# shapes generation axis_align, radius=2, 1 cylinder = shapeCylinder(g2, axis_align, center, radius); sphere",
"plt.pause(args.delay) # Show Unions savedict[\"savename\"]=\"sphere_union_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in",
"default=3, help='pause time between successive updates of plots' ) args = parser.parse_args() def",
"range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sphere2, title='Sphere, C=(-.5, .5)', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'})",
"sph_rect_diff, title='Sphere-Rect Diff', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) if __name__ == '__main__': savedict =",
"]]).T, np.array([[ .5, 1.0 ]]).T) # Set Ops sphere_union = shapeUnion(sphere, sphere2) rect_union",
"rect2, title='Rect by Corners', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect3_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i],",
"g2 = get_grid() # shapes generation axis_align, radius=2, 1 cylinder = shapeCylinder(g2, axis_align,",
"\"Completed\" import argparse from mpl_toolkits.mplot3d import Axes3D import numpy as np import os,",
"title='Sphere, C=(-.5, .5)', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d')",
"for the Value Function') parser.add_argument('--delay', '-dl', type=float, default=3, help='pause time between successive updates",
"in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect_union, title='Union of 2 Rects', savedict=savedict,",
"projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect_comp, title='Rect Complement',",
"g2 = createGrid(g2min, g2max, g2N, process=True) return g2 def main(savedict): # generate signed",
"shapes generation axis_align, radius=2, 1 cylinder = shapeCylinder(g2, axis_align, center, radius); sphere =",
"help='pause time between successive updates of plots' ) args = parser.parse_args() def levelset_viz(g,",
"1),dtype=np.int64) g2 = createGrid(g2min, g2max, g2N, process=True) return g2 def main(savedict): # generate",
"np.array([[ .5, 1.0 ]]).T) # Set Ops sphere_union = shapeUnion(sphere, sphere2) rect_union =",
"ax[2].set_title(f'2D Zero level set', fontdict=fontdict) fig.tight_layout() if savedict[\"save\"]: plt.savefig(join(savedict[\"savepath\"],savedict[\"savename\"]), bbox_inches='tight',facecolor='None') fig.canvas.draw() fig.canvas.flush_events() def",
"2021 \"\"\" parser = argparse.ArgumentParser(description='2D Plotter for Various Implicit Initial Conditions for the",
"g2N, process=True) return g2 def main(savedict): # generate signed distance function for cylinder",
"InitialConditions import * from Visualization import * import matplotlib.pyplot as plt import matplotlib.gridspec",
"facecolor=fc) ax[0].set_xlabel('X', fontdict=fontdict) ax[0].set_ylabel('Y', fontdict=fontdict) ax[0].set_zlabel('Z', fontdict=fontdict) ax[0].set_title(f'{title}', fontdict=fontdict) ax[1].contourf(g.xs[0], g.xs[1], mesh, colors=fc)",
"np.array([[ np.inf, -1.0 ]]).T, ) rect3 = shapeRectangleByCorners(g2, np.array([[ -1.0, -0.5, ]]).T, np.array([[",
"return g2 def main(savedict): # generate signed distance function for cylinder center =",
"9)) gs = gridspec.GridSpec(1, 3, fig) ax = [plt.subplot(gs[i], projection='3d') for i in",
"- set as cyan contour. Author: <NAME>, October 29, 2021 \"\"\" ax[0].plot_surface(g.xs[0], g.xs[1],",
"generation axis_align, radius=2, 1 cylinder = shapeCylinder(g2, axis_align, center, radius); sphere = shapeSphere(g2,",
"cstride=1, cmap='viridis', edgecolor=ec, facecolor=fc) ax[0].set_xlabel('X', fontdict=fontdict) ax[0].set_ylabel('Y', fontdict=fontdict) ax[0].set_zlabel('Z', fontdict=fontdict) ax[0].set_title(f'{title}', fontdict=fontdict) ax[1].contourf(g.xs[0],",
"\"2021, Hamilton-Jacobi Analysis in Python\" __license__ = \"Molux Licence\" __maintainer__ = \"<NAME>\" __email__",
"process=True) return g2 def main(savedict): # generate signed distance function for cylinder center",
"fontdict=fontdict) ax[1].set_title(f'Contours', fontdict=fontdict) ax[2].contour(g.xs[0], g.xs[1], mesh, levels=0, colors=fc) ax[2].set_xlabel('X', fontdict=fontdict) ax[2].set_ylabel('Y', fontdict=fontdict) ax[2].grid('on')",
"0.])).T, radius=1) rect = shapeRectangleByCorners(g2) rect2 = shapeRectangleByCorners(g2, np.array([[ -1.0, -np.inf, ]]).T, np.array([[",
"range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect_union, title='Union of 2 Rects', savedict=savedict, fontdict={'fontsize':12,",
"g2max, g2N, process=True) return g2 def main(savedict): # generate signed distance function for",
"= [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sphere,",
"range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect_comp, title='Rect Complement', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay)",
"\"\"\" Simultaneously visualize the level sets of a value function on a 1X3",
"Various Implicit Initial Conditions for the Value Function') parser.add_argument('--delay', '-dl', type=float, default=3, help='pause",
"Square@Origin', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect2_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i",
"# Show Unions savedict[\"savename\"]=\"sphere_union_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)]",
"cyan contour. Author: <NAME>, October 29, 2021 \"\"\" ax[0].plot_surface(g.xs[0], g.xs[1], mesh, rstride=1, cstride=1,",
"'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"sphere2_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] +",
"\"sphere_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2,",
"createGrid(g2min, g2max, g2N, process=True) return g2 def main(savedict): # generate signed distance function",
"[plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect_comp, title='Rect Complement', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"sph_rect_diff_2d.jpg\" plt.clf()",
"radius=2, 1 cylinder = shapeCylinder(g2, axis_align, center, radius); sphere = shapeSphere(g2, center, radius=1)",
"get_grid(): g2min = -2*np.ones((2, 1),dtype=np.float64) g2max = +2*np.ones((2, 1),dtype=np.float64) g2N = 51*np.ones((2, 1),dtype=np.int64)",
"+ [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sphere, title='Sphere', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"sphere2_2d.jpg\" plt.clf()",
"mesh, rstride=1, cstride=1, cmap='viridis', edgecolor=ec, facecolor=fc) ax[0].set_xlabel('X', fontdict=fontdict) ax[0].set_ylabel('Y', fontdict=fontdict) ax[0].set_zlabel('Z', fontdict=fontdict) ax[0].set_title(f'{title}',",
"= shapeSphere(g2, center=np.array(([-0., 0.])).T, radius=1) rect = shapeRectangleByCorners(g2) rect2 = shapeRectangleByCorners(g2, np.array([[ -1.0,",
"of plots' ) args = parser.parse_args() def levelset_viz(g, ax, fig, mesh, title='', savedict=None,",
"+ [plt.subplot(gs[2])] savedict[\"savename\"] = \"cylinder_2d.jpg\" levelset_viz(g2, ax, fig, cylinder, title='Cylinder', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'})",
"= shapeRectangleByCorners(g2, np.array([[ -1.0, -0.5, ]]).T, np.array([[ .5, 1.0 ]]).T) rect4 = shapeRectangleByCenter(g2,",
"title='RectCent: [1,-0.5], W: [0.5,1.0]', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) # Show Unions savedict[\"savename\"]=\"sphere_union_2d.jpg\" plt.clf()",
"zero - set as cyan contour. Author: <NAME>, October 29, 2021 \"\"\" ax[0].plot_surface(g.xs[0],",
"plt import matplotlib.gridspec as gridspec \"\"\" Test Implicit Functions Lekan Molu, September 07,",
"1),dtype=np.float64) g2N = 51*np.ones((2, 1),dtype=np.int64) g2 = createGrid(g2min, g2max, g2N, process=True) return g2",
"in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sphere_union, title='Spheres+Sphere', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay)",
"fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect4_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)]",
"\"\"\" parser = argparse.ArgumentParser(description='2D Plotter for Various Implicit Initial Conditions for the Value",
"gridspec \"\"\" Test Implicit Functions Lekan Molu, September 07, 2021 \"\"\" parser =",
"axis_align, center, radius); sphere = shapeSphere(g2, center, radius=1) sphere2 = shapeSphere(g2, center=np.array(([-0., 0.])).T,",
"i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect3, title='RectCorner: [1,-0.5], W: [0.5,1.0]',",
"ax[0].set_title(f'{title}', fontdict=fontdict) ax[1].contourf(g.xs[0], g.xs[1], mesh, colors=fc) ax[1].set_xlabel('X', fontdict=fontdict) ax[1].set_title(f'Contours', fontdict=fontdict) ax[2].contour(g.xs[0], g.xs[1], mesh,",
"gs = gridspec.GridSpec(1, 3, fig) ax = [plt.subplot(gs[i], projection='3d') for i in range(2)]",
"import argparse from mpl_toolkits.mplot3d import Axes3D import numpy as np import os, sys",
"cylinder = shapeCylinder(g2, axis_align, center, radius); sphere = shapeSphere(g2, center, radius=1) sphere2 =",
"ax[0].set_zlabel('Z', fontdict=fontdict) ax[0].set_title(f'{title}', fontdict=fontdict) ax[1].contourf(g.xs[0], g.xs[1], mesh, colors=fc) ax[1].set_xlabel('X', fontdict=fontdict) ax[1].set_title(f'Contours', fontdict=fontdict) ax[2].contour(g.xs[0],",
"a surface mesh Chart 132: 2D Value function as colored contour levels Chart",
"Diff', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) if __name__ == '__main__': savedict = dict(save=True, savename='cyl_2d.jpg',\\",
"type=float, default=3, help='pause time between successive updates of plots' ) args = parser.parse_args()",
"]]).T) # Set Ops sphere_union = shapeUnion(sphere, sphere2) rect_union = shapeUnion(rect, rect3) rect_comp",
"]]).T, np.array([[ .5, 1.0 ]]).T) rect4 = shapeRectangleByCenter(g2, np.array([[ -1.0, -0.5, ]]).T, np.array([[",
"savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_union_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in",
"__maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" __status__ = \"Completed\" import argparse from mpl_toolkits.mplot3d",
"[1,-0.5], W: [0.5,1.0]', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) # Show Unions savedict[\"savename\"]=\"sphere_union_2d.jpg\" plt.clf() ax",
"i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sphere_union, title='Spheres+Sphere', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'})",
"1X3 chart: Chart 131: 2D Value function as a surface mesh Chart 132:",
"shapeSphere(g2, center=np.array(([-0., 0.])).T, radius=1) rect = shapeRectangleByCorners(g2) rect2 = shapeRectangleByCorners(g2, np.array([[ -1.0, -np.inf,",
"= -2*np.ones((2, 1),dtype=np.float64) g2max = +2*np.ones((2, 1),dtype=np.float64) g2N = 51*np.ones((2, 1),dtype=np.int64) g2 =",
"from InitialConditions import * from Visualization import * import matplotlib.pyplot as plt import",
"rstride=1, cstride=1, cmap='viridis', edgecolor=ec, facecolor=fc) ax[0].set_xlabel('X', fontdict=fontdict) ax[0].set_ylabel('Y', fontdict=fontdict) ax[0].set_zlabel('Z', fontdict=fontdict) ax[0].set_title(f'{title}', fontdict=fontdict)",
"fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"] = \"sphere_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i",
"\"Molux Licence\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" __status__ = \"Completed\" import argparse",
"= 51*np.ones((2, 1),dtype=np.int64) g2 = createGrid(g2min, g2max, g2N, process=True) return g2 def main(savedict):",
"axis_align, radius=2, 1 cylinder = shapeCylinder(g2, axis_align, center, radius); sphere = shapeSphere(g2, center,",
"= shapeRectangleByCorners(g2) rect2 = shapeRectangleByCorners(g2, np.array([[ -1.0, -np.inf, ]]).T, np.array([[ np.inf, -1.0 ]]).T,",
"np.inf, -1.0 ]]).T, ) rect3 = shapeRectangleByCorners(g2, np.array([[ -1.0, -0.5, ]]).T, np.array([[ .5,",
"sphere = shapeSphere(g2, center, radius=1) sphere2 = shapeSphere(g2, center=np.array(([-0., 0.])).T, radius=1) rect =",
"fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"sph_rect_diff_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)]",
"projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sphere_union, title='Spheres+Sphere', savedict=savedict,",
"import numpy as np import os, sys from os.path import abspath, dirname, exists,",
"parser = argparse.ArgumentParser(description='2D Plotter for Various Implicit Initial Conditions for the Value Function')",
"= shapeUnion(sphere, sphere2) rect_union = shapeUnion(rect, rect3) rect_comp = shapeComplement(rect2) sph_rect_diff = shapeDifference(sphere,",
"set as cyan contour. Author: <NAME>, October 29, 2021 \"\"\" ax[0].plot_surface(g.xs[0], g.xs[1], mesh,",
"fig, rect_union, title='Union of 2 Rects', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_comp_2d.jpg\" plt.clf() ax",
"2021 \"\"\" ax[0].plot_surface(g.xs[0], g.xs[1], mesh, rstride=1, cstride=1, cmap='viridis', edgecolor=ec, facecolor=fc) ax[0].set_xlabel('X', fontdict=fontdict) ax[0].set_ylabel('Y',",
"-1.0, -np.inf, ]]).T, np.array([[ np.inf, -1.0 ]]).T, ) rect3 = shapeRectangleByCorners(g2, np.array([[ -1.0,",
"fig.canvas.draw() fig.canvas.flush_events() def get_grid(): g2min = -2*np.ones((2, 1),dtype=np.float64) g2max = +2*np.ones((2, 1),dtype=np.float64) g2N",
"gridspec.GridSpec(1, 3, fig) ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])]",
"ax, fig, sph_rect_diff, title='Sphere-Rect Diff', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) if __name__ == '__main__':",
"W: [0.5,1.0]', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) # Show Unions savedict[\"savename\"]=\"sphere_union_2d.jpg\" plt.clf() ax =",
"ax[2].set_xlabel('X', fontdict=fontdict) ax[2].set_ylabel('Y', fontdict=fontdict) ax[2].grid('on') ax[2].set_title(f'2D Zero level set', fontdict=fontdict) fig.tight_layout() if savedict[\"save\"]:",
"parser.parse_args() def levelset_viz(g, ax, fig, mesh, title='', savedict=None, fontdict=None, fc='c', ec='k'): \"\"\" Simultaneously",
"levelset_viz(g2, ax, fig, sph_rect_diff, title='Sphere-Rect Diff', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) if __name__ ==",
"# generate signed distance function for cylinder center = np.array(([[-.5,.5]]), np.float64).T g2 =",
"= \"2021, Hamilton-Jacobi Analysis in Python\" __license__ = \"Molux Licence\" __maintainer__ = \"<NAME>\"",
"51*np.ones((2, 1),dtype=np.int64) g2 = createGrid(g2min, g2max, g2N, process=True) return g2 def main(savedict): #",
"for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sph_rect_diff, title='Sphere-Rect Diff', savedict=savedict,",
"132: 2D Value function as colored contour levels Chart 133: 2D Value zero",
"__author__ = \"<NAME>\" __copyright__ = \"2021, Hamilton-Jacobi Analysis in Python\" __license__ = \"Molux",
"* from Visualization import * import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec",
"savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"sph_rect_diff_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in",
"= \"<NAME>\" __email__ = \"<EMAIL>\" __status__ = \"Completed\" import argparse from mpl_toolkits.mplot3d import",
"[0.5,1.0]', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) # Show Unions savedict[\"savename\"]=\"sphere_union_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i],",
"center, radius); sphere = shapeSphere(g2, center, radius=1) sphere2 = shapeSphere(g2, center=np.array(([-0., 0.])).T, radius=1)",
"fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"sphere2_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)]",
"projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect3, title='RectCorner: [1,-0.5],",
"sph_rect_diff = shapeDifference(sphere, rect) fig = plt.figure(figsize=(16, 9)) gs = gridspec.GridSpec(1, 3, fig)",
"Test Implicit Functions Lekan Molu, September 07, 2021 \"\"\" parser = argparse.ArgumentParser(description='2D Plotter",
"sys from os.path import abspath, dirname, exists, join sys.path.append(dirname(dirname(abspath(__file__)))) from Grids import createGrid",
") args = parser.parse_args() def levelset_viz(g, ax, fig, mesh, title='', savedict=None, fontdict=None, fc='c',",
"= \"sphere_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])]",
"main(savedict): # generate signed distance function for cylinder center = np.array(([[-.5,.5]]), np.float64).T g2",
"fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) # Show Unions savedict[\"savename\"]=\"sphere_union_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for",
"os, sys from os.path import abspath, dirname, exists, join sys.path.append(dirname(dirname(abspath(__file__)))) from Grids import",
"savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect2_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in",
"fig.canvas.flush_events() def get_grid(): g2min = -2*np.ones((2, 1),dtype=np.float64) g2max = +2*np.ones((2, 1),dtype=np.float64) g2N =",
"\"<EMAIL>\" __status__ = \"Completed\" import argparse from mpl_toolkits.mplot3d import Axes3D import numpy as",
"for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sphere, title='Sphere', savedict=savedict, fontdict={'fontsize':12,",
"for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sphere_union, title='Spheres+Sphere', savedict=savedict, fontdict={'fontsize':12,",
"rect_union, title='Union of 2 Rects', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_comp_2d.jpg\" plt.clf() ax =",
"+ [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sphere2, title='Sphere, C=(-.5, .5)', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay)",
"1 cylinder = shapeCylinder(g2, axis_align, center, radius); sphere = shapeSphere(g2, center, radius=1) sphere2",
"ax[0].set_ylabel('Y', fontdict=fontdict) ax[0].set_zlabel('Z', fontdict=fontdict) ax[0].set_title(f'{title}', fontdict=fontdict) ax[1].contourf(g.xs[0], g.xs[1], mesh, colors=fc) ax[1].set_xlabel('X', fontdict=fontdict) ax[1].set_title(f'Contours',",
"-0.5, ]]).T, np.array([[ .5, 1.0 ]]).T) # Set Ops sphere_union = shapeUnion(sphere, sphere2)",
"[plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sph_rect_diff, title='Sphere-Rect",
"[1,-0.5], W: [0.5,1.0]', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect4_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d')",
"args = parser.parse_args() def levelset_viz(g, ax, fig, mesh, title='', savedict=None, fontdict=None, fc='c', ec='k'):",
"plt.pause(args.delay) savedict[\"savename\"]=\"rect_comp_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])]",
"Python\" __license__ = \"Molux Licence\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" __status__ =",
"'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_comp_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] +",
"createGrid from InitialConditions import * from Visualization import * import matplotlib.pyplot as plt",
"fontdict=fontdict) ax[0].set_zlabel('Z', fontdict=fontdict) ax[0].set_title(f'{title}', fontdict=fontdict) ax[1].contourf(g.xs[0], g.xs[1], mesh, colors=fc) ax[1].set_xlabel('X', fontdict=fontdict) ax[1].set_title(f'Contours', fontdict=fontdict)",
"as cyan contour. Author: <NAME>, October 29, 2021 \"\"\" ax[0].plot_surface(g.xs[0], g.xs[1], mesh, rstride=1,",
"Chart 131: 2D Value function as a surface mesh Chart 132: 2D Value",
"mesh, levels=0, colors=fc) ax[2].set_xlabel('X', fontdict=fontdict) ax[2].set_ylabel('Y', fontdict=fontdict) ax[2].grid('on') ax[2].set_title(f'2D Zero level set', fontdict=fontdict)",
"= [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect3,",
"shapeComplement(rect2) sph_rect_diff = shapeDifference(sphere, rect) fig = plt.figure(figsize=(16, 9)) gs = gridspec.GridSpec(1, 3,",
"function as colored contour levels Chart 133: 2D Value zero - set as",
"i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sphere, title='Sphere', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'})",
"rect3, title='RectCorner: [1,-0.5], W: [0.5,1.0]', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect4_2d.jpg\" plt.clf() ax =",
"[plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sphere_union, title='Spheres+Sphere',",
"Conditions for the Value Function') parser.add_argument('--delay', '-dl', type=float, default=3, help='pause time between successive",
"shapeRectangleByCenter(g2, np.array([[ -1.0, -0.5, ]]).T, np.array([[ .5, 1.0 ]]).T) # Set Ops sphere_union",
"]]).T, np.array([[ np.inf, -1.0 ]]).T, ) rect3 = shapeRectangleByCorners(g2, np.array([[ -1.0, -0.5, ]]).T,",
"level sets of a value function on a 1X3 chart: Chart 131: 2D",
"cylinder, title='Cylinder', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"] = \"sphere_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i],",
"plt.pause(args.delay) savedict[\"savename\"]=\"rect_union_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])]",
"def levelset_viz(g, ax, fig, mesh, title='', savedict=None, fontdict=None, fc='c', ec='k'): \"\"\" Simultaneously visualize",
"the Value Function') parser.add_argument('--delay', '-dl', type=float, default=3, help='pause time between successive updates of",
"Rects', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_comp_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i",
"g2min = -2*np.ones((2, 1),dtype=np.float64) g2max = +2*np.ones((2, 1),dtype=np.float64) g2N = 51*np.ones((2, 1),dtype=np.int64) g2",
"i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sph_rect_diff, title='Sphere-Rect Diff', savedict=savedict, fontdict={'fontsize':12,",
"fontdict=None, fc='c', ec='k'): \"\"\" Simultaneously visualize the level sets of a value function",
"in Python\" __license__ = \"Molux Licence\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" __status__",
"= shapeRectangleByCenter(g2, np.array([[ -1.0, -0.5, ]]).T, np.array([[ .5, 1.0 ]]).T) # Set Ops",
"savedict[\"savename\"]=\"rect_comp_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2,",
"= shapeRectangleByCorners(g2, np.array([[ -1.0, -np.inf, ]]).T, np.array([[ np.inf, -1.0 ]]).T, ) rect3 =",
"Set Ops sphere_union = shapeUnion(sphere, sphere2) rect_union = shapeUnion(rect, rect3) rect_comp = shapeComplement(rect2)",
"-np.inf, ]]).T, np.array([[ np.inf, -1.0 ]]).T, ) rect3 = shapeRectangleByCorners(g2, np.array([[ -1.0, -0.5,",
"= \"Molux Licence\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" __status__ = \"Completed\" import",
"[plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sphere2, title='Sphere, C=(-.5, .5)', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_2d.jpg\"",
"time between successive updates of plots' ) args = parser.parse_args() def levelset_viz(g, ax,",
"Initial Conditions for the Value Function') parser.add_argument('--delay', '-dl', type=float, default=3, help='pause time between",
"Visualization import * import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec \"\"\" Test",
"fig, cylinder, title='Cylinder', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"] = \"sphere_2d.jpg\" plt.clf() ax =",
"exists, join sys.path.append(dirname(dirname(abspath(__file__)))) from Grids import createGrid from InitialConditions import * from Visualization",
"in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sphere2, title='Sphere, C=(-.5, .5)', savedict=savedict, fontdict={'fontsize':12,",
"= [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect4,",
"surface mesh Chart 132: 2D Value function as colored contour levels Chart 133:",
"3, fig) ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] savedict[\"savename\"]",
"ax, fig, cylinder, title='Cylinder', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"] = \"sphere_2d.jpg\" plt.clf() ax",
"[plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect_union, title='Union of 2 Rects', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay)",
"= [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect_comp,",
"= createGrid(g2min, g2max, g2N, process=True) return g2 def main(savedict): # generate signed distance",
"savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) # Show Unions savedict[\"savename\"]=\"sphere_union_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d')",
"= shapeDifference(sphere, rect) fig = plt.figure(figsize=(16, 9)) gs = gridspec.GridSpec(1, 3, fig) ax",
"range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sph_rect_diff, title='Sphere-Rect Diff', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay)",
"in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect2, title='Rect by Corners', savedict=savedict, fontdict={'fontsize':12,",
"g.xs[1], mesh, levels=0, colors=fc) ax[2].set_xlabel('X', fontdict=fontdict) ax[2].set_ylabel('Y', fontdict=fontdict) ax[2].grid('on') ax[2].set_title(f'2D Zero level set',",
"[plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect2, title='Rect",
"29, 2021 \"\"\" ax[0].plot_surface(g.xs[0], g.xs[1], mesh, rstride=1, cstride=1, cmap='viridis', edgecolor=ec, facecolor=fc) ax[0].set_xlabel('X', fontdict=fontdict)",
"1),dtype=np.float64) g2max = +2*np.ones((2, 1),dtype=np.float64) g2N = 51*np.ones((2, 1),dtype=np.int64) g2 = createGrid(g2min, g2max,",
"[plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sphere, title='Sphere', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"sphere2_2d.jpg\" plt.clf() ax",
"cmap='viridis', edgecolor=ec, facecolor=fc) ax[0].set_xlabel('X', fontdict=fontdict) ax[0].set_ylabel('Y', fontdict=fontdict) ax[0].set_zlabel('Z', fontdict=fontdict) ax[0].set_title(f'{title}', fontdict=fontdict) ax[1].contourf(g.xs[0], g.xs[1],",
"shapeCylinder(g2, axis_align, center, radius); sphere = shapeSphere(g2, center, radius=1) sphere2 = shapeSphere(g2, center=np.array(([-0.,",
"matplotlib.gridspec as gridspec \"\"\" Test Implicit Functions Lekan Molu, September 07, 2021 \"\"\"",
"# Set Ops sphere_union = shapeUnion(sphere, sphere2) rect_union = shapeUnion(rect, rect3) rect_comp =",
"matplotlib.pyplot as plt import matplotlib.gridspec as gridspec \"\"\" Test Implicit Functions Lekan Molu,",
"ax, fig, rect_union, title='Union of 2 Rects', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_comp_2d.jpg\" plt.clf()",
"fontdict=fontdict) ax[2].grid('on') ax[2].set_title(f'2D Zero level set', fontdict=fontdict) fig.tight_layout() if savedict[\"save\"]: plt.savefig(join(savedict[\"savepath\"],savedict[\"savename\"]), bbox_inches='tight',facecolor='None') fig.canvas.draw()",
"savedict[\"savename\"]=\"rect2_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2,",
"'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_union_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] +",
"sphere2 = shapeSphere(g2, center=np.array(([-0., 0.])).T, radius=1) rect = shapeRectangleByCorners(g2) rect2 = shapeRectangleByCorners(g2, np.array([[",
"import * from Visualization import * import matplotlib.pyplot as plt import matplotlib.gridspec as",
"fontdict=fontdict) ax[2].contour(g.xs[0], g.xs[1], mesh, levels=0, colors=fc) ax[2].set_xlabel('X', fontdict=fontdict) ax[2].set_ylabel('Y', fontdict=fontdict) ax[2].grid('on') ax[2].set_title(f'2D Zero",
"fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect2_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)]",
"mesh, title='', savedict=None, fontdict=None, fc='c', ec='k'): \"\"\" Simultaneously visualize the level sets of",
"= [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] savedict[\"savename\"] = \"cylinder_2d.jpg\" levelset_viz(g2,",
"def main(savedict): # generate signed distance function for cylinder center = np.array(([[-.5,.5]]), np.float64).T",
"in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect4, title='RectCent: [1,-0.5], W: [0.5,1.0]', savedict=savedict,",
"plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax,",
"__copyright__ = \"2021, Hamilton-Jacobi Analysis in Python\" __license__ = \"Molux Licence\" __maintainer__ =",
"'fontweight':'bold'}) plt.pause(args.delay) # Show Unions savedict[\"savename\"]=\"sphere_union_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i",
"i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect2, title='Rect by Corners', savedict=savedict,",
"value function on a 1X3 chart: Chart 131: 2D Value function as a",
"projection='3d') for i in range(2)] + [plt.subplot(gs[2])] savedict[\"savename\"] = \"cylinder_2d.jpg\" levelset_viz(g2, ax, fig,",
"2 Rects', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_comp_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for",
"plt.savefig(join(savedict[\"savepath\"],savedict[\"savename\"]), bbox_inches='tight',facecolor='None') fig.canvas.draw() fig.canvas.flush_events() def get_grid(): g2min = -2*np.ones((2, 1),dtype=np.float64) g2max = +2*np.ones((2,",
"title='Spheres+Sphere', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_union_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i",
"+2*np.ones((2, 1),dtype=np.float64) g2N = 51*np.ones((2, 1),dtype=np.int64) g2 = createGrid(g2min, g2max, g2N, process=True) return",
"Value function as colored contour levels Chart 133: 2D Value zero - set",
"rect = shapeRectangleByCorners(g2) rect2 = shapeRectangleByCorners(g2, np.array([[ -1.0, -np.inf, ]]).T, np.array([[ np.inf, -1.0",
"range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sphere, title='Sphere', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"sphere2_2d.jpg\"",
"plots' ) args = parser.parse_args() def levelset_viz(g, ax, fig, mesh, title='', savedict=None, fontdict=None,",
"range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect3, title='RectCorner: [1,-0.5], W: [0.5,1.0]', savedict=savedict, fontdict={'fontsize':12,",
"fig, rect_comp, title='Rect Complement', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"sph_rect_diff_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i],",
"range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect4, title='RectCent: [1,-0.5], W: [0.5,1.0]', savedict=savedict, fontdict={'fontsize':12,",
"= [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect_union,",
"Molu, September 07, 2021 \"\"\" parser = argparse.ArgumentParser(description='2D Plotter for Various Implicit Initial",
"import os, sys from os.path import abspath, dirname, exists, join sys.path.append(dirname(dirname(abspath(__file__)))) from Grids",
"levelset_viz(g2, ax, fig, sphere_union, title='Spheres+Sphere', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_union_2d.jpg\" plt.clf() ax =",
"[0.5,1.0]', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect4_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i",
"fig = plt.figure(figsize=(16, 9)) gs = gridspec.GridSpec(1, 3, fig) ax = [plt.subplot(gs[i], projection='3d')",
"in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect_comp, title='Rect Complement', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'})",
"ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig,",
"range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect, title='Unit Square@Origin', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay)",
"[plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect_union, title='Union",
"import matplotlib.gridspec as gridspec \"\"\" Test Implicit Functions Lekan Molu, September 07, 2021",
"numpy as np import os, sys from os.path import abspath, dirname, exists, join",
"if savedict[\"save\"]: plt.savefig(join(savedict[\"savepath\"],savedict[\"savename\"]), bbox_inches='tight',facecolor='None') fig.canvas.draw() fig.canvas.flush_events() def get_grid(): g2min = -2*np.ones((2, 1),dtype=np.float64) g2max",
"ax[0].plot_surface(g.xs[0], g.xs[1], mesh, rstride=1, cstride=1, cmap='viridis', edgecolor=ec, facecolor=fc) ax[0].set_xlabel('X', fontdict=fontdict) ax[0].set_ylabel('Y', fontdict=fontdict) ax[0].set_zlabel('Z',",
"i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect_union, title='Union of 2 Rects',",
"radius=1) sphere2 = shapeSphere(g2, center=np.array(([-0., 0.])).T, radius=1) rect = shapeRectangleByCorners(g2) rect2 = shapeRectangleByCorners(g2,",
") rect3 = shapeRectangleByCorners(g2, np.array([[ -1.0, -0.5, ]]).T, np.array([[ .5, 1.0 ]]).T) rect4",
"of 2 Rects', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_comp_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d')",
"rect4 = shapeRectangleByCenter(g2, np.array([[ -1.0, -0.5, ]]).T, np.array([[ .5, 1.0 ]]).T) # Set",
"plt.pause(args.delay) savedict[\"savename\"]=\"rect_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])]",
"title='Union of 2 Rects', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_comp_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i],",
"ax, fig, rect_comp, title='Rect Complement', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"sph_rect_diff_2d.jpg\" plt.clf() ax =",
"g2N = 51*np.ones((2, 1),dtype=np.int64) g2 = createGrid(g2min, g2max, g2N, process=True) return g2 def",
"plt.pause(args.delay) savedict[\"savename\"]=\"sph_rect_diff_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])]",
"\"\"\" Test Implicit Functions Lekan Molu, September 07, 2021 \"\"\" parser = argparse.ArgumentParser(description='2D",
"title='Rect by Corners', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect3_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d')",
"savedict[\"savename\"]=\"rect4_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2,",
"by Corners', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect3_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for",
"i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect_comp, title='Rect Complement', savedict=savedict, fontdict={'fontsize':12,",
"the level sets of a value function on a 1X3 chart: Chart 131:",
"ax, fig, rect3, title='RectCorner: [1,-0.5], W: [0.5,1.0]', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect4_2d.jpg\" plt.clf()",
"function for cylinder center = np.array(([[-.5,.5]]), np.float64).T g2 = get_grid() # shapes generation",
"rect_union = shapeUnion(rect, rect3) rect_comp = shapeComplement(rect2) sph_rect_diff = shapeDifference(sphere, rect) fig =",
"rect_comp, title='Rect Complement', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"sph_rect_diff_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d')",
"]]).T, ) rect3 = shapeRectangleByCorners(g2, np.array([[ -1.0, -0.5, ]]).T, np.array([[ .5, 1.0 ]]).T)",
"Grids import createGrid from InitialConditions import * from Visualization import * import matplotlib.pyplot",
"= gridspec.GridSpec(1, 3, fig) ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] +",
"sys.path.append(dirname(dirname(abspath(__file__)))) from Grids import createGrid from InitialConditions import * from Visualization import *",
"1.0 ]]).T) # Set Ops sphere_union = shapeUnion(sphere, sphere2) rect_union = shapeUnion(rect, rect3)",
"ec='k'): \"\"\" Simultaneously visualize the level sets of a value function on a",
"C=(-.5, .5)', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for",
"in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect3, title='RectCorner: [1,-0.5], W: [0.5,1.0]', savedict=savedict,",
"ax, fig, rect4, title='RectCent: [1,-0.5], W: [0.5,1.0]', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) # Show",
"np.array([[ -1.0, -0.5, ]]).T, np.array([[ .5, 1.0 ]]).T) rect4 = shapeRectangleByCenter(g2, np.array([[ -1.0,",
"updates of plots' ) args = parser.parse_args() def levelset_viz(g, ax, fig, mesh, title='',",
"projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sph_rect_diff, title='Sphere-Rect Diff',",
"range(2)] + [plt.subplot(gs[2])] savedict[\"savename\"] = \"cylinder_2d.jpg\" levelset_viz(g2, ax, fig, cylinder, title='Cylinder', savedict=savedict, fontdict={'fontsize':12,",
"range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sphere_union, title='Spheres+Sphere', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_union_2d.jpg\"",
"shapeSphere(g2, center, radius=1) sphere2 = shapeSphere(g2, center=np.array(([-0., 0.])).T, radius=1) rect = shapeRectangleByCorners(g2) rect2",
"signed distance function for cylinder center = np.array(([[-.5,.5]]), np.float64).T g2 = get_grid() #",
"contour levels Chart 133: 2D Value zero - set as cyan contour. Author:",
"= np.array(([[-.5,.5]]), np.float64).T g2 = get_grid() # shapes generation axis_align, radius=2, 1 cylinder",
"levelset_viz(g2, ax, fig, rect3, title='RectCorner: [1,-0.5], W: [0.5,1.0]', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect4_2d.jpg\"",
"projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect, title='Unit Square@Origin',",
"plt.pause(args.delay) savedict[\"savename\"]=\"rect2_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])]",
"plt.figure(figsize=(16, 9)) gs = gridspec.GridSpec(1, 3, fig) ax = [plt.subplot(gs[i], projection='3d') for i",
"level set', fontdict=fontdict) fig.tight_layout() if savedict[\"save\"]: plt.savefig(join(savedict[\"savepath\"],savedict[\"savename\"]), bbox_inches='tight',facecolor='None') fig.canvas.draw() fig.canvas.flush_events() def get_grid(): g2min",
"Unions savedict[\"savename\"]=\"sphere_union_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])]",
"-1.0 ]]).T, ) rect3 = shapeRectangleByCorners(g2, np.array([[ -1.0, -0.5, ]]).T, np.array([[ .5, 1.0",
"argparse.ArgumentParser(description='2D Plotter for Various Implicit Initial Conditions for the Value Function') parser.add_argument('--delay', '-dl',",
"= [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sphere2,",
"fig, sphere, title='Sphere', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"sphere2_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d')",
"get_grid() # shapes generation axis_align, radius=2, 1 cylinder = shapeCylinder(g2, axis_align, center, radius);",
"import * import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec \"\"\" Test Implicit",
"'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"sph_rect_diff_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] +",
"bbox_inches='tight',facecolor='None') fig.canvas.draw() fig.canvas.flush_events() def get_grid(): g2min = -2*np.ones((2, 1),dtype=np.float64) g2max = +2*np.ones((2, 1),dtype=np.float64)",
"ax[2].contour(g.xs[0], g.xs[1], mesh, levels=0, colors=fc) ax[2].set_xlabel('X', fontdict=fontdict) ax[2].set_ylabel('Y', fontdict=fontdict) ax[2].grid('on') ax[2].set_title(f'2D Zero level",
"title='Sphere', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"sphere2_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i",
"= \"<NAME>\" __copyright__ = \"2021, Hamilton-Jacobi Analysis in Python\" __license__ = \"Molux Licence\"",
"for cylinder center = np.array(([[-.5,.5]]), np.float64).T g2 = get_grid() # shapes generation axis_align,",
"between successive updates of plots' ) args = parser.parse_args() def levelset_viz(g, ax, fig,",
"from os.path import abspath, dirname, exists, join sys.path.append(dirname(dirname(abspath(__file__)))) from Grids import createGrid from",
"\"<NAME>\" __copyright__ = \"2021, Hamilton-Jacobi Analysis in Python\" __license__ = \"Molux Licence\" __maintainer__",
"i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect4, title='RectCent: [1,-0.5], W: [0.5,1.0]',",
"as a surface mesh Chart 132: 2D Value function as colored contour levels",
"for i in range(2)] + [plt.subplot(gs[2])] savedict[\"savename\"] = \"cylinder_2d.jpg\" levelset_viz(g2, ax, fig, cylinder,",
"in range(2)] + [plt.subplot(gs[2])] savedict[\"savename\"] = \"cylinder_2d.jpg\" levelset_viz(g2, ax, fig, cylinder, title='Cylinder', savedict=savedict,",
"ax, fig, rect2, title='Rect by Corners', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect3_2d.jpg\" plt.clf() ax",
"[plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sphere_union, title='Spheres+Sphere', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_union_2d.jpg\" plt.clf() ax",
"fig, sphere_union, title='Spheres+Sphere', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_union_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d')",
"+ [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect2, title='Rect by Corners', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay)",
"for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect_union, title='Union of 2",
"sphere2, title='Sphere, C=(-.5, .5)', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i],",
"title='Cylinder', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"] = \"sphere_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d')",
"def get_grid(): g2min = -2*np.ones((2, 1),dtype=np.float64) g2max = +2*np.ones((2, 1),dtype=np.float64) g2N = 51*np.ones((2,",
"sphere2) rect_union = shapeUnion(rect, rect3) rect_comp = shapeComplement(rect2) sph_rect_diff = shapeDifference(sphere, rect) fig",
"levelset_viz(g2, ax, fig, rect, title='Unit Square@Origin', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect2_2d.jpg\" plt.clf() ax",
"dirname, exists, join sys.path.append(dirname(dirname(abspath(__file__)))) from Grids import createGrid from InitialConditions import * from",
"ax[1].set_xlabel('X', fontdict=fontdict) ax[1].set_title(f'Contours', fontdict=fontdict) ax[2].contour(g.xs[0], g.xs[1], mesh, levels=0, colors=fc) ax[2].set_xlabel('X', fontdict=fontdict) ax[2].set_ylabel('Y', fontdict=fontdict)",
"Simultaneously visualize the level sets of a value function on a 1X3 chart:",
"range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect2, title='Rect by Corners', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'})",
"sphere_union, title='Spheres+Sphere', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_union_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for",
"levelset_viz(g, ax, fig, mesh, title='', savedict=None, fontdict=None, fc='c', ec='k'): \"\"\" Simultaneously visualize the",
"levels Chart 133: 2D Value zero - set as cyan contour. Author: <NAME>,",
"ax[1].set_title(f'Contours', fontdict=fontdict) ax[2].contour(g.xs[0], g.xs[1], mesh, levels=0, colors=fc) ax[2].set_xlabel('X', fontdict=fontdict) ax[2].set_ylabel('Y', fontdict=fontdict) ax[2].grid('on') ax[2].set_title(f'2D",
"Analysis in Python\" __license__ = \"Molux Licence\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\"",
"Licence\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" __status__ = \"Completed\" import argparse from",
"'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] +",
"= [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect,",
"= [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sphere_union,",
"savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_comp_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in",
"= shapeCylinder(g2, axis_align, center, radius); sphere = shapeSphere(g2, center, radius=1) sphere2 = shapeSphere(g2,",
".5, 1.0 ]]).T) # Set Ops sphere_union = shapeUnion(sphere, sphere2) rect_union = shapeUnion(rect,",
"center = np.array(([[-.5,.5]]), np.float64).T g2 = get_grid() # shapes generation axis_align, radius=2, 1",
"Function') parser.add_argument('--delay', '-dl', type=float, default=3, help='pause time between successive updates of plots' )",
"plt.pause(args.delay) savedict[\"savename\"]=\"rect4_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])]",
"= \"Completed\" import argparse from mpl_toolkits.mplot3d import Axes3D import numpy as np import",
"for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect4, title='RectCent: [1,-0.5], W:",
"in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sph_rect_diff, title='Sphere-Rect Diff', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'})",
"visualize the level sets of a value function on a 1X3 chart: Chart",
"[plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect3, title='RectCorner:",
"ax, fig, sphere_union, title='Spheres+Sphere', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_union_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i],",
"October 29, 2021 \"\"\" ax[0].plot_surface(g.xs[0], g.xs[1], mesh, rstride=1, cstride=1, cmap='viridis', edgecolor=ec, facecolor=fc) ax[0].set_xlabel('X',",
"= parser.parse_args() def levelset_viz(g, ax, fig, mesh, title='', savedict=None, fontdict=None, fc='c', ec='k'): \"\"\"",
"savedict[\"savename\"]=\"rect_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2,",
"fontdict=fontdict) ax[1].contourf(g.xs[0], g.xs[1], mesh, colors=fc) ax[1].set_xlabel('X', fontdict=fontdict) ax[1].set_title(f'Contours', fontdict=fontdict) ax[2].contour(g.xs[0], g.xs[1], mesh, levels=0,",
"colored contour levels Chart 133: 2D Value zero - set as cyan contour.",
"cylinder center = np.array(([[-.5,.5]]), np.float64).T g2 = get_grid() # shapes generation axis_align, radius=2,",
"shapeDifference(sphere, rect) fig = plt.figure(figsize=(16, 9)) gs = gridspec.GridSpec(1, 3, fig) ax =",
"savedict[\"savename\"] = \"sphere_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] +",
"savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect3_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in",
"title='Unit Square@Origin', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect2_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for",
"colors=fc) ax[2].set_xlabel('X', fontdict=fontdict) ax[2].set_ylabel('Y', fontdict=fontdict) ax[2].grid('on') ax[2].set_title(f'2D Zero level set', fontdict=fontdict) fig.tight_layout() if",
"mpl_toolkits.mplot3d import Axes3D import numpy as np import os, sys from os.path import",
"as colored contour levels Chart 133: 2D Value zero - set as cyan",
"rect2 = shapeRectangleByCorners(g2, np.array([[ -1.0, -np.inf, ]]).T, np.array([[ np.inf, -1.0 ]]).T, ) rect3",
"for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect2, title='Rect by Corners',",
"fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect3_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)]",
"i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect, title='Unit Square@Origin', savedict=savedict, fontdict={'fontsize':12,",
"+ [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect, title='Unit Square@Origin', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect2_2d.jpg\"",
"\"\"\" ax[0].plot_surface(g.xs[0], g.xs[1], mesh, rstride=1, cstride=1, cmap='viridis', edgecolor=ec, facecolor=fc) ax[0].set_xlabel('X', fontdict=fontdict) ax[0].set_ylabel('Y', fontdict=fontdict)",
"[plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sphere2, title='Sphere,",
"savedict[\"savename\"] = \"cylinder_2d.jpg\" levelset_viz(g2, ax, fig, cylinder, title='Cylinder', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]",
"abspath, dirname, exists, join sys.path.append(dirname(dirname(abspath(__file__)))) from Grids import createGrid from InitialConditions import *",
"g.xs[1], mesh, rstride=1, cstride=1, cmap='viridis', edgecolor=ec, facecolor=fc) ax[0].set_xlabel('X', fontdict=fontdict) ax[0].set_ylabel('Y', fontdict=fontdict) ax[0].set_zlabel('Z', fontdict=fontdict)",
"function as a surface mesh Chart 132: 2D Value function as colored contour",
"import Axes3D import numpy as np import os, sys from os.path import abspath,",
"for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect_comp, title='Rect Complement', savedict=savedict,",
"projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect4, title='RectCent: [1,-0.5],",
"ax[2].grid('on') ax[2].set_title(f'2D Zero level set', fontdict=fontdict) fig.tight_layout() if savedict[\"save\"]: plt.savefig(join(savedict[\"savepath\"],savedict[\"savename\"]), bbox_inches='tight',facecolor='None') fig.canvas.draw() fig.canvas.flush_events()",
"parser.add_argument('--delay', '-dl', type=float, default=3, help='pause time between successive updates of plots' ) args",
"[plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect2, title='Rect by Corners', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect3_2d.jpg\"",
"Ops sphere_union = shapeUnion(sphere, sphere2) rect_union = shapeUnion(rect, rect3) rect_comp = shapeComplement(rect2) sph_rect_diff",
"rect3) rect_comp = shapeComplement(rect2) sph_rect_diff = shapeDifference(sphere, rect) fig = plt.figure(figsize=(16, 9)) gs",
"Lekan Molu, September 07, 2021 \"\"\" parser = argparse.ArgumentParser(description='2D Plotter for Various Implicit",
"center=np.array(([-0., 0.])).T, radius=1) rect = shapeRectangleByCorners(g2) rect2 = shapeRectangleByCorners(g2, np.array([[ -1.0, -np.inf, ]]).T,",
"shapeUnion(sphere, sphere2) rect_union = shapeUnion(rect, rect3) rect_comp = shapeComplement(rect2) sph_rect_diff = shapeDifference(sphere, rect)",
"= +2*np.ones((2, 1),dtype=np.float64) g2N = 51*np.ones((2, 1),dtype=np.int64) g2 = createGrid(g2min, g2max, g2N, process=True)",
"Zero level set', fontdict=fontdict) fig.tight_layout() if savedict[\"save\"]: plt.savefig(join(savedict[\"savepath\"],savedict[\"savename\"]), bbox_inches='tight',facecolor='None') fig.canvas.draw() fig.canvas.flush_events() def get_grid():",
"savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in",
"plt.pause(args.delay) savedict[\"savename\"]=\"rect3_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])]",
"rect) fig = plt.figure(figsize=(16, 9)) gs = gridspec.GridSpec(1, 3, fig) ax = [plt.subplot(gs[i],",
"= \"<EMAIL>\" __status__ = \"Completed\" import argparse from mpl_toolkits.mplot3d import Axes3D import numpy",
"projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sphere2, title='Sphere, C=(-.5,",
"= shapeSphere(g2, center, radius=1) sphere2 = shapeSphere(g2, center=np.array(([-0., 0.])).T, radius=1) rect = shapeRectangleByCorners(g2)",
"fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) savedict[\"savename\"]=\"rect_comp_2d.jpg\" plt.clf() ax = [plt.subplot(gs[i], projection='3d') for i in range(2)]",
"plt.pause(args.delay) if __name__ == '__main__': savedict = dict(save=True, savename='cyl_2d.jpg',\\ savepath=join(\"..\", \"jpeg_dumps\")) plt.ion() main(savedict)",
"= shapeUnion(rect, rect3) rect_comp = shapeComplement(rect2) sph_rect_diff = shapeDifference(sphere, rect) fig = plt.figure(figsize=(16,",
"argparse from mpl_toolkits.mplot3d import Axes3D import numpy as np import os, sys from",
"edgecolor=ec, facecolor=fc) ax[0].set_xlabel('X', fontdict=fontdict) ax[0].set_ylabel('Y', fontdict=fontdict) ax[0].set_zlabel('Z', fontdict=fontdict) ax[0].set_title(f'{title}', fontdict=fontdict) ax[1].contourf(g.xs[0], g.xs[1], mesh,",
"[plt.subplot(gs[i], projection='3d') for i in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect4, title='RectCent:",
"as gridspec \"\"\" Test Implicit Functions Lekan Molu, September 07, 2021 \"\"\" parser",
"Value Function') parser.add_argument('--delay', '-dl', type=float, default=3, help='pause time between successive updates of plots'",
"'fontweight':'bold'}) plt.pause(args.delay) if __name__ == '__main__': savedict = dict(save=True, savename='cyl_2d.jpg',\\ savepath=join(\"..\", \"jpeg_dumps\")) plt.ion()",
"in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, rect, title='Unit Square@Origin', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'})",
"= shapeComplement(rect2) sph_rect_diff = shapeDifference(sphere, rect) fig = plt.figure(figsize=(16, 9)) gs = gridspec.GridSpec(1,",
"+ [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sph_rect_diff, title='Sphere-Rect Diff', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay) if",
"os.path import abspath, dirname, exists, join sys.path.append(dirname(dirname(abspath(__file__)))) from Grids import createGrid from InitialConditions",
"in range(2)] + [plt.subplot(gs[2])] levelset_viz(g2, ax, fig, sphere, title='Sphere', savedict=savedict, fontdict={'fontsize':12, 'fontweight':'bold'}) plt.pause(args.delay)"
] |
[
"clean_invite_embed(msg): \"\"\"Prevents invites from embedding\"\"\" return msg.replace(\"discord.gg/\", \"discord.gg/\\u200b\") def clean_backticks(msg): \"\"\"Prevents backticks from",
"from embedding\"\"\" return msg.replace(\"discord.gg/\", \"discord.gg/\\u200b\") def clean_backticks(msg): \"\"\"Prevents backticks from breaking code block",
"clean_all(msg): msg = clean_invite_embed(msg) msg = clean_backticks(msg) msg = clean_mentions(msg) msg = clean_emojis(msg)",
"unwanted content import re def clean_all(msg): msg = clean_invite_embed(msg) msg = clean_backticks(msg) msg",
"a string.\"\"\" return re.sub(r\"([`*_])\", r\"\\\\\\1\", msg) def clean_mentions(msg): \"\"\"Prevent discord mentions\"\"\" return msg.replace(\"@\",",
"mentions\"\"\" return msg.replace(\"@\", \"@\\u200b\") def clean_emojis(msg): \"\"\"Escape custom emojis.\"\"\" return re.sub(r\"<(a)?:([a-zA-Z0-9_]+):([0-9]+)>\", \"<\\u200b\\\\1:\\\\2:\\\\3>\", msg)",
"import re def clean_all(msg): msg = clean_invite_embed(msg) msg = clean_backticks(msg) msg = clean_mentions(msg)",
"formatting items in a string.\"\"\" return re.sub(r\"([`*_])\", r\"\\\\\\1\", msg) def clean_mentions(msg): \"\"\"Prevent discord",
"\"\\U0000ff40\") def clean_formatting(msg): \"\"\"Escape formatting items in a string.\"\"\" return re.sub(r\"([`*_])\", r\"\\\\\\1\", msg)",
"msg def clean_invite_embed(msg): \"\"\"Prevents invites from embedding\"\"\" return msg.replace(\"discord.gg/\", \"discord.gg/\\u200b\") def clean_backticks(msg): \"\"\"Prevents",
"\"discord.gg/\\u200b\") def clean_backticks(msg): \"\"\"Prevents backticks from breaking code block formatting\"\"\" return msg.replace(\"`\", \"\\U0000ff40\")",
"msg = clean_backticks(msg) msg = clean_mentions(msg) msg = clean_emojis(msg) return msg def clean_invite_embed(msg):",
"re.sub(r\"([`*_])\", r\"\\\\\\1\", msg) def clean_mentions(msg): \"\"\"Prevent discord mentions\"\"\" return msg.replace(\"@\", \"@\\u200b\") def clean_emojis(msg):",
"= clean_mentions(msg) msg = clean_emojis(msg) return msg def clean_invite_embed(msg): \"\"\"Prevents invites from embedding\"\"\"",
"from breaking code block formatting\"\"\" return msg.replace(\"`\", \"\\U0000ff40\") def clean_formatting(msg): \"\"\"Escape formatting items",
"embedding\"\"\" return msg.replace(\"discord.gg/\", \"discord.gg/\\u200b\") def clean_backticks(msg): \"\"\"Prevents backticks from breaking code block formatting\"\"\"",
"clean_backticks(msg) msg = clean_mentions(msg) msg = clean_emojis(msg) return msg def clean_invite_embed(msg): \"\"\"Prevents invites",
"def clean_invite_embed(msg): \"\"\"Prevents invites from embedding\"\"\" return msg.replace(\"discord.gg/\", \"discord.gg/\\u200b\") def clean_backticks(msg): \"\"\"Prevents backticks",
"clean_emojis(msg) return msg def clean_invite_embed(msg): \"\"\"Prevents invites from embedding\"\"\" return msg.replace(\"discord.gg/\", \"discord.gg/\\u200b\") def",
"re def clean_all(msg): msg = clean_invite_embed(msg) msg = clean_backticks(msg) msg = clean_mentions(msg) msg",
"\"\"\"Escape formatting items in a string.\"\"\" return re.sub(r\"([`*_])\", r\"\\\\\\1\", msg) def clean_mentions(msg): \"\"\"Prevent",
"return re.sub(r\"([`*_])\", r\"\\\\\\1\", msg) def clean_mentions(msg): \"\"\"Prevent discord mentions\"\"\" return msg.replace(\"@\", \"@\\u200b\") def",
"clean_backticks(msg): \"\"\"Prevents backticks from breaking code block formatting\"\"\" return msg.replace(\"`\", \"\\U0000ff40\") def clean_formatting(msg):",
"block formatting\"\"\" return msg.replace(\"`\", \"\\U0000ff40\") def clean_formatting(msg): \"\"\"Escape formatting items in a string.\"\"\"",
"= clean_backticks(msg) msg = clean_mentions(msg) msg = clean_emojis(msg) return msg def clean_invite_embed(msg): \"\"\"Prevents",
"in a string.\"\"\" return re.sub(r\"([`*_])\", r\"\\\\\\1\", msg) def clean_mentions(msg): \"\"\"Prevent discord mentions\"\"\" return",
"clean_invite_embed(msg) msg = clean_backticks(msg) msg = clean_mentions(msg) msg = clean_emojis(msg) return msg def",
"msg = clean_mentions(msg) msg = clean_emojis(msg) return msg def clean_invite_embed(msg): \"\"\"Prevents invites from",
"def clean_mentions(msg): \"\"\"Prevent discord mentions\"\"\" return msg.replace(\"@\", \"@\\u200b\") def clean_emojis(msg): \"\"\"Escape custom emojis.\"\"\"",
"\"\"\"Prevent discord mentions\"\"\" return msg.replace(\"@\", \"@\\u200b\") def clean_emojis(msg): \"\"\"Escape custom emojis.\"\"\" return re.sub(r\"<(a)?:([a-zA-Z0-9_]+):([0-9]+)>\",",
"from all unwanted content import re def clean_all(msg): msg = clean_invite_embed(msg) msg =",
"formatting\"\"\" return msg.replace(\"`\", \"\\U0000ff40\") def clean_formatting(msg): \"\"\"Escape formatting items in a string.\"\"\" return",
"# Module for cleaning messages from all unwanted content import re def clean_all(msg):",
"msg.replace(\"discord.gg/\", \"discord.gg/\\u200b\") def clean_backticks(msg): \"\"\"Prevents backticks from breaking code block formatting\"\"\" return msg.replace(\"`\",",
"string.\"\"\" return re.sub(r\"([`*_])\", r\"\\\\\\1\", msg) def clean_mentions(msg): \"\"\"Prevent discord mentions\"\"\" return msg.replace(\"@\", \"@\\u200b\")",
"content import re def clean_all(msg): msg = clean_invite_embed(msg) msg = clean_backticks(msg) msg =",
"msg.replace(\"`\", \"\\U0000ff40\") def clean_formatting(msg): \"\"\"Escape formatting items in a string.\"\"\" return re.sub(r\"([`*_])\", r\"\\\\\\1\",",
"\"\"\"Prevents backticks from breaking code block formatting\"\"\" return msg.replace(\"`\", \"\\U0000ff40\") def clean_formatting(msg): \"\"\"Escape",
"messages from all unwanted content import re def clean_all(msg): msg = clean_invite_embed(msg) msg",
"def clean_all(msg): msg = clean_invite_embed(msg) msg = clean_backticks(msg) msg = clean_mentions(msg) msg =",
"items in a string.\"\"\" return re.sub(r\"([`*_])\", r\"\\\\\\1\", msg) def clean_mentions(msg): \"\"\"Prevent discord mentions\"\"\"",
"cleaning messages from all unwanted content import re def clean_all(msg): msg = clean_invite_embed(msg)",
"for cleaning messages from all unwanted content import re def clean_all(msg): msg =",
"r\"\\\\\\1\", msg) def clean_mentions(msg): \"\"\"Prevent discord mentions\"\"\" return msg.replace(\"@\", \"@\\u200b\") def clean_emojis(msg): \"\"\"Escape",
"msg) def clean_mentions(msg): \"\"\"Prevent discord mentions\"\"\" return msg.replace(\"@\", \"@\\u200b\") def clean_emojis(msg): \"\"\"Escape custom",
"code block formatting\"\"\" return msg.replace(\"`\", \"\\U0000ff40\") def clean_formatting(msg): \"\"\"Escape formatting items in a",
"clean_mentions(msg): \"\"\"Prevent discord mentions\"\"\" return msg.replace(\"@\", \"@\\u200b\") def clean_emojis(msg): \"\"\"Escape custom emojis.\"\"\" return",
"clean_mentions(msg) msg = clean_emojis(msg) return msg def clean_invite_embed(msg): \"\"\"Prevents invites from embedding\"\"\" return",
"def clean_backticks(msg): \"\"\"Prevents backticks from breaking code block formatting\"\"\" return msg.replace(\"`\", \"\\U0000ff40\") def",
"clean_formatting(msg): \"\"\"Escape formatting items in a string.\"\"\" return re.sub(r\"([`*_])\", r\"\\\\\\1\", msg) def clean_mentions(msg):",
"= clean_invite_embed(msg) msg = clean_backticks(msg) msg = clean_mentions(msg) msg = clean_emojis(msg) return msg",
"breaking code block formatting\"\"\" return msg.replace(\"`\", \"\\U0000ff40\") def clean_formatting(msg): \"\"\"Escape formatting items in",
"invites from embedding\"\"\" return msg.replace(\"discord.gg/\", \"discord.gg/\\u200b\") def clean_backticks(msg): \"\"\"Prevents backticks from breaking code",
"msg = clean_invite_embed(msg) msg = clean_backticks(msg) msg = clean_mentions(msg) msg = clean_emojis(msg) return",
"all unwanted content import re def clean_all(msg): msg = clean_invite_embed(msg) msg = clean_backticks(msg)",
"return msg.replace(\"`\", \"\\U0000ff40\") def clean_formatting(msg): \"\"\"Escape formatting items in a string.\"\"\" return re.sub(r\"([`*_])\",",
"return msg.replace(\"discord.gg/\", \"discord.gg/\\u200b\") def clean_backticks(msg): \"\"\"Prevents backticks from breaking code block formatting\"\"\" return",
"Module for cleaning messages from all unwanted content import re def clean_all(msg): msg",
"backticks from breaking code block formatting\"\"\" return msg.replace(\"`\", \"\\U0000ff40\") def clean_formatting(msg): \"\"\"Escape formatting",
"def clean_formatting(msg): \"\"\"Escape formatting items in a string.\"\"\" return re.sub(r\"([`*_])\", r\"\\\\\\1\", msg) def",
"msg = clean_emojis(msg) return msg def clean_invite_embed(msg): \"\"\"Prevents invites from embedding\"\"\" return msg.replace(\"discord.gg/\",",
"return msg def clean_invite_embed(msg): \"\"\"Prevents invites from embedding\"\"\" return msg.replace(\"discord.gg/\", \"discord.gg/\\u200b\") def clean_backticks(msg):",
"\"\"\"Prevents invites from embedding\"\"\" return msg.replace(\"discord.gg/\", \"discord.gg/\\u200b\") def clean_backticks(msg): \"\"\"Prevents backticks from breaking",
"discord mentions\"\"\" return msg.replace(\"@\", \"@\\u200b\") def clean_emojis(msg): \"\"\"Escape custom emojis.\"\"\" return re.sub(r\"<(a)?:([a-zA-Z0-9_]+):([0-9]+)>\", \"<\\u200b\\\\1:\\\\2:\\\\3>\",",
"= clean_emojis(msg) return msg def clean_invite_embed(msg): \"\"\"Prevents invites from embedding\"\"\" return msg.replace(\"discord.gg/\", \"discord.gg/\\u200b\")"
] |
[
"list(legend1.keys()) # Plot the results (= shape of the data points cloud) plt.figure(1)",
"yy1, Z1, levels=[0], linewidths=2, colors=colors[i]) legend1_values_list = list(legend1.values()) legend1_keys_list = list(legend1.keys()) # Plot",
"be able to run ML algorithms json_to_python = json.loads(data) per_size = dict() #",
"IP-Response size hostlist = dict() # Data pre-processing here: for y in json_to_python:",
"y in json_to_python: hostlist[y['HOST']] = 1 if y['HOST'] in per_size: per_size[y['HOST']].append(int(y['SIZE'])) else: per_size[y['HOST']]",
"= { \"Empirical Covariance\": EllipticEnvelope(support_fraction=1., contamination=0.261), \"Robust Covariance (Minimum Covariance Determinant)\": EllipticEnvelope(contamination=0.261), \"OCSVM\":",
"numpy as np from sklearn.covariance import EllipticEnvelope from sklearn.svm import OneClassSVM log =",
"IP-Address and Response Size received: Elliptic Envelope ********\" ) log.info( \"******** Check the",
"import logging import matplotlib.font_manager import matplotlib.pyplot as plt import numpy as np from",
"several classifiers xx1, yy1 = np.meshgrid(np.linspace(-8, 28, 500), np.linspace(3, 40, 500)) xx2, yy2",
"working directory ********\" ) # print kmeans.labels_ #################################### ## Analysis 4 (4): Outlier-unsupervised-elliptic",
"and average response size ****\" ) #####*****SIZE******#### #### Analysis #4 (1): IP address",
"log.info( \"******** Check the image elliptic.png saved in the working directory ********\" )",
"zero + \"0\" y[z] = zero + y[z] ip = ip + y[z]",
"from sklearn.covariance import EllipticEnvelope from sklearn.svm import OneClassSVM log = logging.getLogger(__name__) def analyze(data):",
"the results (= shape of the data points cloud) plt.figure(1) # two clusters",
"4 (1): K-means on IP and average response size ****\" ) #####*****SIZE******#### ####",
"legend1_keys_list[2]), loc=\"upper center\", prop=matplotlib.font_manager.FontProperties(size=12)) plt.ylabel(\"Response size received\") plt.xlabel(\"Host-IP address\") ##plt.show() plt.savefig('elliptic.png') def mean(numbers):",
"Input to analysis - 4 (1): K-means on IP and average response size",
"used classifiers = { \"Empirical Covariance\": EllipticEnvelope(support_fraction=1., contamination=0.261), \"Robust Covariance (Minimum Covariance Determinant)\":",
"np.vstack([X, le]) log.info( \"******** Printing Analysis #4: IP-Address and Response Size received: Elliptic",
"\"0\" y[z] = zero + y[z] ip = ip + y[z] # log.debug(",
"X = np.vstack([X, le]) log.info( \"******** Printing Analysis #4: IP-Address and Response Size",
"for i, (clf_name, clf) in enumerate(classifiers.items()): plt.figure(1) clf.fit(X1) Z1 = clf.decision_function(np.c_[xx1.ravel(), yy1.ravel()]) Z1",
"data set: IP-response size received:\") plt.scatter(X1[:, 0], X1[:, 1], color='black') bbox_args = dict(boxstyle=\"round\",",
"500)) xx2, yy2 = np.meshgrid(np.linspace(3, 10, 500), np.linspace(-5, 45, 500)) for i, (clf_name,",
"frontier for outlier detection with several classifiers xx1, yy1 = np.meshgrid(np.linspace(-8, 28, 500),",
"# IP-Response size hostlist = dict() # Data pre-processing here: for y in",
"not working our data)##### X1 = X # Define \"classifiers\" to be used",
"clf.decision_function(np.c_[xx1.ravel(), yy1.ravel()]) Z1 = Z1.reshape(xx1.shape) legend1[clf_name] = plt.contour( xx1, yy1, Z1, levels=[0], linewidths=2,",
"\"\" for z in range(4): l = len(y[z]) l = 3 - l",
"- l if (l > 0): zero = \"\" for t in range(3",
"a frontier for outlier detection with several classifiers xx1, yy1 = np.meshgrid(np.linspace(-8, 28,",
"****\" ) #####*****SIZE******#### #### Analysis #4 (1): IP address - Size of response",
"10, 500), np.linspace(-5, 45, 500)) for i, (clf_name, clf) in enumerate(classifiers.items()): plt.figure(1) clf.fit(X1)",
"log.debug( \"*** Printing Input to analysis - 4 (1): K-means on IP and",
"Covariance\": EllipticEnvelope(support_fraction=1., contamination=0.261), \"Robust Covariance (Minimum Covariance Determinant)\": EllipticEnvelope(contamination=0.261), \"OCSVM\": OneClassSVM(nu=0.261, gamma=0.05) }",
"the working directory ********\" ) # print kmeans.labels_ #################################### ## Analysis 4 (4):",
"Z1 = clf.decision_function(np.c_[xx1.ravel(), yy1.ravel()]) Z1 = Z1.reshape(xx1.shape) legend1[clf_name] = plt.contour( xx1, yy1, Z1,",
"import OneClassSVM log = logging.getLogger(__name__) def analyze(data): # Convert this to python data",
"import numpy as np from sklearn.covariance import EllipticEnvelope from sklearn.svm import OneClassSVM log",
"plt import numpy as np from sklearn.covariance import EllipticEnvelope from sklearn.svm import OneClassSVM",
"two clusters plt.title( \"Outlier detection on a real data set: IP-response size received:\")",
"in enumerate(classifiers.items()): plt.figure(1) clf.fit(X1) Z1 = clf.decision_function(np.c_[xx1.ravel(), yy1.ravel()]) Z1 = Z1.reshape(xx1.shape) legend1[clf_name] =",
"zero + y[z] ip = ip + y[z] # log.debug( str(float(float(ip)/1000)) + \":",
"the data points cloud) plt.figure(1) # two clusters plt.title( \"Outlier detection on a",
"to be able to run ML algorithms json_to_python = json.loads(data) per_size = dict()",
"# log.debug( str(float(float(ip)/1000)) + \": \" + str(avg_size)) le = [float(float(ip) / 1000),",
"\"OCSVM\": OneClassSVM(nu=0.261, gamma=0.05) } colors = ['m', 'g', 'b'] legend1 = {} legend2",
"OneClassSVM(nu=0.261, gamma=0.05) } colors = ['m', 'g', 'b'] legend1 = {} legend2 =",
"[float(float(ip) / 1000), avg_size] X = np.vstack([X, le]) log.info( \"******** Printing Analysis #4:",
"{} # Learn a frontier for outlier detection with several classifiers xx1, yy1",
"Z1 = Z1.reshape(xx1.shape) legend1[clf_name] = plt.contour( xx1, yy1, Z1, levels=[0], linewidths=2, colors=colors[i]) legend1_values_list",
"results (= shape of the data points cloud) plt.figure(1) # two clusters plt.title(",
"+ \": \" + str(avg_size)) y = x.split(\".\") ip = \"\" for z",
"+ \"0\" y[z] = zero + y[z] ip = ip + y[z] #",
"= {} # Learn a frontier for outlier detection with several classifiers xx1,",
"IP and average response size ****\" ) #####*****SIZE******#### #### Analysis #4 (1): IP",
"Determinant)\": EllipticEnvelope(contamination=0.261), \"OCSVM\": OneClassSVM(nu=0.261, gamma=0.05) } colors = ['m', 'g', 'b'] legend1 =",
"\"******** Printing Analysis #4: IP-Address and Response Size received: Elliptic Envelope ********\" )",
"received:\") plt.scatter(X1[:, 0], X1[:, 1], color='black') bbox_args = dict(boxstyle=\"round\", fc=\"0.8\") plt.xlim((xx1.min(), xx1.max())) plt.ylim((yy1.min(),",
"+ \": \" + str(avg_size)) le = [float(float(ip) / 1000), avg_size] X =",
"on a real data set: IP-response size received:\") plt.scatter(X1[:, 0], X1[:, 1], color='black')",
"<gh_stars>1-10 import json import logging import matplotlib.font_manager import matplotlib.pyplot as plt import numpy",
"- 4 (1): K-means on IP and average response size ****\" ) #####*****SIZE******####",
"dict() # Data pre-processing here: for y in json_to_python: hostlist[y['HOST']] = 1 if",
"if y['HOST'] in per_size: per_size[y['HOST']].append(int(y['SIZE'])) else: per_size[y['HOST']] = [int(y['SIZE'])] ##Data pre-processing ends here",
"cloud) plt.figure(1) # two clusters plt.title( \"Outlier detection on a real data set:",
"per_size[y['HOST']].append(int(y['SIZE'])) else: per_size[y['HOST']] = [int(y['SIZE'])] ##Data pre-processing ends here log.debug( \"*** Printing Input",
"\"\" for t in range(3 - len(y[z])): zero = zero + \"0\" y[z]",
"= dict() # IP-Response size hostlist = dict() # Data pre-processing here: for",
"# Data pre-processing here: for y in json_to_python: hostlist[y['HOST']] = 1 if y['HOST']",
"28, 500), np.linspace(3, 40, 500)) xx2, yy2 = np.meshgrid(np.linspace(3, 10, 500), np.linspace(-5, 45,",
"+ str(avg_size)) y = x.split(\".\") ip = \"\" for z in range(4): l",
"# Plot the results (= shape of the data points cloud) plt.figure(1) #",
"matplotlib.pyplot as plt import numpy as np from sklearn.covariance import EllipticEnvelope from sklearn.svm",
"X # Define \"classifiers\" to be used classifiers = { \"Empirical Covariance\": EllipticEnvelope(support_fraction=1.,",
"#4 (1): IP address - Size of response received feature X = np.array([[0.00,",
"zero = \"\" for t in range(3 - len(y[z])): zero = zero +",
"\"classifiers\" to be used classifiers = { \"Empirical Covariance\": EllipticEnvelope(support_fraction=1., contamination=0.261), \"Robust Covariance",
"= ['m', 'g', 'b'] legend1 = {} legend2 = {} # Learn a",
"X1[:, 1], color='black') bbox_args = dict(boxstyle=\"round\", fc=\"0.8\") plt.xlim((xx1.min(), xx1.max())) plt.ylim((yy1.min(), yy1.max())) plt.legend( (legend1_values_list[0].collections[0],",
"to be used classifiers = { \"Empirical Covariance\": EllipticEnvelope(support_fraction=1., contamination=0.261), \"Robust Covariance (Minimum",
"1000), avg_size] X = np.vstack([X, le]) log.info( \"******** Printing Analysis #4: IP-Address and",
"\": \" + str(avg_size)) le = [float(float(ip) / 1000), avg_size] X = np.vstack([X,",
"= plt.contour( xx1, yy1, Z1, levels=[0], linewidths=2, colors=colors[i]) legend1_values_list = list(legend1.values()) legend1_keys_list =",
"plt.ylim((yy1.min(), yy1.max())) plt.legend( (legend1_values_list[0].collections[0], legend1_values_list[1].collections[0], legend1_values_list[2].collections[0]), (legend1_keys_list[0], legend1_keys_list[1], legend1_keys_list[2]), loc=\"upper center\", prop=matplotlib.font_manager.FontProperties(size=12)) plt.ylabel(\"Response",
"['m', 'g', 'b'] legend1 = {} legend2 = {} # Learn a frontier",
"Envelope ********\" ) log.info( \"******** Check the image elliptic.png saved in the working",
"= np.meshgrid(np.linspace(3, 10, 500), np.linspace(-5, 45, 500)) for i, (clf_name, clf) in enumerate(classifiers.items()):",
"= dict(boxstyle=\"round\", fc=\"0.8\") plt.xlim((xx1.min(), xx1.max())) plt.ylim((yy1.min(), yy1.max())) plt.legend( (legend1_values_list[0].collections[0], legend1_values_list[1].collections[0], legend1_values_list[2].collections[0]), (legend1_keys_list[0], legend1_keys_list[1],",
"plt.contour( xx1, yy1, Z1, levels=[0], linewidths=2, colors=colors[i]) legend1_values_list = list(legend1.values()) legend1_keys_list = list(legend1.keys())",
"= {} legend2 = {} # Learn a frontier for outlier detection with",
"detection on a real data set: IP-response size received:\") plt.scatter(X1[:, 0], X1[:, 1],",
"as plt import numpy as np from sklearn.covariance import EllipticEnvelope from sklearn.svm import",
"\": \" + str(avg_size)) y = x.split(\".\") ip = \"\" for z in",
"X = np.array([[0.00, 0.00]]) for x in hostlist: avg_size = mean(per_size[x]) log.debug(x +",
"legend2 = {} # Learn a frontier for outlier detection with several classifiers",
"image elliptic.png saved in the working directory ********\" ) # print kmeans.labels_ ####################################",
"500)) for i, (clf_name, clf) in enumerate(classifiers.items()): plt.figure(1) clf.fit(X1) Z1 = clf.decision_function(np.c_[xx1.ravel(), yy1.ravel()])",
"l if (l > 0): zero = \"\" for t in range(3 -",
"3 - l if (l > 0): zero = \"\" for t in",
"ML algorithms json_to_python = json.loads(data) per_size = dict() # IP-Response size hostlist =",
"data)##### X1 = X # Define \"classifiers\" to be used classifiers = {",
"run ML algorithms json_to_python = json.loads(data) per_size = dict() # IP-Response size hostlist",
"as np from sklearn.covariance import EllipticEnvelope from sklearn.svm import OneClassSVM log = logging.getLogger(__name__)",
"json_to_python = json.loads(data) per_size = dict() # IP-Response size hostlist = dict() #",
"0): zero = \"\" for t in range(3 - len(y[z])): zero = zero",
"= list(legend1.keys()) # Plot the results (= shape of the data points cloud)",
"Printing Input to analysis - 4 (1): K-means on IP and average response",
"len(y[z]) l = 3 - l if (l > 0): zero = \"\"",
"(Minimum Covariance Determinant)\": EllipticEnvelope(contamination=0.261), \"OCSVM\": OneClassSVM(nu=0.261, gamma=0.05) } colors = ['m', 'g', 'b']",
"(4): Outlier-unsupervised-elliptic (Currently not working our data)##### X1 = X # Define \"classifiers\"",
"= zero + \"0\" y[z] = zero + y[z] ip = ip +",
"np.linspace(-5, 45, 500)) for i, (clf_name, clf) in enumerate(classifiers.items()): plt.figure(1) clf.fit(X1) Z1 =",
"Learn a frontier for outlier detection with several classifiers xx1, yy1 = np.meshgrid(np.linspace(-8,",
"analyze(data): # Convert this to python data for us to be able to",
"Response Size received: Elliptic Envelope ********\" ) log.info( \"******** Check the image elliptic.png",
"= np.array([[0.00, 0.00]]) for x in hostlist: avg_size = mean(per_size[x]) log.debug(x + \":",
"- len(y[z])): zero = zero + \"0\" y[z] = zero + y[z] ip",
"/ 1000), avg_size] X = np.vstack([X, le]) log.info( \"******** Printing Analysis #4: IP-Address",
"address - Size of response received feature X = np.array([[0.00, 0.00]]) for x",
"np.meshgrid(np.linspace(-8, 28, 500), np.linspace(3, 40, 500)) xx2, yy2 = np.meshgrid(np.linspace(3, 10, 500), np.linspace(-5,",
"Outlier-unsupervised-elliptic (Currently not working our data)##### X1 = X # Define \"classifiers\" to",
"in hostlist: avg_size = mean(per_size[x]) log.debug(x + \": \" + str(avg_size)) y =",
"linewidths=2, colors=colors[i]) legend1_values_list = list(legend1.values()) legend1_keys_list = list(legend1.keys()) # Plot the results (=",
"json_to_python: hostlist[y['HOST']] = 1 if y['HOST'] in per_size: per_size[y['HOST']].append(int(y['SIZE'])) else: per_size[y['HOST']] = [int(y['SIZE'])]",
"********\" ) # print kmeans.labels_ #################################### ## Analysis 4 (4): Outlier-unsupervised-elliptic (Currently not",
"x in hostlist: avg_size = mean(per_size[x]) log.debug(x + \": \" + str(avg_size)) y",
"(legend1_keys_list[0], legend1_keys_list[1], legend1_keys_list[2]), loc=\"upper center\", prop=matplotlib.font_manager.FontProperties(size=12)) plt.ylabel(\"Response size received\") plt.xlabel(\"Host-IP address\") ##plt.show() plt.savefig('elliptic.png')",
"loc=\"upper center\", prop=matplotlib.font_manager.FontProperties(size=12)) plt.ylabel(\"Response size received\") plt.xlabel(\"Host-IP address\") ##plt.show() plt.savefig('elliptic.png') def mean(numbers): return",
"= \"\" for z in range(4): l = len(y[z]) l = 3 -",
"Size received: Elliptic Envelope ********\" ) log.info( \"******** Check the image elliptic.png saved",
"log.debug( str(float(float(ip)/1000)) + \": \" + str(avg_size)) le = [float(float(ip) / 1000), avg_size]",
"= mean(per_size[x]) log.debug(x + \": \" + str(avg_size)) y = x.split(\".\") ip =",
"for us to be able to run ML algorithms json_to_python = json.loads(data) per_size",
"xx2, yy2 = np.meshgrid(np.linspace(3, 10, 500), np.linspace(-5, 45, 500)) for i, (clf_name, clf)",
"fc=\"0.8\") plt.xlim((xx1.min(), xx1.max())) plt.ylim((yy1.min(), yy1.max())) plt.legend( (legend1_values_list[0].collections[0], legend1_values_list[1].collections[0], legend1_values_list[2].collections[0]), (legend1_keys_list[0], legend1_keys_list[1], legend1_keys_list[2]), loc=\"upper",
"\"Robust Covariance (Minimum Covariance Determinant)\": EllipticEnvelope(contamination=0.261), \"OCSVM\": OneClassSVM(nu=0.261, gamma=0.05) } colors = ['m',",
"{} legend2 = {} # Learn a frontier for outlier detection with several",
"500), np.linspace(3, 40, 500)) xx2, yy2 = np.meshgrid(np.linspace(3, 10, 500), np.linspace(-5, 45, 500))",
"levels=[0], linewidths=2, colors=colors[i]) legend1_values_list = list(legend1.values()) legend1_keys_list = list(legend1.keys()) # Plot the results",
"sklearn.covariance import EllipticEnvelope from sklearn.svm import OneClassSVM log = logging.getLogger(__name__) def analyze(data): #",
"= clf.decision_function(np.c_[xx1.ravel(), yy1.ravel()]) Z1 = Z1.reshape(xx1.shape) legend1[clf_name] = plt.contour( xx1, yy1, Z1, levels=[0],",
"(1): K-means on IP and average response size ****\" ) #####*****SIZE******#### #### Analysis",
"pre-processing ends here log.debug( \"*** Printing Input to analysis - 4 (1): K-means",
"xx1, yy1 = np.meshgrid(np.linspace(-8, 28, 500), np.linspace(3, 40, 500)) xx2, yy2 = np.meshgrid(np.linspace(3,",
"##Data pre-processing ends here log.debug( \"*** Printing Input to analysis - 4 (1):",
"1 if y['HOST'] in per_size: per_size[y['HOST']].append(int(y['SIZE'])) else: per_size[y['HOST']] = [int(y['SIZE'])] ##Data pre-processing ends",
"yy1.max())) plt.legend( (legend1_values_list[0].collections[0], legend1_values_list[1].collections[0], legend1_values_list[2].collections[0]), (legend1_keys_list[0], legend1_keys_list[1], legend1_keys_list[2]), loc=\"upper center\", prop=matplotlib.font_manager.FontProperties(size=12)) plt.ylabel(\"Response size",
"in json_to_python: hostlist[y['HOST']] = 1 if y['HOST'] in per_size: per_size[y['HOST']].append(int(y['SIZE'])) else: per_size[y['HOST']] =",
"log = logging.getLogger(__name__) def analyze(data): # Convert this to python data for us",
"= logging.getLogger(__name__) def analyze(data): # Convert this to python data for us to",
"legend1_values_list[1].collections[0], legend1_values_list[2].collections[0]), (legend1_keys_list[0], legend1_keys_list[1], legend1_keys_list[2]), loc=\"upper center\", prop=matplotlib.font_manager.FontProperties(size=12)) plt.ylabel(\"Response size received\") plt.xlabel(\"Host-IP address\")",
"l = len(y[z]) l = 3 - l if (l > 0): zero",
"shape of the data points cloud) plt.figure(1) # two clusters plt.title( \"Outlier detection",
"here: for y in json_to_python: hostlist[y['HOST']] = 1 if y['HOST'] in per_size: per_size[y['HOST']].append(int(y['SIZE']))",
"y['HOST'] in per_size: per_size[y['HOST']].append(int(y['SIZE'])) else: per_size[y['HOST']] = [int(y['SIZE'])] ##Data pre-processing ends here log.debug(",
"x.split(\".\") ip = \"\" for z in range(4): l = len(y[z]) l =",
"4 (4): Outlier-unsupervised-elliptic (Currently not working our data)##### X1 = X # Define",
"sklearn.svm import OneClassSVM log = logging.getLogger(__name__) def analyze(data): # Convert this to python",
"of the data points cloud) plt.figure(1) # two clusters plt.title( \"Outlier detection on",
"str(float(float(ip)/1000)) + \": \" + str(avg_size)) le = [float(float(ip) / 1000), avg_size] X",
"= np.meshgrid(np.linspace(-8, 28, 500), np.linspace(3, 40, 500)) xx2, yy2 = np.meshgrid(np.linspace(3, 10, 500),",
"IP address - Size of response received feature X = np.array([[0.00, 0.00]]) for",
"analysis - 4 (1): K-means on IP and average response size ****\" )",
"json import logging import matplotlib.font_manager import matplotlib.pyplot as plt import numpy as np",
"\"*** Printing Input to analysis - 4 (1): K-means on IP and average",
"contamination=0.261), \"Robust Covariance (Minimum Covariance Determinant)\": EllipticEnvelope(contamination=0.261), \"OCSVM\": OneClassSVM(nu=0.261, gamma=0.05) } colors =",
"'b'] legend1 = {} legend2 = {} # Learn a frontier for outlier",
"list(legend1.values()) legend1_keys_list = list(legend1.keys()) # Plot the results (= shape of the data",
"Z1, levels=[0], linewidths=2, colors=colors[i]) legend1_values_list = list(legend1.values()) legend1_keys_list = list(legend1.keys()) # Plot the",
"np.array([[0.00, 0.00]]) for x in hostlist: avg_size = mean(per_size[x]) log.debug(x + \": \"",
"size received:\") plt.scatter(X1[:, 0], X1[:, 1], color='black') bbox_args = dict(boxstyle=\"round\", fc=\"0.8\") plt.xlim((xx1.min(), xx1.max()))",
"matplotlib.font_manager import matplotlib.pyplot as plt import numpy as np from sklearn.covariance import EllipticEnvelope",
"0.00]]) for x in hostlist: avg_size = mean(per_size[x]) log.debug(x + \": \" +",
"logging import matplotlib.font_manager import matplotlib.pyplot as plt import numpy as np from sklearn.covariance",
"EllipticEnvelope(contamination=0.261), \"OCSVM\": OneClassSVM(nu=0.261, gamma=0.05) } colors = ['m', 'g', 'b'] legend1 = {}",
"\" + str(avg_size)) y = x.split(\".\") ip = \"\" for z in range(4):",
"response size ****\" ) #####*****SIZE******#### #### Analysis #4 (1): IP address - Size",
"# Convert this to python data for us to be able to run",
"OneClassSVM log = logging.getLogger(__name__) def analyze(data): # Convert this to python data for",
"plt.xlim((xx1.min(), xx1.max())) plt.ylim((yy1.min(), yy1.max())) plt.legend( (legend1_values_list[0].collections[0], legend1_values_list[1].collections[0], legend1_values_list[2].collections[0]), (legend1_keys_list[0], legend1_keys_list[1], legend1_keys_list[2]), loc=\"upper center\",",
"ip = \"\" for z in range(4): l = len(y[z]) l = 3",
"= 1 if y['HOST'] in per_size: per_size[y['HOST']].append(int(y['SIZE'])) else: per_size[y['HOST']] = [int(y['SIZE'])] ##Data pre-processing",
"y[z] ip = ip + y[z] # log.debug( str(float(float(ip)/1000)) + \": \" +",
"#4: IP-Address and Response Size received: Elliptic Envelope ********\" ) log.info( \"******** Check",
"a real data set: IP-response size received:\") plt.scatter(X1[:, 0], X1[:, 1], color='black') bbox_args",
"dict(boxstyle=\"round\", fc=\"0.8\") plt.xlim((xx1.min(), xx1.max())) plt.ylim((yy1.min(), yy1.max())) plt.legend( (legend1_values_list[0].collections[0], legend1_values_list[1].collections[0], legend1_values_list[2].collections[0]), (legend1_keys_list[0], legend1_keys_list[1], legend1_keys_list[2]),",
"500), np.linspace(-5, 45, 500)) for i, (clf_name, clf) in enumerate(classifiers.items()): plt.figure(1) clf.fit(X1) Z1",
"elliptic.png saved in the working directory ********\" ) # print kmeans.labels_ #################################### ##",
"for y in json_to_python: hostlist[y['HOST']] = 1 if y['HOST'] in per_size: per_size[y['HOST']].append(int(y['SIZE'])) else:",
"avg_size = mean(per_size[x]) log.debug(x + \": \" + str(avg_size)) y = x.split(\".\") ip",
"from sklearn.svm import OneClassSVM log = logging.getLogger(__name__) def analyze(data): # Convert this to",
"+ y[z] ip = ip + y[z] # log.debug( str(float(float(ip)/1000)) + \": \"",
"set: IP-response size received:\") plt.scatter(X1[:, 0], X1[:, 1], color='black') bbox_args = dict(boxstyle=\"round\", fc=\"0.8\")",
"classifiers = { \"Empirical Covariance\": EllipticEnvelope(support_fraction=1., contamination=0.261), \"Robust Covariance (Minimum Covariance Determinant)\": EllipticEnvelope(contamination=0.261),",
"us to be able to run ML algorithms json_to_python = json.loads(data) per_size =",
"********\" ) log.info( \"******** Check the image elliptic.png saved in the working directory",
"size received\") plt.xlabel(\"Host-IP address\") ##plt.show() plt.savefig('elliptic.png') def mean(numbers): return float(sum(numbers)) / max(len(numbers), 1)",
"0], X1[:, 1], color='black') bbox_args = dict(boxstyle=\"round\", fc=\"0.8\") plt.xlim((xx1.min(), xx1.max())) plt.ylim((yy1.min(), yy1.max())) plt.legend(",
"+ y[z] # log.debug( str(float(float(ip)/1000)) + \": \" + str(avg_size)) le = [float(float(ip)",
"Define \"classifiers\" to be used classifiers = { \"Empirical Covariance\": EllipticEnvelope(support_fraction=1., contamination=0.261), \"Robust",
"Analysis 4 (4): Outlier-unsupervised-elliptic (Currently not working our data)##### X1 = X #",
"= Z1.reshape(xx1.shape) legend1[clf_name] = plt.contour( xx1, yy1, Z1, levels=[0], linewidths=2, colors=colors[i]) legend1_values_list =",
"plt.title( \"Outlier detection on a real data set: IP-response size received:\") plt.scatter(X1[:, 0],",
"for outlier detection with several classifiers xx1, yy1 = np.meshgrid(np.linspace(-8, 28, 500), np.linspace(3,",
"clf) in enumerate(classifiers.items()): plt.figure(1) clf.fit(X1) Z1 = clf.decision_function(np.c_[xx1.ravel(), yy1.ravel()]) Z1 = Z1.reshape(xx1.shape) legend1[clf_name]",
"[int(y['SIZE'])] ##Data pre-processing ends here log.debug( \"*** Printing Input to analysis - 4",
"to python data for us to be able to run ML algorithms json_to_python",
"per_size: per_size[y['HOST']].append(int(y['SIZE'])) else: per_size[y['HOST']] = [int(y['SIZE'])] ##Data pre-processing ends here log.debug( \"*** Printing",
"kmeans.labels_ #################################### ## Analysis 4 (4): Outlier-unsupervised-elliptic (Currently not working our data)##### X1",
"average response size ****\" ) #####*****SIZE******#### #### Analysis #4 (1): IP address -",
"colors = ['m', 'g', 'b'] legend1 = {} legend2 = {} # Learn",
"for z in range(4): l = len(y[z]) l = 3 - l if",
"Plot the results (= shape of the data points cloud) plt.figure(1) # two",
"of response received feature X = np.array([[0.00, 0.00]]) for x in hostlist: avg_size",
"colors=colors[i]) legend1_values_list = list(legend1.values()) legend1_keys_list = list(legend1.keys()) # Plot the results (= shape",
"np from sklearn.covariance import EllipticEnvelope from sklearn.svm import OneClassSVM log = logging.getLogger(__name__) def",
"str(avg_size)) le = [float(float(ip) / 1000), avg_size] X = np.vstack([X, le]) log.info( \"********",
"legend1[clf_name] = plt.contour( xx1, yy1, Z1, levels=[0], linewidths=2, colors=colors[i]) legend1_values_list = list(legend1.values()) legend1_keys_list",
"python data for us to be able to run ML algorithms json_to_python =",
"= [int(y['SIZE'])] ##Data pre-processing ends here log.debug( \"*** Printing Input to analysis -",
"\" + str(avg_size)) le = [float(float(ip) / 1000), avg_size] X = np.vstack([X, le])",
"(= shape of the data points cloud) plt.figure(1) # two clusters plt.title( \"Outlier",
"data for us to be able to run ML algorithms json_to_python = json.loads(data)",
"yy2 = np.meshgrid(np.linspace(3, 10, 500), np.linspace(-5, 45, 500)) for i, (clf_name, clf) in",
"feature X = np.array([[0.00, 0.00]]) for x in hostlist: avg_size = mean(per_size[x]) log.debug(x",
"per_size[y['HOST']] = [int(y['SIZE'])] ##Data pre-processing ends here log.debug( \"*** Printing Input to analysis",
"Analysis #4: IP-Address and Response Size received: Elliptic Envelope ********\" ) log.info( \"********",
"'g', 'b'] legend1 = {} legend2 = {} # Learn a frontier for",
"log.debug(x + \": \" + str(avg_size)) y = x.split(\".\") ip = \"\" for",
"= np.vstack([X, le]) log.info( \"******** Printing Analysis #4: IP-Address and Response Size received:",
"size hostlist = dict() # Data pre-processing here: for y in json_to_python: hostlist[y['HOST']]",
"with several classifiers xx1, yy1 = np.meshgrid(np.linspace(-8, 28, 500), np.linspace(3, 40, 500)) xx2,",
"ip = ip + y[z] # log.debug( str(float(float(ip)/1000)) + \": \" + str(avg_size))",
"Size of response received feature X = np.array([[0.00, 0.00]]) for x in hostlist:",
"zero = zero + \"0\" y[z] = zero + y[z] ip = ip",
"points cloud) plt.figure(1) # two clusters plt.title( \"Outlier detection on a real data",
"(l > 0): zero = \"\" for t in range(3 - len(y[z])): zero",
"plt.scatter(X1[:, 0], X1[:, 1], color='black') bbox_args = dict(boxstyle=\"round\", fc=\"0.8\") plt.xlim((xx1.min(), xx1.max())) plt.ylim((yy1.min(), yy1.max()))",
"## Analysis 4 (4): Outlier-unsupervised-elliptic (Currently not working our data)##### X1 = X",
"detection with several classifiers xx1, yy1 = np.meshgrid(np.linspace(-8, 28, 500), np.linspace(3, 40, 500))",
"(clf_name, clf) in enumerate(classifiers.items()): plt.figure(1) clf.fit(X1) Z1 = clf.decision_function(np.c_[xx1.ravel(), yy1.ravel()]) Z1 = Z1.reshape(xx1.shape)",
"for t in range(3 - len(y[z])): zero = zero + \"0\" y[z] =",
"= zero + y[z] ip = ip + y[z] # log.debug( str(float(float(ip)/1000)) +",
"(legend1_values_list[0].collections[0], legend1_values_list[1].collections[0], legend1_values_list[2].collections[0]), (legend1_keys_list[0], legend1_keys_list[1], legend1_keys_list[2]), loc=\"upper center\", prop=matplotlib.font_manager.FontProperties(size=12)) plt.ylabel(\"Response size received\") plt.xlabel(\"Host-IP",
"# print kmeans.labels_ #################################### ## Analysis 4 (4): Outlier-unsupervised-elliptic (Currently not working our",
"prop=matplotlib.font_manager.FontProperties(size=12)) plt.ylabel(\"Response size received\") plt.xlabel(\"Host-IP address\") ##plt.show() plt.savefig('elliptic.png') def mean(numbers): return float(sum(numbers)) /",
"Check the image elliptic.png saved in the working directory ********\" ) # print",
"= dict() # Data pre-processing here: for y in json_to_python: hostlist[y['HOST']] = 1",
"in range(4): l = len(y[z]) l = 3 - l if (l >",
"our data)##### X1 = X # Define \"classifiers\" to be used classifiers =",
"outlier detection with several classifiers xx1, yy1 = np.meshgrid(np.linspace(-8, 28, 500), np.linspace(3, 40,",
"= x.split(\".\") ip = \"\" for z in range(4): l = len(y[z]) l",
"y[z] # log.debug( str(float(float(ip)/1000)) + \": \" + str(avg_size)) le = [float(float(ip) /",
"range(4): l = len(y[z]) l = 3 - l if (l > 0):",
"this to python data for us to be able to run ML algorithms",
"avg_size] X = np.vstack([X, le]) log.info( \"******** Printing Analysis #4: IP-Address and Response",
"classifiers xx1, yy1 = np.meshgrid(np.linspace(-8, 28, 500), np.linspace(3, 40, 500)) xx2, yy2 =",
"ip + y[z] # log.debug( str(float(float(ip)/1000)) + \": \" + str(avg_size)) le =",
"be used classifiers = { \"Empirical Covariance\": EllipticEnvelope(support_fraction=1., contamination=0.261), \"Robust Covariance (Minimum Covariance",
"np.linspace(3, 40, 500)) xx2, yy2 = np.meshgrid(np.linspace(3, 10, 500), np.linspace(-5, 45, 500)) for",
"= 3 - l if (l > 0): zero = \"\" for t",
"1], color='black') bbox_args = dict(boxstyle=\"round\", fc=\"0.8\") plt.xlim((xx1.min(), xx1.max())) plt.ylim((yy1.min(), yy1.max())) plt.legend( (legend1_values_list[0].collections[0], legend1_values_list[1].collections[0],",
"to run ML algorithms json_to_python = json.loads(data) per_size = dict() # IP-Response size",
"working our data)##### X1 = X # Define \"classifiers\" to be used classifiers",
"size ****\" ) #####*****SIZE******#### #### Analysis #4 (1): IP address - Size of",
"# Learn a frontier for outlier detection with several classifiers xx1, yy1 =",
"Covariance Determinant)\": EllipticEnvelope(contamination=0.261), \"OCSVM\": OneClassSVM(nu=0.261, gamma=0.05) } colors = ['m', 'g', 'b'] legend1",
"} colors = ['m', 'g', 'b'] legend1 = {} legend2 = {} #",
"able to run ML algorithms json_to_python = json.loads(data) per_size = dict() # IP-Response",
"import json import logging import matplotlib.font_manager import matplotlib.pyplot as plt import numpy as",
"legend1_keys_list[1], legend1_keys_list[2]), loc=\"upper center\", prop=matplotlib.font_manager.FontProperties(size=12)) plt.ylabel(\"Response size received\") plt.xlabel(\"Host-IP address\") ##plt.show() plt.savefig('elliptic.png') def",
"le]) log.info( \"******** Printing Analysis #4: IP-Address and Response Size received: Elliptic Envelope",
"logging.getLogger(__name__) def analyze(data): # Convert this to python data for us to be",
"for x in hostlist: avg_size = mean(per_size[x]) log.debug(x + \": \" + str(avg_size))",
"json.loads(data) per_size = dict() # IP-Response size hostlist = dict() # Data pre-processing",
"\"Outlier detection on a real data set: IP-response size received:\") plt.scatter(X1[:, 0], X1[:,",
"Data pre-processing here: for y in json_to_python: hostlist[y['HOST']] = 1 if y['HOST'] in",
"mean(per_size[x]) log.debug(x + \": \" + str(avg_size)) y = x.split(\".\") ip = \"\"",
"# two clusters plt.title( \"Outlier detection on a real data set: IP-response size",
"t in range(3 - len(y[z])): zero = zero + \"0\" y[z] = zero",
"ends here log.debug( \"*** Printing Input to analysis - 4 (1): K-means on",
"= \"\" for t in range(3 - len(y[z])): zero = zero + \"0\"",
"(Currently not working our data)##### X1 = X # Define \"classifiers\" to be",
"data points cloud) plt.figure(1) # two clusters plt.title( \"Outlier detection on a real",
"Covariance (Minimum Covariance Determinant)\": EllipticEnvelope(contamination=0.261), \"OCSVM\": OneClassSVM(nu=0.261, gamma=0.05) } colors = ['m', 'g',",
"= X # Define \"classifiers\" to be used classifiers = { \"Empirical Covariance\":",
") log.info( \"******** Check the image elliptic.png saved in the working directory ********\"",
"plt.figure(1) # two clusters plt.title( \"Outlier detection on a real data set: IP-response",
"here log.debug( \"*** Printing Input to analysis - 4 (1): K-means on IP",
") #####*****SIZE******#### #### Analysis #4 (1): IP address - Size of response received",
"45, 500)) for i, (clf_name, clf) in enumerate(classifiers.items()): plt.figure(1) clf.fit(X1) Z1 = clf.decision_function(np.c_[xx1.ravel(),",
"(1): IP address - Size of response received feature X = np.array([[0.00, 0.00]])",
"> 0): zero = \"\" for t in range(3 - len(y[z])): zero =",
"clf.fit(X1) Z1 = clf.decision_function(np.c_[xx1.ravel(), yy1.ravel()]) Z1 = Z1.reshape(xx1.shape) legend1[clf_name] = plt.contour( xx1, yy1,",
"yy1 = np.meshgrid(np.linspace(-8, 28, 500), np.linspace(3, 40, 500)) xx2, yy2 = np.meshgrid(np.linspace(3, 10,",
"= list(legend1.values()) legend1_keys_list = list(legend1.keys()) # Plot the results (= shape of the",
"str(avg_size)) y = x.split(\".\") ip = \"\" for z in range(4): l =",
"Elliptic Envelope ********\" ) log.info( \"******** Check the image elliptic.png saved in the",
"color='black') bbox_args = dict(boxstyle=\"round\", fc=\"0.8\") plt.xlim((xx1.min(), xx1.max())) plt.ylim((yy1.min(), yy1.max())) plt.legend( (legend1_values_list[0].collections[0], legend1_values_list[1].collections[0], legend1_values_list[2].collections[0]),",
"z in range(4): l = len(y[z]) l = 3 - l if (l",
"real data set: IP-response size received:\") plt.scatter(X1[:, 0], X1[:, 1], color='black') bbox_args =",
"hostlist[y['HOST']] = 1 if y['HOST'] in per_size: per_size[y['HOST']].append(int(y['SIZE'])) else: per_size[y['HOST']] = [int(y['SIZE'])] ##Data",
"# Define \"classifiers\" to be used classifiers = { \"Empirical Covariance\": EllipticEnvelope(support_fraction=1., contamination=0.261),",
"import matplotlib.pyplot as plt import numpy as np from sklearn.covariance import EllipticEnvelope from",
"dict() # IP-Response size hostlist = dict() # Data pre-processing here: for y",
"response received feature X = np.array([[0.00, 0.00]]) for x in hostlist: avg_size =",
"saved in the working directory ********\" ) # print kmeans.labels_ #################################### ## Analysis",
"hostlist: avg_size = mean(per_size[x]) log.debug(x + \": \" + str(avg_size)) y = x.split(\".\")",
"#################################### ## Analysis 4 (4): Outlier-unsupervised-elliptic (Currently not working our data)##### X1 =",
"center\", prop=matplotlib.font_manager.FontProperties(size=12)) plt.ylabel(\"Response size received\") plt.xlabel(\"Host-IP address\") ##plt.show() plt.savefig('elliptic.png') def mean(numbers): return float(sum(numbers))",
"algorithms json_to_python = json.loads(data) per_size = dict() # IP-Response size hostlist = dict()",
"Analysis #4 (1): IP address - Size of response received feature X =",
"\"******** Check the image elliptic.png saved in the working directory ********\" ) #",
"legend1_keys_list = list(legend1.keys()) # Plot the results (= shape of the data points",
"clusters plt.title( \"Outlier detection on a real data set: IP-response size received:\") plt.scatter(X1[:,",
"print kmeans.labels_ #################################### ## Analysis 4 (4): Outlier-unsupervised-elliptic (Currently not working our data)#####",
"xx1.max())) plt.ylim((yy1.min(), yy1.max())) plt.legend( (legend1_values_list[0].collections[0], legend1_values_list[1].collections[0], legend1_values_list[2].collections[0]), (legend1_keys_list[0], legend1_keys_list[1], legend1_keys_list[2]), loc=\"upper center\", prop=matplotlib.font_manager.FontProperties(size=12))",
"IP-response size received:\") plt.scatter(X1[:, 0], X1[:, 1], color='black') bbox_args = dict(boxstyle=\"round\", fc=\"0.8\") plt.xlim((xx1.min(),",
"plt.legend( (legend1_values_list[0].collections[0], legend1_values_list[1].collections[0], legend1_values_list[2].collections[0]), (legend1_keys_list[0], legend1_keys_list[1], legend1_keys_list[2]), loc=\"upper center\", prop=matplotlib.font_manager.FontProperties(size=12)) plt.ylabel(\"Response size received\")",
"K-means on IP and average response size ****\" ) #####*****SIZE******#### #### Analysis #4",
"Z1.reshape(xx1.shape) legend1[clf_name] = plt.contour( xx1, yy1, Z1, levels=[0], linewidths=2, colors=colors[i]) legend1_values_list = list(legend1.values())",
"X1 = X # Define \"classifiers\" to be used classifiers = { \"Empirical",
"in range(3 - len(y[z])): zero = zero + \"0\" y[z] = zero +",
"in per_size: per_size[y['HOST']].append(int(y['SIZE'])) else: per_size[y['HOST']] = [int(y['SIZE'])] ##Data pre-processing ends here log.debug( \"***",
"the image elliptic.png saved in the working directory ********\" ) # print kmeans.labels_",
"{ \"Empirical Covariance\": EllipticEnvelope(support_fraction=1., contamination=0.261), \"Robust Covariance (Minimum Covariance Determinant)\": EllipticEnvelope(contamination=0.261), \"OCSVM\": OneClassSVM(nu=0.261,",
"directory ********\" ) # print kmeans.labels_ #################################### ## Analysis 4 (4): Outlier-unsupervised-elliptic (Currently",
"= json.loads(data) per_size = dict() # IP-Response size hostlist = dict() # Data",
"legend1 = {} legend2 = {} # Learn a frontier for outlier detection",
"= ip + y[z] # log.debug( str(float(float(ip)/1000)) + \": \" + str(avg_size)) le",
"log.info( \"******** Printing Analysis #4: IP-Address and Response Size received: Elliptic Envelope ********\"",
"\"Empirical Covariance\": EllipticEnvelope(support_fraction=1., contamination=0.261), \"Robust Covariance (Minimum Covariance Determinant)\": EllipticEnvelope(contamination=0.261), \"OCSVM\": OneClassSVM(nu=0.261, gamma=0.05)",
"#### Analysis #4 (1): IP address - Size of response received feature X",
"received: Elliptic Envelope ********\" ) log.info( \"******** Check the image elliptic.png saved in",
"- Size of response received feature X = np.array([[0.00, 0.00]]) for x in",
"= [float(float(ip) / 1000), avg_size] X = np.vstack([X, le]) log.info( \"******** Printing Analysis",
"np.meshgrid(np.linspace(3, 10, 500), np.linspace(-5, 45, 500)) for i, (clf_name, clf) in enumerate(classifiers.items()): plt.figure(1)",
"Printing Analysis #4: IP-Address and Response Size received: Elliptic Envelope ********\" ) log.info(",
"= len(y[z]) l = 3 - l if (l > 0): zero =",
"Convert this to python data for us to be able to run ML",
"y = x.split(\".\") ip = \"\" for z in range(4): l = len(y[z])",
"xx1, yy1, Z1, levels=[0], linewidths=2, colors=colors[i]) legend1_values_list = list(legend1.values()) legend1_keys_list = list(legend1.keys()) #",
"if (l > 0): zero = \"\" for t in range(3 - len(y[z])):",
"pre-processing here: for y in json_to_python: hostlist[y['HOST']] = 1 if y['HOST'] in per_size:",
"import matplotlib.font_manager import matplotlib.pyplot as plt import numpy as np from sklearn.covariance import",
"EllipticEnvelope(support_fraction=1., contamination=0.261), \"Robust Covariance (Minimum Covariance Determinant)\": EllipticEnvelope(contamination=0.261), \"OCSVM\": OneClassSVM(nu=0.261, gamma=0.05) } colors",
"gamma=0.05) } colors = ['m', 'g', 'b'] legend1 = {} legend2 = {}",
"legend1_values_list[2].collections[0]), (legend1_keys_list[0], legend1_keys_list[1], legend1_keys_list[2]), loc=\"upper center\", prop=matplotlib.font_manager.FontProperties(size=12)) plt.ylabel(\"Response size received\") plt.xlabel(\"Host-IP address\") ##plt.show()",
"#####*****SIZE******#### #### Analysis #4 (1): IP address - Size of response received feature",
"+ str(avg_size)) le = [float(float(ip) / 1000), avg_size] X = np.vstack([X, le]) log.info(",
"len(y[z])): zero = zero + \"0\" y[z] = zero + y[z] ip =",
"yy1.ravel()]) Z1 = Z1.reshape(xx1.shape) legend1[clf_name] = plt.contour( xx1, yy1, Z1, levels=[0], linewidths=2, colors=colors[i])",
"i, (clf_name, clf) in enumerate(classifiers.items()): plt.figure(1) clf.fit(X1) Z1 = clf.decision_function(np.c_[xx1.ravel(), yy1.ravel()]) Z1 =",
") # print kmeans.labels_ #################################### ## Analysis 4 (4): Outlier-unsupervised-elliptic (Currently not working",
"else: per_size[y['HOST']] = [int(y['SIZE'])] ##Data pre-processing ends here log.debug( \"*** Printing Input to",
"EllipticEnvelope from sklearn.svm import OneClassSVM log = logging.getLogger(__name__) def analyze(data): # Convert this",
"def analyze(data): # Convert this to python data for us to be able",
"legend1_values_list = list(legend1.values()) legend1_keys_list = list(legend1.keys()) # Plot the results (= shape of",
"y[z] = zero + y[z] ip = ip + y[z] # log.debug( str(float(float(ip)/1000))",
"and Response Size received: Elliptic Envelope ********\" ) log.info( \"******** Check the image",
"on IP and average response size ****\" ) #####*****SIZE******#### #### Analysis #4 (1):",
"le = [float(float(ip) / 1000), avg_size] X = np.vstack([X, le]) log.info( \"******** Printing",
"bbox_args = dict(boxstyle=\"round\", fc=\"0.8\") plt.xlim((xx1.min(), xx1.max())) plt.ylim((yy1.min(), yy1.max())) plt.legend( (legend1_values_list[0].collections[0], legend1_values_list[1].collections[0], legend1_values_list[2].collections[0]), (legend1_keys_list[0],",
"received feature X = np.array([[0.00, 0.00]]) for x in hostlist: avg_size = mean(per_size[x])",
"in the working directory ********\" ) # print kmeans.labels_ #################################### ## Analysis 4",
"l = 3 - l if (l > 0): zero = \"\" for",
"per_size = dict() # IP-Response size hostlist = dict() # Data pre-processing here:",
"range(3 - len(y[z])): zero = zero + \"0\" y[z] = zero + y[z]",
"to analysis - 4 (1): K-means on IP and average response size ****\"",
"hostlist = dict() # Data pre-processing here: for y in json_to_python: hostlist[y['HOST']] =",
"plt.ylabel(\"Response size received\") plt.xlabel(\"Host-IP address\") ##plt.show() plt.savefig('elliptic.png') def mean(numbers): return float(sum(numbers)) / max(len(numbers),",
"enumerate(classifiers.items()): plt.figure(1) clf.fit(X1) Z1 = clf.decision_function(np.c_[xx1.ravel(), yy1.ravel()]) Z1 = Z1.reshape(xx1.shape) legend1[clf_name] = plt.contour(",
"40, 500)) xx2, yy2 = np.meshgrid(np.linspace(3, 10, 500), np.linspace(-5, 45, 500)) for i,",
"import EllipticEnvelope from sklearn.svm import OneClassSVM log = logging.getLogger(__name__) def analyze(data): # Convert",
"plt.figure(1) clf.fit(X1) Z1 = clf.decision_function(np.c_[xx1.ravel(), yy1.ravel()]) Z1 = Z1.reshape(xx1.shape) legend1[clf_name] = plt.contour( xx1,"
] |
[
"= time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq if time == last_time and switched_onepps: print \"Correcting delayed",
"last_seconds > seconds0: # print \"Wrong event order\",seconds0,line # continue last_seconds = seconds0",
"= True time_ch0 = seconds0 if time_ch0 - seconds0 > 50e-9: wait_f0 =",
"wait_fe1 = False else: decay_waiting_ch1 = False if re_2 and dpch2==1: wait_fe2 =",
"onepps_count switched_onepps = True time = fields[10] correction = fields[15] seconds0 = time_to_seconds(time,correction)+(trigger_count",
"print \"No decay\",seconds1,decay_start_time_ch1,seconds1 - decay_start_time_ch1 decay_waiting_ch1 = False else: decay_waiting_ch1 = False print",
"the different options if 0==0: #current analysis for one event. Note, that one",
"False else: print \"no decay in channel 3\" if re_0 and dpch0==1: wait_fe0",
"#seconds1=decay_start_time_ch1 #seconds2=decay_start_time_ch2 #seconds3=decay_start_time_ch3 if fields_next[1]>= \"80\": previous_fe_0 = fe_0 previous_re_1 = re_1 previous_fe_1",
"\"00\" or fields[5] == \"00\")): continue if (ch1==1 and ch2==1 and ch3==1 and",
"dpch1==1: wait_fe1 = True time_ch1 = seconds1 if time_ch1 - seconds1 > 50e-9:",
"BIT7 = 1 << 7 # For DAQ status BIT0 = 1 #",
"and wait_fe2: print \"Pulse ch2\",seconds2,line pulse_ch2 = True wait_fe2 = False if decay_waiting_ch2",
"= False else: decay_waiting_ch0 = False if re_1 and dpch1==1: wait_fe1 = True",
"fields[7] == \"00\"): continue if (ch0==1 and ch1==1 and (fields[1] == \"00\" or",
"wait_f1 = False if fe_1 and wait_fe1: print \"Pulse ch1\",seconds1,line pulse_ch1 = True",
"the single pulse for channel if (ch0==1 and fields[1] == \"00\"): continue if",
"int(fields[0],16) onepps_count = int(fields[9],16) re_0 = (fields[1] >= \"00\") re_1 = (fields[3] >=",
">= \"00\") re_3 = (fields[7] >= \"00\") fe_0 = (fields[2] >= \"00\") fe_1",
"or 1 dpch3 = float(sys.argv[9]) #0 or 1 muon = {0:False,1:False,2:False,\"Time\":0.} freq =",
"= fields[10] correction = fields[15] seconds0 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds1 = time_to_seconds(time,correction)+(trigger_count",
"single pulse for channel if (ch0==1 and fields[1] == \"00\"): continue if (ch1==1",
"wait_f3 = False if fe_3 and wait_fe3: print \"Pulse ch2\",seconds3,line decay_start_time_ch3 = seconds3",
"last_onepps = onepps_count switched_onepps = True time = fields[10] correction = fields[15] seconds0",
"onepps_count)/freq seconds3 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq if time == last_time and switched_onepps: print",
"if 0==0: #current analysis for one event. Note, that one event can be",
"and ch3==1 and (fields[3] == \"00\" and fields[5] == \"00\" or fields[7] ==",
"0 decay_start_time_ch0 = seconds0 decay_waiting_ch0 = True pulse_ch0 = True wait_fe0 = False",
"if decay_waiting_ch1: if re_1: wait_fe1 = True time_ch1 = seconds1 if time_ch1 -",
"= False if fe_3 and wait_fe3: print \"Pulse ch2\",seconds3,line decay_start_time_ch3 = seconds3 decay_waiting_ch3",
"(ch0==1 and ch1==1 and ch2==1 and (fields[1] == \"00\" and fields[3] == \"00\"",
"time_ch0 - seconds0 > 50e-9: wait_f0 = False if fe_0 and wait_fe0: print",
"irrelevent! ##################################################### files = sys.argv[1:] BIT0_4 = 31 BIT5 = 1 << 5",
"\"no decay in channel 2\" if dpch3==1 and (seconds3 != decay_start_time_ch0) and (seconds3",
"ch1==1 and (fields[1] == \"00\" or fields[3] == \"00\")): continue if (ch0==1 and",
"pulse_ch3 = True wait_fe3 = False else: decay_waiting_ch3 = False #seconds0=decay_start_time_ch0 #seconds1=decay_start_time_ch1 #seconds2=decay_start_time_ch2",
"if (ch1==1 and ch2==1 and (fields[3] == \"00\" or fields[5] == \"00\")): continue",
"= True wait_fe2 = False else: decay_waiting_ch2 = False if re_3 and dpch3==1:",
"3\" if re_0 and dpch0==1: wait_fe0 = True time_ch0 = seconds0 if time_ch0",
"pulse_ch0 = True wait_fe0 = False if decay_waiting_ch0 and seconds0 - decay_start_time_ch0 >",
"== \"00\" or fields[7] == \"00\")): continue #check for double pulse if fields[1]",
"fe_1 previous_re_2 = re_2 previous_fe_2 = fe_2 previous_re_3 = re_3 previous_fe_3 = fe_3",
"True wait_fe2 = False if decay_waiting_ch2 and seconds2 - decay_start_time_ch2 > 20: print",
"continue #Ignore everything that is not trigger data if len(fields[0]) != 8: continue",
"wait_fe1 = False time_ch1 = 0. wait_fe2 = False time_ch2 = 0. wait_fe3",
"decay_waiting_ch1 = False print \"Decay ch1 %10.8f ch1microseconds\"%((seconds1 - decay_start_time_ch1),) else: decay_waiting_ch1 =",
"decay_waiting_ch2 = False if re_3 and dpch3==1: wait_fe3 = True time_ch3 = seconds3",
"\"00\")): continue #check for double pulse if fields[1] >= \"80\": for line in",
"if time_ch1 - seconds1 > 50e-9: wait_f1 = False if fe_1 and wait_fe1:",
"#define the different options if 0==0: #current analysis for one event. Note, that",
"\"00\")): continue if (ch0==1 and ch2==1 and (fields[1] == \"00\" or fields[5] ==",
"\"00\" or fields[5] == \"00\")): continue if (ch1==1 and ch3==1 and (fields[3] ==",
"False else: print \"no decay in channel 0\" if dpch1==1 and (seconds1 !=",
"float(sys.argv[4]) #0 or 1 ch3 = float(sys.argv[5]) #0 or 1 dpch0 = float(sys.argv[6])",
"re_2 = (fields[5] >= \"00\") re_3 = (fields[7] >= \"00\") fe_0 = (fields[2]",
"if (ch3==1 and fields[7] == \"00\"): continue if (ch0==1 and ch1==1 and (fields[1]",
"- decay_start_time_ch3 decay_waiting_ch3 = False else: decay_waiting_ch3 = False print \"Decay ch3 %10.8f",
"print \"seconds0:\",seconds0 print \"decay_start_time_ch0: \",decay_start_time_ch0 print \"decay_start_time_ch1: \",decay_start_time_ch1 print \"decay_start_time_ch2: \",decay_start_time_ch2 print \"decay_start_time_ch3:",
"= 0. last_triggercount = 0 switched_onepps = False last_onepps = 0 onepps_count =",
"wait_f1 = False if fe_1 and wait_fe1: #print \"Pulse ch1\",seconds1,line decay_start_time_ch1 = 0",
"# GPS data possible corrupted BIT3 = 1 << 3 # Current or",
"in f: fields_next = line.rstrip(\"\\n\").split(\" \") #define the different options if 0==0: #current",
"wait_fe0: print \"Pulse ch0\",seconds0,line pulse_ch0 = True wait_fe0 = False if decay_waiting_ch0 and",
"and wait_fe1: print \"Pulse ch1\",seconds1,line pulse_ch1 = True wait_fe1 = False if decay_waiting_ch1",
"rate not within range def time_to_seconds(time, correction): ''' Convert hhmmss,xxx string int seconds",
"(seconds1 != decay_start_time_ch2) and (seconds1 != decay_start_time_ch3) : if decay_waiting_ch1: if re_1: wait_fe1",
"pending BIT2 = 1 << 2 # GPS data possible corrupted BIT3 =",
"= False if trigger_count < last_triggercount and not switched_onepps: print \"Correcting trigger count",
"and switched_onepps: print \"Correcting delayed onepps switch:\",seconds0,line seconds0 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds1",
"1 # Trigger interrupt pending BIT2 = 1 << 2 # GPS data",
"True seconds3 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq time_ch3 = seconds3 if time_ch3 - seconds3",
"+= int(0xFFFFFFFF)/freq seconds1 += int(0xFFFFFFFF)/freq seconds2 += int(0xFFFFFFFF)/freq seconds3 += int(0xFFFFFFFF)/freq else: last_triggercount",
"else: decay_waiting_ch3 = False else: print \"no decay in channel 3\" if re_0",
"since day start ''' # print time,correction tfields = time.split(\".\") t = tfields[0]",
"== \"00\")): continue if (ch1==1 and ch3==1 and (fields[3] == \"00\" or fields[7]",
"1 ch2 = float(sys.argv[4]) #0 or 1 ch3 = float(sys.argv[5]) #0 or 1",
"seconds since day start ''' # print time,correction tfields = time.split(\".\") t =",
"0 switched_onepps = False last_onepps = 0 onepps_count = 0 counter = 0.0",
"wait_fe3 = False else: decay_waiting_ch3 = False #seconds0=decay_start_time_ch0 #seconds1=decay_start_time_ch1 #seconds2=decay_start_time_ch2 #seconds3=decay_start_time_ch3 if fields_next[1]>=",
"if time_ch2 - seconds2 > 50e-9: wait_f2 = False decay_waiting_ch2 = False if",
"\"Pulse ch1\",seconds1,line decay_start_time_ch1 = 0 decay_start_time_ch1 = seconds1 decay_waiting_ch1 = True pulse_ch1 =",
"round(evt_time) #filename = sys.argv[1] f = open(sys.argv[1]) for filename in files: ch0 =",
"False decay_waiting_ch0 = False if fe_0 and wait_fe0: print \"Pulse ch0\",seconds0,line pulse_ch0 =",
"pulse for channel if (ch0==1 and fields[1] == \"00\"): continue if (ch1==1 and",
"and (fields[3] == \"00\" or fields[5] == \"00\")): continue if (ch1==1 and ch3==1",
"return round(evt_time) #filename = sys.argv[1] f = open(sys.argv[1]) for filename in files: ch0",
"float(onepps_count - last_onepps) else: freq = float(0xFFFFFFFF + onepps_count - last_onepps) prevlast_onepps =",
"= True time_ch1 = seconds1 if time_ch1 - seconds1 > 50e-9: wait_f1 =",
"#check the single pulse for channel if (ch0==1 and fields[1] == \"00\"): continue",
"50e-9: wait_f1 = False if fe_1 and wait_fe1: #print \"Pulse ch1\",seconds1,line decay_start_time_ch1 =",
"= False if fe_0 and wait_fe0: print \"Pulse ch0\",seconds0,line pulse_ch0 = True wait_fe0",
"50e-9: wait_f1 = False if fe_1 and wait_fe1: print \"Pulse ch1\",seconds1,line pulse_ch1 =",
"time_to_seconds(time, correction): ''' Convert hhmmss,xxx string int seconds since day start ''' #",
"correction = fields[15] seconds0 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds1 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq",
"False if fe_2 and wait_fe2: print \"Pulse ch2\",seconds2,line pulse_ch2 = True wait_fe2 =",
"0\" if dpch1==1 and (seconds1 != decay_start_time_ch0) and (seconds1 != decay_start_time_ch2) and (seconds1",
"time_ch1 - seconds1 > 50e-9: wait_f1 = False if fe_1 and wait_fe1: #print",
"channel 3\" if re_0 and dpch0==1: wait_fe0 = True time_ch0 = seconds0 if",
"- prevlast_onepps)/freq seconds1 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds2 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds3",
"\"00\")): continue if (ch1==1 and ch2==1 and (fields[3] == \"00\" or fields[5] ==",
"prevlast_onepps)/freq seconds2 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds3 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq else: last_time",
"= time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds2 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds3 = time_to_seconds(time,correction)+(trigger_count -",
"if re_2: wait_fe2 = True time_ch2 = seconds2 if time_ch2 - seconds2 >",
"\",decay_start_time_ch2 print \"decay_start_time_ch3: \",decay_start_time_ch3 print \"difference: \",seconds0-decay_start_time_ch0 pulse_ch0 = False pulse_ch1 = False",
"wait_fe1: print \"Pulse ch1\",seconds1,line pulse_ch1 = True wait_fe1 = False if decay_waiting_ch1 and",
"= fe_0 previous_re_1 = re_1 previous_fe_1 = fe_1 previous_re_2 = re_2 previous_fe_2 =",
"== \"00\" or fields[5] == \"00\")): continue if (ch0==1 and ch3==1 and (fields[1]",
"ch0\",seconds0,line decay_start_time_ch0 = 0 decay_start_time_ch0 = seconds0 decay_waiting_ch0 = True pulse_ch0 = True",
"False last_seconds = 0. last_time = 0. last_triggercount = 0 switched_onepps = False",
"and (seconds3 != decay_start_time_ch2) : if decay_waiting_ch3: if re_3: wait_fe3 = True seconds3",
"#if last_seconds > seconds0: # print \"Wrong event order\",seconds0,line # continue last_seconds =",
"muon_start = 0. nmuons = 0 last_pulse = 0. decay_start_time_ch0 = 0. decay_waiting_ch0",
"be described by more than one line! if last_onepps != onepps_count: if onepps_count",
"#!/usr/bin/env python import sys import gzip ##################################################### #This is coincident level 0!! #Order",
"else: print \"no decay in channel 1\" if dpch2==1 and (seconds2 != decay_start_time_ch0)",
"try: int(fields[len(fields)-1]) except ValueError: continue trigger_count = int(fields[0],16) onepps_count = int(fields[9],16) re_0 =",
"> 50e-9: wait_f0 = False decay_waiting_ch0 = False if fe_0 and wait_fe0: print",
"if (ch0==1 and ch1==1 and ch2==1 and (fields[1] == \"00\" and fields[3] ==",
"onepps_count = int(fields[9],16) re_0 = (fields[1] >= \"00\") re_1 = (fields[3] >= \"00\")",
"= 0 last_pulse = 0. decay_start_time_ch0 = 0. decay_waiting_ch0 = False decay_start_time_ch1 =",
"\"00\" or fields[7] == \"00\")): continue #check for double pulse if fields[1] >=",
"- seconds2 > 50e-9: wait_f2 = False if fe_2 and wait_fe2: print \"Pulse",
"False print \"Decay ch1 %10.8f ch1microseconds\"%((seconds1 - decay_start_time_ch1),) else: decay_waiting_ch1 = False else:",
"print \"Decay ch0 %10.8f ch0microseconds\"%((seconds0 - decay_start_time_ch0),) else: decay_waiting_ch0 = False else: print",
"%10.8f ch3microseconds\"%((seconds3 - decay_start_time_ch3),) else: decay_waiting_ch3 = False else: print \"no decay in",
"''' Convert hhmmss,xxx string int seconds since day start ''' # print time,correction",
"Note, that one event can be described by more than one line! if",
"BIT3 = 1 << 3 # Current or last 1PPS rate not within",
"if onepps_count > last_onepps: freq = float(onepps_count - last_onepps) else: freq = float(0xFFFFFFFF",
"ch3==1 and (fields[3] == \"00\" or fields[7] == \"00\")): continue if (ch2==1 and",
"if (ch0==1 and fields[1] == \"00\"): continue if (ch1==1 and fields[3] == \"00\"):",
"continue try: int(fields[len(fields)-1]) except ValueError: continue trigger_count = int(fields[0],16) onepps_count = int(fields[9],16) re_0",
"0. last_time = 0. last_triggercount = 0 switched_onepps = False last_onepps = 0",
"ch2microseconds\"%((seconds2 - decay_start_time_ch2),) else: decay_waiting_ch2 = False else: print \"no decay in channel",
"ValueError: continue trigger_count = int(fields[0],16) onepps_count = int(fields[9],16) re_0 = (fields[1] >= \"00\")",
"decay_start_time_ch1) and (seconds3 != decay_start_time_ch2) : if decay_waiting_ch3: if re_3: wait_fe3 = True",
"False else: decay_waiting_ch1 = False if re_2 and dpch2==1: wait_fe2 = True time_ch2",
"ch0 = float(sys.argv[2]) #0 or 1 ch1 = float(sys.argv[3]) #0 or 1 ch2",
"if time_ch0 - seconds0 > 50e-9: wait_f0 = False if fe_0 and wait_fe0:",
"not within range def time_to_seconds(time, correction): ''' Convert hhmmss,xxx string int seconds since",
"decay_waiting_ch2 and seconds2 - decay_start_time_ch2 > 20: print \"No decay\",seconds2,decay_start_time_ch2, seconds2 - decay_start_time_ch2",
"channel 1\" if dpch2==1 and (seconds2 != decay_start_time_ch0) and (seconds2 != decay_start_time_ch1) and",
"if len(fields) != 16: continue #Ignore everything that is not trigger data if",
"gzip ##################################################### #This is coincident level 0!! #Order of scintillators is irrelevent! #####################################################",
"trigger data if len(fields[0]) != 8: continue try: int(fields[len(fields)-1]) except ValueError: continue trigger_count",
": if decay_waiting_ch3: if re_3: wait_fe3 = True seconds3 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq",
"\"fields: \",fields #print \"line: \",line # Ignore malformed lines if len(fields) != 16:",
"or 1 dpch0 = float(sys.argv[6]) #0 or 1 dpch1 = float(sys.argv[7]) #0 or",
"= time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq else: last_time = time switched_onepps = False if trigger_count",
"in channel 3\" if re_0 and dpch0==1: wait_fe0 = True time_ch0 = seconds0",
"decay_waiting_ch1 = False else: decay_waiting_ch1 = False print \"Decay ch1 %10.8f ch1microseconds\"%((seconds1 -",
"ch1 = float(sys.argv[3]) #0 or 1 ch2 = float(sys.argv[4]) #0 or 1 ch3",
"decay_start_time_ch1),) else: decay_waiting_ch1 = False else: print \"no decay in channel 1\" if",
"decay_start_time_ch2) and (seconds1 != decay_start_time_ch3) : if decay_waiting_ch1: if re_1: wait_fe1 = True",
"for filename in files: ch0 = float(sys.argv[2]) #0 or 1 ch1 = float(sys.argv[3])",
"trigger count rollover:\",seconds0,line seconds0 += int(0xFFFFFFFF)/freq seconds1 += int(0xFFFFFFFF)/freq seconds2 += int(0xFFFFFFFF)/freq seconds3",
"fe_2 and wait_fe2: print \"Pulse ch2\",seconds2,line decay_start_time_ch2 = seconds2 decay_waiting_ch2 = True pulse_ch2",
"dpch0==1 and (seconds0 !=decay_start_time_ch1 ) and (seconds0 != decay_start_time_ch2) and (seconds0 != decay_start_time_ch3)",
"decay_waiting_ch3 = False else: decay_waiting_ch3 = False print \"Decay ch3 %10.8f ch3microseconds\"%((seconds3 -",
"= 0. decay_waiting_ch3 = False last_seconds = 0. last_time = 0. last_triggercount =",
"= False else: print \"no decay in channel 1\" if dpch2==1 and (seconds2",
"!= decay_start_time_ch0) and (seconds1 != decay_start_time_ch2) and (seconds1 != decay_start_time_ch3) : if decay_waiting_ch1:",
"ch2==1 and (fields[3] == \"00\" or fields[5] == \"00\")): continue if (ch1==1 and",
"decay_waiting_ch0 = False if re_1 and dpch1==1: wait_fe1 = True time_ch1 = seconds1",
"decay\",seconds3,decay_start_time_ch3,seconds3 - decay_start_time_ch3 decay_waiting_ch3 = False else: decay_waiting_ch3 = False print \"Decay ch3",
"ch3==1 and (fields[1] == \"00\" or fields[7] == \"00\")): continue if (ch1==1 and",
"double pulse if fields[1] >= \"80\": for line in f: fields_next = line.rstrip(\"\\n\").split(\"",
"= False else: decay_waiting_ch2 = False print \"Decay ch2 %10.8f ch2microseconds\"%((seconds2 - decay_start_time_ch2),)",
"!= decay_start_time_ch0) and (seconds2 != decay_start_time_ch1) and (seconds2 != decay_start_time_ch3): if decay_waiting_ch2: if",
"= time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds3 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq if time == last_time",
"seconds1 > 50e-9: wait_f1 = False if fe_1 and wait_fe1: print \"Pulse ch1\",seconds1,line",
"ch2==1 and (fields[1] == \"00\" and fields[3] == \"00\" or fields[5] == \"00\")):",
"last_triggercount and not switched_onepps: print \"Correcting trigger count rollover:\",seconds0,line seconds0 += int(0xFFFFFFFF)/freq seconds1",
"True wait_fe0 = False if decay_waiting_ch0 and seconds0 - decay_start_time_ch0 > 20: print",
"False #single channel++++++++++++++++++++++++++++ if dpch0==1 and (seconds0 !=decay_start_time_ch1 ) and (seconds0 != decay_start_time_ch2)",
"ch3\",seconds3,line pulse_ch3 = True wait_fe3 = False if decay_waiting_ch3 and seconds3 - decay_start_time_ch3",
"= False else: decay_waiting_ch2 = False if re_3 and dpch3==1: wait_fe3 = True",
"False else: decay_waiting_ch3 = False #seconds0=decay_start_time_ch0 #seconds1=decay_start_time_ch1 #seconds2=decay_start_time_ch2 #seconds3=decay_start_time_ch3 if fields_next[1]>= \"80\": previous_fe_0",
"(fields[1] == \"00\" or fields[7] == \"00\")): continue if (ch1==1 and ch2==1 and",
"rollover:\",seconds0,line seconds0 += int(0xFFFFFFFF)/freq seconds1 += int(0xFFFFFFFF)/freq seconds2 += int(0xFFFFFFFF)/freq seconds3 += int(0xFFFFFFFF)/freq",
"decay_waiting_ch3: if re_3: wait_fe3 = True seconds3 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq time_ch3 =",
"20: print \"No decay\",seconds2,decay_start_time_ch2, seconds2 - decay_start_time_ch2 decay_waiting_ch2 = False else: decay_waiting_ch2 =",
"\"Decay ch0 %10.8f ch0microseconds\"%((seconds0 - decay_start_time_ch0),) else: decay_waiting_ch0 = False else: print \"no",
"= tfields[0] secs_since_day_start = int(t[0:2])*3600+int(t[2:4])*60+int(t[4:6]) evt_time = secs_since_day_start + int(tfields[1])/1000.0+int(correction)/1000.0 return round(evt_time) #filename",
"= float(sys.argv[2]) #0 or 1 ch1 = float(sys.argv[3]) #0 or 1 ch2 =",
"and not switched_onepps: print \"Correcting trigger count rollover:\",seconds0,line seconds0 += int(0xFFFFFFFF)/freq seconds1 +=",
"''' # print time,correction tfields = time.split(\".\") t = tfields[0] secs_since_day_start = int(t[0:2])*3600+int(t[2:4])*60+int(t[4:6])",
"or fields[7] == \"00\")): continue if (ch2==1 and ch3==1 and (fields[5] == \"00\"",
"(fields[7] >= \"00\") fe_0 = (fields[2] >= \"00\") fe_1 = (fields[4] >= \"00\")",
"seconds3 > 50e-9: wait_f3 = False if fe_3 and wait_fe3: print \"Pulse ch3\",seconds3,line",
"#0 or 1 muon = {0:False,1:False,2:False,\"Time\":0.} freq = 25e6 # 25 MHz last_onepps",
"ch0microseconds\"%((seconds0 - decay_start_time_ch0),) else: decay_waiting_ch0 = False else: print \"no decay in channel",
"dpch3==1: wait_fe3 = True time_ch3 = seconds3 if time_ch3 - seconds3 > 50e-9:",
"#Ignore everything that is not trigger data if len(fields[0]) != 8: continue try:",
"!= decay_start_time_ch2) and (seconds0 != decay_start_time_ch3) : print \"dpch0\" print \"Decay ch0 %10.8f",
"float(0xFFFFFFFF + onepps_count - last_onepps) prevlast_onepps = last_onepps last_onepps = onepps_count switched_onepps =",
"<< 3 # Current or last 1PPS rate not within range def time_to_seconds(time,",
"secs_since_day_start = int(t[0:2])*3600+int(t[2:4])*60+int(t[4:6]) evt_time = secs_since_day_start + int(tfields[1])/1000.0+int(correction)/1000.0 return round(evt_time) #filename = sys.argv[1]",
"True wait_fe3 = False else: decay_waiting_ch3 = False #seconds0=decay_start_time_ch0 #seconds1=decay_start_time_ch1 #seconds2=decay_start_time_ch2 #seconds3=decay_start_time_ch3 if",
"or fields[7] == \"00\")): continue if (ch1==1 and ch2==1 and (fields[3] == \"00\"",
"False if fe_3 and wait_fe3: print \"Pulse ch3\",seconds3,line pulse_ch3 = True wait_fe3 =",
"\"00\") fe_1 = (fields[4] >= \"00\") fe_2 = (fields[6] >= \"00\") fe_3 =",
"else: decay_waiting_ch2 = False else: print \"no decay in channel 2\" if dpch3==1",
"= time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq time_ch3 = seconds3 if time_ch3 - seconds3 > 50e-9:",
"int(fields[len(fields)-1]) except ValueError: continue trigger_count = int(fields[0],16) onepps_count = int(fields[9],16) re_0 = (fields[1]",
"(ch2==1 and ch3==1 and (fields[5] == \"00\" or fields[7] == \"00\")): continue if",
"print \"Decay ch3 %10.8f ch3microseconds\"%((seconds3 - decay_start_time_ch3),) else: decay_waiting_ch3 = False else: print",
"= True time_ch2 = seconds2 if time_ch2 - seconds2 > 50e-9: wait_f2 =",
"wait_fe2 = False if decay_waiting_ch2 and seconds2 - decay_start_time_ch2 > 20: print \"No",
"by more than one line! if last_onepps != onepps_count: if onepps_count > last_onepps:",
"\"00\" or fields[7] == \"00\")): continue if (ch1==1 and ch2==1 and (fields[3] ==",
"= seconds0 if time_ch0 - seconds0 > 50e-9: wait_f0 = False if fe_0",
"fe_3 = (fields[8] >= \"00\") #check the single pulse for channel if (ch0==1",
"re_1: wait_fe1 = True time_ch1 = seconds1 if time_ch1 - seconds1 > 50e-9:",
"= (fields[5] >= \"00\") re_3 = (fields[7] >= \"00\") fe_0 = (fields[2] >=",
"print \"Pulse ch0\",seconds0,line decay_start_time_ch0 = 0 decay_start_time_ch0 = seconds0 decay_waiting_ch0 = True pulse_ch0",
"time.split(\".\") t = tfields[0] secs_since_day_start = int(t[0:2])*3600+int(t[2:4])*60+int(t[4:6]) evt_time = secs_since_day_start + int(tfields[1])/1000.0+int(correction)/1000.0 return",
"and dpch0==1: wait_fe0 = True time_ch0 = seconds0 if time_ch0 - seconds0 >",
"decay_start_time_ch1 > 20: print \"No decay\",seconds1,decay_start_time_ch1,seconds1 - decay_start_time_ch1 decay_waiting_ch1 = False else: decay_waiting_ch1",
"and wait_fe3: print \"Pulse ch2\",seconds3,line decay_start_time_ch3 = seconds3 decay_waiting_ch3 = True pulse_ch3 =",
"and (seconds2 != decay_start_time_ch1) and (seconds2 != decay_start_time_ch3): if decay_waiting_ch2: if re_2: wait_fe2",
"\"decay_start_time_ch0: \",decay_start_time_ch0 print \"decay_start_time_ch1: \",decay_start_time_ch1 print \"decay_start_time_ch2: \",decay_start_time_ch2 print \"decay_start_time_ch3: \",decay_start_time_ch3 print \"difference:",
"continue if (ch1==1 and fields[3] == \"00\"): continue if (ch2==1 and fields[5] ==",
"than one line! if last_onepps != onepps_count: if onepps_count > last_onepps: freq =",
"\"00\" or fields[5] == \"00\")): continue if (ch0==1 and ch3==1 and (fields[1] ==",
"1 # 1 PPS interrupt pending BIT1 = 1 << 1 # Trigger",
"50e-9: wait_f2 = False if fe_2 and wait_fe2: print \"Pulse ch2\",seconds2,line decay_start_time_ch2 =",
"previous_fe_0 = fe_0 previous_re_1 = re_1 previous_fe_1 = fe_1 previous_re_2 = re_2 previous_fe_2",
"= False time_ch0 = 0. wait_fe1 = False time_ch1 = 0. wait_fe2 =",
">= \"00\") fe_0 = (fields[2] >= \"00\") fe_1 = (fields[4] >= \"00\") fe_2",
"\"no decay in channel 0\" if dpch1==1 and (seconds1 != decay_start_time_ch0) and (seconds1",
"> 20: print \"No decay\",seconds0,decay_start_time_ch0, seconds0 - decay_start_time_ch0 decay_waiting_ch0 = False else: decay_waiting_ch0",
"len(fields) != 16: continue #Ignore everything that is not trigger data if len(fields[0])",
"<< 5 BIT7 = 1 << 7 # For DAQ status BIT0 =",
"seconds0 - decay_start_time_ch0 > 20: print \"No decay\",seconds0,decay_start_time_ch0, seconds0 - decay_start_time_ch0 decay_waiting_ch0 =",
"0. decay_waiting_ch3 = False last_seconds = 0. last_time = 0. last_triggercount = 0",
"True pulse_ch1 = True wait_fe1 = False else: decay_waiting_ch1 = False if re_2",
"0. muon_start = 0. nmuons = 0 last_pulse = 0. decay_start_time_ch0 = 0.",
"seconds3 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq if time == last_time and switched_onepps: print \"Correcting",
"ch3==1 and (fields[3] == \"00\" and fields[5] == \"00\" or fields[7] == \"00\")):",
"sys.argv[1:] BIT0_4 = 31 BIT5 = 1 << 5 BIT7 = 1 <<",
"(fields[5] >= \"00\") re_3 = (fields[7] >= \"00\") fe_0 = (fields[2] >= \"00\")",
"== \"00\" or fields[3] == \"00\")): continue if (ch0==1 and ch2==1 and (fields[1]",
"- seconds1 > 50e-9: wait_f1 = False if fe_1 and wait_fe1: #print \"Pulse",
"= line.rstrip(\"\\n\").split(\" \") #print \"fields: \",fields #print \"line: \",line # Ignore malformed lines",
"1 dpch0 = float(sys.argv[6]) #0 or 1 dpch1 = float(sys.argv[7]) #0 or 1",
"\"Decay ch3 %10.8f ch3microseconds\"%((seconds3 - decay_start_time_ch3),) else: decay_waiting_ch3 = False else: print \"no",
"False if re_3 and dpch3==1: wait_fe3 = True time_ch3 = seconds3 if time_ch3",
"0. wait_fe3 = False time_ch3 = 0. muon_start = 0. nmuons = 0",
"False if decay_waiting_ch2 and seconds2 - decay_start_time_ch2 > 20: print \"No decay\",seconds2,decay_start_time_ch2, seconds2",
"(ch0==1 and ch2==1 and (fields[1] == \"00\" or fields[5] == \"00\")): continue if",
"else: last_time = time switched_onepps = False if trigger_count < last_triggercount and not",
"\"00\") re_3 = (fields[7] >= \"00\") fe_0 = (fields[2] >= \"00\") fe_1 =",
"== \"00\")): continue if (ch0==1 and ch2==1 and (fields[1] == \"00\" or fields[5]",
"= 25e6 # 25 MHz last_onepps = 0 last_muon = 0 wait_fe0 =",
"print \"decay_start_time_ch0: \",decay_start_time_ch0 print \"decay_start_time_ch1: \",decay_start_time_ch1 print \"decay_start_time_ch2: \",decay_start_time_ch2 print \"decay_start_time_ch3: \",decay_start_time_ch3 print",
"1 PPS interrupt pending BIT1 = 1 << 1 # Trigger interrupt pending",
"== \"00\")): continue #check for double pulse if fields[1] >= \"80\": for line",
"# print time,correction tfields = time.split(\".\") t = tfields[0] secs_since_day_start = int(t[0:2])*3600+int(t[2:4])*60+int(t[4:6]) evt_time",
"True wait_fe2 = False else: decay_waiting_ch2 = False if re_3 and dpch3==1: wait_fe3",
"if re_3: wait_fe3 = True seconds3 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq time_ch3 = seconds3",
"wait_fe0 = False if decay_waiting_ch0 and seconds0 - decay_start_time_ch0 > 20: print \"No",
"switched_onepps: print \"Correcting delayed onepps switch:\",seconds0,line seconds0 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds1 =",
"= float(sys.argv[9]) #0 or 1 muon = {0:False,1:False,2:False,\"Time\":0.} freq = 25e6 # 25",
"= 0. wait_fe2 = False time_ch2 = 0. wait_fe3 = False time_ch3 =",
"\"Pulse ch0\",seconds0,line pulse_ch0 = True wait_fe0 = False if decay_waiting_ch0 and seconds0 -",
"fe_3 and wait_fe3: print \"Pulse ch2\",seconds3,line decay_start_time_ch3 = seconds3 decay_waiting_ch3 = True pulse_ch3",
"0. decay_waiting_ch1 = False decay_start_time_ch2 = 0. decay_waiting_ch2 = False decay_start_time_ch3 = 0.",
"time_ch2 = seconds2 if time_ch2 - seconds2 > 50e-9: wait_f2 = False decay_waiting_ch2",
"fe_0 = (fields[2] >= \"00\") fe_1 = (fields[4] >= \"00\") fe_2 = (fields[6]",
"\"Correcting trigger count rollover:\",seconds0,line seconds0 += int(0xFFFFFFFF)/freq seconds1 += int(0xFFFFFFFF)/freq seconds2 += int(0xFFFFFFFF)/freq",
"#seconds2=decay_start_time_ch2 #seconds3=decay_start_time_ch3 if fields_next[1]>= \"80\": previous_fe_0 = fe_0 previous_re_1 = re_1 previous_fe_1 =",
"is irrelevent! ##################################################### files = sys.argv[1:] BIT0_4 = 31 BIT5 = 1 <<",
"wait_fe3: print \"Pulse ch2\",seconds3,line decay_start_time_ch3 = seconds3 decay_waiting_ch3 = True pulse_ch3 = True",
"#0 or 1 ch3 = float(sys.argv[5]) #0 or 1 dpch0 = float(sys.argv[6]) #0",
"= 1 << 1 # Trigger interrupt pending BIT2 = 1 << 2",
"= 0 switched_onepps = False last_onepps = 0 onepps_count = 0 counter =",
"decay in channel 1\" if dpch2==1 and (seconds2 != decay_start_time_ch0) and (seconds2 !=",
"fields[10] correction = fields[15] seconds0 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds1 = time_to_seconds(time,correction)+(trigger_count -",
"= {0:False,1:False,2:False,\"Time\":0.} freq = 25e6 # 25 MHz last_onepps = 0 last_muon =",
"if (ch0==1 and ch3==1 and (fields[1] == \"00\" or fields[7] == \"00\")): continue",
"continue if (ch1==1 and ch3==1 and (fields[3] == \"00\" or fields[7] == \"00\")):",
"\"00\")): continue if (ch1==1 and ch3==1 and (fields[3] == \"00\" or fields[7] ==",
"filename.endswith('.gz'): f = gzip.open(filename) else: f = open(sys.argv[1]) for line in f: fields",
"pulse_ch3 = False #single channel++++++++++++++++++++++++++++ if dpch0==1 and (seconds0 !=decay_start_time_ch1 ) and (seconds0",
"== \"00\" and fields[3] == \"00\" or fields[5] == \"00\")): continue if (ch1==1",
"1 << 3 # Current or last 1PPS rate not within range def",
">= \"00\") re_1 = (fields[3] >= \"00\") re_2 = (fields[5] >= \"00\") re_3",
"if re_0 and dpch0==1: wait_fe0 = True time_ch0 = seconds0 if time_ch0 -",
"1 muon = {0:False,1:False,2:False,\"Time\":0.} freq = 25e6 # 25 MHz last_onepps = 0",
"False else: decay_waiting_ch3 = False print \"Decay ch3 %10.8f ch3microseconds\"%((seconds3 - decay_start_time_ch3),) else:",
"= False decay_start_time_ch1 = 0. decay_waiting_ch1 = False decay_start_time_ch2 = 0. decay_waiting_ch2 =",
"analysis for one event. Note, that one event can be described by more",
"if (ch2==1 and ch3==1 and (fields[5] == \"00\" or fields[7] == \"00\")): continue",
"decay in channel 2\" if dpch3==1 and (seconds3 != decay_start_time_ch0) and (seconds3 !=",
"last_triggercount = 0 switched_onepps = False last_onepps = 0 onepps_count = 0 counter",
"== \"00\"): continue if (ch2==1 and fields[5] == \"00\"): continue if (ch3==1 and",
"if decay_waiting_ch3 and seconds3 - decay_start_time_ch3 > 20: print \"No decay\",seconds3,decay_start_time_ch3,seconds3 - decay_start_time_ch3",
"= False print \"Decay ch3 %10.8f ch3microseconds\"%((seconds3 - decay_start_time_ch3),) else: decay_waiting_ch3 = False",
"not switched_onepps: print \"Correcting trigger count rollover:\",seconds0,line seconds0 += int(0xFFFFFFFF)/freq seconds1 += int(0xFFFFFFFF)/freq",
"evt_time = secs_since_day_start + int(tfields[1])/1000.0+int(correction)/1000.0 return round(evt_time) #filename = sys.argv[1] f = open(sys.argv[1])",
"decay_waiting_ch0 and seconds0 - decay_start_time_ch0 > 20: print \"No decay\",seconds0,decay_start_time_ch0, seconds0 - decay_start_time_ch0",
"float(sys.argv[9]) #0 or 1 muon = {0:False,1:False,2:False,\"Time\":0.} freq = 25e6 # 25 MHz",
"wait_fe0 = False time_ch0 = 0. wait_fe1 = False time_ch1 = 0. wait_fe2",
"fe_1 = (fields[4] >= \"00\") fe_2 = (fields[6] >= \"00\") fe_3 = (fields[8]",
"decay_start_time_ch3 = 0. decay_waiting_ch3 = False last_seconds = 0. last_time = 0. last_triggercount",
": print \"dpch0\" print \"Decay ch0 %10.8f microseconds\"%(1e6*(seconds0 - decay_start_time_ch0),) if decay_waiting_ch0: if",
"#print \"Pulse ch1\",seconds1,line decay_start_time_ch1 = 0 decay_start_time_ch1 = seconds1 decay_waiting_ch1 = True pulse_ch1",
"else: decay_waiting_ch0 = False if re_1 and dpch1==1: wait_fe1 = True time_ch1 =",
"1 dpch2 = float(sys.argv[8]) #0 or 1 dpch3 = float(sys.argv[9]) #0 or 1",
"== \"00\" or fields[7] == \"00\")): continue if (ch0==1 and ch1==1 and ch2==1",
"\"line: \",line # Ignore malformed lines if len(fields) != 16: continue #Ignore everything",
"print \"Pulse ch0\",seconds0,line pulse_ch0 = True wait_fe0 = False if decay_waiting_ch0 and seconds0",
"= 0. decay_waiting_ch2 = False decay_start_time_ch3 = 0. decay_waiting_ch3 = False last_seconds =",
"decay_start_time_ch0) and (seconds3 != decay_start_time_ch1) and (seconds3 != decay_start_time_ch2) : if decay_waiting_ch3: if",
"> seconds0: # print \"Wrong event order\",seconds0,line # continue last_seconds = seconds0 print",
"True wait_fe0 = False else: decay_waiting_ch0 = False if re_1 and dpch1==1: wait_fe1",
"pulse_ch1 = True wait_fe1 = False else: decay_waiting_ch1 = False if re_2 and",
"that one event can be described by more than one line! if last_onepps",
"line in f: fields = line.rstrip(\"\\n\").split(\" \") #print \"fields: \",fields #print \"line: \",line",
"False time_ch1 = 0. wait_fe2 = False time_ch2 = 0. wait_fe3 = False",
"time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds1 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds2 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq",
"0 last_pulse = 0. decay_start_time_ch0 = 0. decay_waiting_ch0 = False decay_start_time_ch1 = 0.",
"last_triggercount = trigger_count #if last_seconds > seconds0: # print \"Wrong event order\",seconds0,line #",
"wait_fe1: #print \"Pulse ch1\",seconds1,line decay_start_time_ch1 = 0 decay_start_time_ch1 = seconds1 decay_waiting_ch1 = True",
"(seconds3 != decay_start_time_ch0) and (seconds3 != decay_start_time_ch1) and (seconds3 != decay_start_time_ch2) : if",
"50e-9: wait_f3 = False if fe_3 and wait_fe3: print \"Pulse ch2\",seconds3,line decay_start_time_ch3 =",
"and seconds2 - decay_start_time_ch2 > 20: print \"No decay\",seconds2,decay_start_time_ch2, seconds2 - decay_start_time_ch2 decay_waiting_ch2",
"\"seconds0:\",seconds0 print \"decay_start_time_ch0: \",decay_start_time_ch0 print \"decay_start_time_ch1: \",decay_start_time_ch1 print \"decay_start_time_ch2: \",decay_start_time_ch2 print \"decay_start_time_ch3: \",decay_start_time_ch3",
"= float(sys.argv[5]) #0 or 1 dpch0 = float(sys.argv[6]) #0 or 1 dpch1 =",
"time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq time_ch3 = seconds3 if time_ch3 - seconds3 > 50e-9: wait_f3",
"decay_waiting_ch3 and seconds3 - decay_start_time_ch3 > 20: print \"No decay\",seconds3,decay_start_time_ch3,seconds3 - decay_start_time_ch3 decay_waiting_ch3",
"MHz last_onepps = 0 last_muon = 0 wait_fe0 = False time_ch0 = 0.",
"continue if (ch1==1 and ch2==1 and (fields[3] == \"00\" or fields[5] == \"00\")):",
"decay_waiting_ch0 = False if fe_0 and wait_fe0: print \"Pulse ch0\",seconds0,line pulse_ch0 = True",
"> 20: print \"No decay\",seconds3,decay_start_time_ch3,seconds3 - decay_start_time_ch3 decay_waiting_ch3 = False else: decay_waiting_ch3 =",
"31 BIT5 = 1 << 5 BIT7 = 1 << 7 # For",
"decay_start_time_ch3 = seconds3 decay_waiting_ch3 = True pulse_ch3 = True wait_fe3 = False else:",
"decay_waiting_ch0 = False else: print \"no decay in channel 0\" if dpch1==1 and",
"\"Decay ch0 %10.8f microseconds\"%(1e6*(seconds0 - decay_start_time_ch0),) if decay_waiting_ch0: if re_0: wait_fe0 = True",
"\"No decay\",seconds3,decay_start_time_ch3,seconds3 - decay_start_time_ch3 decay_waiting_ch3 = False else: decay_waiting_ch3 = False print \"Decay",
"if decay_waiting_ch3: if re_3: wait_fe3 = True seconds3 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq time_ch3",
"> 20: print \"No decay\",seconds2,decay_start_time_ch2, seconds2 - decay_start_time_ch2 decay_waiting_ch2 = False else: decay_waiting_ch2",
"in channel 0\" if dpch1==1 and (seconds1 != decay_start_time_ch0) and (seconds1 != decay_start_time_ch2)",
"and wait_fe0: print \"Pulse ch0\",seconds0,line decay_start_time_ch0 = 0 decay_start_time_ch0 = seconds0 decay_waiting_ch0 =",
"fields = line.rstrip(\"\\n\").split(\" \") #print \"fields: \",fields #print \"line: \",line # Ignore malformed",
"False decay_start_time_ch2 = 0. decay_waiting_ch2 = False decay_start_time_ch3 = 0. decay_waiting_ch3 = False",
"False else: decay_waiting_ch1 = False print \"Decay ch1 %10.8f ch1microseconds\"%((seconds1 - decay_start_time_ch1),) else:",
"= sys.argv[1] f = open(sys.argv[1]) for filename in files: ch0 = float(sys.argv[2]) #0",
"50e-9: wait_f2 = False decay_waiting_ch2 = False if fe_2 and wait_fe2: print \"Pulse",
"!= decay_start_time_ch3) : print \"dpch0\" print \"Decay ch0 %10.8f microseconds\"%(1e6*(seconds0 - decay_start_time_ch0),) if",
"last_onepps) prevlast_onepps = last_onepps last_onepps = onepps_count switched_onepps = True time = fields[10]",
"onepps_count = 0 counter = 0.0 if filename.endswith('.gz'): f = gzip.open(filename) else: f",
"not trigger data if len(fields[0]) != 8: continue try: int(fields[len(fields)-1]) except ValueError: continue",
"(ch1==1 and fields[3] == \"00\"): continue if (ch2==1 and fields[5] == \"00\"): continue",
"= onepps_count switched_onepps = True time = fields[10] correction = fields[15] seconds0 =",
"decay_waiting_ch0 = False print \"Decay ch0 %10.8f ch0microseconds\"%((seconds0 - decay_start_time_ch0),) else: decay_waiting_ch0 =",
"decay_start_time_ch2 = seconds2 decay_waiting_ch2 = True pulse_ch2 = True wait_fe2 = False else:",
"and (seconds3 != decay_start_time_ch0) and (seconds3 != decay_start_time_ch1) and (seconds3 != decay_start_time_ch2) :",
"= False #seconds0=decay_start_time_ch0 #seconds1=decay_start_time_ch1 #seconds2=decay_start_time_ch2 #seconds3=decay_start_time_ch3 if fields_next[1]>= \"80\": previous_fe_0 = fe_0 previous_re_1",
"seconds1 - decay_start_time_ch1 > 20: print \"No decay\",seconds1,decay_start_time_ch1,seconds1 - decay_start_time_ch1 decay_waiting_ch1 = False",
"True pulse_ch3 = True wait_fe3 = False else: decay_waiting_ch3 = False #seconds0=decay_start_time_ch0 #seconds1=decay_start_time_ch1",
"Trigger interrupt pending BIT2 = 1 << 2 # GPS data possible corrupted",
"data possible corrupted BIT3 = 1 << 3 # Current or last 1PPS",
"\"Pulse ch1\",seconds1,line pulse_ch1 = True wait_fe1 = False if decay_waiting_ch1 and seconds1 -",
"(seconds0 != decay_start_time_ch3) : print \"dpch0\" print \"Decay ch0 %10.8f microseconds\"%(1e6*(seconds0 - decay_start_time_ch0),)",
"and wait_fe0: print \"Pulse ch0\",seconds0,line pulse_ch0 = True wait_fe0 = False if decay_waiting_ch0",
"(ch0==1 and ch3==1 and (fields[1] == \"00\" or fields[7] == \"00\")): continue if",
"else: decay_waiting_ch0 = False else: print \"no decay in channel 0\" if dpch1==1",
"time_ch1 - seconds1 > 50e-9: wait_f1 = False if fe_1 and wait_fe1: print",
"= seconds0 decay_waiting_ch0 = True pulse_ch0 = True wait_fe0 = False else: decay_waiting_ch0",
"decay_waiting_ch1 = False if re_2 and dpch2==1: wait_fe2 = True time_ch2 = seconds2",
"import gzip ##################################################### #This is coincident level 0!! #Order of scintillators is irrelevent!",
"= float(sys.argv[7]) #0 or 1 dpch2 = float(sys.argv[8]) #0 or 1 dpch3 =",
"seconds2 if time_ch2 - seconds2 > 50e-9: wait_f2 = False decay_waiting_ch2 = False",
"= 0 decay_start_time_ch1 = seconds1 decay_waiting_ch1 = True pulse_ch1 = True wait_fe1 =",
"- last_onepps) prevlast_onepps = last_onepps last_onepps = onepps_count switched_onepps = True time =",
"\"80\": previous_fe_0 = fe_0 previous_re_1 = re_1 previous_fe_1 = fe_1 previous_re_2 = re_2",
"if time_ch3 - seconds3 > 50e-9: wait_f3 = False if fe_3 and wait_fe3:",
"print \"Decay ch2 %10.8f ch2microseconds\"%((seconds2 - decay_start_time_ch2),) else: decay_waiting_ch2 = False else: print",
"fe_3 and wait_fe3: print \"Pulse ch3\",seconds3,line pulse_ch3 = True wait_fe3 = False if",
"(seconds1 != decay_start_time_ch3) : if decay_waiting_ch1: if re_1: wait_fe1 = True time_ch1 =",
"fields[15] seconds0 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds1 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds2 =",
"fe_1 and wait_fe1: print \"Pulse ch1\",seconds1,line pulse_ch1 = True wait_fe1 = False if",
"decay_start_time_ch1) and (seconds2 != decay_start_time_ch3): if decay_waiting_ch2: if re_2: wait_fe2 = True time_ch2",
"#filename = sys.argv[1] f = open(sys.argv[1]) for filename in files: ch0 = float(sys.argv[2])",
"if time == last_time and switched_onepps: print \"Correcting delayed onepps switch:\",seconds0,line seconds0 =",
"if (ch1==1 and ch2==1 and ch3==1 and (fields[3] == \"00\" and fields[5] ==",
"True time_ch0 = seconds0 if time_ch0 - seconds0 > 50e-9: wait_f0 = False",
"= False decay_waiting_ch0 = False if fe_0 and wait_fe0: print \"Pulse ch0\",seconds0,line pulse_ch0",
"else: decay_waiting_ch1 = False print \"Decay ch1 %10.8f ch1microseconds\"%((seconds1 - decay_start_time_ch1),) else: decay_waiting_ch1",
"of scintillators is irrelevent! ##################################################### files = sys.argv[1:] BIT0_4 = 31 BIT5 =",
"if fe_3 and wait_fe3: print \"Pulse ch2\",seconds3,line decay_start_time_ch3 = seconds3 decay_waiting_ch3 = True",
"and ch3==1 and (fields[5] == \"00\" or fields[7] == \"00\")): continue if (ch0==1",
"print \"dpch0\" print \"Decay ch0 %10.8f microseconds\"%(1e6*(seconds0 - decay_start_time_ch0),) if decay_waiting_ch0: if re_0:",
"\") #define the different options if 0==0: #current analysis for one event. Note,",
"= fe_1 previous_re_2 = re_2 previous_fe_2 = fe_2 previous_re_3 = re_3 previous_fe_3 =",
"# Ignore malformed lines if len(fields) != 16: continue #Ignore everything that is",
"start ''' # print time,correction tfields = time.split(\".\") t = tfields[0] secs_since_day_start =",
"if fe_0 and wait_fe0: print \"Pulse ch0\",seconds0,line decay_start_time_ch0 = 0 decay_start_time_ch0 = seconds0",
"\"Pulse ch3\",seconds3,line pulse_ch3 = True wait_fe3 = False if decay_waiting_ch3 and seconds3 -",
"(fields[3] == \"00\" and fields[5] == \"00\" or fields[7] == \"00\")): continue #check",
"\"00\") fe_3 = (fields[8] >= \"00\") #check the single pulse for channel if",
"#This is coincident level 0!! #Order of scintillators is irrelevent! ##################################################### files =",
"\"Decay ch2 %10.8f ch2microseconds\"%((seconds2 - decay_start_time_ch2),) else: decay_waiting_ch2 = False else: print \"no",
"decay_start_time_ch3 decay_waiting_ch3 = False else: decay_waiting_ch3 = False print \"Decay ch3 %10.8f ch3microseconds\"%((seconds3",
"\"00\")): continue if (ch1==1 and ch2==1 and ch3==1 and (fields[3] == \"00\" and",
"(fields[6] >= \"00\") fe_3 = (fields[8] >= \"00\") #check the single pulse for",
"fields[7] == \"00\")): continue if (ch2==1 and ch3==1 and (fields[5] == \"00\" or",
"seconds0 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds1 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds2 = time_to_seconds(time,correction)+(trigger_count",
"tfields = time.split(\".\") t = tfields[0] secs_since_day_start = int(t[0:2])*3600+int(t[2:4])*60+int(t[4:6]) evt_time = secs_since_day_start +",
"wait_f0 = False decay_waiting_ch0 = False if fe_0 and wait_fe0: print \"Pulse ch0\",seconds0,line",
"False decay_start_time_ch3 = 0. decay_waiting_ch3 = False last_seconds = 0. last_time = 0.",
"(fields[2] >= \"00\") fe_1 = (fields[4] >= \"00\") fe_2 = (fields[6] >= \"00\")",
"decay_start_time_ch0 = seconds0 decay_waiting_ch0 = True pulse_ch0 = True wait_fe0 = False else:",
"pulse_ch1 = False pulse_ch2 = False pulse_ch3 = False #single channel++++++++++++++++++++++++++++ if dpch0==1",
"seconds2 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds3 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq else: last_time =",
"(fields[3] == \"00\" or fields[5] == \"00\")): continue if (ch1==1 and ch3==1 and",
"print \"no decay in channel 2\" if dpch3==1 and (seconds3 != decay_start_time_ch0) and",
"1PPS rate not within range def time_to_seconds(time, correction): ''' Convert hhmmss,xxx string int",
"= False time_ch1 = 0. wait_fe2 = False time_ch2 = 0. wait_fe3 =",
"(seconds2 != decay_start_time_ch1) and (seconds2 != decay_start_time_ch3): if decay_waiting_ch2: if re_2: wait_fe2 =",
"False if decay_waiting_ch3 and seconds3 - decay_start_time_ch3 > 20: print \"No decay\",seconds3,decay_start_time_ch3,seconds3 -",
"BIT2 = 1 << 2 # GPS data possible corrupted BIT3 = 1",
"(fields[8] >= \"00\") #check the single pulse for channel if (ch0==1 and fields[1]",
"re_1 and dpch1==1: wait_fe1 = True time_ch1 = seconds1 if time_ch1 - seconds1",
"fields[7] == \"00\")): continue if (ch0==1 and ch1==1 and ch2==1 and (fields[1] ==",
"1\" if dpch2==1 and (seconds2 != decay_start_time_ch0) and (seconds2 != decay_start_time_ch1) and (seconds2",
"channel 2\" if dpch3==1 and (seconds3 != decay_start_time_ch0) and (seconds3 != decay_start_time_ch1) and",
"- onepps_count)/freq if time == last_time and switched_onepps: print \"Correcting delayed onepps switch:\",seconds0,line",
"= False if fe_0 and wait_fe0: print \"Pulse ch0\",seconds0,line decay_start_time_ch0 = 0 decay_start_time_ch0",
"True time_ch3 = seconds3 if time_ch3 - seconds3 > 50e-9: wait_f3 = False",
"- onepps_count)/freq seconds2 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds3 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq if",
"level 0!! #Order of scintillators is irrelevent! ##################################################### files = sys.argv[1:] BIT0_4 =",
"channel 0\" if dpch1==1 and (seconds1 != decay_start_time_ch0) and (seconds1 != decay_start_time_ch2) and",
"2\" if dpch3==1 and (seconds3 != decay_start_time_ch0) and (seconds3 != decay_start_time_ch1) and (seconds3",
"False else: print \"no decay in channel 2\" if dpch3==1 and (seconds3 !=",
"16: continue #Ignore everything that is not trigger data if len(fields[0]) != 8:",
"= seconds3 decay_waiting_ch3 = True pulse_ch3 = True wait_fe3 = False else: decay_waiting_ch3",
"re_2: wait_fe2 = True time_ch2 = seconds2 if time_ch2 - seconds2 > 50e-9:",
"#0 or 1 dpch1 = float(sys.argv[7]) #0 or 1 dpch2 = float(sys.argv[8]) #0",
"== \"00\")): continue if (ch0==1 and ch3==1 and (fields[1] == \"00\" or fields[7]",
"\"decay_start_time_ch2: \",decay_start_time_ch2 print \"decay_start_time_ch3: \",decay_start_time_ch3 print \"difference: \",seconds0-decay_start_time_ch0 pulse_ch0 = False pulse_ch1 =",
"= int(fields[0],16) onepps_count = int(fields[9],16) re_0 = (fields[1] >= \"00\") re_1 = (fields[3]",
"= False last_seconds = 0. last_time = 0. last_triggercount = 0 switched_onepps =",
"\",fields #print \"line: \",line # Ignore malformed lines if len(fields) != 16: continue",
"= False if decay_waiting_ch2 and seconds2 - decay_start_time_ch2 > 20: print \"No decay\",seconds2,decay_start_time_ch2,",
"def time_to_seconds(time, correction): ''' Convert hhmmss,xxx string int seconds since day start '''",
"else: decay_waiting_ch1 = False else: print \"no decay in channel 1\" if dpch2==1",
"= True wait_fe0 = False else: decay_waiting_ch0 = False if re_1 and dpch1==1:",
"wait_fe2 = False else: decay_waiting_ch2 = False if re_3 and dpch3==1: wait_fe3 =",
"int(fields[9],16) re_0 = (fields[1] >= \"00\") re_1 = (fields[3] >= \"00\") re_2 =",
"and (seconds0 != decay_start_time_ch2) and (seconds0 != decay_start_time_ch3) : print \"dpch0\" print \"Decay",
"\"decay_start_time_ch3: \",decay_start_time_ch3 print \"difference: \",seconds0-decay_start_time_ch0 pulse_ch0 = False pulse_ch1 = False pulse_ch2 =",
"line.rstrip(\"\\n\").split(\" \") #define the different options if 0==0: #current analysis for one event.",
"= fields[15] seconds0 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds1 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds2",
"= seconds1 if time_ch1 - seconds1 > 50e-9: wait_f1 = False if fe_1",
"or fields[7] == \"00\")): continue if (ch0==1 and ch1==1 and ch2==1 and (fields[1]",
"trigger_count = int(fields[0],16) onepps_count = int(fields[9],16) re_0 = (fields[1] >= \"00\") re_1 =",
"counter = 0.0 if filename.endswith('.gz'): f = gzip.open(filename) else: f = open(sys.argv[1]) for",
"open(sys.argv[1]) for filename in files: ch0 = float(sys.argv[2]) #0 or 1 ch1 =",
"dpch2==1 and (seconds2 != decay_start_time_ch0) and (seconds2 != decay_start_time_ch1) and (seconds2 != decay_start_time_ch3):",
"1 << 1 # Trigger interrupt pending BIT2 = 1 << 2 #",
"possible corrupted BIT3 = 1 << 3 # Current or last 1PPS rate",
"print \"difference: \",seconds0-decay_start_time_ch0 pulse_ch0 = False pulse_ch1 = False pulse_ch2 = False pulse_ch3",
"= False else: decay_waiting_ch1 = False print \"Decay ch1 %10.8f ch1microseconds\"%((seconds1 - decay_start_time_ch1),)",
"wait_fe2 = True time_ch2 = seconds2 if time_ch2 - seconds2 > 50e-9: wait_f2",
"== \"00\"): continue if (ch1==1 and fields[3] == \"00\"): continue if (ch2==1 and",
"switched_onepps = False last_onepps = 0 onepps_count = 0 counter = 0.0 if",
"if (ch1==1 and fields[3] == \"00\"): continue if (ch2==1 and fields[5] == \"00\"):",
"if re_0: wait_fe0 = True time_ch0 = seconds0 if time_ch0 - seconds0 >",
"print \"decay_start_time_ch2: \",decay_start_time_ch2 print \"decay_start_time_ch3: \",decay_start_time_ch3 print \"difference: \",seconds0-decay_start_time_ch0 pulse_ch0 = False pulse_ch1",
"(fields[1] == \"00\" or fields[5] == \"00\")): continue if (ch0==1 and ch3==1 and",
"+ onepps_count - last_onepps) prevlast_onepps = last_onepps last_onepps = onepps_count switched_onepps = True",
"float(sys.argv[7]) #0 or 1 dpch2 = float(sys.argv[8]) #0 or 1 dpch3 = float(sys.argv[9])",
"or fields[5] == \"00\")): continue if (ch1==1 and ch3==1 and (fields[3] == \"00\"",
"= False if decay_waiting_ch0 and seconds0 - decay_start_time_ch0 > 20: print \"No decay\",seconds0,decay_start_time_ch0,",
"decay_start_time_ch0) and (seconds2 != decay_start_time_ch1) and (seconds2 != decay_start_time_ch3): if decay_waiting_ch2: if re_2:",
"print \"decay_start_time_ch1: \",decay_start_time_ch1 print \"decay_start_time_ch2: \",decay_start_time_ch2 print \"decay_start_time_ch3: \",decay_start_time_ch3 print \"difference: \",seconds0-decay_start_time_ch0 pulse_ch0",
"False print \"Decay ch0 %10.8f ch0microseconds\"%((seconds0 - decay_start_time_ch0),) else: decay_waiting_ch0 = False else:",
"+= int(0xFFFFFFFF)/freq seconds3 += int(0xFFFFFFFF)/freq else: last_triggercount = trigger_count #if last_seconds > seconds0:",
"# Trigger interrupt pending BIT2 = 1 << 2 # GPS data possible",
"(ch1==1 and ch2==1 and (fields[3] == \"00\" or fields[5] == \"00\")): continue if",
"and ch3==1 and (fields[1] == \"00\" or fields[7] == \"00\")): continue if (ch1==1",
"seconds2 > 50e-9: wait_f2 = False decay_waiting_ch2 = False if fe_2 and wait_fe2:",
"\",line # Ignore malformed lines if len(fields) != 16: continue #Ignore everything that",
") and (seconds0 != decay_start_time_ch2) and (seconds0 != decay_start_time_ch3) : print \"dpch0\" print",
"!= decay_start_time_ch2) : if decay_waiting_ch3: if re_3: wait_fe3 = True seconds3 = time_to_seconds(time,correction)+(trigger_count",
"ch1==1 and ch2==1 and (fields[1] == \"00\" and fields[3] == \"00\" or fields[5]",
"False pulse_ch1 = False pulse_ch2 = False pulse_ch3 = False #single channel++++++++++++++++++++++++++++ if",
"and ch2==1 and ch3==1 and (fields[3] == \"00\" and fields[5] == \"00\" or",
"decay_start_time_ch1 = seconds1 decay_waiting_ch1 = True pulse_ch1 = True wait_fe1 = False else:",
"f: fields_next = line.rstrip(\"\\n\").split(\" \") #define the different options if 0==0: #current analysis",
"re_1 previous_fe_1 = fe_1 previous_re_2 = re_2 previous_fe_2 = fe_2 previous_re_3 = re_3",
"or 1 ch1 = float(sys.argv[3]) #0 or 1 ch2 = float(sys.argv[4]) #0 or",
"0 counter = 0.0 if filename.endswith('.gz'): f = gzip.open(filename) else: f = open(sys.argv[1])",
"\"00\"): continue if (ch1==1 and fields[3] == \"00\"): continue if (ch2==1 and fields[5]",
"= 0. last_time = 0. last_triggercount = 0 switched_onepps = False last_onepps =",
"switched_onepps = False if trigger_count < last_triggercount and not switched_onepps: print \"Correcting trigger",
"#print \"line: \",line # Ignore malformed lines if len(fields) != 16: continue #Ignore",
"\"00\")): continue if (ch2==1 and ch3==1 and (fields[5] == \"00\" or fields[7] ==",
"= 31 BIT5 = 1 << 5 BIT7 = 1 << 7 #",
"False time_ch2 = 0. wait_fe3 = False time_ch3 = 0. muon_start = 0.",
"1 << 7 # For DAQ status BIT0 = 1 # 1 PPS",
"= True wait_fe2 = False if decay_waiting_ch2 and seconds2 - decay_start_time_ch2 > 20:",
"wait_f2 = False if fe_2 and wait_fe2: print \"Pulse ch2\",seconds2,line decay_start_time_ch2 = seconds2",
"described by more than one line! if last_onepps != onepps_count: if onepps_count >",
"previous_re_1 = re_1 previous_fe_1 = fe_1 previous_re_2 = re_2 previous_fe_2 = fe_2 previous_re_3",
"False else: decay_waiting_ch2 = False print \"Decay ch2 %10.8f ch2microseconds\"%((seconds2 - decay_start_time_ch2),) else:",
"0!! #Order of scintillators is irrelevent! ##################################################### files = sys.argv[1:] BIT0_4 = 31",
"= line.rstrip(\"\\n\").split(\" \") #define the different options if 0==0: #current analysis for one",
"line.rstrip(\"\\n\").split(\" \") #print \"fields: \",fields #print \"line: \",line # Ignore malformed lines if",
"decay_waiting_ch3 = True pulse_ch3 = True wait_fe3 = False else: decay_waiting_ch3 = False",
"if re_1: wait_fe1 = True time_ch1 = seconds1 if time_ch1 - seconds1 >",
"(ch0==1 and ch1==1 and (fields[1] == \"00\" or fields[3] == \"00\")): continue if",
"!= decay_start_time_ch3) : if decay_waiting_ch1: if re_1: wait_fe1 = True time_ch1 = seconds1",
"for line in f: fields_next = line.rstrip(\"\\n\").split(\" \") #define the different options if",
"- prevlast_onepps)/freq else: last_time = time switched_onepps = False if trigger_count < last_triggercount",
"if fields_next[1]>= \"80\": previous_fe_0 = fe_0 previous_re_1 = re_1 previous_fe_1 = fe_1 previous_re_2",
"0. decay_waiting_ch0 = False decay_start_time_ch1 = 0. decay_waiting_ch1 = False decay_start_time_ch2 = 0.",
"(ch0==1 and fields[1] == \"00\"): continue if (ch1==1 and fields[3] == \"00\"): continue",
"= seconds2 decay_waiting_ch2 = True pulse_ch2 = True wait_fe2 = False else: decay_waiting_ch2",
"False else: decay_waiting_ch0 = False print \"Decay ch0 %10.8f ch0microseconds\"%((seconds0 - decay_start_time_ch0),) else:",
"- seconds0 > 50e-9: wait_f0 = False if fe_0 and wait_fe0: print \"Pulse",
"dpch3 = float(sys.argv[9]) #0 or 1 muon = {0:False,1:False,2:False,\"Time\":0.} freq = 25e6 #",
"string int seconds since day start ''' # print time,correction tfields = time.split(\".\")",
"float(sys.argv[8]) #0 or 1 dpch3 = float(sys.argv[9]) #0 or 1 muon = {0:False,1:False,2:False,\"Time\":0.}",
"else: decay_waiting_ch3 = False print \"Decay ch3 %10.8f ch3microseconds\"%((seconds3 - decay_start_time_ch3),) else: decay_waiting_ch3",
"seconds1 decay_waiting_ch1 = True pulse_ch1 = True wait_fe1 = False else: decay_waiting_ch1 =",
"= True wait_fe3 = False else: decay_waiting_ch3 = False #seconds0=decay_start_time_ch0 #seconds1=decay_start_time_ch1 #seconds2=decay_start_time_ch2 #seconds3=decay_start_time_ch3",
"False decay_start_time_ch1 = 0. decay_waiting_ch1 = False decay_start_time_ch2 = 0. decay_waiting_ch2 = False",
"- decay_start_time_ch0 decay_waiting_ch0 = False else: decay_waiting_ch0 = False print \"Decay ch0 %10.8f",
"print \"no decay in channel 1\" if dpch2==1 and (seconds2 != decay_start_time_ch0) and",
"= gzip.open(filename) else: f = open(sys.argv[1]) for line in f: fields = line.rstrip(\"\\n\").split(\"",
"time == last_time and switched_onepps: print \"Correcting delayed onepps switch:\",seconds0,line seconds0 = time_to_seconds(time,correction)+(trigger_count",
"print \"Correcting trigger count rollover:\",seconds0,line seconds0 += int(0xFFFFFFFF)/freq seconds1 += int(0xFFFFFFFF)/freq seconds2 +=",
"and (seconds2 != decay_start_time_ch0) and (seconds2 != decay_start_time_ch1) and (seconds2 != decay_start_time_ch3): if",
"event. Note, that one event can be described by more than one line!",
"decay in channel 0\" if dpch1==1 and (seconds1 != decay_start_time_ch0) and (seconds1 !=",
"else: decay_waiting_ch1 = False if re_2 and dpch2==1: wait_fe2 = True time_ch2 =",
"20: print \"No decay\",seconds1,decay_start_time_ch1,seconds1 - decay_start_time_ch1 decay_waiting_ch1 = False else: decay_waiting_ch1 = False",
"or 1 ch3 = float(sys.argv[5]) #0 or 1 dpch0 = float(sys.argv[6]) #0 or",
"= False if decay_waiting_ch1 and seconds1 - decay_start_time_ch1 > 20: print \"No decay\",seconds1,decay_start_time_ch1,seconds1",
"more than one line! if last_onepps != onepps_count: if onepps_count > last_onepps: freq",
"- prevlast_onepps)/freq seconds2 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds3 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq else:",
"and ch2==1 and (fields[3] == \"00\" or fields[5] == \"00\")): continue if (ch1==1",
"if re_1 and dpch1==1: wait_fe1 = True time_ch1 = seconds1 if time_ch1 -",
"##################################################### #This is coincident level 0!! #Order of scintillators is irrelevent! ##################################################### files",
"= 0. decay_waiting_ch0 = False decay_start_time_ch1 = 0. decay_waiting_ch1 = False decay_start_time_ch2 =",
"wait_fe3 = False if decay_waiting_ch3 and seconds3 - decay_start_time_ch3 > 20: print \"No",
"1 ch1 = float(sys.argv[3]) #0 or 1 ch2 = float(sys.argv[4]) #0 or 1",
"= (fields[8] >= \"00\") #check the single pulse for channel if (ch0==1 and",
"if fe_1 and wait_fe1: print \"Pulse ch1\",seconds1,line pulse_ch1 = True wait_fe1 = False",
"0. decay_start_time_ch0 = 0. decay_waiting_ch0 = False decay_start_time_ch1 = 0. decay_waiting_ch1 = False",
"f = gzip.open(filename) else: f = open(sys.argv[1]) for line in f: fields =",
"time_ch3 - seconds3 > 50e-9: wait_f3 = False if fe_3 and wait_fe3: print",
"re_0 = (fields[1] >= \"00\") re_1 = (fields[3] >= \"00\") re_2 = (fields[5]",
"and wait_fe3: print \"Pulse ch3\",seconds3,line pulse_ch3 = True wait_fe3 = False if decay_waiting_ch3",
"ch2 %10.8f ch2microseconds\"%((seconds2 - decay_start_time_ch2),) else: decay_waiting_ch2 = False else: print \"no decay",
"8: continue try: int(fields[len(fields)-1]) except ValueError: continue trigger_count = int(fields[0],16) onepps_count = int(fields[9],16)",
"and (seconds1 != decay_start_time_ch2) and (seconds1 != decay_start_time_ch3) : if decay_waiting_ch1: if re_1:",
"+ int(tfields[1])/1000.0+int(correction)/1000.0 return round(evt_time) #filename = sys.argv[1] f = open(sys.argv[1]) for filename in",
"+= int(0xFFFFFFFF)/freq seconds2 += int(0xFFFFFFFF)/freq seconds3 += int(0xFFFFFFFF)/freq else: last_triggercount = trigger_count #if",
"= float(sys.argv[4]) #0 or 1 ch3 = float(sys.argv[5]) #0 or 1 dpch0 =",
"#Order of scintillators is irrelevent! ##################################################### files = sys.argv[1:] BIT0_4 = 31 BIT5",
"GPS data possible corrupted BIT3 = 1 << 3 # Current or last",
"pulse_ch2 = True wait_fe2 = False if decay_waiting_ch2 and seconds2 - decay_start_time_ch2 >",
"in files: ch0 = float(sys.argv[2]) #0 or 1 ch1 = float(sys.argv[3]) #0 or",
"wait_fe3: print \"Pulse ch3\",seconds3,line pulse_ch3 = True wait_fe3 = False if decay_waiting_ch3 and",
"gzip.open(filename) else: f = open(sys.argv[1]) for line in f: fields = line.rstrip(\"\\n\").split(\" \")",
"\"00\") re_2 = (fields[5] >= \"00\") re_3 = (fields[7] >= \"00\") fe_0 =",
"time = fields[10] correction = fields[15] seconds0 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds1 =",
"= 0. muon_start = 0. nmuons = 0 last_pulse = 0. decay_start_time_ch0 =",
"time_ch3 = seconds3 if time_ch3 - seconds3 > 50e-9: wait_f3 = False if",
"for channel if (ch0==1 and fields[1] == \"00\"): continue if (ch1==1 and fields[3]",
"\"00\") #check the single pulse for channel if (ch0==1 and fields[1] == \"00\"):",
"(seconds0 != decay_start_time_ch2) and (seconds0 != decay_start_time_ch3) : print \"dpch0\" print \"Decay ch0",
"True pulse_ch2 = True wait_fe2 = False else: decay_waiting_ch2 = False if re_3",
"pulse_ch2 = True wait_fe2 = False else: decay_waiting_ch2 = False if re_3 and",
"continue if (ch3==1 and fields[7] == \"00\"): continue if (ch0==1 and ch1==1 and",
"count rollover:\",seconds0,line seconds0 += int(0xFFFFFFFF)/freq seconds1 += int(0xFFFFFFFF)/freq seconds2 += int(0xFFFFFFFF)/freq seconds3 +=",
"- decay_start_time_ch1 > 20: print \"No decay\",seconds1,decay_start_time_ch1,seconds1 - decay_start_time_ch1 decay_waiting_ch1 = False else:",
"wait_fe0 = False else: decay_waiting_ch0 = False if re_1 and dpch1==1: wait_fe1 =",
"(fields[4] >= \"00\") fe_2 = (fields[6] >= \"00\") fe_3 = (fields[8] >= \"00\")",
"print \"Pulse ch3\",seconds3,line pulse_ch3 = True wait_fe3 = False if decay_waiting_ch3 and seconds3",
"= True wait_fe1 = False if decay_waiting_ch1 and seconds1 - decay_start_time_ch1 > 20:",
"fields[7] == \"00\")): continue #check for double pulse if fields[1] >= \"80\": for",
"== \"00\"): continue if (ch0==1 and ch1==1 and (fields[1] == \"00\" or fields[3]",
"decay_waiting_ch3 = False print \"Decay ch3 %10.8f ch3microseconds\"%((seconds3 - decay_start_time_ch3),) else: decay_waiting_ch3 =",
"decay_start_time_ch0 > 20: print \"No decay\",seconds0,decay_start_time_ch0, seconds0 - decay_start_time_ch0 decay_waiting_ch0 = False else:",
"ch0 %10.8f ch0microseconds\"%((seconds0 - decay_start_time_ch0),) else: decay_waiting_ch0 = False else: print \"no decay",
"if dpch2==1 and (seconds2 != decay_start_time_ch0) and (seconds2 != decay_start_time_ch1) and (seconds2 !=",
"and (seconds0 !=decay_start_time_ch1 ) and (seconds0 != decay_start_time_ch2) and (seconds0 != decay_start_time_ch3) :",
"fields[3] == \"00\"): continue if (ch2==1 and fields[5] == \"00\"): continue if (ch3==1",
"print \"Correcting delayed onepps switch:\",seconds0,line seconds0 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds1 = time_to_seconds(time,correction)+(trigger_count",
"time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds2 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds3 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq",
"continue if (ch2==1 and fields[5] == \"00\"): continue if (ch3==1 and fields[7] ==",
"!= decay_start_time_ch1) and (seconds2 != decay_start_time_ch3): if decay_waiting_ch2: if re_2: wait_fe2 = True",
"- decay_start_time_ch2 > 20: print \"No decay\",seconds2,decay_start_time_ch2, seconds2 - decay_start_time_ch2 decay_waiting_ch2 = False",
"seconds0 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds1 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds2 = time_to_seconds(time,correction)+(trigger_count",
"float(sys.argv[6]) #0 or 1 dpch1 = float(sys.argv[7]) #0 or 1 dpch2 = float(sys.argv[8])",
"trigger_count < last_triggercount and not switched_onepps: print \"Correcting trigger count rollover:\",seconds0,line seconds0 +=",
"ch2==1 and (fields[1] == \"00\" or fields[5] == \"00\")): continue if (ch0==1 and",
"Convert hhmmss,xxx string int seconds since day start ''' # print time,correction tfields",
"switched_onepps: print \"Correcting trigger count rollover:\",seconds0,line seconds0 += int(0xFFFFFFFF)/freq seconds1 += int(0xFFFFFFFF)/freq seconds2",
"int(tfields[1])/1000.0+int(correction)/1000.0 return round(evt_time) #filename = sys.argv[1] f = open(sys.argv[1]) for filename in files:",
"= 0 last_muon = 0 wait_fe0 = False time_ch0 = 0. wait_fe1 =",
"= seconds0 print \"seconds0:\",seconds0 print \"decay_start_time_ch0: \",decay_start_time_ch0 print \"decay_start_time_ch1: \",decay_start_time_ch1 print \"decay_start_time_ch2: \",decay_start_time_ch2",
"filename in files: ch0 = float(sys.argv[2]) #0 or 1 ch1 = float(sys.argv[3]) #0",
"- seconds0 > 50e-9: wait_f0 = False decay_waiting_ch0 = False if fe_0 and",
"continue if (ch0==1 and ch3==1 and (fields[1] == \"00\" or fields[7] == \"00\")):",
"and ch1==1 and ch2==1 and (fields[1] == \"00\" and fields[3] == \"00\" or",
"= False else: print \"no decay in channel 0\" if dpch1==1 and (seconds1",
"# For DAQ status BIT0 = 1 # 1 PPS interrupt pending BIT1",
"0. wait_fe2 = False time_ch2 = 0. wait_fe3 = False time_ch3 = 0.",
"decay_start_time_ch0),) else: decay_waiting_ch0 = False else: print \"no decay in channel 0\" if",
"50e-9: wait_f0 = False if fe_0 and wait_fe0: print \"Pulse ch0\",seconds0,line decay_start_time_ch0 =",
"hhmmss,xxx string int seconds since day start ''' # print time,correction tfields =",
"- prevlast_onepps)/freq seconds3 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq else: last_time = time switched_onepps =",
"if dpch1==1 and (seconds1 != decay_start_time_ch0) and (seconds1 != decay_start_time_ch2) and (seconds1 !=",
"secs_since_day_start + int(tfields[1])/1000.0+int(correction)/1000.0 return round(evt_time) #filename = sys.argv[1] f = open(sys.argv[1]) for filename",
"\"no decay in channel 1\" if dpch2==1 and (seconds2 != decay_start_time_ch0) and (seconds2",
"re_0 and dpch0==1: wait_fe0 = True time_ch0 = seconds0 if time_ch0 - seconds0",
"print \"No decay\",seconds0,decay_start_time_ch0, seconds0 - decay_start_time_ch0 decay_waiting_ch0 = False else: decay_waiting_ch0 = False",
"\"00\") fe_2 = (fields[6] >= \"00\") fe_3 = (fields[8] >= \"00\") #check the",
"time_ch3 = 0. muon_start = 0. nmuons = 0 last_pulse = 0. decay_start_time_ch0",
"\"00\" or fields[7] == \"00\")): continue if (ch0==1 and ch1==1 and ch2==1 and",
"= False else: decay_waiting_ch3 = False #seconds0=decay_start_time_ch0 #seconds1=decay_start_time_ch1 #seconds2=decay_start_time_ch2 #seconds3=decay_start_time_ch3 if fields_next[1]>= \"80\":",
"(seconds0 !=decay_start_time_ch1 ) and (seconds0 != decay_start_time_ch2) and (seconds0 != decay_start_time_ch3) : print",
"\"No decay\",seconds0,decay_start_time_ch0, seconds0 - decay_start_time_ch0 decay_waiting_ch0 = False else: decay_waiting_ch0 = False print",
"time_ch0 = seconds0 if time_ch0 - seconds0 > 50e-9: wait_f0 = False if",
"day start ''' # print time,correction tfields = time.split(\".\") t = tfields[0] secs_since_day_start",
"seconds3 if time_ch3 - seconds3 > 50e-9: wait_f3 = False if fe_3 and",
"else: print \"no decay in channel 3\" if re_0 and dpch0==1: wait_fe0 =",
"20: print \"No decay\",seconds3,decay_start_time_ch3,seconds3 - decay_start_time_ch3 decay_waiting_ch3 = False else: decay_waiting_ch3 = False",
"decay_waiting_ch1 = False else: print \"no decay in channel 1\" if dpch2==1 and",
"onepps_count > last_onepps: freq = float(onepps_count - last_onepps) else: freq = float(0xFFFFFFFF +",
"int(0xFFFFFFFF)/freq seconds3 += int(0xFFFFFFFF)/freq else: last_triggercount = trigger_count #if last_seconds > seconds0: #",
"seconds0: # print \"Wrong event order\",seconds0,line # continue last_seconds = seconds0 print \"seconds0:\",seconds0",
"False if fe_1 and wait_fe1: #print \"Pulse ch1\",seconds1,line decay_start_time_ch1 = 0 decay_start_time_ch1 =",
"#current analysis for one event. Note, that one event can be described by",
"wait_f0 = False if fe_0 and wait_fe0: print \"Pulse ch0\",seconds0,line decay_start_time_ch0 = 0",
"sys import gzip ##################################################### #This is coincident level 0!! #Order of scintillators is",
"PPS interrupt pending BIT1 = 1 << 1 # Trigger interrupt pending BIT2",
"files = sys.argv[1:] BIT0_4 = 31 BIT5 = 1 << 5 BIT7 =",
"onepps_count: if onepps_count > last_onepps: freq = float(onepps_count - last_onepps) else: freq =",
"# Current or last 1PPS rate not within range def time_to_seconds(time, correction): '''",
"False if decay_waiting_ch0 and seconds0 - decay_start_time_ch0 > 20: print \"No decay\",seconds0,decay_start_time_ch0, seconds0",
"last_time = time switched_onepps = False if trigger_count < last_triggercount and not switched_onepps:",
"= sys.argv[1:] BIT0_4 = 31 BIT5 = 1 << 5 BIT7 = 1",
"fe_1 and wait_fe1: #print \"Pulse ch1\",seconds1,line decay_start_time_ch1 = 0 decay_start_time_ch1 = seconds1 decay_waiting_ch1",
"= False else: print \"no decay in channel 3\" if re_0 and dpch0==1:",
"wait_f2 = False decay_waiting_ch2 = False if fe_2 and wait_fe2: print \"Pulse ch2\",seconds2,line",
"time_ch0 - seconds0 > 50e-9: wait_f0 = False decay_waiting_ch0 = False if fe_0",
"- decay_start_time_ch2),) else: decay_waiting_ch2 = False else: print \"no decay in channel 2\"",
"pulse_ch2 = False pulse_ch3 = False #single channel++++++++++++++++++++++++++++ if dpch0==1 and (seconds0 !=decay_start_time_ch1",
"#0 or 1 dpch0 = float(sys.argv[6]) #0 or 1 dpch1 = float(sys.argv[7]) #0",
"and fields[3] == \"00\" or fields[5] == \"00\")): continue if (ch1==1 and ch2==1",
"everything that is not trigger data if len(fields[0]) != 8: continue try: int(fields[len(fields)-1])",
"lines if len(fields) != 16: continue #Ignore everything that is not trigger data",
"fields[5] == \"00\")): continue if (ch1==1 and ch3==1 and (fields[3] == \"00\" or",
"\"Correcting delayed onepps switch:\",seconds0,line seconds0 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds1 = time_to_seconds(time,correction)+(trigger_count -",
"False decay_waiting_ch2 = False if fe_2 and wait_fe2: print \"Pulse ch2\",seconds2,line pulse_ch2 =",
"\"decay_start_time_ch1: \",decay_start_time_ch1 print \"decay_start_time_ch2: \",decay_start_time_ch2 print \"decay_start_time_ch3: \",decay_start_time_ch3 print \"difference: \",seconds0-decay_start_time_ch0 pulse_ch0 =",
"False pulse_ch3 = False #single channel++++++++++++++++++++++++++++ if dpch0==1 and (seconds0 !=decay_start_time_ch1 ) and",
"seconds1 += int(0xFFFFFFFF)/freq seconds2 += int(0xFFFFFFFF)/freq seconds3 += int(0xFFFFFFFF)/freq else: last_triggercount = trigger_count",
"\"00\")): continue if (ch0==1 and ch1==1 and ch2==1 and (fields[1] == \"00\" and",
"= True pulse_ch2 = True wait_fe2 = False else: decay_waiting_ch2 = False if",
"= False decay_start_time_ch2 = 0. decay_waiting_ch2 = False decay_start_time_ch3 = 0. decay_waiting_ch3 =",
"fields_next[1]>= \"80\": previous_fe_0 = fe_0 previous_re_1 = re_1 previous_fe_1 = fe_1 previous_re_2 =",
"decay_start_time_ch0 decay_waiting_ch0 = False else: decay_waiting_ch0 = False print \"Decay ch0 %10.8f ch0microseconds\"%((seconds0",
"if trigger_count < last_triggercount and not switched_onepps: print \"Correcting trigger count rollover:\",seconds0,line seconds0",
"malformed lines if len(fields) != 16: continue #Ignore everything that is not trigger",
"freq = float(onepps_count - last_onepps) else: freq = float(0xFFFFFFFF + onepps_count - last_onepps)",
"ch1\",seconds1,line decay_start_time_ch1 = 0 decay_start_time_ch1 = seconds1 decay_waiting_ch1 = True pulse_ch1 = True",
"else: freq = float(0xFFFFFFFF + onepps_count - last_onepps) prevlast_onepps = last_onepps last_onepps =",
"= seconds1 decay_waiting_ch1 = True pulse_ch1 = True wait_fe1 = False else: decay_waiting_ch1",
"> 50e-9: wait_f2 = False if fe_2 and wait_fe2: print \"Pulse ch2\",seconds2,line decay_start_time_ch2",
"seconds3 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq time_ch3 = seconds3 if time_ch3 - seconds3 >",
"status BIT0 = 1 # 1 PPS interrupt pending BIT1 = 1 <<",
"= seconds2 if time_ch2 - seconds2 > 50e-9: wait_f2 = False decay_waiting_ch2 =",
"decay_waiting_ch3 = False else: print \"no decay in channel 3\" if re_0 and",
"and (seconds1 != decay_start_time_ch3) : if decay_waiting_ch1: if re_1: wait_fe1 = True time_ch1",
"> last_onepps: freq = float(onepps_count - last_onepps) else: freq = float(0xFFFFFFFF + onepps_count",
"(seconds3 != decay_start_time_ch1) and (seconds3 != decay_start_time_ch2) : if decay_waiting_ch3: if re_3: wait_fe3",
"> 50e-9: wait_f1 = False if fe_1 and wait_fe1: #print \"Pulse ch1\",seconds1,line decay_start_time_ch1",
"= False if re_3 and dpch3==1: wait_fe3 = True time_ch3 = seconds3 if",
"if re_2 and dpch2==1: wait_fe2 = True time_ch2 = seconds2 if time_ch2 -",
"decay\",seconds2,decay_start_time_ch2, seconds2 - decay_start_time_ch2 decay_waiting_ch2 = False else: decay_waiting_ch2 = False print \"Decay",
"BIT0 = 1 # 1 PPS interrupt pending BIT1 = 1 << 1",
"= False pulse_ch3 = False #single channel++++++++++++++++++++++++++++ if dpch0==1 and (seconds0 !=decay_start_time_ch1 )",
"seconds1 > 50e-9: wait_f1 = False if fe_1 and wait_fe1: #print \"Pulse ch1\",seconds1,line",
"and seconds1 - decay_start_time_ch1 > 20: print \"No decay\",seconds1,decay_start_time_ch1,seconds1 - decay_start_time_ch1 decay_waiting_ch1 =",
"False print \"Decay ch2 %10.8f ch2microseconds\"%((seconds2 - decay_start_time_ch2),) else: decay_waiting_ch2 = False else:",
"if (ch2==1 and fields[5] == \"00\"): continue if (ch3==1 and fields[7] == \"00\"):",
"(seconds2 != decay_start_time_ch0) and (seconds2 != decay_start_time_ch1) and (seconds2 != decay_start_time_ch3): if decay_waiting_ch2:",
"Current or last 1PPS rate not within range def time_to_seconds(time, correction): ''' Convert",
"seconds1 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds2 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds3 = time_to_seconds(time,correction)+(trigger_count",
"time_ch2 - seconds2 > 50e-9: wait_f2 = False if fe_2 and wait_fe2: print",
"= time.split(\".\") t = tfields[0] secs_since_day_start = int(t[0:2])*3600+int(t[2:4])*60+int(t[4:6]) evt_time = secs_since_day_start + int(tfields[1])/1000.0+int(correction)/1000.0",
"or 1 ch2 = float(sys.argv[4]) #0 or 1 ch3 = float(sys.argv[5]) #0 or",
"= secs_since_day_start + int(tfields[1])/1000.0+int(correction)/1000.0 return round(evt_time) #filename = sys.argv[1] f = open(sys.argv[1]) for",
"= False if re_1 and dpch1==1: wait_fe1 = True time_ch1 = seconds1 if",
"= 0. decay_waiting_ch1 = False decay_start_time_ch2 = 0. decay_waiting_ch2 = False decay_start_time_ch3 =",
"- seconds3 > 50e-9: wait_f3 = False if fe_3 and wait_fe3: print \"Pulse",
"> 50e-9: wait_f3 = False if fe_3 and wait_fe3: print \"Pulse ch3\",seconds3,line pulse_ch3",
"continue #check for double pulse if fields[1] >= \"80\": for line in f:",
"- onepps_count)/freq time_ch3 = seconds3 if time_ch3 - seconds3 > 50e-9: wait_f3 =",
"\"00\" and fields[5] == \"00\" or fields[7] == \"00\")): continue #check for double",
"!= 16: continue #Ignore everything that is not trigger data if len(fields[0]) !=",
"(seconds3 != decay_start_time_ch2) : if decay_waiting_ch3: if re_3: wait_fe3 = True seconds3 =",
"is not trigger data if len(fields[0]) != 8: continue try: int(fields[len(fields)-1]) except ValueError:",
"prevlast_onepps)/freq seconds1 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds2 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds3 =",
"scintillators is irrelevent! ##################################################### files = sys.argv[1:] BIT0_4 = 31 BIT5 = 1",
"0.0 if filename.endswith('.gz'): f = gzip.open(filename) else: f = open(sys.argv[1]) for line in",
"and ch2==1 and (fields[1] == \"00\" or fields[5] == \"00\")): continue if (ch0==1",
"in channel 2\" if dpch3==1 and (seconds3 != decay_start_time_ch0) and (seconds3 != decay_start_time_ch1)",
"int(0xFFFFFFFF)/freq seconds2 += int(0xFFFFFFFF)/freq seconds3 += int(0xFFFFFFFF)/freq else: last_triggercount = trigger_count #if last_seconds",
"(ch2==1 and fields[5] == \"00\"): continue if (ch3==1 and fields[7] == \"00\"): continue",
"= time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds1 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds2 = time_to_seconds(time,correction)+(trigger_count -",
"ch2==1 and ch3==1 and (fields[3] == \"00\" and fields[5] == \"00\" or fields[7]",
"seconds2 += int(0xFFFFFFFF)/freq seconds3 += int(0xFFFFFFFF)/freq else: last_triggercount = trigger_count #if last_seconds >",
"fields[5] == \"00\")): continue if (ch1==1 and ch2==1 and ch3==1 and (fields[3] ==",
"0. last_triggercount = 0 switched_onepps = False last_onepps = 0 onepps_count = 0",
"!= decay_start_time_ch2) and (seconds1 != decay_start_time_ch3) : if decay_waiting_ch1: if re_1: wait_fe1 =",
"if decay_waiting_ch0 and seconds0 - decay_start_time_ch0 > 20: print \"No decay\",seconds0,decay_start_time_ch0, seconds0 -",
"\"80\": for line in f: fields_next = line.rstrip(\"\\n\").split(\" \") #define the different options",
"and ch3==1 and (fields[3] == \"00\" or fields[7] == \"00\")): continue if (ch2==1",
"= True seconds3 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq time_ch3 = seconds3 if time_ch3 -",
"decay_start_time_ch2 > 20: print \"No decay\",seconds2,decay_start_time_ch2, seconds2 - decay_start_time_ch2 decay_waiting_ch2 = False else:",
"one event can be described by more than one line! if last_onepps !=",
"True time = fields[10] correction = fields[15] seconds0 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds1",
"- decay_start_time_ch3 > 20: print \"No decay\",seconds3,decay_start_time_ch3,seconds3 - decay_start_time_ch3 decay_waiting_ch3 = False else:",
"dpch0==1: wait_fe0 = True time_ch0 = seconds0 if time_ch0 - seconds0 > 50e-9:",
"and wait_fe2: print \"Pulse ch2\",seconds2,line decay_start_time_ch2 = seconds2 decay_waiting_ch2 = True pulse_ch2 =",
"time_ch2 = seconds2 if time_ch2 - seconds2 > 50e-9: wait_f2 = False if",
"decay_start_time_ch0),) if decay_waiting_ch0: if re_0: wait_fe0 = True time_ch0 = seconds0 if time_ch0",
"int(t[0:2])*3600+int(t[2:4])*60+int(t[4:6]) evt_time = secs_since_day_start + int(tfields[1])/1000.0+int(correction)/1000.0 return round(evt_time) #filename = sys.argv[1] f =",
"re_3 = (fields[7] >= \"00\") fe_0 = (fields[2] >= \"00\") fe_1 = (fields[4]",
"= False if decay_waiting_ch3 and seconds3 - decay_start_time_ch3 > 20: print \"No decay\",seconds3,decay_start_time_ch3,seconds3",
"= False else: decay_waiting_ch1 = False if re_2 and dpch2==1: wait_fe2 = True",
"else: f = open(sys.argv[1]) for line in f: fields = line.rstrip(\"\\n\").split(\" \") #print",
"(ch1==1 and ch3==1 and (fields[3] == \"00\" or fields[7] == \"00\")): continue if",
"#seconds0=decay_start_time_ch0 #seconds1=decay_start_time_ch1 #seconds2=decay_start_time_ch2 #seconds3=decay_start_time_ch3 if fields_next[1]>= \"80\": previous_fe_0 = fe_0 previous_re_1 = re_1",
"for double pulse if fields[1] >= \"80\": for line in f: fields_next =",
"dpch1 = float(sys.argv[7]) #0 or 1 dpch2 = float(sys.argv[8]) #0 or 1 dpch3",
"fields[3] == \"00\" or fields[5] == \"00\")): continue if (ch1==1 and ch2==1 and",
"False if fe_1 and wait_fe1: print \"Pulse ch1\",seconds1,line pulse_ch1 = True wait_fe1 =",
"float(sys.argv[5]) #0 or 1 dpch0 = float(sys.argv[6]) #0 or 1 dpch1 = float(sys.argv[7])",
"(fields[5] == \"00\" or fields[7] == \"00\")): continue if (ch0==1 and ch1==1 and",
"= False print \"Decay ch1 %10.8f ch1microseconds\"%((seconds1 - decay_start_time_ch1),) else: decay_waiting_ch1 = False",
"tfields[0] secs_since_day_start = int(t[0:2])*3600+int(t[2:4])*60+int(t[4:6]) evt_time = secs_since_day_start + int(tfields[1])/1000.0+int(correction)/1000.0 return round(evt_time) #filename =",
"0 last_muon = 0 wait_fe0 = False time_ch0 = 0. wait_fe1 = False",
"\") #print \"fields: \",fields #print \"line: \",line # Ignore malformed lines if len(fields)",
"fields[7] == \"00\")): continue if (ch1==1 and ch2==1 and (fields[3] == \"00\" or",
"\"00\" and fields[3] == \"00\" or fields[5] == \"00\")): continue if (ch1==1 and",
": if decay_waiting_ch1: if re_1: wait_fe1 = True time_ch1 = seconds1 if time_ch1",
"or fields[5] == \"00\")): continue if (ch1==1 and ch2==1 and ch3==1 and (fields[3]",
"\"00\" or fields[7] == \"00\")): continue if (ch2==1 and ch3==1 and (fields[5] ==",
"= True time = fields[10] correction = fields[15] seconds0 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq",
"!=decay_start_time_ch1 ) and (seconds0 != decay_start_time_ch2) and (seconds0 != decay_start_time_ch3) : print \"dpch0\"",
"print \"Pulse ch2\",seconds2,line decay_start_time_ch2 = seconds2 decay_waiting_ch2 = True pulse_ch2 = True wait_fe2",
"that is not trigger data if len(fields[0]) != 8: continue try: int(fields[len(fields)-1]) except",
"decay\",seconds1,decay_start_time_ch1,seconds1 - decay_start_time_ch1 decay_waiting_ch1 = False else: decay_waiting_ch1 = False print \"Decay ch1",
"seconds0 - decay_start_time_ch0 decay_waiting_ch0 = False else: decay_waiting_ch0 = False print \"Decay ch0",
"!= onepps_count: if onepps_count > last_onepps: freq = float(onepps_count - last_onepps) else: freq",
"# 25 MHz last_onepps = 0 last_muon = 0 wait_fe0 = False time_ch0",
"True time_ch2 = seconds2 if time_ch2 - seconds2 > 50e-9: wait_f2 = False",
"(seconds1 != decay_start_time_ch0) and (seconds1 != decay_start_time_ch2) and (seconds1 != decay_start_time_ch3) : if",
"= False decay_waiting_ch2 = False if fe_2 and wait_fe2: print \"Pulse ch2\",seconds2,line pulse_ch2",
"print time,correction tfields = time.split(\".\") t = tfields[0] secs_since_day_start = int(t[0:2])*3600+int(t[2:4])*60+int(t[4:6]) evt_time =",
"== \"00\" or fields[5] == \"00\")): continue if (ch1==1 and ch2==1 and ch3==1",
"for one event. Note, that one event can be described by more than",
"seconds0 decay_waiting_ch0 = True pulse_ch0 = True wait_fe0 = False else: decay_waiting_ch0 =",
"== \"00\" or fields[7] == \"00\")): continue if (ch2==1 and ch3==1 and (fields[5]",
"# print \"Wrong event order\",seconds0,line # continue last_seconds = seconds0 print \"seconds0:\",seconds0 print",
"decay_start_time_ch3),) else: decay_waiting_ch3 = False else: print \"no decay in channel 3\" if",
"one event. Note, that one event can be described by more than one",
"or last 1PPS rate not within range def time_to_seconds(time, correction): ''' Convert hhmmss,xxx",
"if re_3 and dpch3==1: wait_fe3 = True time_ch3 = seconds3 if time_ch3 -",
"for line in f: fields = line.rstrip(\"\\n\").split(\" \") #print \"fields: \",fields #print \"line:",
"channel++++++++++++++++++++++++++++ if dpch0==1 and (seconds0 !=decay_start_time_ch1 ) and (seconds0 != decay_start_time_ch2) and (seconds0",
"= False pulse_ch1 = False pulse_ch2 = False pulse_ch3 = False #single channel++++++++++++++++++++++++++++",
"#print \"fields: \",fields #print \"line: \",line # Ignore malformed lines if len(fields) !=",
"(fields[1] >= \"00\") re_1 = (fields[3] >= \"00\") re_2 = (fields[5] >= \"00\")",
"= True pulse_ch1 = True wait_fe1 = False else: decay_waiting_ch1 = False if",
"True wait_fe3 = False if decay_waiting_ch3 and seconds3 - decay_start_time_ch3 > 20: print",
"last_onepps != onepps_count: if onepps_count > last_onepps: freq = float(onepps_count - last_onepps) else:",
"False #seconds0=decay_start_time_ch0 #seconds1=decay_start_time_ch1 #seconds2=decay_start_time_ch2 #seconds3=decay_start_time_ch3 if fields_next[1]>= \"80\": previous_fe_0 = fe_0 previous_re_1 =",
"pulse_ch3 = True wait_fe3 = False if decay_waiting_ch3 and seconds3 - decay_start_time_ch3 >",
"pulse_ch1 = True wait_fe1 = False if decay_waiting_ch1 and seconds1 - decay_start_time_ch1 >",
"seconds3 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq else: last_time = time switched_onepps = False if",
"and wait_fe1: #print \"Pulse ch1\",seconds1,line decay_start_time_ch1 = 0 decay_start_time_ch1 = seconds1 decay_waiting_ch1 =",
"wait_fe1 = True time_ch1 = seconds1 if time_ch1 - seconds1 > 50e-9: wait_f1",
"##################################################### files = sys.argv[1:] BIT0_4 = 31 BIT5 = 1 << 5 BIT7",
"%10.8f ch0microseconds\"%((seconds0 - decay_start_time_ch0),) else: decay_waiting_ch0 = False else: print \"no decay in",
"== \"00\" or fields[5] == \"00\")): continue if (ch1==1 and ch3==1 and (fields[3]",
"t = tfields[0] secs_since_day_start = int(t[0:2])*3600+int(t[2:4])*60+int(t[4:6]) evt_time = secs_since_day_start + int(tfields[1])/1000.0+int(correction)/1000.0 return round(evt_time)",
"and ch2==1 and (fields[1] == \"00\" and fields[3] == \"00\" or fields[5] ==",
"decay_waiting_ch1: if re_1: wait_fe1 = True time_ch1 = seconds1 if time_ch1 - seconds1",
"if (ch1==1 and ch3==1 and (fields[3] == \"00\" or fields[7] == \"00\")): continue",
"- last_onepps) else: freq = float(0xFFFFFFFF + onepps_count - last_onepps) prevlast_onepps = last_onepps",
"onepps switch:\",seconds0,line seconds0 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds1 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds2",
"False print \"Decay ch3 %10.8f ch3microseconds\"%((seconds3 - decay_start_time_ch3),) else: decay_waiting_ch3 = False else:",
"decay_waiting_ch1 = True pulse_ch1 = True wait_fe1 = False else: decay_waiting_ch1 = False",
"import sys import gzip ##################################################### #This is coincident level 0!! #Order of scintillators",
"= 0 decay_start_time_ch0 = seconds0 decay_waiting_ch0 = True pulse_ch0 = True wait_fe0 =",
"<< 7 # For DAQ status BIT0 = 1 # 1 PPS interrupt",
"= True wait_fe0 = False if decay_waiting_ch0 and seconds0 - decay_start_time_ch0 > 20:",
"= True pulse_ch3 = True wait_fe3 = False else: decay_waiting_ch3 = False #seconds0=decay_start_time_ch0",
"last_seconds = seconds0 print \"seconds0:\",seconds0 print \"decay_start_time_ch0: \",decay_start_time_ch0 print \"decay_start_time_ch1: \",decay_start_time_ch1 print \"decay_start_time_ch2:",
">= \"00\") fe_3 = (fields[8] >= \"00\") #check the single pulse for channel",
"pulse_ch0 = True wait_fe0 = False else: decay_waiting_ch0 = False if re_1 and",
"decay_start_time_ch3 > 20: print \"No decay\",seconds3,decay_start_time_ch3,seconds3 - decay_start_time_ch3 decay_waiting_ch3 = False else: decay_waiting_ch3",
"int(0xFFFFFFFF)/freq seconds1 += int(0xFFFFFFFF)/freq seconds2 += int(0xFFFFFFFF)/freq seconds3 += int(0xFFFFFFFF)/freq else: last_triggercount =",
"re_0: wait_fe0 = True time_ch0 = seconds0 if time_ch0 - seconds0 > 50e-9:",
"in channel 1\" if dpch2==1 and (seconds2 != decay_start_time_ch0) and (seconds2 != decay_start_time_ch1)",
"= 1 << 5 BIT7 = 1 << 7 # For DAQ status",
"\"No decay\",seconds2,decay_start_time_ch2, seconds2 - decay_start_time_ch2 decay_waiting_ch2 = False else: decay_waiting_ch2 = False print",
"= (fields[7] >= \"00\") fe_0 = (fields[2] >= \"00\") fe_1 = (fields[4] >=",
"last_pulse = 0. decay_start_time_ch0 = 0. decay_waiting_ch0 = False decay_start_time_ch1 = 0. decay_waiting_ch1",
"- decay_start_time_ch3),) else: decay_waiting_ch3 = False else: print \"no decay in channel 3\"",
"previous_fe_1 = fe_1 previous_re_2 = re_2 previous_fe_2 = fe_2 previous_re_3 = re_3 previous_fe_3",
"> 20: print \"No decay\",seconds1,decay_start_time_ch1,seconds1 - decay_start_time_ch1 decay_waiting_ch1 = False else: decay_waiting_ch1 =",
"and dpch1==1: wait_fe1 = True time_ch1 = seconds1 if time_ch1 - seconds1 >",
"event can be described by more than one line! if last_onepps != onepps_count:",
"fe_0 and wait_fe0: print \"Pulse ch0\",seconds0,line decay_start_time_ch0 = 0 decay_start_time_ch0 = seconds0 decay_waiting_ch0",
"and (fields[1] == \"00\" or fields[5] == \"00\")): continue if (ch0==1 and ch3==1",
"continue if (ch0==1 and ch1==1 and ch2==1 and (fields[1] == \"00\" and fields[3]",
"Ignore malformed lines if len(fields) != 16: continue #Ignore everything that is not",
"- decay_start_time_ch0),) else: decay_waiting_ch0 = False else: print \"no decay in channel 0\"",
"decay_start_time_ch1 = 0 decay_start_time_ch1 = seconds1 decay_waiting_ch1 = True pulse_ch1 = True wait_fe1",
"wait_fe3 = True seconds3 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq time_ch3 = seconds3 if time_ch3",
"= int(fields[9],16) re_0 = (fields[1] >= \"00\") re_1 = (fields[3] >= \"00\") re_2",
"and (fields[3] == \"00\" and fields[5] == \"00\" or fields[7] == \"00\")): continue",
"and seconds3 - decay_start_time_ch3 > 20: print \"No decay\",seconds3,decay_start_time_ch3,seconds3 - decay_start_time_ch3 decay_waiting_ch3 =",
"False if re_2 and dpch2==1: wait_fe2 = True time_ch2 = seconds2 if time_ch2",
"= float(sys.argv[8]) #0 or 1 dpch3 = float(sys.argv[9]) #0 or 1 muon =",
"and dpch2==1: wait_fe2 = True time_ch2 = seconds2 if time_ch2 - seconds2 >",
"onepps_count - last_onepps) prevlast_onepps = last_onepps last_onepps = onepps_count switched_onepps = True time",
"if time_ch2 - seconds2 > 50e-9: wait_f2 = False if fe_2 and wait_fe2:",
"line in f: fields_next = line.rstrip(\"\\n\").split(\" \") #define the different options if 0==0:",
"and (seconds2 != decay_start_time_ch3): if decay_waiting_ch2: if re_2: wait_fe2 = True time_ch2 =",
"%10.8f microseconds\"%(1e6*(seconds0 - decay_start_time_ch0),) if decay_waiting_ch0: if re_0: wait_fe0 = True time_ch0 =",
"False time_ch0 = 0. wait_fe1 = False time_ch1 = 0. wait_fe2 = False",
"True wait_fe1 = False else: decay_waiting_ch1 = False if re_2 and dpch2==1: wait_fe2",
"decay in channel 3\" if re_0 and dpch0==1: wait_fe0 = True time_ch0 =",
"print \"Wrong event order\",seconds0,line # continue last_seconds = seconds0 print \"seconds0:\",seconds0 print \"decay_start_time_ch0:",
"False if fe_2 and wait_fe2: print \"Pulse ch2\",seconds2,line decay_start_time_ch2 = seconds2 decay_waiting_ch2 =",
"False if trigger_count < last_triggercount and not switched_onepps: print \"Correcting trigger count rollover:\",seconds0,line",
"float(sys.argv[2]) #0 or 1 ch1 = float(sys.argv[3]) #0 or 1 ch2 = float(sys.argv[4])",
"and seconds0 - decay_start_time_ch0 > 20: print \"No decay\",seconds0,decay_start_time_ch0, seconds0 - decay_start_time_ch0 decay_waiting_ch0",
"False else: print \"no decay in channel 1\" if dpch2==1 and (seconds2 !=",
"within range def time_to_seconds(time, correction): ''' Convert hhmmss,xxx string int seconds since day",
"== \"00\")): continue if (ch1==1 and ch2==1 and ch3==1 and (fields[3] == \"00\"",
"print \"Decay ch0 %10.8f microseconds\"%(1e6*(seconds0 - decay_start_time_ch0),) if decay_waiting_ch0: if re_0: wait_fe0 =",
"== \"00\")): continue if (ch0==1 and ch1==1 and ch2==1 and (fields[1] == \"00\"",
"- seconds1 > 50e-9: wait_f1 = False if fe_1 and wait_fe1: print \"Pulse",
"decay_waiting_ch2 = False else: decay_waiting_ch2 = False print \"Decay ch2 %10.8f ch2microseconds\"%((seconds2 -",
"#seconds3=decay_start_time_ch3 if fields_next[1]>= \"80\": previous_fe_0 = fe_0 previous_re_1 = re_1 previous_fe_1 = fe_1",
"= False print \"Decay ch0 %10.8f ch0microseconds\"%((seconds0 - decay_start_time_ch0),) else: decay_waiting_ch0 = False",
"files: ch0 = float(sys.argv[2]) #0 or 1 ch1 = float(sys.argv[3]) #0 or 1",
"fields[5] == \"00\" or fields[7] == \"00\")): continue #check for double pulse if",
"= int(t[0:2])*3600+int(t[2:4])*60+int(t[4:6]) evt_time = secs_since_day_start + int(tfields[1])/1000.0+int(correction)/1000.0 return round(evt_time) #filename = sys.argv[1] f",
"3 # Current or last 1PPS rate not within range def time_to_seconds(time, correction):",
"False time_ch3 = 0. muon_start = 0. nmuons = 0 last_pulse = 0.",
"last_seconds = 0. last_time = 0. last_triggercount = 0 switched_onepps = False last_onepps",
"(ch3==1 and fields[7] == \"00\"): continue if (ch0==1 and ch1==1 and (fields[1] ==",
"fields[1] >= \"80\": for line in f: fields_next = line.rstrip(\"\\n\").split(\" \") #define the",
"0. wait_fe1 = False time_ch1 = 0. wait_fe2 = False time_ch2 = 0.",
"fields[5] == \"00\")): continue if (ch0==1 and ch3==1 and (fields[1] == \"00\" or",
"- onepps_count)/freq seconds3 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq if time == last_time and switched_onepps:",
"%10.8f ch2microseconds\"%((seconds2 - decay_start_time_ch2),) else: decay_waiting_ch2 = False else: print \"no decay in",
"and (seconds0 != decay_start_time_ch3) : print \"dpch0\" print \"Decay ch0 %10.8f microseconds\"%(1e6*(seconds0 -",
"False if fe_0 and wait_fe0: print \"Pulse ch0\",seconds0,line decay_start_time_ch0 = 0 decay_start_time_ch0 =",
"5 BIT7 = 1 << 7 # For DAQ status BIT0 = 1",
"if fe_1 and wait_fe1: #print \"Pulse ch1\",seconds1,line decay_start_time_ch1 = 0 decay_start_time_ch1 = seconds1",
"and (fields[1] == \"00\" or fields[7] == \"00\")): continue if (ch1==1 and ch2==1",
"and (fields[3] == \"00\" or fields[7] == \"00\")): continue if (ch2==1 and ch3==1",
"time switched_onepps = False if trigger_count < last_triggercount and not switched_onepps: print \"Correcting",
"ch3 = float(sys.argv[5]) #0 or 1 dpch0 = float(sys.argv[6]) #0 or 1 dpch1",
"time_ch1 = seconds1 if time_ch1 - seconds1 > 50e-9: wait_f1 = False if",
"= False #single channel++++++++++++++++++++++++++++ if dpch0==1 and (seconds0 !=decay_start_time_ch1 ) and (seconds0 !=",
"DAQ status BIT0 = 1 # 1 PPS interrupt pending BIT1 = 1",
"and fields[7] == \"00\"): continue if (ch0==1 and ch1==1 and (fields[1] == \"00\"",
"> 50e-9: wait_f2 = False decay_waiting_ch2 = False if fe_2 and wait_fe2: print",
"last_onepps) else: freq = float(0xFFFFFFFF + onepps_count - last_onepps) prevlast_onepps = last_onepps last_onepps",
"seconds3 += int(0xFFFFFFFF)/freq else: last_triggercount = trigger_count #if last_seconds > seconds0: # print",
"= seconds0 if time_ch0 - seconds0 > 50e-9: wait_f0 = False decay_waiting_ch0 =",
"pulse if fields[1] >= \"80\": for line in f: fields_next = line.rstrip(\"\\n\").split(\" \")",
"seconds0 if time_ch0 - seconds0 > 50e-9: wait_f0 = False decay_waiting_ch0 = False",
"print \"decay_start_time_ch3: \",decay_start_time_ch3 print \"difference: \",seconds0-decay_start_time_ch0 pulse_ch0 = False pulse_ch1 = False pulse_ch2",
"2 # GPS data possible corrupted BIT3 = 1 << 3 # Current",
"< last_triggercount and not switched_onepps: print \"Correcting trigger count rollover:\",seconds0,line seconds0 += int(0xFFFFFFFF)/freq",
"- seconds2 > 50e-9: wait_f2 = False decay_waiting_ch2 = False if fe_2 and",
"= float(0xFFFFFFFF + onepps_count - last_onepps) prevlast_onepps = last_onepps last_onepps = onepps_count switched_onepps",
"20: print \"No decay\",seconds0,decay_start_time_ch0, seconds0 - decay_start_time_ch0 decay_waiting_ch0 = False else: decay_waiting_ch0 =",
"decay_start_time_ch2 = 0. decay_waiting_ch2 = False decay_start_time_ch3 = 0. decay_waiting_ch3 = False last_seconds",
"f: fields = line.rstrip(\"\\n\").split(\" \") #print \"fields: \",fields #print \"line: \",line # Ignore",
"seconds2 - decay_start_time_ch2 decay_waiting_ch2 = False else: decay_waiting_ch2 = False print \"Decay ch2",
"order\",seconds0,line # continue last_seconds = seconds0 print \"seconds0:\",seconds0 print \"decay_start_time_ch0: \",decay_start_time_ch0 print \"decay_start_time_ch1:",
"dpch2==1: wait_fe2 = True time_ch2 = seconds2 if time_ch2 - seconds2 > 50e-9:",
"seconds1 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds2 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds3 = time_to_seconds(time,correction)+(trigger_count",
"\"difference: \",seconds0-decay_start_time_ch0 pulse_ch0 = False pulse_ch1 = False pulse_ch2 = False pulse_ch3 =",
"= False if fe_3 and wait_fe3: print \"Pulse ch3\",seconds3,line pulse_ch3 = True wait_fe3",
"or fields[3] == \"00\")): continue if (ch0==1 and ch2==1 and (fields[1] == \"00\"",
"if filename.endswith('.gz'): f = gzip.open(filename) else: f = open(sys.argv[1]) for line in f:",
"decay_start_time_ch3) : if decay_waiting_ch1: if re_1: wait_fe1 = True time_ch1 = seconds1 if",
"if fe_3 and wait_fe3: print \"Pulse ch3\",seconds3,line pulse_ch3 = True wait_fe3 = False",
"= True wait_fe1 = False else: decay_waiting_ch1 = False if re_2 and dpch2==1:",
"#check for double pulse if fields[1] >= \"80\": for line in f: fields_next",
">= \"00\") #check the single pulse for channel if (ch0==1 and fields[1] ==",
"\"00\") re_1 = (fields[3] >= \"00\") re_2 = (fields[5] >= \"00\") re_3 =",
"25 MHz last_onepps = 0 last_muon = 0 wait_fe0 = False time_ch0 =",
"if decay_waiting_ch2: if re_2: wait_fe2 = True time_ch2 = seconds2 if time_ch2 -",
"decay_waiting_ch2 = False if fe_2 and wait_fe2: print \"Pulse ch2\",seconds2,line pulse_ch2 = True",
"time_ch0 = 0. wait_fe1 = False time_ch1 = 0. wait_fe2 = False time_ch2",
"- decay_start_time_ch0 > 20: print \"No decay\",seconds0,decay_start_time_ch0, seconds0 - decay_start_time_ch0 decay_waiting_ch0 = False",
"True time_ch1 = seconds1 if time_ch1 - seconds1 > 50e-9: wait_f1 = False",
"False else: decay_waiting_ch0 = False if re_1 and dpch1==1: wait_fe1 = True time_ch1",
"0 decay_start_time_ch1 = seconds1 decay_waiting_ch1 = True pulse_ch1 = True wait_fe1 = False",
"decay_start_time_ch0 = 0. decay_waiting_ch0 = False decay_start_time_ch1 = 0. decay_waiting_ch1 = False decay_start_time_ch2",
"and (fields[5] == \"00\" or fields[7] == \"00\")): continue if (ch0==1 and ch1==1",
"ch2 = float(sys.argv[4]) #0 or 1 ch3 = float(sys.argv[5]) #0 or 1 dpch0",
"BIT0_4 = 31 BIT5 = 1 << 5 BIT7 = 1 << 7",
"- onepps_count)/freq seconds1 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds2 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds3",
"print \"No decay\",seconds3,decay_start_time_ch3,seconds3 - decay_start_time_ch3 decay_waiting_ch3 = False else: decay_waiting_ch3 = False print",
">= \"80\": for line in f: fields_next = line.rstrip(\"\\n\").split(\" \") #define the different",
"False pulse_ch2 = False pulse_ch3 = False #single channel++++++++++++++++++++++++++++ if dpch0==1 and (seconds0",
"fields_next = line.rstrip(\"\\n\").split(\" \") #define the different options if 0==0: #current analysis for",
"= False if re_2 and dpch2==1: wait_fe2 = True time_ch2 = seconds2 if",
"!= decay_start_time_ch0) and (seconds3 != decay_start_time_ch1) and (seconds3 != decay_start_time_ch2) : if decay_waiting_ch3:",
"else: decay_waiting_ch3 = False #seconds0=decay_start_time_ch0 #seconds1=decay_start_time_ch1 #seconds2=decay_start_time_ch2 #seconds3=decay_start_time_ch3 if fields_next[1]>= \"80\": previous_fe_0 =",
"0. decay_waiting_ch2 = False decay_start_time_ch3 = 0. decay_waiting_ch3 = False last_seconds = 0.",
"= False if fe_2 and wait_fe2: print \"Pulse ch2\",seconds2,line pulse_ch2 = True wait_fe2",
"decay_waiting_ch2 = False print \"Decay ch2 %10.8f ch2microseconds\"%((seconds2 - decay_start_time_ch2),) else: decay_waiting_ch2 =",
"<< 1 # Trigger interrupt pending BIT2 = 1 << 2 # GPS",
"<< 2 # GPS data possible corrupted BIT3 = 1 << 3 #",
"False if re_1 and dpch1==1: wait_fe1 = True time_ch1 = seconds1 if time_ch1",
"\"dpch0\" print \"Decay ch0 %10.8f microseconds\"%(1e6*(seconds0 - decay_start_time_ch0),) if decay_waiting_ch0: if re_0: wait_fe0",
"= False else: decay_waiting_ch3 = False print \"Decay ch3 %10.8f ch3microseconds\"%((seconds3 - decay_start_time_ch3),)",
"+= int(0xFFFFFFFF)/freq else: last_triggercount = trigger_count #if last_seconds > seconds0: # print \"Wrong",
"seconds0 print \"seconds0:\",seconds0 print \"decay_start_time_ch0: \",decay_start_time_ch0 print \"decay_start_time_ch1: \",decay_start_time_ch1 print \"decay_start_time_ch2: \",decay_start_time_ch2 print",
"and (fields[1] == \"00\" and fields[3] == \"00\" or fields[5] == \"00\")): continue",
"or 1 dpch2 = float(sys.argv[8]) #0 or 1 dpch3 = float(sys.argv[9]) #0 or",
"options if 0==0: #current analysis for one event. Note, that one event can",
"decay_start_time_ch0 = 0 decay_start_time_ch0 = seconds0 decay_waiting_ch0 = True pulse_ch0 = True wait_fe0",
"fields[3] == \"00\")): continue if (ch0==1 and ch2==1 and (fields[1] == \"00\" or",
"coincident level 0!! #Order of scintillators is irrelevent! ##################################################### files = sys.argv[1:] BIT0_4",
"= (fields[3] >= \"00\") re_2 = (fields[5] >= \"00\") re_3 = (fields[7] >=",
"time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds3 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq else: last_time = time switched_onepps",
"\"00\") fe_0 = (fields[2] >= \"00\") fe_1 = (fields[4] >= \"00\") fe_2 =",
"\"00\"): continue if (ch3==1 and fields[7] == \"00\"): continue if (ch0==1 and ch1==1",
"and (seconds1 != decay_start_time_ch0) and (seconds1 != decay_start_time_ch2) and (seconds1 != decay_start_time_ch3) :",
"decay_waiting_ch0: if re_0: wait_fe0 = True time_ch0 = seconds0 if time_ch0 - seconds0",
"previous_re_2 = re_2 previous_fe_2 = fe_2 previous_re_3 = re_3 previous_fe_3 = fe_3 break",
"ch2\",seconds2,line pulse_ch2 = True wait_fe2 = False if decay_waiting_ch2 and seconds2 - decay_start_time_ch2",
"ch1microseconds\"%((seconds1 - decay_start_time_ch1),) else: decay_waiting_ch1 = False else: print \"no decay in channel",
"> 50e-9: wait_f1 = False if fe_1 and wait_fe1: print \"Pulse ch1\",seconds1,line pulse_ch1",
"= False pulse_ch2 = False pulse_ch3 = False #single channel++++++++++++++++++++++++++++ if dpch0==1 and",
"last_onepps: freq = float(onepps_count - last_onepps) else: freq = float(0xFFFFFFFF + onepps_count -",
"= True time_ch3 = seconds3 if time_ch3 - seconds3 > 50e-9: wait_f3 =",
"decay_waiting_ch1 and seconds1 - decay_start_time_ch1 > 20: print \"No decay\",seconds1,decay_start_time_ch1,seconds1 - decay_start_time_ch1 decay_waiting_ch1",
"time_ch1 = 0. wait_fe2 = False time_ch2 = 0. wait_fe3 = False time_ch3",
"if dpch0==1 and (seconds0 !=decay_start_time_ch1 ) and (seconds0 != decay_start_time_ch2) and (seconds0 !=",
"= False time_ch3 = 0. muon_start = 0. nmuons = 0 last_pulse =",
"!= 8: continue try: int(fields[len(fields)-1]) except ValueError: continue trigger_count = int(fields[0],16) onepps_count =",
"wait_fe2: print \"Pulse ch2\",seconds2,line decay_start_time_ch2 = seconds2 decay_waiting_ch2 = True pulse_ch2 = True",
"seconds1 if time_ch1 - seconds1 > 50e-9: wait_f1 = False if fe_1 and",
"50e-9: wait_f0 = False decay_waiting_ch0 = False if fe_0 and wait_fe0: print \"Pulse",
"decay_start_time_ch1 = 0. decay_waiting_ch1 = False decay_start_time_ch2 = 0. decay_waiting_ch2 = False decay_start_time_ch3",
"prevlast_onepps = last_onepps last_onepps = onepps_count switched_onepps = True time = fields[10] correction",
"= 0. nmuons = 0 last_pulse = 0. decay_start_time_ch0 = 0. decay_waiting_ch0 =",
"onepps_count)/freq if time == last_time and switched_onepps: print \"Correcting delayed onepps switch:\",seconds0,line seconds0",
"= 0 counter = 0.0 if filename.endswith('.gz'): f = gzip.open(filename) else: f =",
"decay_waiting_ch2 = True pulse_ch2 = True wait_fe2 = False else: decay_waiting_ch2 = False",
"if fe_2 and wait_fe2: print \"Pulse ch2\",seconds2,line decay_start_time_ch2 = seconds2 decay_waiting_ch2 = True",
"onepps_count)/freq time_ch3 = seconds3 if time_ch3 - seconds3 > 50e-9: wait_f3 = False",
"if fe_2 and wait_fe2: print \"Pulse ch2\",seconds2,line pulse_ch2 = True wait_fe2 = False",
"sys.argv[1] f = open(sys.argv[1]) for filename in files: ch0 = float(sys.argv[2]) #0 or",
"= seconds3 if time_ch3 - seconds3 > 50e-9: wait_f3 = False if fe_3",
"continue trigger_count = int(fields[0],16) onepps_count = int(fields[9],16) re_0 = (fields[1] >= \"00\") re_1",
"and (seconds3 != decay_start_time_ch1) and (seconds3 != decay_start_time_ch2) : if decay_waiting_ch3: if re_3:",
"fe_2 = (fields[6] >= \"00\") fe_3 = (fields[8] >= \"00\") #check the single",
"= False decay_start_time_ch3 = 0. decay_waiting_ch3 = False last_seconds = 0. last_time =",
"= float(sys.argv[6]) #0 or 1 dpch1 = float(sys.argv[7]) #0 or 1 dpch2 =",
"continue last_seconds = seconds0 print \"seconds0:\",seconds0 print \"decay_start_time_ch0: \",decay_start_time_ch0 print \"decay_start_time_ch1: \",decay_start_time_ch1 print",
"fe_2 and wait_fe2: print \"Pulse ch2\",seconds2,line pulse_ch2 = True wait_fe2 = False if",
"== \"00\")): continue if (ch2==1 and ch3==1 and (fields[5] == \"00\" or fields[7]",
"decay_start_time_ch2),) else: decay_waiting_ch2 = False else: print \"no decay in channel 2\" if",
"dpch2 = float(sys.argv[8]) #0 or 1 dpch3 = float(sys.argv[9]) #0 or 1 muon",
"1 dpch3 = float(sys.argv[9]) #0 or 1 muon = {0:False,1:False,2:False,\"Time\":0.} freq = 25e6",
"nmuons = 0 last_pulse = 0. decay_start_time_ch0 = 0. decay_waiting_ch0 = False decay_start_time_ch1",
"else: decay_waiting_ch2 = False if re_3 and dpch3==1: wait_fe3 = True time_ch3 =",
"and fields[1] == \"00\"): continue if (ch1==1 and fields[3] == \"00\"): continue if",
"print \"Decay ch1 %10.8f ch1microseconds\"%((seconds1 - decay_start_time_ch1),) else: decay_waiting_ch1 = False else: print",
"fields[1] == \"00\"): continue if (ch1==1 and fields[3] == \"00\"): continue if (ch2==1",
"decay_waiting_ch3 = False last_seconds = 0. last_time = 0. last_triggercount = 0 switched_onepps",
"decay_waiting_ch2: if re_2: wait_fe2 = True time_ch2 = seconds2 if time_ch2 - seconds2",
"decay_start_time_ch0) and (seconds1 != decay_start_time_ch2) and (seconds1 != decay_start_time_ch3) : if decay_waiting_ch1: if",
"microseconds\"%(1e6*(seconds0 - decay_start_time_ch0),) if decay_waiting_ch0: if re_0: wait_fe0 = True time_ch0 = seconds0",
"seconds2 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds3 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq if time ==",
"ch0 %10.8f microseconds\"%(1e6*(seconds0 - decay_start_time_ch0),) if decay_waiting_ch0: if re_0: wait_fe0 = True time_ch0",
"re_2 and dpch2==1: wait_fe2 = True time_ch2 = seconds2 if time_ch2 - seconds2",
"= 1 << 3 # Current or last 1PPS rate not within range",
"1 << 5 BIT7 = 1 << 7 # For DAQ status BIT0",
"trigger_count #if last_seconds > seconds0: # print \"Wrong event order\",seconds0,line # continue last_seconds",
"continue if (ch2==1 and ch3==1 and (fields[5] == \"00\" or fields[7] == \"00\")):",
"BIT1 = 1 << 1 # Trigger interrupt pending BIT2 = 1 <<",
"\"00\" or fields[3] == \"00\")): continue if (ch0==1 and ch2==1 and (fields[1] ==",
"muon = {0:False,1:False,2:False,\"Time\":0.} freq = 25e6 # 25 MHz last_onepps = 0 last_muon",
"!= decay_start_time_ch3): if decay_waiting_ch2: if re_2: wait_fe2 = True time_ch2 = seconds2 if",
"last_muon = 0 wait_fe0 = False time_ch0 = 0. wait_fe1 = False time_ch1",
"= open(sys.argv[1]) for filename in files: ch0 = float(sys.argv[2]) #0 or 1 ch1",
"= time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds2 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds3 = time_to_seconds(time,correction)+(trigger_count -",
"= False last_onepps = 0 onepps_count = 0 counter = 0.0 if filename.endswith('.gz'):",
"= 0. decay_start_time_ch0 = 0. decay_waiting_ch0 = False decay_start_time_ch1 = 0. decay_waiting_ch1 =",
"wait_fe1 = False if decay_waiting_ch1 and seconds1 - decay_start_time_ch1 > 20: print \"No",
"decay_waiting_ch0 = False decay_start_time_ch1 = 0. decay_waiting_ch1 = False decay_start_time_ch2 = 0. decay_waiting_ch2",
"decay_waiting_ch1 = False decay_start_time_ch2 = 0. decay_waiting_ch2 = False decay_start_time_ch3 = 0. decay_waiting_ch3",
"f = open(sys.argv[1]) for line in f: fields = line.rstrip(\"\\n\").split(\" \") #print \"fields:",
"ch2\",seconds3,line decay_start_time_ch3 = seconds3 decay_waiting_ch3 = True pulse_ch3 = True wait_fe3 = False",
"decay\",seconds0,decay_start_time_ch0, seconds0 - decay_start_time_ch0 decay_waiting_ch0 = False else: decay_waiting_ch0 = False print \"Decay",
"print \"No decay\",seconds2,decay_start_time_ch2, seconds2 - decay_start_time_ch2 decay_waiting_ch2 = False else: decay_waiting_ch2 = False",
"wait_fe2 = False time_ch2 = 0. wait_fe3 = False time_ch3 = 0. muon_start",
"- decay_start_time_ch1),) else: decay_waiting_ch1 = False else: print \"no decay in channel 1\"",
"{0:False,1:False,2:False,\"Time\":0.} freq = 25e6 # 25 MHz last_onepps = 0 last_muon = 0",
"\"Pulse ch2\",seconds2,line pulse_ch2 = True wait_fe2 = False if decay_waiting_ch2 and seconds2 -",
"== \"00\" and fields[5] == \"00\" or fields[7] == \"00\")): continue #check for",
"False else: decay_waiting_ch2 = False if re_3 and dpch3==1: wait_fe3 = True time_ch3",
"= True pulse_ch0 = True wait_fe0 = False else: decay_waiting_ch0 = False if",
"last 1PPS rate not within range def time_to_seconds(time, correction): ''' Convert hhmmss,xxx string",
"decay_start_time_ch2) and (seconds0 != decay_start_time_ch3) : print \"dpch0\" print \"Decay ch0 %10.8f microseconds\"%(1e6*(seconds0",
"(fields[3] >= \"00\") re_2 = (fields[5] >= \"00\") re_3 = (fields[7] >= \"00\")",
"= float(onepps_count - last_onepps) else: freq = float(0xFFFFFFFF + onepps_count - last_onepps) prevlast_onepps",
"if decay_waiting_ch0: if re_0: wait_fe0 = True time_ch0 = seconds0 if time_ch0 -",
"one line! if last_onepps != onepps_count: if onepps_count > last_onepps: freq = float(onepps_count",
"and fields[3] == \"00\"): continue if (ch2==1 and fields[5] == \"00\"): continue if",
"switch:\",seconds0,line seconds0 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds1 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds2 =",
"time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds1 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds2 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq",
"= 0. wait_fe3 = False time_ch3 = 0. muon_start = 0. nmuons =",
"line! if last_onepps != onepps_count: if onepps_count > last_onepps: freq = float(onepps_count -",
"seconds2 if time_ch2 - seconds2 > 50e-9: wait_f2 = False if fe_2 and",
"print \"Pulse ch2\",seconds2,line pulse_ch2 = True wait_fe2 = False if decay_waiting_ch2 and seconds2",
"0. nmuons = 0 last_pulse = 0. decay_start_time_ch0 = 0. decay_waiting_ch0 = False",
"last_time = 0. last_triggercount = 0 switched_onepps = False last_onepps = 0 onepps_count",
"seconds2 decay_waiting_ch2 = True pulse_ch2 = True wait_fe2 = False else: decay_waiting_ch2 =",
"25e6 # 25 MHz last_onepps = 0 last_muon = 0 wait_fe0 = False",
"= False if fe_1 and wait_fe1: print \"Pulse ch1\",seconds1,line pulse_ch1 = True wait_fe1",
"except ValueError: continue trigger_count = int(fields[0],16) onepps_count = int(fields[9],16) re_0 = (fields[1] >=",
"0 onepps_count = 0 counter = 0.0 if filename.endswith('.gz'): f = gzip.open(filename) else:",
"\"Pulse ch2\",seconds2,line decay_start_time_ch2 = seconds2 decay_waiting_ch2 = True pulse_ch2 = True wait_fe2 =",
"= False if fe_2 and wait_fe2: print \"Pulse ch2\",seconds2,line decay_start_time_ch2 = seconds2 decay_waiting_ch2",
"correction): ''' Convert hhmmss,xxx string int seconds since day start ''' # print",
"if (ch0==1 and ch1==1 and (fields[1] == \"00\" or fields[3] == \"00\")): continue",
"= seconds2 if time_ch2 - seconds2 > 50e-9: wait_f2 = False if fe_2",
"(fields[1] == \"00\" and fields[3] == \"00\" or fields[5] == \"00\")): continue if",
"seconds3 > 50e-9: wait_f3 = False if fe_3 and wait_fe3: print \"Pulse ch2\",seconds3,line",
"\",decay_start_time_ch1 print \"decay_start_time_ch2: \",decay_start_time_ch2 print \"decay_start_time_ch3: \",decay_start_time_ch3 print \"difference: \",seconds0-decay_start_time_ch0 pulse_ch0 = False",
"decay_start_time_ch1 decay_waiting_ch1 = False else: decay_waiting_ch1 = False print \"Decay ch1 %10.8f ch1microseconds\"%((seconds1",
"seconds2 - decay_start_time_ch2 > 20: print \"No decay\",seconds2,decay_start_time_ch2, seconds2 - decay_start_time_ch2 decay_waiting_ch2 =",
"event order\",seconds0,line # continue last_seconds = seconds0 print \"seconds0:\",seconds0 print \"decay_start_time_ch0: \",decay_start_time_ch0 print",
"decay_waiting_ch2 = False decay_start_time_ch3 = 0. decay_waiting_ch3 = False last_seconds = 0. last_time",
"= time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds1 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds2 = time_to_seconds(time,correction)+(trigger_count -",
"if time_ch0 - seconds0 > 50e-9: wait_f0 = False decay_waiting_ch0 = False if",
"decay_start_time_ch2 decay_waiting_ch2 = False else: decay_waiting_ch2 = False print \"Decay ch2 %10.8f ch2microseconds\"%((seconds2",
"= (fields[1] >= \"00\") re_1 = (fields[3] >= \"00\") re_2 = (fields[5] >=",
"\"No decay\",seconds1,decay_start_time_ch1,seconds1 - decay_start_time_ch1 decay_waiting_ch1 = False else: decay_waiting_ch1 = False print \"Decay",
"is coincident level 0!! #Order of scintillators is irrelevent! ##################################################### files = sys.argv[1:]",
"f = open(sys.argv[1]) for filename in files: ch0 = float(sys.argv[2]) #0 or 1",
"True pulse_ch0 = True wait_fe0 = False else: decay_waiting_ch0 = False if re_1",
"re_1 = (fields[3] >= \"00\") re_2 = (fields[5] >= \"00\") re_3 = (fields[7]",
"python import sys import gzip ##################################################### #This is coincident level 0!! #Order of",
"wait_fe0 = True time_ch0 = seconds0 if time_ch0 - seconds0 > 50e-9: wait_f0",
"onepps_count)/freq seconds2 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds3 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq if time",
"int seconds since day start ''' # print time,correction tfields = time.split(\".\") t",
"\",decay_start_time_ch0 print \"decay_start_time_ch1: \",decay_start_time_ch1 print \"decay_start_time_ch2: \",decay_start_time_ch2 print \"decay_start_time_ch3: \",decay_start_time_ch3 print \"difference: \",seconds0-decay_start_time_ch0",
"7 # For DAQ status BIT0 = 1 # 1 PPS interrupt pending",
"last_onepps = 0 last_muon = 0 wait_fe0 = False time_ch0 = 0. wait_fe1",
"False if decay_waiting_ch1 and seconds1 - decay_start_time_ch1 > 20: print \"No decay\",seconds1,decay_start_time_ch1,seconds1 -",
"pulse_ch0 = False pulse_ch1 = False pulse_ch2 = False pulse_ch3 = False #single",
"can be described by more than one line! if last_onepps != onepps_count: if",
"range def time_to_seconds(time, correction): ''' Convert hhmmss,xxx string int seconds since day start",
"or fields[5] == \"00\")): continue if (ch0==1 and ch3==1 and (fields[1] == \"00\"",
"prevlast_onepps)/freq else: last_time = time switched_onepps = False if trigger_count < last_triggercount and",
">= \"00\") fe_2 = (fields[6] >= \"00\") fe_3 = (fields[8] >= \"00\") #check",
"pending BIT1 = 1 << 1 # Trigger interrupt pending BIT2 = 1",
"decay_waiting_ch0 = True pulse_ch0 = True wait_fe0 = False else: decay_waiting_ch0 = False",
"time_ch0 = seconds0 if time_ch0 - seconds0 > 50e-9: wait_f0 = False decay_waiting_ch0",
"if fe_0 and wait_fe0: print \"Pulse ch0\",seconds0,line pulse_ch0 = True wait_fe0 = False",
"#single channel++++++++++++++++++++++++++++ if dpch0==1 and (seconds0 !=decay_start_time_ch1 ) and (seconds0 != decay_start_time_ch2) and",
"For DAQ status BIT0 = 1 # 1 PPS interrupt pending BIT1 =",
"50e-9: wait_f3 = False if fe_3 and wait_fe3: print \"Pulse ch3\",seconds3,line pulse_ch3 =",
"freq = float(0xFFFFFFFF + onepps_count - last_onepps) prevlast_onepps = last_onepps last_onepps = onepps_count",
"\"Wrong event order\",seconds0,line # continue last_seconds = seconds0 print \"seconds0:\",seconds0 print \"decay_start_time_ch0: \",decay_start_time_ch0",
"#0 or 1 dpch2 = float(sys.argv[8]) #0 or 1 dpch3 = float(sys.argv[9]) #0",
"last_onepps last_onepps = onepps_count switched_onepps = True time = fields[10] correction = fields[15]",
"\"Pulse ch2\",seconds3,line decay_start_time_ch3 = seconds3 decay_waiting_ch3 = True pulse_ch3 = True wait_fe3 =",
"wait_fe0: print \"Pulse ch0\",seconds0,line decay_start_time_ch0 = 0 decay_start_time_ch0 = seconds0 decay_waiting_ch0 = True",
"print \"no decay in channel 3\" if re_0 and dpch0==1: wait_fe0 = True",
"time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds3 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq if time == last_time and",
"time_ch2 - seconds2 > 50e-9: wait_f2 = False decay_waiting_ch2 = False if fe_2",
"re_3 and dpch3==1: wait_fe3 = True time_ch3 = seconds3 if time_ch3 - seconds3",
"and ch1==1 and (fields[1] == \"00\" or fields[3] == \"00\")): continue if (ch0==1",
"= float(sys.argv[3]) #0 or 1 ch2 = float(sys.argv[4]) #0 or 1 ch3 =",
"and (fields[1] == \"00\" or fields[3] == \"00\")): continue if (ch0==1 and ch2==1",
"fe_0 previous_re_1 = re_1 previous_fe_1 = fe_1 previous_re_2 = re_2 previous_fe_2 = fe_2",
"different options if 0==0: #current analysis for one event. Note, that one event",
"- decay_start_time_ch0),) if decay_waiting_ch0: if re_0: wait_fe0 = True time_ch0 = seconds0 if",
"else: decay_waiting_ch2 = False print \"Decay ch2 %10.8f ch2microseconds\"%((seconds2 - decay_start_time_ch2),) else: decay_waiting_ch2",
"seconds0 if time_ch0 - seconds0 > 50e-9: wait_f0 = False if fe_0 and",
"if decay_waiting_ch1 and seconds1 - decay_start_time_ch1 > 20: print \"No decay\",seconds1,decay_start_time_ch1,seconds1 - decay_start_time_ch1",
"(fields[1] == \"00\" or fields[3] == \"00\")): continue if (ch0==1 and ch2==1 and",
"1 dpch1 = float(sys.argv[7]) #0 or 1 dpch2 = float(sys.argv[8]) #0 or 1",
"== last_time and switched_onepps: print \"Correcting delayed onepps switch:\",seconds0,line seconds0 = time_to_seconds(time,correction)+(trigger_count -",
"1 << 2 # GPS data possible corrupted BIT3 = 1 << 3",
"= (fields[4] >= \"00\") fe_2 = (fields[6] >= \"00\") fe_3 = (fields[8] >=",
"ch1 %10.8f ch1microseconds\"%((seconds1 - decay_start_time_ch1),) else: decay_waiting_ch1 = False else: print \"no decay",
"= True wait_fe3 = False if decay_waiting_ch3 and seconds3 - decay_start_time_ch3 > 20:",
"(seconds2 != decay_start_time_ch3): if decay_waiting_ch2: if re_2: wait_fe2 = True time_ch2 = seconds2",
"%10.8f ch1microseconds\"%((seconds1 - decay_start_time_ch1),) else: decay_waiting_ch1 = False else: print \"no decay in",
"if fields[1] >= \"80\": for line in f: fields_next = line.rstrip(\"\\n\").split(\" \") #define",
"in f: fields = line.rstrip(\"\\n\").split(\" \") #print \"fields: \",fields #print \"line: \",line #",
"\",decay_start_time_ch3 print \"difference: \",seconds0-decay_start_time_ch0 pulse_ch0 = False pulse_ch1 = False pulse_ch2 = False",
"\"Decay ch1 %10.8f ch1microseconds\"%((seconds1 - decay_start_time_ch1),) else: decay_waiting_ch1 = False else: print \"no",
"switched_onepps = True time = fields[10] correction = fields[15] seconds0 = time_to_seconds(time,correction)+(trigger_count -",
"or 1 dpch1 = float(sys.argv[7]) #0 or 1 dpch2 = float(sys.argv[8]) #0 or",
">= \"00\") fe_1 = (fields[4] >= \"00\") fe_2 = (fields[6] >= \"00\") fe_3",
"(ch1==1 and ch2==1 and ch3==1 and (fields[3] == \"00\" and fields[5] == \"00\"",
"= time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds3 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq else: last_time = time",
"len(fields[0]) != 8: continue try: int(fields[len(fields)-1]) except ValueError: continue trigger_count = int(fields[0],16) onepps_count",
"0 wait_fe0 = False time_ch0 = 0. wait_fe1 = False time_ch1 = 0.",
"\"00\")): continue if (ch0==1 and ch3==1 and (fields[1] == \"00\" or fields[7] ==",
"last_time and switched_onepps: print \"Correcting delayed onepps switch:\",seconds0,line seconds0 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq",
"= 1 # 1 PPS interrupt pending BIT1 = 1 << 1 #",
"- decay_start_time_ch2 decay_waiting_ch2 = False else: decay_waiting_ch2 = False print \"Decay ch2 %10.8f",
"ch1\",seconds1,line pulse_ch1 = True wait_fe1 = False if decay_waiting_ch1 and seconds1 - decay_start_time_ch1",
"False last_onepps = 0 onepps_count = 0 counter = 0.0 if filename.endswith('.gz'): f",
"\"00\"): continue if (ch0==1 and ch1==1 and (fields[1] == \"00\" or fields[3] ==",
"# 1 PPS interrupt pending BIT1 = 1 << 1 # Trigger interrupt",
"#0 or 1 dpch3 = float(sys.argv[9]) #0 or 1 muon = {0:False,1:False,2:False,\"Time\":0.} freq",
"= time switched_onepps = False if trigger_count < last_triggercount and not switched_onepps: print",
"= False if fe_1 and wait_fe1: #print \"Pulse ch1\",seconds1,line decay_start_time_ch1 = 0 decay_start_time_ch1",
"corrupted BIT3 = 1 << 3 # Current or last 1PPS rate not",
"= trigger_count #if last_seconds > seconds0: # print \"Wrong event order\",seconds0,line # continue",
"time_ch2 = 0. wait_fe3 = False time_ch3 = 0. muon_start = 0. nmuons",
">= \"00\") re_2 = (fields[5] >= \"00\") re_3 = (fields[7] >= \"00\") fe_0",
"dpch3==1 and (seconds3 != decay_start_time_ch0) and (seconds3 != decay_start_time_ch1) and (seconds3 != decay_start_time_ch2)",
"interrupt pending BIT1 = 1 << 1 # Trigger interrupt pending BIT2 =",
"!= decay_start_time_ch1) and (seconds3 != decay_start_time_ch2) : if decay_waiting_ch3: if re_3: wait_fe3 =",
"(fields[3] == \"00\" or fields[7] == \"00\")): continue if (ch2==1 and ch3==1 and",
"ch3 %10.8f ch3microseconds\"%((seconds3 - decay_start_time_ch3),) else: decay_waiting_ch3 = False else: print \"no decay",
"= open(sys.argv[1]) for line in f: fields = line.rstrip(\"\\n\").split(\" \") #print \"fields: \",fields",
"and fields[5] == \"00\"): continue if (ch3==1 and fields[7] == \"00\"): continue if",
"fields[5] == \"00\"): continue if (ch3==1 and fields[7] == \"00\"): continue if (ch0==1",
"continue if (ch0==1 and ch1==1 and (fields[1] == \"00\" or fields[3] == \"00\")):",
"= 0 wait_fe0 = False time_ch0 = 0. wait_fe1 = False time_ch1 =",
"= False time_ch2 = 0. wait_fe3 = False time_ch3 = 0. muon_start =",
"seconds0 += int(0xFFFFFFFF)/freq seconds1 += int(0xFFFFFFFF)/freq seconds2 += int(0xFFFFFFFF)/freq seconds3 += int(0xFFFFFFFF)/freq else:",
"= (fields[2] >= \"00\") fe_1 = (fields[4] >= \"00\") fe_2 = (fields[6] >=",
"if (ch0==1 and ch2==1 and (fields[1] == \"00\" or fields[5] == \"00\")): continue",
"decay_waiting_ch0 = False else: decay_waiting_ch0 = False print \"Decay ch0 %10.8f ch0microseconds\"%((seconds0 -",
"fe_0 and wait_fe0: print \"Pulse ch0\",seconds0,line pulse_ch0 = True wait_fe0 = False if",
"wait_fe2: print \"Pulse ch2\",seconds2,line pulse_ch2 = True wait_fe2 = False if decay_waiting_ch2 and",
"interrupt pending BIT2 = 1 << 2 # GPS data possible corrupted BIT3",
"#0 or 1 ch1 = float(sys.argv[3]) #0 or 1 ch2 = float(sys.argv[4]) #0",
"\"00\"): continue if (ch2==1 and fields[5] == \"00\"): continue if (ch3==1 and fields[7]",
"\"Pulse ch0\",seconds0,line decay_start_time_ch0 = 0 decay_start_time_ch0 = seconds0 decay_waiting_ch0 = True pulse_ch0 =",
"seconds3 decay_waiting_ch3 = True pulse_ch3 = True wait_fe3 = False else: decay_waiting_ch3 =",
"seconds3 - decay_start_time_ch3 > 20: print \"No decay\",seconds3,decay_start_time_ch3,seconds3 - decay_start_time_ch3 decay_waiting_ch3 = False",
"decay_waiting_ch2 = False else: print \"no decay in channel 2\" if dpch3==1 and",
"print \"Pulse ch1\",seconds1,line pulse_ch1 = True wait_fe1 = False if decay_waiting_ch1 and seconds1",
"delayed onepps switch:\",seconds0,line seconds0 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds1 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq",
"False if fe_0 and wait_fe0: print \"Pulse ch0\",seconds0,line pulse_ch0 = True wait_fe0 =",
"int(0xFFFFFFFF)/freq else: last_triggercount = trigger_count #if last_seconds > seconds0: # print \"Wrong event",
"> 50e-9: wait_f3 = False if fe_3 and wait_fe3: print \"Pulse ch2\",seconds3,line decay_start_time_ch3",
"data if len(fields[0]) != 8: continue try: int(fields[len(fields)-1]) except ValueError: continue trigger_count =",
"channel if (ch0==1 and fields[1] == \"00\"): continue if (ch1==1 and fields[3] ==",
"ch3==1 and (fields[5] == \"00\" or fields[7] == \"00\")): continue if (ch0==1 and",
"if dpch3==1 and (seconds3 != decay_start_time_ch0) and (seconds3 != decay_start_time_ch1) and (seconds3 !=",
"= re_1 previous_fe_1 = fe_1 previous_re_2 = re_2 previous_fe_2 = fe_2 previous_re_3 =",
"if len(fields[0]) != 8: continue try: int(fields[len(fields)-1]) except ValueError: continue trigger_count = int(fields[0],16)",
"float(sys.argv[3]) #0 or 1 ch2 = float(sys.argv[4]) #0 or 1 ch3 = float(sys.argv[5])",
"and fields[5] == \"00\" or fields[7] == \"00\")): continue #check for double pulse",
"time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq else: last_time = time switched_onepps = False if trigger_count <",
"decay_start_time_ch3): if decay_waiting_ch2: if re_2: wait_fe2 = True time_ch2 = seconds2 if time_ch2",
"= False else: decay_waiting_ch0 = False print \"Decay ch0 %10.8f ch0microseconds\"%((seconds0 - decay_start_time_ch0),)",
"= (fields[6] >= \"00\") fe_3 = (fields[8] >= \"00\") #check the single pulse",
"ch0\",seconds0,line pulse_ch0 = True wait_fe0 = False if decay_waiting_ch0 and seconds0 - decay_start_time_ch0",
"False if fe_3 and wait_fe3: print \"Pulse ch2\",seconds3,line decay_start_time_ch3 = seconds3 decay_waiting_ch3 =",
"\",seconds0-decay_start_time_ch0 pulse_ch0 = False pulse_ch1 = False pulse_ch2 = False pulse_ch3 = False",
"else: print \"no decay in channel 0\" if dpch1==1 and (seconds1 != decay_start_time_ch0)",
"# continue last_seconds = seconds0 print \"seconds0:\",seconds0 print \"decay_start_time_ch0: \",decay_start_time_ch0 print \"decay_start_time_ch1: \",decay_start_time_ch1",
"= 0 onepps_count = 0 counter = 0.0 if filename.endswith('.gz'): f = gzip.open(filename)",
"wait_f3 = False if fe_3 and wait_fe3: print \"Pulse ch3\",seconds3,line pulse_ch3 = True",
"#0 or 1 ch2 = float(sys.argv[4]) #0 or 1 ch3 = float(sys.argv[5]) #0",
"= 0. wait_fe1 = False time_ch1 = 0. wait_fe2 = False time_ch2 =",
"== \"00\")): continue if (ch1==1 and ch2==1 and (fields[3] == \"00\" or fields[5]",
"time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq if time == last_time and switched_onepps: print \"Correcting delayed onepps",
"0==0: #current analysis for one event. Note, that one event can be described",
"\"no decay in channel 3\" if re_0 and dpch0==1: wait_fe0 = True time_ch0",
"wait_fe3 = False time_ch3 = 0. muon_start = 0. nmuons = 0 last_pulse",
"= 1 << 2 # GPS data possible corrupted BIT3 = 1 <<",
"continue if (ch1==1 and ch2==1 and ch3==1 and (fields[3] == \"00\" and fields[5]",
"seconds0 > 50e-9: wait_f0 = False decay_waiting_ch0 = False if fe_0 and wait_fe0:",
"last_onepps = 0 onepps_count = 0 counter = 0.0 if filename.endswith('.gz'): f =",
"seconds2 > 50e-9: wait_f2 = False if fe_2 and wait_fe2: print \"Pulse ch2\",seconds2,line",
"decay_waiting_ch3 = False #seconds0=decay_start_time_ch0 #seconds1=decay_start_time_ch1 #seconds2=decay_start_time_ch2 #seconds3=decay_start_time_ch3 if fields_next[1]>= \"80\": previous_fe_0 = fe_0",
"and dpch3==1: wait_fe3 = True time_ch3 = seconds3 if time_ch3 - seconds3 >",
"if last_onepps != onepps_count: if onepps_count > last_onepps: freq = float(onepps_count - last_onepps)",
"- decay_start_time_ch1 decay_waiting_ch1 = False else: decay_waiting_ch1 = False print \"Decay ch1 %10.8f",
"= False else: print \"no decay in channel 2\" if dpch3==1 and (seconds3",
"1 ch3 = float(sys.argv[5]) #0 or 1 dpch0 = float(sys.argv[6]) #0 or 1",
"dpch0 = float(sys.argv[6]) #0 or 1 dpch1 = float(sys.argv[7]) #0 or 1 dpch2",
"= 1 << 7 # For DAQ status BIT0 = 1 # 1",
"seconds0 > 50e-9: wait_f0 = False if fe_0 and wait_fe0: print \"Pulse ch0\",seconds0,line",
"continue if (ch0==1 and ch2==1 and (fields[1] == \"00\" or fields[5] == \"00\")):",
"= 0.0 if filename.endswith('.gz'): f = gzip.open(filename) else: f = open(sys.argv[1]) for line",
"ch3microseconds\"%((seconds3 - decay_start_time_ch3),) else: decay_waiting_ch3 = False else: print \"no decay in channel",
"or fields[7] == \"00\")): continue #check for double pulse if fields[1] >= \"80\":",
"open(sys.argv[1]) for line in f: fields = line.rstrip(\"\\n\").split(\" \") #print \"fields: \",fields #print",
"else: decay_waiting_ch0 = False print \"Decay ch0 %10.8f ch0microseconds\"%((seconds0 - decay_start_time_ch0),) else: decay_waiting_ch0",
"onepps_count)/freq seconds1 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds2 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq seconds3 =",
"time,correction tfields = time.split(\".\") t = tfields[0] secs_since_day_start = int(t[0:2])*3600+int(t[2:4])*60+int(t[4:6]) evt_time = secs_since_day_start",
"re_3: wait_fe3 = True seconds3 = time_to_seconds(time,correction)+(trigger_count - onepps_count)/freq time_ch3 = seconds3 if",
"freq = 25e6 # 25 MHz last_onepps = 0 last_muon = 0 wait_fe0",
"if decay_waiting_ch2 and seconds2 - decay_start_time_ch2 > 20: print \"No decay\",seconds2,decay_start_time_ch2, seconds2 -",
"decay_start_time_ch3) : print \"dpch0\" print \"Decay ch0 %10.8f microseconds\"%(1e6*(seconds0 - decay_start_time_ch0),) if decay_waiting_ch0:",
"or 1 muon = {0:False,1:False,2:False,\"Time\":0.} freq = 25e6 # 25 MHz last_onepps =",
"= False print \"Decay ch2 %10.8f ch2microseconds\"%((seconds2 - decay_start_time_ch2),) else: decay_waiting_ch2 = False",
"print \"Pulse ch2\",seconds3,line decay_start_time_ch3 = seconds3 decay_waiting_ch3 = True pulse_ch3 = True wait_fe3",
"True wait_fe1 = False if decay_waiting_ch1 and seconds1 - decay_start_time_ch1 > 20: print",
"BIT5 = 1 << 5 BIT7 = 1 << 7 # For DAQ",
"else: print \"no decay in channel 2\" if dpch3==1 and (seconds3 != decay_start_time_ch0)",
"time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds2 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq seconds3 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq",
"ch2\",seconds2,line decay_start_time_ch2 = seconds2 decay_waiting_ch2 = True pulse_ch2 = True wait_fe2 = False",
"print \"no decay in channel 0\" if dpch1==1 and (seconds1 != decay_start_time_ch0) and",
"prevlast_onepps)/freq seconds3 = time_to_seconds(time,correction)+(trigger_count - prevlast_onepps)/freq else: last_time = time switched_onepps = False",
"dpch1==1 and (seconds1 != decay_start_time_ch0) and (seconds1 != decay_start_time_ch2) and (seconds1 != decay_start_time_ch3)",
"== \"00\" or fields[7] == \"00\")): continue if (ch1==1 and ch2==1 and (fields[3]",
"decay_start_time_ch2) : if decay_waiting_ch3: if re_3: wait_fe3 = True seconds3 = time_to_seconds(time,correction)+(trigger_count -",
"> 50e-9: wait_f0 = False if fe_0 and wait_fe0: print \"Pulse ch0\",seconds0,line decay_start_time_ch0",
"else: last_triggercount = trigger_count #if last_seconds > seconds0: # print \"Wrong event order\",seconds0,line",
"wait_fe3 = True time_ch3 = seconds3 if time_ch3 - seconds3 > 50e-9: wait_f3",
"== \"00\"): continue if (ch3==1 and fields[7] == \"00\"): continue if (ch0==1 and",
"= last_onepps last_onepps = onepps_count switched_onepps = True time = fields[10] correction ="
] |
[
"default = Label(\"//tools/bzldoc:bzl2yaml\"), doc = \"The path to the bzl2yaml tool itself.\", ),",
"), \"out\": attr.output( mandatory = True, doc = \"YAML file to generate.\", ),",
"\"src\": attr.label( allow_files = [\".bzl\"], doc = \"BZL file to parse.\", ), \"out\":",
"% name], visibility = [\"//visibility:public\"], ) mdfmt_filter( name = \"%s-md-gen\" % name, out",
"f.short_path) args.add(\"--output\", ctx.outputs.out.path) ctx.actions.run( inputs = ctx.files.src, outputs = [ctx.outputs.out], executable = ctx.executable.bzl2yaml_tool,",
"header files can be found. attrs = { \"src\": attr.label( allow_files = [\".bzl\"],",
"= [\"%s.yaml\" % name], visibility = [\"//visibility:public\"], ) mdfmt_filter( name = \"%s-md-gen\" %",
"[\"//visibility:public\"], ) mdfmt_filter( name = \"%s-md-gen\" % name, out = name + \".md\",",
"\"bzl2yaml_tool\": attr.label( executable = True, cfg = \"exec\", allow_files = True, default =",
"= ctx.files.src, outputs = [ctx.outputs.out], executable = ctx.executable.bzl2yaml_tool, arguments = [args], ) bzl2yaml",
"= { \"src\": attr.label( allow_files = [\".bzl\"], doc = \"BZL file to parse.\",",
"rule( doc = \"\"\" Runs bzl2yaml to parse a bzl file into data.",
"codegen( name = \"%s-md-unformatted-gen\" % name, outs = [name + \".md.unformatted\"], srcs =",
"bzl2yaml = rule( doc = \"\"\" Runs bzl2yaml to parse a bzl file",
"ctx.files.src: args.add(\"--input\", f) args.add(\"--short_path\", f.short_path) args.add(\"--output\", ctx.outputs.out.path) ctx.actions.run( inputs = ctx.files.src, outputs =",
"that header files can be found. attrs = { \"src\": attr.label( allow_files =",
"bzl2yaml tool itself.\", ), }, ) def bzldoc(name, src): \"\"\"Convert a BZL file",
"\"YAML file to generate.\", ), \"bzl2yaml_tool\": attr.label( executable = True, cfg = \"exec\",",
"ctx.executable.bzl2yaml_tool, arguments = [args], ) bzl2yaml = rule( doc = \"\"\" Runs bzl2yaml",
"bzl2yaml( name = \"%s-bzl2yaml\" % name, src = src, out = \"%s.yaml\" %",
"f in ctx.files.src: args.add(\"--input\", f) args.add(\"--short_path\", f.short_path) args.add(\"--output\", ctx.outputs.out.path) ctx.actions.run( inputs = ctx.files.src,",
"name, out = name + \".md\", src = name + \".md.unformatted\", visibility =",
"}, ) def bzldoc(name, src): \"\"\"Convert a BZL file into documentation.\"\"\" bzl2yaml( name",
"parse a bzl file into data. \"\"\", implementation = _bzl2yaml_impl, output_to_genfiles = True,",
"\"\"\"Convert a BZL file into documentation.\"\"\" bzl2yaml( name = \"%s-bzl2yaml\" % name, src",
"outs = [name + \".md.unformatted\"], srcs = [\"@enkit//tools/bzldoc:md.template\"], data = [\"%s.yaml\" % name],",
"bzl file into data. \"\"\", implementation = _bzl2yaml_impl, output_to_genfiles = True, # so",
"files can be found. attrs = { \"src\": attr.label( allow_files = [\".bzl\"], doc",
"\"%s-md-unformatted-gen\" % name, outs = [name + \".md.unformatted\"], srcs = [\"@enkit//tools/bzldoc:md.template\"], data =",
"file to parse.\", ), \"out\": attr.output( mandatory = True, doc = \"YAML file",
"= \"%s-md-unformatted-gen\" % name, outs = [name + \".md.unformatted\"], srcs = [\"@enkit//tools/bzldoc:md.template\"], data",
"src, out = \"%s.yaml\" % name, ) codegen( name = \"%s-md-unformatted-gen\" % name,",
"[ctx.outputs.out], executable = ctx.executable.bzl2yaml_tool, arguments = [args], ) bzl2yaml = rule( doc =",
"name = \"%s-bzl2yaml\" % name, src = src, out = \"%s.yaml\" % name,",
"+ \".md.unformatted\"], srcs = [\"@enkit//tools/bzldoc:md.template\"], data = [\"%s.yaml\" % name], visibility = [\"//visibility:public\"],",
"attr.label( allow_files = [\".bzl\"], doc = \"BZL file to parse.\", ), \"out\": attr.output(",
"True, cfg = \"exec\", allow_files = True, default = Label(\"//tools/bzldoc:bzl2yaml\"), doc = \"The",
"ctx.actions.args() for f in ctx.files.src: args.add(\"--input\", f) args.add(\"--short_path\", f.short_path) args.add(\"--output\", ctx.outputs.out.path) ctx.actions.run( inputs",
"be found. attrs = { \"src\": attr.label( allow_files = [\".bzl\"], doc = \"BZL",
"implementation = _bzl2yaml_impl, output_to_genfiles = True, # so that header files can be",
"Label(\"//tools/bzldoc:bzl2yaml\"), doc = \"The path to the bzl2yaml tool itself.\", ), }, )",
"[name + \".md.unformatted\"], srcs = [\"@enkit//tools/bzldoc:md.template\"], data = [\"%s.yaml\" % name], visibility =",
"f) args.add(\"--short_path\", f.short_path) args.add(\"--output\", ctx.outputs.out.path) ctx.actions.run( inputs = ctx.files.src, outputs = [ctx.outputs.out], executable",
"into data. \"\"\", implementation = _bzl2yaml_impl, output_to_genfiles = True, # so that header",
"data. \"\"\", implementation = _bzl2yaml_impl, output_to_genfiles = True, # so that header files",
"= True, doc = \"YAML file to generate.\", ), \"bzl2yaml_tool\": attr.label( executable =",
"\"exec\", allow_files = True, default = Label(\"//tools/bzldoc:bzl2yaml\"), doc = \"The path to the",
"mdfmt_filter( name = \"%s-md-gen\" % name, out = name + \".md\", src =",
"arguments = [args], ) bzl2yaml = rule( doc = \"\"\" Runs bzl2yaml to",
"\"BZL file to parse.\", ), \"out\": attr.output( mandatory = True, doc = \"YAML",
"cfg = \"exec\", allow_files = True, default = Label(\"//tools/bzldoc:bzl2yaml\"), doc = \"The path",
"name, src = src, out = \"%s.yaml\" % name, ) codegen( name =",
"args.add(\"--output\", ctx.outputs.out.path) ctx.actions.run( inputs = ctx.files.src, outputs = [ctx.outputs.out], executable = ctx.executable.bzl2yaml_tool, arguments",
"name, ) codegen( name = \"%s-md-unformatted-gen\" % name, outs = [name + \".md.unformatted\"],",
"outputs = [ctx.outputs.out], executable = ctx.executable.bzl2yaml_tool, arguments = [args], ) bzl2yaml = rule(",
"path to the bzl2yaml tool itself.\", ), }, ) def bzldoc(name, src): \"\"\"Convert",
"\"mdfmt_filter\") def _bzl2yaml_impl(ctx): args = ctx.actions.args() for f in ctx.files.src: args.add(\"--input\", f) args.add(\"--short_path\",",
"= True, # so that header files can be found. attrs = {",
"True, default = Label(\"//tools/bzldoc:bzl2yaml\"), doc = \"The path to the bzl2yaml tool itself.\",",
"for f in ctx.files.src: args.add(\"--input\", f) args.add(\"--short_path\", f.short_path) args.add(\"--output\", ctx.outputs.out.path) ctx.actions.run( inputs =",
") codegen( name = \"%s-md-unformatted-gen\" % name, outs = [name + \".md.unformatted\"], srcs",
"<filename>tools/bzldoc/bzldoc.bzl<gh_stars>0 load(\"//tools/codegen:codegen.bzl\", \"codegen\") load(\"//tools/mdfmt:mdfmt.bzl\", \"mdfmt_filter\") def _bzl2yaml_impl(ctx): args = ctx.actions.args() for f in",
"into documentation.\"\"\" bzl2yaml( name = \"%s-bzl2yaml\" % name, src = src, out =",
"= _bzl2yaml_impl, output_to_genfiles = True, # so that header files can be found.",
"= \"exec\", allow_files = True, default = Label(\"//tools/bzldoc:bzl2yaml\"), doc = \"The path to",
"[\".bzl\"], doc = \"BZL file to parse.\", ), \"out\": attr.output( mandatory = True,",
"out = name + \".md\", src = name + \".md.unformatted\", visibility = [\"//visibility:public\"],",
"name = \"%s-md-unformatted-gen\" % name, outs = [name + \".md.unformatted\"], srcs = [\"@enkit//tools/bzldoc:md.template\"],",
"= True, default = Label(\"//tools/bzldoc:bzl2yaml\"), doc = \"The path to the bzl2yaml tool",
"file to generate.\", ), \"bzl2yaml_tool\": attr.label( executable = True, cfg = \"exec\", allow_files",
"ctx.outputs.out.path) ctx.actions.run( inputs = ctx.files.src, outputs = [ctx.outputs.out], executable = ctx.executable.bzl2yaml_tool, arguments =",
"executable = True, cfg = \"exec\", allow_files = True, default = Label(\"//tools/bzldoc:bzl2yaml\"), doc",
"% name, ) codegen( name = \"%s-md-unformatted-gen\" % name, outs = [name +",
"args.add(\"--short_path\", f.short_path) args.add(\"--output\", ctx.outputs.out.path) ctx.actions.run( inputs = ctx.files.src, outputs = [ctx.outputs.out], executable =",
"itself.\", ), }, ) def bzldoc(name, src): \"\"\"Convert a BZL file into documentation.\"\"\"",
"name = \"%s-md-gen\" % name, out = name + \".md\", src = name",
"src = src, out = \"%s.yaml\" % name, ) codegen( name = \"%s-md-unformatted-gen\"",
"in ctx.files.src: args.add(\"--input\", f) args.add(\"--short_path\", f.short_path) args.add(\"--output\", ctx.outputs.out.path) ctx.actions.run( inputs = ctx.files.src, outputs",
"doc = \"The path to the bzl2yaml tool itself.\", ), }, ) def",
") def bzldoc(name, src): \"\"\"Convert a BZL file into documentation.\"\"\" bzl2yaml( name =",
"mandatory = True, doc = \"YAML file to generate.\", ), \"bzl2yaml_tool\": attr.label( executable",
"args = ctx.actions.args() for f in ctx.files.src: args.add(\"--input\", f) args.add(\"--short_path\", f.short_path) args.add(\"--output\", ctx.outputs.out.path)",
"\"%s.yaml\" % name, ) codegen( name = \"%s-md-unformatted-gen\" % name, outs = [name",
"\"%s-md-gen\" % name, out = name + \".md\", src = name + \".md.unformatted\",",
"= [name + \".md.unformatted\"], srcs = [\"@enkit//tools/bzldoc:md.template\"], data = [\"%s.yaml\" % name], visibility",
"file into documentation.\"\"\" bzl2yaml( name = \"%s-bzl2yaml\" % name, src = src, out",
"attrs = { \"src\": attr.label( allow_files = [\".bzl\"], doc = \"BZL file to",
"load(\"//tools/mdfmt:mdfmt.bzl\", \"mdfmt_filter\") def _bzl2yaml_impl(ctx): args = ctx.actions.args() for f in ctx.files.src: args.add(\"--input\", f)",
"attr.label( executable = True, cfg = \"exec\", allow_files = True, default = Label(\"//tools/bzldoc:bzl2yaml\"),",
"args.add(\"--input\", f) args.add(\"--short_path\", f.short_path) args.add(\"--output\", ctx.outputs.out.path) ctx.actions.run( inputs = ctx.files.src, outputs = [ctx.outputs.out],",
"found. attrs = { \"src\": attr.label( allow_files = [\".bzl\"], doc = \"BZL file",
"= \"BZL file to parse.\", ), \"out\": attr.output( mandatory = True, doc =",
"= ctx.executable.bzl2yaml_tool, arguments = [args], ) bzl2yaml = rule( doc = \"\"\" Runs",
"= \"The path to the bzl2yaml tool itself.\", ), }, ) def bzldoc(name,",
"generate.\", ), \"bzl2yaml_tool\": attr.label( executable = True, cfg = \"exec\", allow_files = True,",
"\".md.unformatted\"], srcs = [\"@enkit//tools/bzldoc:md.template\"], data = [\"%s.yaml\" % name], visibility = [\"//visibility:public\"], )",
"= \"%s-md-gen\" % name, out = name + \".md\", src = name +",
"doc = \"BZL file to parse.\", ), \"out\": attr.output( mandatory = True, doc",
"a bzl file into data. \"\"\", implementation = _bzl2yaml_impl, output_to_genfiles = True, #",
"= src, out = \"%s.yaml\" % name, ) codegen( name = \"%s-md-unformatted-gen\" %",
") mdfmt_filter( name = \"%s-md-gen\" % name, out = name + \".md\", src",
"to parse a bzl file into data. \"\"\", implementation = _bzl2yaml_impl, output_to_genfiles =",
"doc = \"YAML file to generate.\", ), \"bzl2yaml_tool\": attr.label( executable = True, cfg",
"out = \"%s.yaml\" % name, ) codegen( name = \"%s-md-unformatted-gen\" % name, outs",
"_bzl2yaml_impl(ctx): args = ctx.actions.args() for f in ctx.files.src: args.add(\"--input\", f) args.add(\"--short_path\", f.short_path) args.add(\"--output\",",
"the bzl2yaml tool itself.\", ), }, ) def bzldoc(name, src): \"\"\"Convert a BZL",
"= [ctx.outputs.out], executable = ctx.executable.bzl2yaml_tool, arguments = [args], ) bzl2yaml = rule( doc",
"ctx.files.src, outputs = [ctx.outputs.out], executable = ctx.executable.bzl2yaml_tool, arguments = [args], ) bzl2yaml =",
"bzl2yaml to parse a bzl file into data. \"\"\", implementation = _bzl2yaml_impl, output_to_genfiles",
"[\"@enkit//tools/bzldoc:md.template\"], data = [\"%s.yaml\" % name], visibility = [\"//visibility:public\"], ) mdfmt_filter( name =",
"attr.output( mandatory = True, doc = \"YAML file to generate.\", ), \"bzl2yaml_tool\": attr.label(",
"to the bzl2yaml tool itself.\", ), }, ) def bzldoc(name, src): \"\"\"Convert a",
"data = [\"%s.yaml\" % name], visibility = [\"//visibility:public\"], ) mdfmt_filter( name = \"%s-md-gen\"",
"\"codegen\") load(\"//tools/mdfmt:mdfmt.bzl\", \"mdfmt_filter\") def _bzl2yaml_impl(ctx): args = ctx.actions.args() for f in ctx.files.src: args.add(\"--input\",",
"), \"bzl2yaml_tool\": attr.label( executable = True, cfg = \"exec\", allow_files = True, default",
"executable = ctx.executable.bzl2yaml_tool, arguments = [args], ) bzl2yaml = rule( doc = \"\"\"",
"parse.\", ), \"out\": attr.output( mandatory = True, doc = \"YAML file to generate.\",",
"a BZL file into documentation.\"\"\" bzl2yaml( name = \"%s-bzl2yaml\" % name, src =",
"allow_files = [\".bzl\"], doc = \"BZL file to parse.\", ), \"out\": attr.output( mandatory",
"src): \"\"\"Convert a BZL file into documentation.\"\"\" bzl2yaml( name = \"%s-bzl2yaml\" % name,",
"Runs bzl2yaml to parse a bzl file into data. \"\"\", implementation = _bzl2yaml_impl,",
"inputs = ctx.files.src, outputs = [ctx.outputs.out], executable = ctx.executable.bzl2yaml_tool, arguments = [args], )",
"\"out\": attr.output( mandatory = True, doc = \"YAML file to generate.\", ), \"bzl2yaml_tool\":",
"documentation.\"\"\" bzl2yaml( name = \"%s-bzl2yaml\" % name, src = src, out = \"%s.yaml\"",
") bzl2yaml = rule( doc = \"\"\" Runs bzl2yaml to parse a bzl",
"# so that header files can be found. attrs = { \"src\": attr.label(",
"= [\"@enkit//tools/bzldoc:md.template\"], data = [\"%s.yaml\" % name], visibility = [\"//visibility:public\"], ) mdfmt_filter( name",
"\"The path to the bzl2yaml tool itself.\", ), }, ) def bzldoc(name, src):",
"= ctx.actions.args() for f in ctx.files.src: args.add(\"--input\", f) args.add(\"--short_path\", f.short_path) args.add(\"--output\", ctx.outputs.out.path) ctx.actions.run(",
"srcs = [\"@enkit//tools/bzldoc:md.template\"], data = [\"%s.yaml\" % name], visibility = [\"//visibility:public\"], ) mdfmt_filter(",
"= [args], ) bzl2yaml = rule( doc = \"\"\" Runs bzl2yaml to parse",
"% name, src = src, out = \"%s.yaml\" % name, ) codegen( name",
"load(\"//tools/codegen:codegen.bzl\", \"codegen\") load(\"//tools/mdfmt:mdfmt.bzl\", \"mdfmt_filter\") def _bzl2yaml_impl(ctx): args = ctx.actions.args() for f in ctx.files.src:",
"= [\"//visibility:public\"], ) mdfmt_filter( name = \"%s-md-gen\" % name, out = name +",
"[args], ) bzl2yaml = rule( doc = \"\"\" Runs bzl2yaml to parse a",
"= True, cfg = \"exec\", allow_files = True, default = Label(\"//tools/bzldoc:bzl2yaml\"), doc =",
"_bzl2yaml_impl, output_to_genfiles = True, # so that header files can be found. attrs",
"so that header files can be found. attrs = { \"src\": attr.label( allow_files",
"\"\"\" Runs bzl2yaml to parse a bzl file into data. \"\"\", implementation =",
"allow_files = True, default = Label(\"//tools/bzldoc:bzl2yaml\"), doc = \"The path to the bzl2yaml",
"= Label(\"//tools/bzldoc:bzl2yaml\"), doc = \"The path to the bzl2yaml tool itself.\", ), },",
"tool itself.\", ), }, ) def bzldoc(name, src): \"\"\"Convert a BZL file into",
"\"%s-bzl2yaml\" % name, src = src, out = \"%s.yaml\" % name, ) codegen(",
"def _bzl2yaml_impl(ctx): args = ctx.actions.args() for f in ctx.files.src: args.add(\"--input\", f) args.add(\"--short_path\", f.short_path)",
"True, doc = \"YAML file to generate.\", ), \"bzl2yaml_tool\": attr.label( executable = True,",
"[\"%s.yaml\" % name], visibility = [\"//visibility:public\"], ) mdfmt_filter( name = \"%s-md-gen\" % name,",
"def bzldoc(name, src): \"\"\"Convert a BZL file into documentation.\"\"\" bzl2yaml( name = \"%s-bzl2yaml\"",
"), }, ) def bzldoc(name, src): \"\"\"Convert a BZL file into documentation.\"\"\" bzl2yaml(",
"to generate.\", ), \"bzl2yaml_tool\": attr.label( executable = True, cfg = \"exec\", allow_files =",
"BZL file into documentation.\"\"\" bzl2yaml( name = \"%s-bzl2yaml\" % name, src = src,",
"to parse.\", ), \"out\": attr.output( mandatory = True, doc = \"YAML file to",
"visibility = [\"//visibility:public\"], ) mdfmt_filter( name = \"%s-md-gen\" % name, out = name",
"= [\".bzl\"], doc = \"BZL file to parse.\", ), \"out\": attr.output( mandatory =",
"bzldoc(name, src): \"\"\"Convert a BZL file into documentation.\"\"\" bzl2yaml( name = \"%s-bzl2yaml\" %",
"True, # so that header files can be found. attrs = { \"src\":",
"= \"\"\" Runs bzl2yaml to parse a bzl file into data. \"\"\", implementation",
"\"\"\", implementation = _bzl2yaml_impl, output_to_genfiles = True, # so that header files can",
"% name, out = name + \".md\", src = name + \".md.unformatted\", visibility",
"doc = \"\"\" Runs bzl2yaml to parse a bzl file into data. \"\"\",",
"file into data. \"\"\", implementation = _bzl2yaml_impl, output_to_genfiles = True, # so that",
"= rule( doc = \"\"\" Runs bzl2yaml to parse a bzl file into",
"can be found. attrs = { \"src\": attr.label( allow_files = [\".bzl\"], doc =",
"output_to_genfiles = True, # so that header files can be found. attrs =",
"{ \"src\": attr.label( allow_files = [\".bzl\"], doc = \"BZL file to parse.\", ),",
"% name, outs = [name + \".md.unformatted\"], srcs = [\"@enkit//tools/bzldoc:md.template\"], data = [\"%s.yaml\"",
"= \"%s.yaml\" % name, ) codegen( name = \"%s-md-unformatted-gen\" % name, outs =",
"name], visibility = [\"//visibility:public\"], ) mdfmt_filter( name = \"%s-md-gen\" % name, out =",
"= \"YAML file to generate.\", ), \"bzl2yaml_tool\": attr.label( executable = True, cfg =",
"ctx.actions.run( inputs = ctx.files.src, outputs = [ctx.outputs.out], executable = ctx.executable.bzl2yaml_tool, arguments = [args],",
"= name + \".md\", src = name + \".md.unformatted\", visibility = [\"//visibility:public\"], )",
"= \"%s-bzl2yaml\" % name, src = src, out = \"%s.yaml\" % name, )",
"name, outs = [name + \".md.unformatted\"], srcs = [\"@enkit//tools/bzldoc:md.template\"], data = [\"%s.yaml\" %"
] |
[
"KerasModel def main(): logging.basicConfig( level=logging.INFO, format=\"%(asctime)s : \" + \"%(module)s (%(lineno)s) - %(levelname)s",
"wordsim.nn.utils import evaluate from wordsim.nn.data import create_datasets from wordsim.nn.model import KerasModel def main():",
"conf = ConfigParser(os.environ) conf.read(sys.argv[1]) vectorizers = get_models(conf) training_data, dev_data, test_data = create_datasets(conf) if",
"dev_data, test_data = create_datasets(conf) if conf.getboolean('main', 'train'): epochs = conf.getint('training', 'epochs') batch_size =",
"evaluate from wordsim.nn.data import create_datasets from wordsim.nn.model import KerasModel def main(): logging.basicConfig( level=logging.INFO,",
"input_size, input_dim = training_data.vectors.shape model = KerasModel(conf, input_dim, 1) # output is a",
"import KerasModel def main(): logging.basicConfig( level=logging.INFO, format=\"%(asctime)s : \" + \"%(module)s (%(lineno)s) -",
"import logging import os import sys from wordsim.models import get_models from wordsim.nn.utils import",
"wordsim.models import get_models from wordsim.nn.utils import evaluate from wordsim.nn.data import create_datasets from wordsim.nn.model",
"def main(): logging.basicConfig( level=logging.INFO, format=\"%(asctime)s : \" + \"%(module)s (%(lineno)s) - %(levelname)s -",
"'batch_size') training_data.vectorize(vectorizers) input_size, input_dim = training_data.vectors.shape model = KerasModel(conf, input_dim, 1) # output",
"training_data.vectors.shape model = KerasModel(conf, input_dim, 1) # output is a score model.train(training_data, epochs,",
"'epochs') batch_size = conf.getint('training', 'batch_size') training_data.vectorize(vectorizers) input_size, input_dim = training_data.vectors.shape model = KerasModel(conf,",
"logging import os import sys from wordsim.models import get_models from wordsim.nn.utils import evaluate",
"format=\"%(asctime)s : \" + \"%(module)s (%(lineno)s) - %(levelname)s - %(message)s\") conf = ConfigParser(os.environ)",
"training_data, dev_data, test_data = create_datasets(conf) if conf.getboolean('main', 'train'): epochs = conf.getint('training', 'epochs') batch_size",
"import evaluate from wordsim.nn.data import create_datasets from wordsim.nn.model import KerasModel def main(): logging.basicConfig(",
"= ConfigParser(os.environ) conf.read(sys.argv[1]) vectorizers = get_models(conf) training_data, dev_data, test_data = create_datasets(conf) if conf.getboolean('main',",
"batch_size = conf.getint('training', 'batch_size') training_data.vectorize(vectorizers) input_size, input_dim = training_data.vectors.shape model = KerasModel(conf, input_dim,",
"training_data.vectorize(vectorizers) input_size, input_dim = training_data.vectors.shape model = KerasModel(conf, input_dim, 1) # output is",
"= KerasModel(conf, input_dim, 1) # output is a score model.train(training_data, epochs, batch_size) model.save()",
"wordsim.nn.data import create_datasets from wordsim.nn.model import KerasModel def main(): logging.basicConfig( level=logging.INFO, format=\"%(asctime)s :",
"from ConfigParser import ConfigParser import logging import os import sys from wordsim.models import",
"'train'): epochs = conf.getint('training', 'epochs') batch_size = conf.getint('training', 'batch_size') training_data.vectorize(vectorizers) input_size, input_dim =",
"\"%(module)s (%(lineno)s) - %(levelname)s - %(message)s\") conf = ConfigParser(os.environ) conf.read(sys.argv[1]) vectorizers = get_models(conf)",
"\" + \"%(module)s (%(lineno)s) - %(levelname)s - %(message)s\") conf = ConfigParser(os.environ) conf.read(sys.argv[1]) vectorizers",
"= conf.getint('training', 'batch_size') training_data.vectorize(vectorizers) input_size, input_dim = training_data.vectors.shape model = KerasModel(conf, input_dim, 1)",
"get_models(conf) training_data, dev_data, test_data = create_datasets(conf) if conf.getboolean('main', 'train'): epochs = conf.getint('training', 'epochs')",
"from wordsim.nn.model import KerasModel def main(): logging.basicConfig( level=logging.INFO, format=\"%(asctime)s : \" + \"%(module)s",
"conf.getboolean('main', 'train'): epochs = conf.getint('training', 'epochs') batch_size = conf.getint('training', 'batch_size') training_data.vectorize(vectorizers) input_size, input_dim",
"epochs = conf.getint('training', 'epochs') batch_size = conf.getint('training', 'batch_size') training_data.vectorize(vectorizers) input_size, input_dim = training_data.vectors.shape",
"+ \"%(module)s (%(lineno)s) - %(levelname)s - %(message)s\") conf = ConfigParser(os.environ) conf.read(sys.argv[1]) vectorizers =",
"get_models from wordsim.nn.utils import evaluate from wordsim.nn.data import create_datasets from wordsim.nn.model import KerasModel",
"is a score model.train(training_data, epochs, batch_size) model.save() test_data.vectorize(vectorizers) evaluate(model, dev_data) if __name__ ==",
"import sys from wordsim.models import get_models from wordsim.nn.utils import evaluate from wordsim.nn.data import",
"os import sys from wordsim.models import get_models from wordsim.nn.utils import evaluate from wordsim.nn.data",
"sys from wordsim.models import get_models from wordsim.nn.utils import evaluate from wordsim.nn.data import create_datasets",
"conf.getint('training', 'epochs') batch_size = conf.getint('training', 'batch_size') training_data.vectorize(vectorizers) input_size, input_dim = training_data.vectors.shape model =",
"%(levelname)s - %(message)s\") conf = ConfigParser(os.environ) conf.read(sys.argv[1]) vectorizers = get_models(conf) training_data, dev_data, test_data",
"ConfigParser import ConfigParser import logging import os import sys from wordsim.models import get_models",
"import ConfigParser import logging import os import sys from wordsim.models import get_models from",
"- %(levelname)s - %(message)s\") conf = ConfigParser(os.environ) conf.read(sys.argv[1]) vectorizers = get_models(conf) training_data, dev_data,",
"create_datasets from wordsim.nn.model import KerasModel def main(): logging.basicConfig( level=logging.INFO, format=\"%(asctime)s : \" +",
"a score model.train(training_data, epochs, batch_size) model.save() test_data.vectorize(vectorizers) evaluate(model, dev_data) if __name__ == \"__main__\":",
"input_dim, 1) # output is a score model.train(training_data, epochs, batch_size) model.save() test_data.vectorize(vectorizers) evaluate(model,",
"score model.train(training_data, epochs, batch_size) model.save() test_data.vectorize(vectorizers) evaluate(model, dev_data) if __name__ == \"__main__\": main()",
"vectorizers = get_models(conf) training_data, dev_data, test_data = create_datasets(conf) if conf.getboolean('main', 'train'): epochs =",
"import get_models from wordsim.nn.utils import evaluate from wordsim.nn.data import create_datasets from wordsim.nn.model import",
"ConfigParser import logging import os import sys from wordsim.models import get_models from wordsim.nn.utils",
"= get_models(conf) training_data, dev_data, test_data = create_datasets(conf) if conf.getboolean('main', 'train'): epochs = conf.getint('training',",
"from wordsim.nn.data import create_datasets from wordsim.nn.model import KerasModel def main(): logging.basicConfig( level=logging.INFO, format=\"%(asctime)s",
"model = KerasModel(conf, input_dim, 1) # output is a score model.train(training_data, epochs, batch_size)",
"from wordsim.models import get_models from wordsim.nn.utils import evaluate from wordsim.nn.data import create_datasets from",
"wordsim.nn.model import KerasModel def main(): logging.basicConfig( level=logging.INFO, format=\"%(asctime)s : \" + \"%(module)s (%(lineno)s)",
"level=logging.INFO, format=\"%(asctime)s : \" + \"%(module)s (%(lineno)s) - %(levelname)s - %(message)s\") conf =",
"if conf.getboolean('main', 'train'): epochs = conf.getint('training', 'epochs') batch_size = conf.getint('training', 'batch_size') training_data.vectorize(vectorizers) input_size,",
"test_data = create_datasets(conf) if conf.getboolean('main', 'train'): epochs = conf.getint('training', 'epochs') batch_size = conf.getint('training',",
"= training_data.vectors.shape model = KerasModel(conf, input_dim, 1) # output is a score model.train(training_data,",
"# output is a score model.train(training_data, epochs, batch_size) model.save() test_data.vectorize(vectorizers) evaluate(model, dev_data) if",
"= create_datasets(conf) if conf.getboolean('main', 'train'): epochs = conf.getint('training', 'epochs') batch_size = conf.getint('training', 'batch_size')",
"import os import sys from wordsim.models import get_models from wordsim.nn.utils import evaluate from",
"= conf.getint('training', 'epochs') batch_size = conf.getint('training', 'batch_size') training_data.vectorize(vectorizers) input_size, input_dim = training_data.vectors.shape model",
"from wordsim.nn.utils import evaluate from wordsim.nn.data import create_datasets from wordsim.nn.model import KerasModel def",
"logging.basicConfig( level=logging.INFO, format=\"%(asctime)s : \" + \"%(module)s (%(lineno)s) - %(levelname)s - %(message)s\") conf",
"KerasModel(conf, input_dim, 1) # output is a score model.train(training_data, epochs, batch_size) model.save() test_data.vectorize(vectorizers)",
"(%(lineno)s) - %(levelname)s - %(message)s\") conf = ConfigParser(os.environ) conf.read(sys.argv[1]) vectorizers = get_models(conf) training_data,",
"conf.read(sys.argv[1]) vectorizers = get_models(conf) training_data, dev_data, test_data = create_datasets(conf) if conf.getboolean('main', 'train'): epochs",
": \" + \"%(module)s (%(lineno)s) - %(levelname)s - %(message)s\") conf = ConfigParser(os.environ) conf.read(sys.argv[1])",
"ConfigParser(os.environ) conf.read(sys.argv[1]) vectorizers = get_models(conf) training_data, dev_data, test_data = create_datasets(conf) if conf.getboolean('main', 'train'):",
"import create_datasets from wordsim.nn.model import KerasModel def main(): logging.basicConfig( level=logging.INFO, format=\"%(asctime)s : \"",
"conf.getint('training', 'batch_size') training_data.vectorize(vectorizers) input_size, input_dim = training_data.vectors.shape model = KerasModel(conf, input_dim, 1) #",
"1) # output is a score model.train(training_data, epochs, batch_size) model.save() test_data.vectorize(vectorizers) evaluate(model, dev_data)",
"create_datasets(conf) if conf.getboolean('main', 'train'): epochs = conf.getint('training', 'epochs') batch_size = conf.getint('training', 'batch_size') training_data.vectorize(vectorizers)",
"input_dim = training_data.vectors.shape model = KerasModel(conf, input_dim, 1) # output is a score",
"- %(message)s\") conf = ConfigParser(os.environ) conf.read(sys.argv[1]) vectorizers = get_models(conf) training_data, dev_data, test_data =",
"output is a score model.train(training_data, epochs, batch_size) model.save() test_data.vectorize(vectorizers) evaluate(model, dev_data) if __name__",
"%(message)s\") conf = ConfigParser(os.environ) conf.read(sys.argv[1]) vectorizers = get_models(conf) training_data, dev_data, test_data = create_datasets(conf)",
"main(): logging.basicConfig( level=logging.INFO, format=\"%(asctime)s : \" + \"%(module)s (%(lineno)s) - %(levelname)s - %(message)s\")"
] |
[
"API. See api_version in realms.proto. API_VERSION = 1 def merge(permissions, realms, out=None): \"\"\"Merges",
"the index in the final merged proto (or None if undefined). old_to_new =",
"# Add the relabeled realm to the output. assert old_realm.name.startswith(proj_id+':'), old_realm.name new_realm =",
"Authors. All rights reserved. # Use of this source code is governed under",
"out.permissions.extend(permissions) # Permission name => its index in the merged realms_pb2.Realms. perm_index =",
"out: a realms_pb2.Realms to write the result into (will not be cleared!). Returns:",
"file. \"\"\"Utilities to work with realms_pb2 messages.\"\"\" from .proto import realms_pb2 # Currently",
"LICENSE file. \"\"\"Utilities to work with realms_pb2 messages.\"\"\" from .proto import realms_pb2 #",
"governed under the Apache License, Version 2.0 # that can be found in",
"realms_pb2.Realms to write the result into (will not be cleared!). Returns: `out` or",
"to the asynchronous nature of realms config updates (e.g. a role change that",
"2020 The LUCI Authors. All rights reserved. # Use of this source code",
"to # the index in the final merged proto (or None if undefined).",
"given list of permissions will become authoritative: if some realm uses a permission",
"be silently dropped from the bindings. This can potentially happen due to the",
"authoritative: if some realm uses a permission not in the list, it will",
"in the list, it will be silently dropped from the bindings. This can",
"due to the asynchronous nature of realms config updates (e.g. a role change",
"messages.\"\"\" from .proto import realms_pb2 # Currently acceptable version of Realms API. See",
"Calculate a mapping from the permission index in `proj_realms` to # the index",
"proj_id, proj_realms in sorted(realms.items()): # Calculate a mapping from the permission index in",
"the permission index in `proj_realms` to # the index in the final merged",
"change that deletes some permissions can be committed into the AuthDB before realms_pb2.Realms",
"the bindings. This can potentially happen due to the asynchronous nature of realms",
"principals=principals) for perms, principals in sorted(bindings, key=lambda x: x[0]) ) if old_realm.HasField('data'): new_realm.data.CopyFrom(old_realm.data)",
"old_to_new = [perm_index.get(p.name) for p in proj_realms.permissions] # Visit all bindings in all",
"out.realms.add() new_realm.name = old_realm.name new_realm.bindings.extend( realms_pb2.Binding(permissions=perms, principals=principals) for perms, principals in sorted(bindings, key=lambda",
"with realms_pb2 messages.\"\"\" from .proto import realms_pb2 # Currently acceptable version of Realms",
"cleared!). Returns: `out` or a new realms_pb2.Realms if out was None. \"\"\" out",
"100% consistent. Args: permissions: a sorted list of realms_pb2.Permission with all permissions. realms:",
"should converge to be 100% consistent. Args: permissions: a sorted list of realms_pb2.Permission",
"permission indexes, drop empty bindings that may appear. bindings = [] for b",
"is not None ) if perms: bindings.append((perms, b.principals)) # Add the relabeled realm",
"= [] for b in old_realm.bindings: perms = sorted( old_to_new[idx] for idx in",
"fills in `api_version`. The given list of permissions will become authoritative: if some",
"dropped from the bindings. This can potentially happen due to the asynchronous nature",
"(or None if undefined). old_to_new = [perm_index.get(p.name) for p in proj_realms.permissions] # Visit",
"the list, it will be silently dropped from the bindings. This can potentially",
"# the index in the final merged proto (or None if undefined). old_to_new",
"list of permissions will become authoritative: if some realm uses a permission not",
"`proj_realms` to # the index in the final merged proto (or None if",
"undefined). old_to_new = [perm_index.get(p.name) for p in proj_realms.permissions] # Visit all bindings in",
"in proj_realms.realms: # Relabel permission indexes, drop empty bindings that may appear. bindings",
"the merged realms_pb2.Realms. perm_index = {p.name: idx for idx, p in enumerate(permissions)} #",
"can potentially happen due to the asynchronous nature of realms config updates (e.g.",
"may appear. bindings = [] for b in old_realm.bindings: perms = sorted( old_to_new[idx]",
"proj_realms.permissions] # Visit all bindings in all realms. for old_realm in proj_realms.realms: #",
"for perms, principals in sorted(bindings, key=lambda x: x[0]) ) if old_realm.HasField('data'): new_realm.data.CopyFrom(old_realm.data) return",
"in order of project IDs. for proj_id, proj_realms in sorted(realms.items()): # Calculate a",
"perms, principals in sorted(bindings, key=lambda x: x[0]) ) if old_realm.HasField('data'): new_realm.data.CopyFrom(old_realm.data) return out",
"one, fills in `api_version`. The given list of permissions will become authoritative: if",
"realm uses a permission not in the list, it will be silently dropped",
"= {p.name: idx for idx, p in enumerate(permissions)} # Visit in order of",
"(will not be cleared!). Returns: `out` or a new realms_pb2.Realms if out was",
"License, Version 2.0 # that can be found in the LICENSE file. \"\"\"Utilities",
"rights reserved. # Use of this source code is governed under the Apache",
"role change that deletes some permissions can be committed into the AuthDB before",
"list of realms_pb2.Permission with all permissions. realms: a dict {project ID -> realms_pb2.Realms",
"merge. out: a realms_pb2.Realms to write the result into (will not be cleared!).",
"None if undefined). old_to_new = [perm_index.get(p.name) for p in proj_realms.permissions] # Visit all",
"from .proto import realms_pb2 # Currently acceptable version of Realms API. See api_version",
"b.principals)) # Add the relabeled realm to the output. assert old_realm.name.startswith(proj_id+':'), old_realm.name new_realm",
"final merged proto (or None if undefined). old_to_new = [perm_index.get(p.name) for p in",
"a realms_pb2.Realms to write the result into (will not be cleared!). Returns: `out`",
"a role change that deletes some permissions can be committed into the AuthDB",
"api_version in realms.proto. API_VERSION = 1 def merge(permissions, realms, out=None): \"\"\"Merges multiple realms_pb2.Realms",
"out or realms_pb2.Realms() out.api_version = API_VERSION out.permissions.extend(permissions) # Permission name => its index",
"uses a permission not in the list, it will be silently dropped from",
"in the merged realms_pb2.Realms. perm_index = {p.name: idx for idx, p in enumerate(permissions)}",
"realm to the output. assert old_realm.name.startswith(proj_id+':'), old_realm.name new_realm = out.realms.add() new_realm.name = old_realm.name",
"the final merged proto (or None if undefined). old_to_new = [perm_index.get(p.name) for p",
"in `proj_realms` to # the index in the final merged proto (or None",
"dict {project ID -> realms_pb2.Realms with its realms} to merge. out: a realms_pb2.Realms",
"idx, p in enumerate(permissions)} # Visit in order of project IDs. for proj_id,",
"proj_realms in sorted(realms.items()): # Calculate a mapping from the permission index in `proj_realms`",
"index in `proj_realms` to # the index in the final merged proto (or",
"for old_realm in proj_realms.realms: # Relabel permission indexes, drop empty bindings that may",
"to write the result into (will not be cleared!). Returns: `out` or a",
"Returns: `out` or a new realms_pb2.Realms if out was None. \"\"\" out =",
"asynchronous nature of realms config updates (e.g. a role change that deletes some",
"`out` or a new realms_pb2.Realms if out was None. \"\"\" out = out",
"Eventually the state should converge to be 100% consistent. Args: permissions: a sorted",
".proto import realms_pb2 # Currently acceptable version of Realms API. See api_version in",
"idx in b.permissions if old_to_new[idx] is not None ) if perms: bindings.append((perms, b.principals))",
"2.0 # that can be found in the LICENSE file. \"\"\"Utilities to work",
"index in the merged realms_pb2.Realms. perm_index = {p.name: idx for idx, p in",
"realms config updates (e.g. a role change that deletes some permissions can be",
"old_realm.bindings: perms = sorted( old_to_new[idx] for idx in b.permissions if old_to_new[idx] is not",
"{project ID -> realms_pb2.Realms with its realms} to merge. out: a realms_pb2.Realms to",
"out.api_version = API_VERSION out.permissions.extend(permissions) # Permission name => its index in the merged",
"# Permission name => its index in the merged realms_pb2.Realms. perm_index = {p.name:",
"for idx in b.permissions if old_to_new[idx] is not None ) if perms: bindings.append((perms,",
"Apache License, Version 2.0 # that can be found in the LICENSE file.",
"list, it will be silently dropped from the bindings. This can potentially happen",
"All rights reserved. # Use of this source code is governed under the",
"# Use of this source code is governed under the Apache License, Version",
"bindings.append((perms, b.principals)) # Add the relabeled realm to the output. assert old_realm.name.startswith(proj_id+':'), old_realm.name",
"b.permissions if old_to_new[idx] is not None ) if perms: bindings.append((perms, b.principals)) # Add",
"a new realms_pb2.Realms if out was None. \"\"\" out = out or realms_pb2.Realms()",
"p in enumerate(permissions)} # Visit in order of project IDs. for proj_id, proj_realms",
"in enumerate(permissions)} # Visit in order of project IDs. for proj_id, proj_realms in",
"index in the final merged proto (or None if undefined). old_to_new = [perm_index.get(p.name)",
"sorted list of realms_pb2.Permission with all permissions. realms: a dict {project ID ->",
"new realms_pb2.Realms if out was None. \"\"\" out = out or realms_pb2.Realms() out.api_version",
"will be silently dropped from the bindings. This can potentially happen due to",
"Relabel permission indexes, drop empty bindings that may appear. bindings = [] for",
"\"\"\"Utilities to work with realms_pb2 messages.\"\"\" from .proto import realms_pb2 # Currently acceptable",
"Realms API. See api_version in realms.proto. API_VERSION = 1 def merge(permissions, realms, out=None):",
"committed into the AuthDB before realms_pb2.Realms are reevaluated). Eventually the state should converge",
"a permission not in the list, it will be silently dropped from the",
"a sorted list of realms_pb2.Permission with all permissions. realms: a dict {project ID",
"if out was None. \"\"\" out = out or realms_pb2.Realms() out.api_version = API_VERSION",
"multiple realms_pb2.Realms into one, fills in `api_version`. The given list of permissions will",
"a mapping from the permission index in `proj_realms` to # the index in",
"-> realms_pb2.Realms with its realms} to merge. out: a realms_pb2.Realms to write the",
"to be 100% consistent. Args: permissions: a sorted list of realms_pb2.Permission with all",
"be committed into the AuthDB before realms_pb2.Realms are reevaluated). Eventually the state should",
"appear. bindings = [] for b in old_realm.bindings: perms = sorted( old_to_new[idx] for",
"=> its index in the merged realms_pb2.Realms. perm_index = {p.name: idx for idx,",
"Add the relabeled realm to the output. assert old_realm.name.startswith(proj_id+':'), old_realm.name new_realm = out.realms.add()",
"from the permission index in `proj_realms` to # the index in the final",
"in b.permissions if old_to_new[idx] is not None ) if perms: bindings.append((perms, b.principals)) #",
"new_realm.name = old_realm.name new_realm.bindings.extend( realms_pb2.Binding(permissions=perms, principals=principals) for perms, principals in sorted(bindings, key=lambda x:",
"some realm uses a permission not in the list, it will be silently",
"old_realm in proj_realms.realms: # Relabel permission indexes, drop empty bindings that may appear.",
"is governed under the Apache License, Version 2.0 # that can be found",
"it will be silently dropped from the bindings. This can potentially happen due",
"out=None): \"\"\"Merges multiple realms_pb2.Realms into one, fills in `api_version`. The given list of",
"permissions will become authoritative: if some realm uses a permission not in the",
"[perm_index.get(p.name) for p in proj_realms.permissions] # Visit all bindings in all realms. for",
"be cleared!). Returns: `out` or a new realms_pb2.Realms if out was None. \"\"\"",
"of this source code is governed under the Apache License, Version 2.0 #",
"sorted( old_to_new[idx] for idx in b.permissions if old_to_new[idx] is not None ) if",
"its realms} to merge. out: a realms_pb2.Realms to write the result into (will",
"for b in old_realm.bindings: perms = sorted( old_to_new[idx] for idx in b.permissions if",
"= 1 def merge(permissions, realms, out=None): \"\"\"Merges multiple realms_pb2.Realms into one, fills in",
"all permissions. realms: a dict {project ID -> realms_pb2.Realms with its realms} to",
"this source code is governed under the Apache License, Version 2.0 # that",
"or realms_pb2.Realms() out.api_version = API_VERSION out.permissions.extend(permissions) # Permission name => its index in",
"realms: a dict {project ID -> realms_pb2.Realms with its realms} to merge. out:",
"not be cleared!). Returns: `out` or a new realms_pb2.Realms if out was None.",
"# Copyright 2020 The LUCI Authors. All rights reserved. # Use of this",
"old_realm.name new_realm.bindings.extend( realms_pb2.Binding(permissions=perms, principals=principals) for perms, principals in sorted(bindings, key=lambda x: x[0]) )",
"= API_VERSION out.permissions.extend(permissions) # Permission name => its index in the merged realms_pb2.Realms.",
"\"\"\" out = out or realms_pb2.Realms() out.api_version = API_VERSION out.permissions.extend(permissions) # Permission name",
"# Calculate a mapping from the permission index in `proj_realms` to # the",
"found in the LICENSE file. \"\"\"Utilities to work with realms_pb2 messages.\"\"\" from .proto",
"None. \"\"\" out = out or realms_pb2.Realms() out.api_version = API_VERSION out.permissions.extend(permissions) # Permission",
"proj_realms.realms: # Relabel permission indexes, drop empty bindings that may appear. bindings =",
"can be found in the LICENSE file. \"\"\"Utilities to work with realms_pb2 messages.\"\"\"",
"Copyright 2020 The LUCI Authors. All rights reserved. # Use of this source",
"the Apache License, Version 2.0 # that can be found in the LICENSE",
"LUCI Authors. All rights reserved. # Use of this source code is governed",
"[] for b in old_realm.bindings: perms = sorted( old_to_new[idx] for idx in b.permissions",
"if old_to_new[idx] is not None ) if perms: bindings.append((perms, b.principals)) # Add the",
"\"\"\"Merges multiple realms_pb2.Realms into one, fills in `api_version`. The given list of permissions",
") if perms: bindings.append((perms, b.principals)) # Add the relabeled realm to the output.",
"bindings in all realms. for old_realm in proj_realms.realms: # Relabel permission indexes, drop",
"all realms. for old_realm in proj_realms.realms: # Relabel permission indexes, drop empty bindings",
"be 100% consistent. Args: permissions: a sorted list of realms_pb2.Permission with all permissions.",
"b in old_realm.bindings: perms = sorted( old_to_new[idx] for idx in b.permissions if old_to_new[idx]",
"deletes some permissions can be committed into the AuthDB before realms_pb2.Realms are reevaluated).",
"in the final merged proto (or None if undefined). old_to_new = [perm_index.get(p.name) for",
"if perms: bindings.append((perms, b.principals)) # Add the relabeled realm to the output. assert",
"under the Apache License, Version 2.0 # that can be found in the",
"new_realm = out.realms.add() new_realm.name = old_realm.name new_realm.bindings.extend( realms_pb2.Binding(permissions=perms, principals=principals) for perms, principals in",
"a dict {project ID -> realms_pb2.Realms with its realms} to merge. out: a",
"= out or realms_pb2.Realms() out.api_version = API_VERSION out.permissions.extend(permissions) # Permission name => its",
"result into (will not be cleared!). Returns: `out` or a new realms_pb2.Realms if",
"None ) if perms: bindings.append((perms, b.principals)) # Add the relabeled realm to the",
"{p.name: idx for idx, p in enumerate(permissions)} # Visit in order of project",
"source code is governed under the Apache License, Version 2.0 # that can",
"to the output. assert old_realm.name.startswith(proj_id+':'), old_realm.name new_realm = out.realms.add() new_realm.name = old_realm.name new_realm.bindings.extend(",
"proto (or None if undefined). old_to_new = [perm_index.get(p.name) for p in proj_realms.permissions] #",
"This can potentially happen due to the asynchronous nature of realms config updates",
"mapping from the permission index in `proj_realms` to # the index in the",
"the asynchronous nature of realms config updates (e.g. a role change that deletes",
"nature of realms config updates (e.g. a role change that deletes some permissions",
"realms_pb2.Realms. perm_index = {p.name: idx for idx, p in enumerate(permissions)} # Visit in",
"ID -> realms_pb2.Realms with its realms} to merge. out: a realms_pb2.Realms to write",
"merged realms_pb2.Realms. perm_index = {p.name: idx for idx, p in enumerate(permissions)} # Visit",
"= sorted( old_to_new[idx] for idx in b.permissions if old_to_new[idx] is not None )",
"all bindings in all realms. for old_realm in proj_realms.realms: # Relabel permission indexes,",
"The given list of permissions will become authoritative: if some realm uses a",
"the AuthDB before realms_pb2.Realms are reevaluated). Eventually the state should converge to be",
"the relabeled realm to the output. assert old_realm.name.startswith(proj_id+':'), old_realm.name new_realm = out.realms.add() new_realm.name",
"project IDs. for proj_id, proj_realms in sorted(realms.items()): # Calculate a mapping from the",
"or a new realms_pb2.Realms if out was None. \"\"\" out = out or",
"Version 2.0 # that can be found in the LICENSE file. \"\"\"Utilities to",
"of realms_pb2.Permission with all permissions. realms: a dict {project ID -> realms_pb2.Realms with",
"API_VERSION out.permissions.extend(permissions) # Permission name => its index in the merged realms_pb2.Realms. perm_index",
"happen due to the asynchronous nature of realms config updates (e.g. a role",
"# that can be found in the LICENSE file. \"\"\"Utilities to work with",
"in proj_realms.permissions] # Visit all bindings in all realms. for old_realm in proj_realms.realms:",
"permission not in the list, it will be silently dropped from the bindings.",
"that can be found in the LICENSE file. \"\"\"Utilities to work with realms_pb2",
"version of Realms API. See api_version in realms.proto. API_VERSION = 1 def merge(permissions,",
"See api_version in realms.proto. API_VERSION = 1 def merge(permissions, realms, out=None): \"\"\"Merges multiple",
"out = out or realms_pb2.Realms() out.api_version = API_VERSION out.permissions.extend(permissions) # Permission name =>",
"with its realms} to merge. out: a realms_pb2.Realms to write the result into",
"work with realms_pb2 messages.\"\"\" from .proto import realms_pb2 # Currently acceptable version of",
"in sorted(realms.items()): # Calculate a mapping from the permission index in `proj_realms` to",
"relabeled realm to the output. assert old_realm.name.startswith(proj_id+':'), old_realm.name new_realm = out.realms.add() new_realm.name =",
"= out.realms.add() new_realm.name = old_realm.name new_realm.bindings.extend( realms_pb2.Binding(permissions=perms, principals=principals) for perms, principals in sorted(bindings,",
"name => its index in the merged realms_pb2.Realms. perm_index = {p.name: idx for",
"realms_pb2 messages.\"\"\" from .proto import realms_pb2 # Currently acceptable version of Realms API.",
"the LICENSE file. \"\"\"Utilities to work with realms_pb2 messages.\"\"\" from .proto import realms_pb2",
"idx for idx, p in enumerate(permissions)} # Visit in order of project IDs.",
"realms_pb2 # Currently acceptable version of Realms API. See api_version in realms.proto. API_VERSION",
"in `api_version`. The given list of permissions will become authoritative: if some realm",
"Permission name => its index in the merged realms_pb2.Realms. perm_index = {p.name: idx",
"new_realm.bindings.extend( realms_pb2.Binding(permissions=perms, principals=principals) for perms, principals in sorted(bindings, key=lambda x: x[0]) ) if",
"= old_realm.name new_realm.bindings.extend( realms_pb2.Binding(permissions=perms, principals=principals) for perms, principals in sorted(bindings, key=lambda x: x[0])",
"merge(permissions, realms, out=None): \"\"\"Merges multiple realms_pb2.Realms into one, fills in `api_version`. The given",
"assert old_realm.name.startswith(proj_id+':'), old_realm.name new_realm = out.realms.add() new_realm.name = old_realm.name new_realm.bindings.extend( realms_pb2.Binding(permissions=perms, principals=principals) for",
"realms_pb2.Realms with its realms} to merge. out: a realms_pb2.Realms to write the result",
"was None. \"\"\" out = out or realms_pb2.Realms() out.api_version = API_VERSION out.permissions.extend(permissions) #",
"Visit in order of project IDs. for proj_id, proj_realms in sorted(realms.items()): # Calculate",
"drop empty bindings that may appear. bindings = [] for b in old_realm.bindings:",
"of realms config updates (e.g. a role change that deletes some permissions can",
"the output. assert old_realm.name.startswith(proj_id+':'), old_realm.name new_realm = out.realms.add() new_realm.name = old_realm.name new_realm.bindings.extend( realms_pb2.Binding(permissions=perms,",
"Use of this source code is governed under the Apache License, Version 2.0",
"`api_version`. The given list of permissions will become authoritative: if some realm uses",
"into (will not be cleared!). Returns: `out` or a new realms_pb2.Realms if out",
"Visit all bindings in all realms. for old_realm in proj_realms.realms: # Relabel permission",
"to work with realms_pb2 messages.\"\"\" from .proto import realms_pb2 # Currently acceptable version",
"realms} to merge. out: a realms_pb2.Realms to write the result into (will not",
"(e.g. a role change that deletes some permissions can be committed into the",
"permissions: a sorted list of realms_pb2.Permission with all permissions. realms: a dict {project",
"that may appear. bindings = [] for b in old_realm.bindings: perms = sorted(",
"in all realms. for old_realm in proj_realms.realms: # Relabel permission indexes, drop empty",
"= [perm_index.get(p.name) for p in proj_realms.permissions] # Visit all bindings in all realms.",
"be found in the LICENSE file. \"\"\"Utilities to work with realms_pb2 messages.\"\"\" from",
"will become authoritative: if some realm uses a permission not in the list,",
"realms_pb2.Binding(permissions=perms, principals=principals) for perms, principals in sorted(bindings, key=lambda x: x[0]) ) if old_realm.HasField('data'):",
"perms = sorted( old_to_new[idx] for idx in b.permissions if old_to_new[idx] is not None",
"realms_pb2.Realms() out.api_version = API_VERSION out.permissions.extend(permissions) # Permission name => its index in the",
"reserved. # Use of this source code is governed under the Apache License,",
"updates (e.g. a role change that deletes some permissions can be committed into",
"bindings. This can potentially happen due to the asynchronous nature of realms config",
"permissions. realms: a dict {project ID -> realms_pb2.Realms with its realms} to merge.",
"order of project IDs. for proj_id, proj_realms in sorted(realms.items()): # Calculate a mapping",
"import realms_pb2 # Currently acceptable version of Realms API. See api_version in realms.proto.",
"its index in the merged realms_pb2.Realms. perm_index = {p.name: idx for idx, p",
"merged proto (or None if undefined). old_to_new = [perm_index.get(p.name) for p in proj_realms.permissions]",
"realms, out=None): \"\"\"Merges multiple realms_pb2.Realms into one, fills in `api_version`. The given list",
"the result into (will not be cleared!). Returns: `out` or a new realms_pb2.Realms",
"permissions can be committed into the AuthDB before realms_pb2.Realms are reevaluated). Eventually the",
"to merge. out: a realms_pb2.Realms to write the result into (will not be",
"def merge(permissions, realms, out=None): \"\"\"Merges multiple realms_pb2.Realms into one, fills in `api_version`. The",
"potentially happen due to the asynchronous nature of realms config updates (e.g. a",
"of Realms API. See api_version in realms.proto. API_VERSION = 1 def merge(permissions, realms,",
"Args: permissions: a sorted list of realms_pb2.Permission with all permissions. realms: a dict",
"bindings = [] for b in old_realm.bindings: perms = sorted( old_to_new[idx] for idx",
"realms_pb2.Realms into one, fills in `api_version`. The given list of permissions will become",
"realms_pb2.Realms are reevaluated). Eventually the state should converge to be 100% consistent. Args:",
"consistent. Args: permissions: a sorted list of realms_pb2.Permission with all permissions. realms: a",
"code is governed under the Apache License, Version 2.0 # that can be",
"if some realm uses a permission not in the list, it will be",
"reevaluated). Eventually the state should converge to be 100% consistent. Args: permissions: a",
"old_to_new[idx] for idx in b.permissions if old_to_new[idx] is not None ) if perms:",
"that deletes some permissions can be committed into the AuthDB before realms_pb2.Realms are",
"old_realm.name new_realm = out.realms.add() new_realm.name = old_realm.name new_realm.bindings.extend( realms_pb2.Binding(permissions=perms, principals=principals) for perms, principals",
"# Visit in order of project IDs. for proj_id, proj_realms in sorted(realms.items()): #",
"# Currently acceptable version of Realms API. See api_version in realms.proto. API_VERSION =",
"in old_realm.bindings: perms = sorted( old_to_new[idx] for idx in b.permissions if old_to_new[idx] is",
"the state should converge to be 100% consistent. Args: permissions: a sorted list",
"silently dropped from the bindings. This can potentially happen due to the asynchronous",
"# Visit all bindings in all realms. for old_realm in proj_realms.realms: # Relabel",
"perms: bindings.append((perms, b.principals)) # Add the relabeled realm to the output. assert old_realm.name.startswith(proj_id+':'),",
"with all permissions. realms: a dict {project ID -> realms_pb2.Realms with its realms}",
"of project IDs. for proj_id, proj_realms in sorted(realms.items()): # Calculate a mapping from",
"realms. for old_realm in proj_realms.realms: # Relabel permission indexes, drop empty bindings that",
"state should converge to be 100% consistent. Args: permissions: a sorted list of",
"not in the list, it will be silently dropped from the bindings. This",
"before realms_pb2.Realms are reevaluated). Eventually the state should converge to be 100% consistent.",
"become authoritative: if some realm uses a permission not in the list, it",
"of permissions will become authoritative: if some realm uses a permission not in",
"realms_pb2.Realms if out was None. \"\"\" out = out or realms_pb2.Realms() out.api_version =",
"are reevaluated). Eventually the state should converge to be 100% consistent. Args: permissions:",
"permission index in `proj_realms` to # the index in the final merged proto",
"write the result into (will not be cleared!). Returns: `out` or a new",
"API_VERSION = 1 def merge(permissions, realms, out=None): \"\"\"Merges multiple realms_pb2.Realms into one, fills",
"config updates (e.g. a role change that deletes some permissions can be committed",
"p in proj_realms.permissions] # Visit all bindings in all realms. for old_realm in",
"for p in proj_realms.permissions] # Visit all bindings in all realms. for old_realm",
"for proj_id, proj_realms in sorted(realms.items()): # Calculate a mapping from the permission index",
"old_realm.name.startswith(proj_id+':'), old_realm.name new_realm = out.realms.add() new_realm.name = old_realm.name new_realm.bindings.extend( realms_pb2.Binding(permissions=perms, principals=principals) for perms,",
"acceptable version of Realms API. See api_version in realms.proto. API_VERSION = 1 def",
"realms_pb2.Permission with all permissions. realms: a dict {project ID -> realms_pb2.Realms with its",
"indexes, drop empty bindings that may appear. bindings = [] for b in",
"# Relabel permission indexes, drop empty bindings that may appear. bindings = []",
"out was None. \"\"\" out = out or realms_pb2.Realms() out.api_version = API_VERSION out.permissions.extend(permissions)",
"for idx, p in enumerate(permissions)} # Visit in order of project IDs. for",
"if undefined). old_to_new = [perm_index.get(p.name) for p in proj_realms.permissions] # Visit all bindings",
"Currently acceptable version of Realms API. See api_version in realms.proto. API_VERSION = 1",
"IDs. for proj_id, proj_realms in sorted(realms.items()): # Calculate a mapping from the permission",
"converge to be 100% consistent. Args: permissions: a sorted list of realms_pb2.Permission with",
"AuthDB before realms_pb2.Realms are reevaluated). Eventually the state should converge to be 100%",
"from the bindings. This can potentially happen due to the asynchronous nature of",
"into the AuthDB before realms_pb2.Realms are reevaluated). Eventually the state should converge to",
"in the LICENSE file. \"\"\"Utilities to work with realms_pb2 messages.\"\"\" from .proto import",
"1 def merge(permissions, realms, out=None): \"\"\"Merges multiple realms_pb2.Realms into one, fills in `api_version`.",
"into one, fills in `api_version`. The given list of permissions will become authoritative:",
"output. assert old_realm.name.startswith(proj_id+':'), old_realm.name new_realm = out.realms.add() new_realm.name = old_realm.name new_realm.bindings.extend( realms_pb2.Binding(permissions=perms, principals=principals)",
"empty bindings that may appear. bindings = [] for b in old_realm.bindings: perms",
"sorted(realms.items()): # Calculate a mapping from the permission index in `proj_realms` to #",
"old_to_new[idx] is not None ) if perms: bindings.append((perms, b.principals)) # Add the relabeled",
"The LUCI Authors. All rights reserved. # Use of this source code is",
"not None ) if perms: bindings.append((perms, b.principals)) # Add the relabeled realm to",
"bindings that may appear. bindings = [] for b in old_realm.bindings: perms =",
"enumerate(permissions)} # Visit in order of project IDs. for proj_id, proj_realms in sorted(realms.items()):",
"some permissions can be committed into the AuthDB before realms_pb2.Realms are reevaluated). Eventually",
"can be committed into the AuthDB before realms_pb2.Realms are reevaluated). Eventually the state",
"realms.proto. API_VERSION = 1 def merge(permissions, realms, out=None): \"\"\"Merges multiple realms_pb2.Realms into one,",
"in realms.proto. API_VERSION = 1 def merge(permissions, realms, out=None): \"\"\"Merges multiple realms_pb2.Realms into",
"perm_index = {p.name: idx for idx, p in enumerate(permissions)} # Visit in order"
] |
[
"ContextManager() cm.fallback_context = \"m\" cm.initial_contexts = [\"m\"] cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) c1 = cm.create_context(\"t1\")",
"constructor\"\"\" c = Context(\"test_context\", lambda *a, **k: True) self.assertIsNotNone(c) def test_threading(self): \"\"\"Tests whether",
"def scenario(): r.keymap[\"KEY_LEFT\"]() assert not r.in_foreground # If the test fails, either the",
"os.sys.path.append(os.path.dirname(os.path.abspath('.'))) # Store original __import__ orig_import = __import__ def import_mock(name, *args, **kwargs): if",
"flag, otherwise a validation check fails c.activate() assert(not e.isSet()) assert(not finished.isSet()) c.threaded =",
"side_effect=scenario) as p: r.activate() #The scenario should only be called once assert r.idle_loop.called",
"0.1) assert(r.iterations_before_refresh == 10) # Refresh intervals up until 0.1 don't change the",
"side_effect=import_mock): from context_manager import ContextManager, Context, ContextError class TestContext(unittest.TestCase): \"\"\"tests context class\"\"\" def",
"r = Refresher(lambda: \"Hello\", get_mock_input(), get_mock_output(), name=r_name) r.refresh = lambda *args, **kwargs: None",
"= Event() cm.register_context_target(\"t1\", e1.wait) cm.register_context_target(\"t2\", e2.wait) cm.switch_to_context(\"t1\") # Removing c1.set_target(None) del c1.thread c1.signal_finished",
"c2.i # Both current and new contexts are fucked up cm.switch_to_context(\"t2\") # Setting",
"e1 = Event() e2 = Event() cm.register_context_target(\"t1\", e1.wait) cm.register_context_target(\"t2\", e2.wait) cm.switch_to_context(\"t1\") # Removing",
"r.pause() r.idle_loop() assert o.display_data.call_count == 2 #paused, so count shouldn't change r.resume() assert",
"\"test1\") cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\") assert(cm.get_previous_context(\"test1\") == \"test2\") #Setting events so that threads",
"'idle_loop', side_effect=scenario) as p: try: r.activate() except KeyboardInterrupt: pass #Test succeeded def test_shows_data_on_screen(self):",
"so that threads exit e1.set() e2.set() def test_context_switching_on_context_finish(self): \"\"\"Tests whether basic context switching",
"True c2.set_target(None) # Again, switcing to the fucked up context cm.switch_to_context(\"t2\") # Setting",
"== cm.fallback_context) cm.switch_to_context(\"test2\") assert(cm.current_context == \"test2\") assert(cm.get_previous_context(\"test2\") == \"test1\") cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\")",
"are app-accessible, # we can't really rely on them staying the same del",
"i.set_keymap.call_args[0][0] != r.keymap r.resume() assert i.set_keymap.call_count == 3 #one explicitly done in the",
"ImportError: print(\"Absolute imports failed, trying relative imports\") os.sys.path.append(os.path.dirname(os.path.abspath('.'))) # Store original __import__ orig_import",
"\"finished\") finished.set() with patch.object(c, 'signal_finished', side_effect=new_signal_finished) as p: e1.set() #Waiting for the thread",
"== 0.1) assert(r.iterations_before_refresh == 1) # Refresh intervals less than 0.1 change sleep_time",
"= ContextManager() cm.fallback_context = \"m\" cm.initial_contexts = [\"m\"] cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) c1 =",
"= __import__ def import_mock(name, *args, **kwargs): if name in ['helpers'] and not kwargs:",
"stays 0 #and idle_loop always refreshes #Doing what an activate() would do, but",
"2 #not paused r.pause() r.idle_loop() assert o.display_data.call_count == 2 #paused, so count shouldn't",
"ContextManager, Context, ContextError except ImportError: print(\"Absolute imports failed, trying relative imports\") os.sys.path.append(os.path.dirname(os.path.abspath('.'))) #",
"name=r_name, refresh_interval=0.1) r.refresh = lambda *args, **kwargs: None # We need to patch",
"Removing c1.set_target(None) del c1.thread c1.signal_finished = lambda: True c2.set_target(None) # Again, switcing to",
"assert(r.iterations_before_refresh == 10) # Refresh intervals up until 0.1 don't change the sleep",
"that _counter always stays 0 #and idle_loop always refreshes #Doing what an activate()",
"Refresher(lambda: \"Hello\", i, o, name=r_name, refresh_interval=0.1) r.refresh = lambda *args, **kwargs: None #",
"i.set_keymap(None) assert i.set_keymap.call_args[0][0] != r.keymap r.resume() assert i.set_keymap.call_count == 3 #one explicitly done",
"def import_mock(name, *args, **kwargs): if name in ['helpers'] and not kwargs: #Have to",
"\"test2\"] cm.init_io(Mock(), Mock()) assert(cm.current_context is None) cm.switch_to_context(cm.fallback_context) assert(cm.current_context == cm.fallback_context) e1 = Event()",
"\"test1\") assert(cm.get_previous_context(\"test1\") == \"test2\") #Setting events so that threads exit e1.set() e2.set() def",
"assert o.display_data.call_count == 2 #not paused r.pause() r.idle_loop() assert o.display_data.call_count == 2 #paused,",
"i.set_keymap.call_count == 3 #one explicitly done in the test right beforehand assert i.set_keymap.call_args[0][0]",
"sleep_time to match refresh interval r.set_refresh_interval(0.01) assert(r.refresh_interval == 0.01) assert(r.sleep_time == 0.01) assert(r.iterations_before_refresh",
"Context, ContextError class TestContext(unittest.TestCase): \"\"\"tests context class\"\"\" def test_constructor(self): \"\"\"Tests constructor\"\"\" c =",
"o.display_data.call_count == 3 #resume() refreshes the display r.idle_loop() assert o.display_data.call_count == 4 #should",
"c.activate() except: raise AssertionError else: pass class TestContextManager(unittest.TestCase): \"\"\"tests context manager class and",
"basic context switching works\"\"\" cm = ContextManager() cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) e1 = Event()",
"assert o.display_data.call_count == 2 #One in to_foreground, and one in patched idle_loop assert",
"assert(r.iterations_before_refresh == 100) def test_update_keymap(self): i = get_mock_input() o = get_mock_output() r =",
"= get_mock_input() o = get_mock_output() r = Refresher(lambda: \"Hello\", i, o, name=r_name) def",
"Event() finished = Event() c.signal_finished = finished.set c.threaded = False # Need to",
"normally now def test_keymap_restore_on_resume(self): i = get_mock_input() o = get_mock_output() r = Refresher(lambda:",
"class TestContextManager(unittest.TestCase): \"\"\"tests context manager class and interaction between contexts\"\"\" def test_constructor(self): \"\"\"Tests",
"don't change the sleep time r.set_refresh_interval(0.1) assert(r.refresh_interval == 0.1) assert(r.sleep_time == 0.1) assert(r.iterations_before_refresh",
"test_constructor(self): \"\"\"Tests constructor\"\"\" cm = ContextManager() self.assertIsNotNone(cm) def test_initial_contexts(self): \"\"\"Tests whether initial contexts",
"assert(cm.current_context == cm.fallback_context) def test_failsafe_fallback_on_io_fail(self): cm = ContextManager() cm.fallback_context = \"m\" cm.initial_contexts =",
"__name__ == '__main__': unittest.main() \"\"\" def test_left_key_exits(self): r = Refresher(lambda: \"Hello\", get_mock_input(), get_mock_output(),",
"3 #one explicitly done in the test right beforehand assert i.set_keymap.call_args[0][0] == r.keymap",
"def test_pause_resume(self): i = get_mock_input() o = get_mock_output() r = Refresher(lambda: \"Hello\", i,",
"test_basic_context_switching(self): \"\"\"Tests whether basic context switching works\"\"\" cm = ContextManager() cm.initial_contexts = [cm.fallback_context,",
"equivalence with patch.object(r, 'process_callback', side_effect=lambda keymap:keymap) as p: keymap1 = {\"KEY_LEFT\": lambda:1} r.update_keymap(keymap1)",
"from context_manager import ContextManager, Context, ContextError except ImportError: print(\"Absolute imports failed, trying relative",
"e1 = Event() c = cm.create_context(\"test1\") cm.register_context_target(\"test1\", e1.wait) cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\") finished",
"o.display_data.call_count == 2 #paused, so count shouldn't change r.resume() assert o.display_data.call_count == 3",
"a test failure, # or the idle loop will just run indefinitely #",
"Refresher exits # It only tests whether the in_foreground attribute is set #",
"and not kwargs: #Have to filter for kwargs since there's a package in",
"*args, **kwargs): if name in ['helpers'] and not kwargs: #Have to filter for",
"assert(cm.current_context == \"test2\") assert(cm.get_previous_context(\"test2\") == \"test1\") cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\") assert(cm.get_previous_context(\"test1\") == \"test2\")",
"= False try: c.activate() except: raise AssertionError else: pass class TestContextManager(unittest.TestCase): \"\"\"tests context",
"and ContextManager objects\"\"\" import os import unittest from threading import Event from mock",
"change the sleep time r.set_refresh_interval(0.1) assert(r.refresh_interval == 0.1) assert(r.sleep_time == 0.1) assert(r.iterations_before_refresh ==",
"lambda *a, **k: True) self.assertIsNotNone(c) def test_threading(self): \"\"\"Tests whether threaded and non-threaded contexts",
"e1.wait) cm.register_context_target(\"t2\", e2.wait) cm.switch_to_context(\"t1\") # Removing c1.set_target(None) del c1.thread c1.signal_finished = lambda: True",
"be refresh the display normally now def test_keymap_restore_on_resume(self): i = get_mock_input() o =",
"== 0.1) assert(r.iterations_before_refresh == 10) # Refresh intervals up until 0.1 don't change",
"get_mock_output() r = Refresher(lambda: \"Hello\", i, o, name=r_name) def scenario(): r.refresh() r.deactivate() with",
"cm = ContextManager() cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) e1 = Event() c = cm.create_context(\"test1\") cm.register_context_target(\"test1\",",
"works\"\"\" cm = ContextManager() cm.initial_contexts = [cm.fallback_context, \"test1\", \"test2\"] cm.init_io(Mock(), Mock()) assert(cm.current_context is",
"r = Refresher(lambda: \"Hello\", i, o, name=r_name, refresh_interval=1) assert(r.refresh_interval == 1) assert(r.sleep_time ==",
"r.set_refresh_interval(10) assert(r.refresh_interval == 10) assert(r.sleep_time == 0.1) # Back to normal assert(r.iterations_before_refresh ==",
"[\"m\"] cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) c1 = cm.create_context(\"t1\") c2 = cm.create_context(\"t2\") e1 = Event()",
"# This test doesn't actually test whether the Refresher exits # It only",
"activate OK c.threaded = False try: c.activate() except: raise AssertionError else: pass class",
"i.set_keymap.call_args[0][0] == r.keymap assert \"KEY_LEFT\" in r.keymap r.pause() assert i.set_keymap.call_count == 1 #paused,",
"TestContextManager(unittest.TestCase): \"\"\"tests context manager class and interaction between contexts\"\"\" def test_constructor(self): \"\"\"Tests constructor\"\"\"",
"to a high value r.set_refresh_interval(10) assert(r.refresh_interval == 10) assert(r.sleep_time == 0.1) # Back",
"side_effect=new_signal_finished) as p: e1.set() #Waiting for the thread to exit finished.wait() assert(cm.current_context ==",
"def test_failsafe_fallback_on_io_fail(self): cm = ContextManager() cm.fallback_context = \"m\" cm.initial_contexts = [\"m\"] cm.init_io(Mock(), Mock())",
"patch.object(r, 'idle_loop', side_effect=scenario) as p: r.activate() #The scenario should only be called once",
"# We need to patch \"process_callback\" because otherwise the keymap callbacks # are",
"*args, **kwargs: None # This test doesn't actually test whether the Refresher exits",
"assert o.display_data.call_count == 3 #resume() refreshes the display r.idle_loop() assert o.display_data.call_count == 4",
"Now setting refresh_interval to a high value r.set_refresh_interval(10) assert(r.refresh_interval == 10) assert(r.sleep_time ==",
"def test_threading(self): \"\"\"Tests whether threaded and non-threaded contexts behave as they should\"\"\" c",
"def scenario(): r.refresh() r.deactivate() with patch.object(r, 'idle_loop', side_effect=scenario) as p: r.activate() #The scenario",
"to the fucked up context cm.switch_to_context(\"t2\") # Setting events so that threads exit",
"Refresh intervals less than 0.1 change sleep_time to match refresh interval r.set_refresh_interval(0.01) assert(r.refresh_interval",
"staying the same del c1.i c1.signal_finished = lambda: True del c2.i # Both",
"\"\"\"Tests whether initial contexts are getting created\"\"\" cm = ContextManager() cm.init_io(Mock(), Mock()) #Implicitly",
"so that threads exit e1.set() e2.set() assert(cm.current_context == cm.fallback_context) if __name__ == '__main__':",
"(\"Hello\", ) def test_pause_resume(self): i = get_mock_input() o = get_mock_output() r = Refresher(lambda:",
"can't really rely on them staying the same del c1.i c1.signal_finished = lambda:",
"# Both current and new contexts are fucked up cm.switch_to_context(\"t2\") # Setting events",
"= ContextManager() cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) cm.create_context(\"test1\") assert(cm.current_context == cm.fallback_context) cm.switch_to_context(\"test1\") assert(cm.current_context == cm.fallback_context)",
"After marking context as non-threaded, it should activate OK c.threaded = False try:",
"assert(r.refresh_interval == 1) assert(r.sleep_time == 0.1) assert(r.iterations_before_refresh == 10) # Refresh intervals up",
"= True c.set_target(e.set) c.activate() finished.wait() assert(e.isSet()) def test_targetless_threaded_context(self): \"\"\"Tests whether a target-less threaded",
"that switching to a target-less context fails\"\"\" cm = ContextManager() cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context)",
"Refresher(lambda: \"Hello\", i, o, name=r_name, refresh_interval=0.1) r.refresh = lambda *args, **kwargs: None r.to_foreground()",
"# we can't really rely on them staying the same del c1.i c1.signal_finished",
"loop will just run indefinitely # The exception thrown should protect from the",
"**kwargs: None # We need to patch \"process_callback\" because otherwise the keymap callbacks",
"patch.object(c, 'signal_finished', side_effect=new_signal_finished) as p: e1.set() #Waiting for the thread to exit finished.wait()",
"scenario should only be called once assert r.idle_loop.called assert r.idle_loop.call_count == 1 assert",
"validation check fails c.activate() assert(not e.isSet()) assert(not finished.isSet()) c.threaded = True c.set_target(e.set) c.activate()",
"get_mock_output() r = Refresher(lambda: \"Hello\", i, o, name=r_name, refresh_interval=0.1) #refresh_interval is 0.1 so",
"ContextManager objects\"\"\" import os import unittest from threading import Event from mock import",
"in the test right beforehand assert i.set_keymap.call_args[0][0] == r.keymap def test_set_interval(self): i =",
"assert o.display_data.call_count == 4 #should be refresh the display normally now def test_keymap_restore_on_resume(self):",
"\"\"\"Tests whether basic context switching works\"\"\" cm = ContextManager() cm.initial_contexts = [cm.fallback_context, \"test1\",",
"e2.set() assert(cm.current_context == cm.fallback_context) if __name__ == '__main__': unittest.main() \"\"\" def test_left_key_exits(self): r",
"# It only tests whether the in_foreground attribute is set # Any ideas?",
"whether the in_foreground attribute is set # Any ideas? Maybe use some kind",
"assert(r.iterations_before_refresh == 1) # Now setting refresh_interval to a high value r.set_refresh_interval(10) assert(r.refresh_interval",
"Context and ContextManager objects\"\"\" import os import unittest from threading import Event from",
"c.event_cb(c.name, \"finished\") finished.set() with patch.object(c, 'signal_finished', side_effect=new_signal_finished) as p: e1.set() #Waiting for the",
"don't want to mock that call return Mock() return orig_import(name, *args, **kwargs) with",
"True) self.assertIsNotNone(c) def test_threading(self): \"\"\"Tests whether threaded and non-threaded contexts behave as they",
"r.in_foreground # If the test fails, either the assert will trigger a test",
"i, o, name=r_name, refresh_interval=1) assert(r.refresh_interval == 1) assert(r.sleep_time == 0.1) assert(r.iterations_before_refresh == 10)",
"= Event() e2 = Event() cm.register_context_target(\"test1\", e1.wait) cm.register_context_target(\"test2\", e2.wait) cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\")",
"exits # It only tests whether the in_foreground attribute is set # Any",
"test fails, either the assert will trigger a test failure, # or the",
"that call return Mock() return orig_import(name, *args, **kwargs) with patch('__builtin__.__import__', side_effect=import_mock): from context_manager",
"\"test1\") finished = Event() def new_signal_finished(): c.event_cb(c.name, \"finished\") finished.set() with patch.object(c, 'signal_finished', side_effect=new_signal_finished)",
"Event() c.signal_finished = finished.set c.threaded = False # Need to set this flag,",
"test_failsafe_fallback_on_io_fail(self): cm = ContextManager() cm.fallback_context = \"m\" cm.initial_contexts = [\"m\"] cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context)",
"thrown should protect from the latter raise KeyboardInterrupt with patch.object(r, 'idle_loop', side_effect=scenario) as",
"None r.to_foreground() assert i.set_keymap.called assert i.set_keymap.call_count == 1 assert i.set_keymap.call_args[0][0] == r.keymap assert",
"library? def scenario(): r.keymap[\"KEY_LEFT\"]() assert not r.in_foreground # If the test fails, either",
"r.keymap[\"KEY_LEFT\"]() assert not r.in_foreground # If the test fails, either the assert will",
"r.keymap r.resume() assert i.set_keymap.call_count == 3 #one explicitly done in the test right",
"import ContextManager, Context, ContextError class TestContext(unittest.TestCase): \"\"\"tests context class\"\"\" def test_constructor(self): \"\"\"Tests constructor\"\"\"",
"we don't want to mock that call return Mock() return orig_import(name, *args, **kwargs)",
"whether basic context switching works\"\"\" cm = ContextManager() cm.initial_contexts = [cm.fallback_context, \"test1\", \"test2\"]",
"def test_shows_data_on_screen(self): i = get_mock_input() o = get_mock_output() r = Refresher(lambda: \"Hello\", i,",
"assert o.display_data.called assert o.display_data.call_count == 1 #to_foreground calls refresh() r.idle_loop() assert o.display_data.call_count ==",
"with patch('__builtin__.__import__', side_effect=import_mock): from context_manager import ContextManager, Context, ContextError class TestContext(unittest.TestCase): \"\"\"tests context",
"c1.signal_finished = lambda: True del c2.i # Both current and new contexts are",
"cm.switch_to_context(\"t2\") # Setting events so that threads exit e1.set() e2.set() assert(cm.current_context == cm.fallback_context)",
"change r.resume() assert o.display_data.call_count == 3 #resume() refreshes the display r.idle_loop() assert o.display_data.call_count",
"cm.switch_to_context(\"t1\") # Fucking things up - since context objects are app-accessible, # we",
"If the test fails, either the assert will trigger a test failure, #",
"0.01) assert(r.sleep_time == 0.01) assert(r.iterations_before_refresh == 1) # Now setting refresh_interval to a",
"with patch.object(r, 'idle_loop', side_effect=scenario) as p: try: r.activate() except KeyboardInterrupt: pass #Test succeeded",
"== cm.fallback_context) def test_targetless_context_switching(self): \"\"\"Tests that switching to a target-less context fails\"\"\" cm",
"callbacks # are wrapped and we can't test equivalence with patch.object(r, 'process_callback', side_effect=lambda",
"context as non-threaded, it should activate OK c.threaded = False try: c.activate() except:",
"r.refresh = lambda *args, **kwargs: None r.to_foreground() assert i.set_keymap.called assert i.set_keymap.call_count == 1",
"lambda *args, **kwargs: None # We need to patch \"process_callback\" because otherwise the",
"print(\"Absolute imports failed, trying relative imports\") os.sys.path.append(os.path.dirname(os.path.abspath('.'))) # Store original __import__ orig_import =",
"it should activate OK c.threaded = False try: c.activate() except: raise AssertionError else:",
"KeyboardInterrupt: pass #Test succeeded def test_shows_data_on_screen(self): i = get_mock_input() o = get_mock_output() r",
"orig_import = __import__ def import_mock(name, *args, **kwargs): if name in ['helpers'] and not",
"assert i.set_keymap.call_count == 1 assert i.set_keymap.call_args[0][0] == r.keymap assert \"KEY_LEFT\" in r.keymap r.pause()",
"high value r.set_refresh_interval(10) assert(r.refresh_interval == 10) assert(r.sleep_time == 0.1) # Back to normal",
"e1.set() e2.set() assert(cm.current_context == cm.fallback_context) if __name__ == '__main__': unittest.main() \"\"\" def test_left_key_exits(self):",
"exception thrown should protect from the latter raise KeyboardInterrupt with patch.object(r, 'idle_loop', side_effect=scenario)",
"or the idle loop will just run indefinitely # The exception thrown should",
"r.idle_loop() assert o.display_data.call_count == 2 #not paused r.pause() r.idle_loop() assert o.display_data.call_count == 2",
"10) assert(r.sleep_time == 0.1) # Back to normal assert(r.iterations_before_refresh == 100) def test_update_keymap(self):",
"cm.init_io(Mock(), Mock()) assert(cm.current_context is None) cm.switch_to_context(cm.fallback_context) assert(cm.current_context == cm.fallback_context) e1 = Event() e2",
"as p: keymap1 = {\"KEY_LEFT\": lambda:1} r.update_keymap(keymap1) assert(r.keymap == keymap1) keymap2 = {\"KEY_RIGHT\":",
"cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\") assert(cm.get_previous_context(\"test1\") == cm.fallback_context) cm.switch_to_context(\"test2\") assert(cm.current_context == \"test2\") assert(cm.get_previous_context(\"test2\") ==",
"side_effect=scenario) as p: try: r.activate() except KeyboardInterrupt: pass #Test succeeded def test_shows_data_on_screen(self): i",
"test_threading(self): \"\"\"Tests whether threaded and non-threaded contexts behave as they should\"\"\" c =",
"\"\"\" def test_left_key_exits(self): r = Refresher(lambda: \"Hello\", get_mock_input(), get_mock_output(), name=r_name) r.refresh = lambda",
"None # We need to patch \"process_callback\" because otherwise the keymap callbacks #",
"= finished.set c.threaded = False # Need to set this flag, otherwise a",
"OK c.threaded = False try: c.activate() except: raise AssertionError else: pass class TestContextManager(unittest.TestCase):",
"None) cm.switch_to_context(cm.fallback_context) assert(cm.current_context == cm.fallback_context) e1 = Event() e2 = Event() cm.register_context_target(\"test1\", e1.wait)",
"c.activate() except ContextError: pass else: raise AssertionError # After marking context as non-threaded,",
"c.threaded = False try: c.activate() except: raise AssertionError else: pass class TestContextManager(unittest.TestCase): \"\"\"tests",
"== \"test2\") assert(cm.get_previous_context(\"test2\") == \"test1\") cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\") assert(cm.get_previous_context(\"test1\") == \"test2\") #Setting",
"interaction between contexts\"\"\" def test_constructor(self): \"\"\"Tests constructor\"\"\" cm = ContextManager() self.assertIsNotNone(cm) def test_initial_contexts(self):",
"== 10) assert(r.sleep_time == 0.1) # Back to normal assert(r.iterations_before_refresh == 100) def",
"and interaction between contexts\"\"\" def test_constructor(self): \"\"\"Tests constructor\"\"\" cm = ContextManager() self.assertIsNotNone(cm) def",
"always stays 0 #and idle_loop always refreshes #Doing what an activate() would do,",
"that threads exit e1.set() e2.set() assert(cm.current_context == cm.fallback_context) if __name__ == '__main__': unittest.main()",
"\"process_callback\" because otherwise the keymap callbacks # are wrapped and we can't test",
"2 #One in to_foreground, and one in patched idle_loop assert o.display_data.call_args_list[0][0] == (\"Hello\",",
"keymap callbacks # are wrapped and we can't test equivalence with patch.object(r, 'process_callback',",
"== 100) def test_update_keymap(self): i = get_mock_input() o = get_mock_output() r = Refresher(lambda:",
"= get_mock_output() r = Refresher(lambda: \"Hello\", i, o, name=r_name, refresh_interval=0.1) #refresh_interval is 0.1",
"ContextManager() cm.initial_contexts = [cm.fallback_context, \"test1\", \"test2\"] cm.init_io(Mock(), Mock()) assert(cm.current_context is None) cm.switch_to_context(cm.fallback_context) assert(cm.current_context",
"1) # Now setting refresh_interval to a high value r.set_refresh_interval(10) assert(r.refresh_interval == 10)",
"the thread to exit finished.wait() assert(cm.current_context == cm.fallback_context) def test_targetless_context_switching(self): \"\"\"Tests that switching",
"ContextManager() self.assertIsNotNone(cm) def test_initial_contexts(self): \"\"\"Tests whether initial contexts are getting created\"\"\" cm =",
"ContextManager() cm.init_io(Mock(), Mock()) #Implicitly creates initial contexts for context_alias, context in cm.contexts.items(): assert(context_alias",
"== cm.fallback_context) cm.switch_to_context(\"test1\") assert(cm.current_context == cm.fallback_context) def test_failsafe_fallback_on_io_fail(self): cm = ContextManager() cm.fallback_context =",
"#to_foreground calls refresh() r.idle_loop() assert o.display_data.call_count == 2 #not paused r.pause() r.idle_loop() assert",
"#not paused r.pause() r.idle_loop() assert o.display_data.call_count == 2 #paused, so count shouldn't change",
"Mock()) assert(cm.current_context is None) cm.switch_to_context(cm.fallback_context) assert(cm.current_context == cm.fallback_context) e1 = Event() e2 =",
"= Context(\"test_context\", lambda *a, **k: True) self.assertIsNotNone(c) def test_threading(self): \"\"\"Tests whether threaded and",
"== \"test1\") cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\") assert(cm.get_previous_context(\"test1\") == \"test2\") #Setting events so that",
"def test_targetless_threaded_context(self): \"\"\"Tests whether a target-less threaded context fails to activate\"\"\" c =",
"e = Event() finished = Event() c.signal_finished = finished.set c.threaded = False #",
"== 0.1) # Back to normal assert(r.iterations_before_refresh == 100) def test_update_keymap(self): i =",
"a high value r.set_refresh_interval(10) assert(r.refresh_interval == 10) assert(r.sleep_time == 0.1) # Back to",
"= lambda *args, **kwargs: None # This test doesn't actually test whether the",
"up until 0.1 don't change the sleep time r.set_refresh_interval(0.1) assert(r.refresh_interval == 0.1) assert(r.sleep_time",
"c = Context(\"test_context\", lambda *a, **k: True) e = Event() finished = Event()",
"cm.switch_to_context(cm.fallback_context) cm.create_context(\"test1\") assert(cm.current_context == cm.fallback_context) cm.switch_to_context(\"test1\") assert(cm.current_context == cm.fallback_context) def test_failsafe_fallback_on_io_fail(self): cm =",
"as p: e1.set() #Waiting for the thread to exit finished.wait() assert(cm.current_context == cm.fallback_context)",
"# Fucking things up - since context objects are app-accessible, # we can't",
"and new contexts are fucked up cm.switch_to_context(\"t2\") # Setting events so that threads",
"c2 = cm.create_context(\"t2\") e1 = Event() e2 = Event() cm.register_context_target(\"t1\", e1.wait) cm.register_context_target(\"t2\", e2.wait)",
"== 0.1) assert(r.sleep_time == 0.1) assert(r.iterations_before_refresh == 1) # Refresh intervals less than",
"contexts\"\"\" def test_constructor(self): \"\"\"Tests constructor\"\"\" cm = ContextManager() self.assertIsNotNone(cm) def test_initial_contexts(self): \"\"\"Tests whether",
"name=r_name) def scenario(): r.refresh() r.deactivate() with patch.object(r, 'idle_loop', side_effect=scenario) as p: r.activate() #The",
"\"test2\") #Setting events so that threads exit e1.set() e2.set() def test_context_switching_on_context_finish(self): \"\"\"Tests whether",
"would do, but without a loop r.to_foreground() assert o.display_data.called assert o.display_data.call_count == 1",
"== 0.01) assert(r.iterations_before_refresh == 1) # Now setting refresh_interval to a high value",
"class TestContext(unittest.TestCase): \"\"\"tests context class\"\"\" def test_constructor(self): \"\"\"Tests constructor\"\"\" c = Context(\"test_context\", lambda",
"context_alias, context in cm.contexts.items(): assert(context_alias in cm.initial_contexts) assert(context) def test_basic_context_switching(self): \"\"\"Tests whether basic",
"check fails c.activate() assert(not e.isSet()) assert(not finished.isSet()) c.threaded = True c.set_target(e.set) c.activate() finished.wait()",
"there's a package in 'json' #that calls __builtins__.__import__ with keyword arguments #and we",
"AssertionError else: pass class TestContextManager(unittest.TestCase): \"\"\"tests context manager class and interaction between contexts\"\"\"",
"\"m\" cm.initial_contexts = [\"m\"] cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) c1 = cm.create_context(\"t1\") c2 = cm.create_context(\"t2\")",
"assert(context_alias in cm.initial_contexts) assert(context) def test_basic_context_switching(self): \"\"\"Tests whether basic context switching works\"\"\" cm",
"name=r_name) r.refresh = lambda *args, **kwargs: None # This test doesn't actually test",
"\"\"\"Tests constructor\"\"\" c = Context(\"test_context\", lambda *a, **k: True) self.assertIsNotNone(c) def test_threading(self): \"\"\"Tests",
"them staying the same del c1.i c1.signal_finished = lambda: True del c2.i #",
"\"\"\"Tests that switching to a target-less context fails\"\"\" cm = ContextManager() cm.init_io(Mock(), Mock())",
"now def test_keymap_restore_on_resume(self): i = get_mock_input() o = get_mock_output() r = Refresher(lambda: \"Hello\",",
"#Waiting for the thread to exit finished.wait() assert(cm.current_context == cm.fallback_context) def test_targetless_context_switching(self): \"\"\"Tests",
"get_mock_input() o = get_mock_output() r = Refresher(lambda: \"Hello\", i, o, name=r_name, refresh_interval=0.1) r.refresh",
"calls __builtins__.__import__ with keyword arguments #and we don't want to mock that call",
"e1.set() #Waiting for the thread to exit finished.wait() assert(cm.current_context == cm.fallback_context) def test_targetless_context_switching(self):",
"calls refresh() r.idle_loop() assert o.display_data.call_count == 2 #not paused r.pause() r.idle_loop() assert o.display_data.call_count",
"intervals less than 0.1 change sleep_time to match refresh interval r.set_refresh_interval(0.01) assert(r.refresh_interval ==",
"It only tests whether the in_foreground attribute is set # Any ideas? Maybe",
"the idle loop will just run indefinitely # The exception thrown should protect",
"refresh_interval to a high value r.set_refresh_interval(10) assert(r.refresh_interval == 10) assert(r.sleep_time == 0.1) #",
"cm.switch_to_context(cm.fallback_context) assert(cm.current_context == cm.fallback_context) e1 = Event() e2 = Event() cm.register_context_target(\"test1\", e1.wait) cm.register_context_target(\"test2\",",
"to normal assert(r.iterations_before_refresh == 100) def test_update_keymap(self): i = get_mock_input() o = get_mock_output()",
"to activate\"\"\" c = Context(\"test_context\", lambda *a, **k: True) try: c.activate() except ContextError:",
"\"\"\"tests context class\"\"\" def test_constructor(self): \"\"\"Tests constructor\"\"\" c = Context(\"test_context\", lambda *a, **k:",
"objects are app-accessible, # we can't really rely on them staying the same",
"\"\"\"Tests whether a target-less threaded context fails to activate\"\"\" c = Context(\"test_context\", lambda",
"the assert will trigger a test failure, # or the idle loop will",
"ContextManager, Context, ContextError class TestContext(unittest.TestCase): \"\"\"tests context class\"\"\" def test_constructor(self): \"\"\"Tests constructor\"\"\" c",
"assert(cm.current_context == \"test1\") assert(cm.get_previous_context(\"test1\") == \"test2\") #Setting events so that threads exit e1.set()",
"Context(\"test_context\", lambda *a, **k: True) self.assertIsNotNone(c) def test_threading(self): \"\"\"Tests whether threaded and non-threaded",
"*a, **k: True) try: c.activate() except ContextError: pass else: raise AssertionError # After",
"e2.set() assert(cm.current_context == cm.fallback_context) def test_failsafe_fallback_on_thread_fail(self): cm = ContextManager() cm.fallback_context = \"m\" cm.initial_contexts",
"ContextError class TestContext(unittest.TestCase): \"\"\"tests context class\"\"\" def test_constructor(self): \"\"\"Tests constructor\"\"\" c = Context(\"test_context\",",
"#Implicitly creates initial contexts for context_alias, context in cm.contexts.items(): assert(context_alias in cm.initial_contexts) assert(context)",
"**k: True) try: c.activate() except ContextError: pass else: raise AssertionError # After marking",
"for the thread to exit finished.wait() assert(cm.current_context == cm.fallback_context) def test_targetless_context_switching(self): \"\"\"Tests that",
"i.set_keymap.call_count == 1 #paused, so count shouldn't change i.set_keymap(None) assert i.set_keymap.call_args[0][0] != r.keymap",
"== 2 #not paused r.pause() r.idle_loop() assert o.display_data.call_count == 2 #paused, so count",
"= Event() finished = Event() c.signal_finished = finished.set c.threaded = False # Need",
"really rely on them staying the same del c1.i c1.signal_finished = lambda: True",
"10) # Refresh intervals up until 0.1 don't change the sleep time r.set_refresh_interval(0.1)",
"# Store original __import__ orig_import = __import__ def import_mock(name, *args, **kwargs): if name",
"\"\"\"Tests whether threaded and non-threaded contexts behave as they should\"\"\" c = Context(\"test_context\",",
"cm.switch_to_context(cm.fallback_context) c1 = cm.create_context(\"t1\") c2 = cm.create_context(\"t2\") e1 = Event() e2 = Event()",
"r.resume() assert i.set_keymap.call_count == 3 #one explicitly done in the test right beforehand",
"cm.register_context_target(\"t1\", e1.wait) cm.register_context_target(\"t2\", e2.wait) cm.switch_to_context(\"t1\") # Removing c1.set_target(None) del c1.thread c1.signal_finished = lambda:",
"0.1 don't change the sleep time r.set_refresh_interval(0.1) assert(r.refresh_interval == 0.1) assert(r.sleep_time == 0.1)",
"e1.wait) cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\") finished = Event() def new_signal_finished(): c.event_cb(c.name, \"finished\") finished.set()",
"# Setting events so that threads exit e1.set() e2.set() assert(cm.current_context == cm.fallback_context) def",
"def test_basic_context_switching(self): \"\"\"Tests whether basic context switching works\"\"\" cm = ContextManager() cm.initial_contexts =",
"True del c2.i # Both current and new contexts are fucked up cm.switch_to_context(\"t2\")",
"cm.fallback_context) cm.switch_to_context(\"test2\") assert(cm.current_context == \"test2\") assert(cm.get_previous_context(\"test2\") == \"test1\") cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\") assert(cm.get_previous_context(\"test1\")",
"will trigger a test failure, # or the idle loop will just run",
"unittest.main() \"\"\" def test_left_key_exits(self): r = Refresher(lambda: \"Hello\", get_mock_input(), get_mock_output(), name=r_name) r.refresh =",
"shouldn't change r.resume() assert o.display_data.call_count == 3 #resume() refreshes the display r.idle_loop() assert",
"assert(not finished.isSet()) c.threaded = True c.set_target(e.set) c.activate() finished.wait() assert(e.isSet()) def test_targetless_threaded_context(self): \"\"\"Tests whether",
"c = cm.create_context(\"test1\") cm.register_context_target(\"test1\", e1.wait) cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\") finished = Event() def",
"= get_mock_output() r = Refresher(lambda: \"Hello\", i, o, name=r_name) def scenario(): r.refresh() r.deactivate()",
"== r.keymap def test_set_interval(self): i = get_mock_input() o = get_mock_output() r = Refresher(lambda:",
"#and idle_loop always refreshes #Doing what an activate() would do, but without a",
"['helpers'] and not kwargs: #Have to filter for kwargs since there's a package",
"**k: True) self.assertIsNotNone(c) def test_threading(self): \"\"\"Tests whether threaded and non-threaded contexts behave as",
"cm.create_context(\"test1\") assert(cm.current_context == cm.fallback_context) cm.switch_to_context(\"test1\") assert(cm.current_context == cm.fallback_context) def test_failsafe_fallback_on_io_fail(self): cm = ContextManager()",
"switching works\"\"\" cm = ContextManager() cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) e1 = Event() c =",
"o.display_data.called assert o.display_data.call_count == 1 #to_foreground calls refresh() r.idle_loop() assert o.display_data.call_count == 2",
"r.keymap def test_set_interval(self): i = get_mock_input() o = get_mock_output() r = Refresher(lambda: \"Hello\",",
"the same del c1.i c1.signal_finished = lambda: True del c2.i # Both current",
"3 #resume() refreshes the display r.idle_loop() assert o.display_data.call_count == 4 #should be refresh",
"test_update_keymap(self): i = get_mock_input() o = get_mock_output() r = Refresher(lambda: \"Hello\", i, o,",
"def new_signal_finished(): c.event_cb(c.name, \"finished\") finished.set() with patch.object(c, 'signal_finished', side_effect=new_signal_finished) as p: e1.set() #Waiting",
"c2.set_target(None) # Again, switcing to the fucked up context cm.switch_to_context(\"t2\") # Setting events",
"r.set_refresh_interval(0.01) assert(r.refresh_interval == 0.01) assert(r.sleep_time == 0.01) assert(r.iterations_before_refresh == 1) # Now setting",
"Event() def new_signal_finished(): c.event_cb(c.name, \"finished\") finished.set() with patch.object(c, 'signal_finished', side_effect=new_signal_finished) as p: e1.set()",
"r.refresh() r.deactivate() with patch.object(r, 'idle_loop', side_effect=scenario) as p: r.activate() #The scenario should only",
"#One in to_foreground, and one in patched idle_loop assert o.display_data.call_args_list[0][0] == (\"Hello\", )",
"the fucked up context cm.switch_to_context(\"t2\") # Setting events so that threads exit e1.set()",
"== cm.fallback_context) e1 = Event() e2 = Event() cm.register_context_target(\"test1\", e1.wait) cm.register_context_target(\"test2\", e2.wait) cm.switch_to_context(\"test1\")",
"interval r.set_refresh_interval(0.01) assert(r.refresh_interval == 0.01) assert(r.sleep_time == 0.01) assert(r.iterations_before_refresh == 1) # Now",
"p: e1.set() #Waiting for the thread to exit finished.wait() assert(cm.current_context == cm.fallback_context) def",
"Store original __import__ orig_import = __import__ def import_mock(name, *args, **kwargs): if name in",
"is 0.1 so that _counter always stays 0 #and idle_loop always refreshes #Doing",
"Any ideas? Maybe use some kind of \"timeout\" library? def scenario(): r.keymap[\"KEY_LEFT\"]() assert",
"o.display_data.call_count == 2 #One in to_foreground, and one in patched idle_loop assert o.display_data.call_args_list[0][0]",
"name in ['helpers'] and not kwargs: #Have to filter for kwargs since there's",
"= lambda *args, **kwargs: None r.to_foreground() assert i.set_keymap.called assert i.set_keymap.call_count == 1 assert",
"\"KEY_LEFT\" in r.keymap r.pause() assert i.set_keymap.call_count == 1 #paused, so count shouldn't change",
"name=r_name, refresh_interval=0.1) #refresh_interval is 0.1 so that _counter always stays 0 #and idle_loop",
"keymap1 = {\"KEY_LEFT\": lambda:1} r.update_keymap(keymap1) assert(r.keymap == keymap1) keymap2 = {\"KEY_RIGHT\": lambda:2} r.update_keymap(keymap2)",
"# Refresh intervals up until 0.1 don't change the sleep time r.set_refresh_interval(0.1) assert(r.refresh_interval",
"assert o.display_data.call_count == 1 #to_foreground calls refresh() r.idle_loop() assert o.display_data.call_count == 2 #not",
"cm.init_io(Mock(), Mock()) #Implicitly creates initial contexts for context_alias, context in cm.contexts.items(): assert(context_alias in",
"try: from context_manager import ContextManager, Context, ContextError except ImportError: print(\"Absolute imports failed, trying",
"a validation check fails c.activate() assert(not e.isSet()) assert(not finished.isSet()) c.threaded = True c.set_target(e.set)",
"works\"\"\" cm = ContextManager() cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) e1 = Event() c = cm.create_context(\"test1\")",
"context_manager import ContextManager, Context, ContextError except ImportError: print(\"Absolute imports failed, trying relative imports\")",
"r.to_foreground() assert o.display_data.called assert o.display_data.call_count == 1 #to_foreground calls refresh() r.idle_loop() assert o.display_data.call_count",
"set # Any ideas? Maybe use some kind of \"timeout\" library? def scenario():",
"del c1.i c1.signal_finished = lambda: True del c2.i # Both current and new",
"e2.wait) cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\") assert(cm.get_previous_context(\"test1\") == cm.fallback_context) cm.switch_to_context(\"test2\") assert(cm.current_context == \"test2\") assert(cm.get_previous_context(\"test2\")",
"The exception thrown should protect from the latter raise KeyboardInterrupt with patch.object(r, 'idle_loop',",
"scenario(): r.keymap[\"KEY_LEFT\"]() assert not r.in_foreground # If the test fails, either the assert",
"to filter for kwargs since there's a package in 'json' #that calls __builtins__.__import__",
"= [cm.fallback_context, \"test1\", \"test2\"] cm.init_io(Mock(), Mock()) assert(cm.current_context is None) cm.switch_to_context(cm.fallback_context) assert(cm.current_context == cm.fallback_context)",
"raise AssertionError # After marking context as non-threaded, it should activate OK c.threaded",
"test_constructor(self): \"\"\"Tests constructor\"\"\" c = Context(\"test_context\", lambda *a, **k: True) self.assertIsNotNone(c) def test_threading(self):",
"are wrapped and we can't test equivalence with patch.object(r, 'process_callback', side_effect=lambda keymap:keymap) as",
"the test fails, either the assert will trigger a test failure, # or",
"== 2 #paused, so count shouldn't change r.resume() assert o.display_data.call_count == 3 #resume()",
"whether the Refresher exits # It only tests whether the in_foreground attribute is",
"not r.in_foreground # If the test fails, either the assert will trigger a",
"return orig_import(name, *args, **kwargs) with patch('__builtin__.__import__', side_effect=import_mock): from context_manager import ContextManager, Context, ContextError",
"r.keymap assert \"KEY_LEFT\" in r.keymap r.pause() assert i.set_keymap.call_count == 1 #paused, so count",
"should protect from the latter raise KeyboardInterrupt with patch.object(r, 'idle_loop', side_effect=scenario) as p:",
"will just run indefinitely # The exception thrown should protect from the latter",
"= ContextManager() cm.initial_contexts = [cm.fallback_context, \"test1\", \"test2\"] cm.init_io(Mock(), Mock()) assert(cm.current_context is None) cm.switch_to_context(cm.fallback_context)",
"beforehand assert i.set_keymap.call_args[0][0] == r.keymap def test_set_interval(self): i = get_mock_input() o = get_mock_output()",
"def test_set_interval(self): i = get_mock_input() o = get_mock_output() r = Refresher(lambda: \"Hello\", i,",
"Mock try: from context_manager import ContextManager, Context, ContextError except ImportError: print(\"Absolute imports failed,",
"we can't really rely on them staying the same del c1.i c1.signal_finished =",
"**k: True) e = Event() finished = Event() c.signal_finished = finished.set c.threaded =",
"as they should\"\"\" c = Context(\"test_context\", lambda *a, **k: True) e = Event()",
"patched idle_loop assert o.display_data.call_args_list[0][0] == (\"Hello\", ) assert o.display_data.call_args_list[1][0] == (\"Hello\", ) def",
"assert i.set_keymap.call_args[0][0] != r.keymap r.resume() assert i.set_keymap.call_count == 3 #one explicitly done in",
"orig_import(name, *args, **kwargs) with patch('__builtin__.__import__', side_effect=import_mock): from context_manager import ContextManager, Context, ContextError class",
"cm.initial_contexts) assert(context) def test_basic_context_switching(self): \"\"\"Tests whether basic context switching works\"\"\" cm = ContextManager()",
"assert r.idle_loop.call_count == 1 assert o.display_data.called assert o.display_data.call_count == 2 #One in to_foreground,",
"new contexts are fucked up cm.switch_to_context(\"t2\") # Setting events so that threads exit",
"lambda *a, **k: True) try: c.activate() except ContextError: pass else: raise AssertionError #",
"e1 = Event() e2 = Event() cm.register_context_target(\"test1\", e1.wait) cm.register_context_target(\"test2\", e2.wait) cm.switch_to_context(\"test1\") assert(cm.current_context ==",
"finished.set() with patch.object(c, 'signal_finished', side_effect=new_signal_finished) as p: e1.set() #Waiting for the thread to",
"#refresh_interval is 0.1 so that _counter always stays 0 #and idle_loop always refreshes",
"== 0.01) assert(r.sleep_time == 0.01) assert(r.iterations_before_refresh == 1) # Now setting refresh_interval to",
"= {\"KEY_LEFT\": lambda:1} r.update_keymap(keymap1) assert(r.keymap == keymap1) keymap2 = {\"KEY_RIGHT\": lambda:2} r.update_keymap(keymap2) keymap2.update(keymap1)",
"trigger a test failure, # or the idle loop will just run indefinitely",
"is set # Any ideas? Maybe use some kind of \"timeout\" library? def",
"that threads exit e1.set() e2.set() def test_context_switching_on_context_finish(self): \"\"\"Tests whether basic context switching works\"\"\"",
"marking context as non-threaded, it should activate OK c.threaded = False try: c.activate()",
"test_initial_contexts(self): \"\"\"Tests whether initial contexts are getting created\"\"\" cm = ContextManager() cm.init_io(Mock(), Mock())",
"assert(not e.isSet()) assert(not finished.isSet()) c.threaded = True c.set_target(e.set) c.activate() finished.wait() assert(e.isSet()) def test_targetless_threaded_context(self):",
"to_foreground, and one in patched idle_loop assert o.display_data.call_args_list[0][0] == (\"Hello\", ) assert o.display_data.call_args_list[1][0]",
"r = Refresher(lambda: \"Hello\", i, o, name=r_name) def scenario(): r.refresh() r.deactivate() with patch.object(r,",
"for kwargs since there's a package in 'json' #that calls __builtins__.__import__ with keyword",
"succeeded def test_shows_data_on_screen(self): i = get_mock_input() o = get_mock_output() r = Refresher(lambda: \"Hello\",",
"== 10) # Refresh intervals up until 0.1 don't change the sleep time",
"# Now setting refresh_interval to a high value r.set_refresh_interval(10) assert(r.refresh_interval == 10) assert(r.sleep_time",
"once assert r.idle_loop.called assert r.idle_loop.call_count == 1 assert o.display_data.called assert o.display_data.call_count == 2",
"0.1) assert(r.sleep_time == 0.1) assert(r.iterations_before_refresh == 1) # Refresh intervals less than 0.1",
"== 1 assert o.display_data.called assert o.display_data.call_count == 2 #One in to_foreground, and one",
"assert o.display_data.call_count == 2 #paused, so count shouldn't change r.resume() assert o.display_data.call_count ==",
"exit e1.set() e2.set() assert(cm.current_context == cm.fallback_context) if __name__ == '__main__': unittest.main() \"\"\" def",
"to patch \"process_callback\" because otherwise the keymap callbacks # are wrapped and we",
"cm = ContextManager() cm.init_io(Mock(), Mock()) #Implicitly creates initial contexts for context_alias, context in",
"#Test succeeded def test_shows_data_on_screen(self): i = get_mock_input() o = get_mock_output() r = Refresher(lambda:",
"AssertionError # After marking context as non-threaded, it should activate OK c.threaded =",
"e2.set() def test_context_switching_on_context_finish(self): \"\"\"Tests whether basic context switching works\"\"\" cm = ContextManager() cm.init_io(Mock(),",
"r.to_foreground() assert i.set_keymap.called assert i.set_keymap.call_count == 1 assert i.set_keymap.call_args[0][0] == r.keymap assert \"KEY_LEFT\"",
"are getting created\"\"\" cm = ContextManager() cm.init_io(Mock(), Mock()) #Implicitly creates initial contexts for",
"are fucked up cm.switch_to_context(\"t2\") # Setting events so that threads exit e1.set() e2.set()",
"assert o.display_data.call_args_list[0][0] == (\"Hello\", ) assert o.display_data.call_args_list[1][0] == (\"Hello\", ) def test_pause_resume(self): i",
"whether initial contexts are getting created\"\"\" cm = ContextManager() cm.init_io(Mock(), Mock()) #Implicitly creates",
"Mock()) cm.switch_to_context(cm.fallback_context) c1 = cm.create_context(\"t1\") c2 = cm.create_context(\"t2\") e1 = Event() e2 =",
"finished = Event() c.signal_finished = finished.set c.threaded = False # Need to set",
"in_foreground attribute is set # Any ideas? Maybe use some kind of \"timeout\"",
"\"Hello\", get_mock_input(), get_mock_output(), name=r_name) r.refresh = lambda *args, **kwargs: None # This test",
") assert o.display_data.call_args_list[1][0] == (\"Hello\", ) def test_pause_resume(self): i = get_mock_input() o =",
"refresh_interval=0.1) #refresh_interval is 0.1 so that _counter always stays 0 #and idle_loop always",
"i, o, name=r_name, refresh_interval=0.1) r.refresh = lambda *args, **kwargs: None r.to_foreground() assert i.set_keymap.called",
"'__main__': unittest.main() \"\"\" def test_left_key_exits(self): r = Refresher(lambda: \"Hello\", get_mock_input(), get_mock_output(), name=r_name) r.refresh",
"assert(r.sleep_time == 0.1) assert(r.iterations_before_refresh == 1) # Refresh intervals less than 0.1 change",
"cm.switch_to_context(\"t1\") # Removing c1.set_target(None) del c1.thread c1.signal_finished = lambda: True c2.set_target(None) # Again,",
"a target-less context fails\"\"\" cm = ContextManager() cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) cm.create_context(\"test1\") assert(cm.current_context ==",
"kwargs: #Have to filter for kwargs since there's a package in 'json' #that",
"1) assert(r.sleep_time == 0.1) assert(r.iterations_before_refresh == 10) # Refresh intervals up until 0.1",
"r.idle_loop.called assert r.idle_loop.call_count == 1 assert o.display_data.called assert o.display_data.call_count == 2 #One in",
"cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) cm.create_context(\"test1\") assert(cm.current_context == cm.fallback_context) cm.switch_to_context(\"test1\") assert(cm.current_context == cm.fallback_context) def test_failsafe_fallback_on_io_fail(self):",
"to exit finished.wait() assert(cm.current_context == cm.fallback_context) def test_targetless_context_switching(self): \"\"\"Tests that switching to a",
"= Event() e2 = Event() cm.register_context_target(\"t1\", e1.wait) cm.register_context_target(\"t2\", e2.wait) cm.switch_to_context(\"t1\") # Removing c1.set_target(None)",
"so count shouldn't change r.resume() assert o.display_data.call_count == 3 #resume() refreshes the display",
"display r.idle_loop() assert o.display_data.call_count == 4 #should be refresh the display normally now",
"events so that threads exit e1.set() e2.set() def test_context_switching_on_context_finish(self): \"\"\"Tests whether basic context",
"o.display_data.call_count == 1 #to_foreground calls refresh() r.idle_loop() assert o.display_data.call_count == 2 #not paused",
"= Event() cm.register_context_target(\"t1\", e1.wait) cm.register_context_target(\"t2\", e2.wait) cm.switch_to_context(\"t1\") # Fucking things up - since",
"*args, **kwargs: None # We need to patch \"process_callback\" because otherwise the keymap",
"from threading import Event from mock import patch, Mock try: from context_manager import",
"in cm.initial_contexts) assert(context) def test_basic_context_switching(self): \"\"\"Tests whether basic context switching works\"\"\" cm =",
"else: pass class TestContextManager(unittest.TestCase): \"\"\"tests context manager class and interaction between contexts\"\"\" def",
"e1.set() e2.set() def test_context_switching_on_context_finish(self): \"\"\"Tests whether basic context switching works\"\"\" cm = ContextManager()",
"the latter raise KeyboardInterrupt with patch.object(r, 'idle_loop', side_effect=scenario) as p: try: r.activate() except",
"refresh the display normally now def test_keymap_restore_on_resume(self): i = get_mock_input() o = get_mock_output()",
"r = Refresher(lambda: \"Hello\", i, o, name=r_name, refresh_interval=0.1) r.refresh = lambda *args, **kwargs:",
"Refresh intervals up until 0.1 don't change the sleep time r.set_refresh_interval(0.1) assert(r.refresh_interval ==",
"= Event() c = cm.create_context(\"test1\") cm.register_context_target(\"test1\", e1.wait) cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\") finished =",
"'idle_loop', side_effect=scenario) as p: r.activate() #The scenario should only be called once assert",
"exit e1.set() e2.set() assert(cm.current_context == cm.fallback_context) def test_failsafe_fallback_on_thread_fail(self): cm = ContextManager() cm.fallback_context =",
"test_set_interval(self): i = get_mock_input() o = get_mock_output() r = Refresher(lambda: \"Hello\", i, o,",
"0.1) assert(r.iterations_before_refresh == 1) # Refresh intervals less than 0.1 change sleep_time to",
"= Event() def new_signal_finished(): c.event_cb(c.name, \"finished\") finished.set() with patch.object(c, 'signal_finished', side_effect=new_signal_finished) as p:",
"pass #Test succeeded def test_shows_data_on_screen(self): i = get_mock_input() o = get_mock_output() r =",
"called once assert r.idle_loop.called assert r.idle_loop.call_count == 1 assert o.display_data.called assert o.display_data.call_count ==",
"count shouldn't change i.set_keymap(None) assert i.set_keymap.call_args[0][0] != r.keymap r.resume() assert i.set_keymap.call_count == 3",
"initial contexts for context_alias, context in cm.contexts.items(): assert(context_alias in cm.initial_contexts) assert(context) def test_basic_context_switching(self):",
"0 #and idle_loop always refreshes #Doing what an activate() would do, but without",
"def test_constructor(self): \"\"\"Tests constructor\"\"\" cm = ContextManager() self.assertIsNotNone(cm) def test_initial_contexts(self): \"\"\"Tests whether initial",
"(\"Hello\", ) assert o.display_data.call_args_list[1][0] == (\"Hello\", ) def test_pause_resume(self): i = get_mock_input() o",
"be called once assert r.idle_loop.called assert r.idle_loop.call_count == 1 assert o.display_data.called assert o.display_data.call_count",
"= False # Need to set this flag, otherwise a validation check fails",
"0.01) assert(r.iterations_before_refresh == 1) # Now setting refresh_interval to a high value r.set_refresh_interval(10)",
"need to patch \"process_callback\" because otherwise the keymap callbacks # are wrapped and",
"cm.register_context_target(\"test1\", e1.wait) cm.register_context_target(\"test2\", e2.wait) cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\") assert(cm.get_previous_context(\"test1\") == cm.fallback_context) cm.switch_to_context(\"test2\") assert(cm.current_context",
"behave as they should\"\"\" c = Context(\"test_context\", lambda *a, **k: True) e =",
"- since context objects are app-accessible, # we can't really rely on them",
"c.activate() assert(not e.isSet()) assert(not finished.isSet()) c.threaded = True c.set_target(e.set) c.activate() finished.wait() assert(e.isSet()) def",
"get_mock_input() o = get_mock_output() r = Refresher(lambda: \"Hello\", i, o, name=r_name, refresh_interval=0.1) #refresh_interval",
"assert(r.sleep_time == 0.01) assert(r.iterations_before_refresh == 1) # Now setting refresh_interval to a high",
"assert(cm.current_context == cm.fallback_context) def test_targetless_context_switching(self): \"\"\"Tests that switching to a target-less context fails\"\"\"",
"= get_mock_output() r = Refresher(lambda: \"Hello\", i, o, name=r_name, refresh_interval=0.1) r.refresh = lambda",
"\"Hello\", i, o, name=r_name, refresh_interval=0.1) r.refresh = lambda *args, **kwargs: None # We",
"with patch.object(r, 'process_callback', side_effect=lambda keymap:keymap) as p: keymap1 = {\"KEY_LEFT\": lambda:1} r.update_keymap(keymap1) assert(r.keymap",
"test_context_switching_on_context_finish(self): \"\"\"Tests whether basic context switching works\"\"\" cm = ContextManager() cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context)",
"e2.wait) cm.switch_to_context(\"t1\") # Fucking things up - since context objects are app-accessible, #",
"raise KeyboardInterrupt with patch.object(r, 'idle_loop', side_effect=scenario) as p: try: r.activate() except KeyboardInterrupt: pass",
"{\"KEY_LEFT\": lambda:1} r.update_keymap(keymap1) assert(r.keymap == keymap1) keymap2 = {\"KEY_RIGHT\": lambda:2} r.update_keymap(keymap2) keymap2.update(keymap1) assert(r.keymap",
"# Back to normal assert(r.iterations_before_refresh == 100) def test_update_keymap(self): i = get_mock_input() o",
"imports failed, trying relative imports\") os.sys.path.append(os.path.dirname(os.path.abspath('.'))) # Store original __import__ orig_import = __import__",
"raise AssertionError else: pass class TestContextManager(unittest.TestCase): \"\"\"tests context manager class and interaction between",
"value r.set_refresh_interval(10) assert(r.refresh_interval == 10) assert(r.sleep_time == 0.1) # Back to normal assert(r.iterations_before_refresh",
"the sleep time r.set_refresh_interval(0.1) assert(r.refresh_interval == 0.1) assert(r.sleep_time == 0.1) assert(r.iterations_before_refresh == 1)",
"indefinitely # The exception thrown should protect from the latter raise KeyboardInterrupt with",
"can't test equivalence with patch.object(r, 'process_callback', side_effect=lambda keymap:keymap) as p: keymap1 = {\"KEY_LEFT\":",
"non-threaded, it should activate OK c.threaded = False try: c.activate() except: raise AssertionError",
"= cm.create_context(\"t2\") e1 = Event() e2 = Event() cm.register_context_target(\"t1\", e1.wait) cm.register_context_target(\"t2\", e2.wait) cm.switch_to_context(\"t1\")",
"just run indefinitely # The exception thrown should protect from the latter raise",
"finished.wait() assert(cm.current_context == cm.fallback_context) def test_targetless_context_switching(self): \"\"\"Tests that switching to a target-less context",
"same del c1.i c1.signal_finished = lambda: True del c2.i # Both current and",
"def test_update_keymap(self): i = get_mock_input() o = get_mock_output() r = Refresher(lambda: \"Hello\", i,",
"non-threaded contexts behave as they should\"\"\" c = Context(\"test_context\", lambda *a, **k: True)",
"and one in patched idle_loop assert o.display_data.call_args_list[0][0] == (\"Hello\", ) assert o.display_data.call_args_list[1][0] ==",
"p: keymap1 = {\"KEY_LEFT\": lambda:1} r.update_keymap(keymap1) assert(r.keymap == keymap1) keymap2 = {\"KEY_RIGHT\": lambda:2}",
"#and we don't want to mock that call return Mock() return orig_import(name, *args,",
"assert(r.refresh_interval == 0.01) assert(r.sleep_time == 0.01) assert(r.iterations_before_refresh == 1) # Now setting refresh_interval",
"refresh interval r.set_refresh_interval(0.01) assert(r.refresh_interval == 0.01) assert(r.sleep_time == 0.01) assert(r.iterations_before_refresh == 1) #",
"cm.register_context_target(\"test2\", e2.wait) cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\") assert(cm.get_previous_context(\"test1\") == cm.fallback_context) cm.switch_to_context(\"test2\") assert(cm.current_context == \"test2\")",
"assert(cm.current_context == \"test1\") finished = Event() def new_signal_finished(): c.event_cb(c.name, \"finished\") finished.set() with patch.object(c,",
"i.set_keymap.called assert i.set_keymap.call_count == 1 assert i.set_keymap.call_args[0][0] == r.keymap assert \"KEY_LEFT\" in r.keymap",
"Fucking things up - since context objects are app-accessible, # we can't really",
"r.deactivate() with patch.object(r, 'idle_loop', side_effect=scenario) as p: r.activate() #The scenario should only be",
"ContextError: pass else: raise AssertionError # After marking context as non-threaded, it should",
"assert \"KEY_LEFT\" in r.keymap r.pause() assert i.set_keymap.call_count == 1 #paused, so count shouldn't",
"so that _counter always stays 0 #and idle_loop always refreshes #Doing what an",
"a package in 'json' #that calls __builtins__.__import__ with keyword arguments #and we don't",
"is None) cm.switch_to_context(cm.fallback_context) assert(cm.current_context == cm.fallback_context) e1 = Event() e2 = Event() cm.register_context_target(\"test1\",",
"in ['helpers'] and not kwargs: #Have to filter for kwargs since there's a",
"i.set_keymap.call_args[0][0] == r.keymap def test_set_interval(self): i = get_mock_input() o = get_mock_output() r =",
"fails\"\"\" cm = ContextManager() cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) cm.create_context(\"test1\") assert(cm.current_context == cm.fallback_context) cm.switch_to_context(\"test1\") assert(cm.current_context",
"done in the test right beforehand assert i.set_keymap.call_args[0][0] == r.keymap def test_set_interval(self): i",
"== 1) assert(r.sleep_time == 0.1) assert(r.iterations_before_refresh == 10) # Refresh intervals up until",
"o.display_data.called assert o.display_data.call_count == 2 #One in to_foreground, and one in patched idle_loop",
"threads exit e1.set() e2.set() assert(cm.current_context == cm.fallback_context) def test_failsafe_fallback_on_thread_fail(self): cm = ContextManager() cm.fallback_context",
"TestContext(unittest.TestCase): \"\"\"tests context class\"\"\" def test_constructor(self): \"\"\"Tests constructor\"\"\" c = Context(\"test_context\", lambda *a,",
"and non-threaded contexts behave as they should\"\"\" c = Context(\"test_context\", lambda *a, **k:",
"'json' #that calls __builtins__.__import__ with keyword arguments #and we don't want to mock",
"until 0.1 don't change the sleep time r.set_refresh_interval(0.1) assert(r.refresh_interval == 0.1) assert(r.sleep_time ==",
"assert(cm.current_context == cm.fallback_context) def test_failsafe_fallback_on_thread_fail(self): cm = ContextManager() cm.fallback_context = \"m\" cm.initial_contexts =",
"fucked up cm.switch_to_context(\"t2\") # Setting events so that threads exit e1.set() e2.set() assert(cm.current_context",
"#resume() refreshes the display r.idle_loop() assert o.display_data.call_count == 4 #should be refresh the",
"want to mock that call return Mock() return orig_import(name, *args, **kwargs) with patch('__builtin__.__import__',",
"contexts are getting created\"\"\" cm = ContextManager() cm.init_io(Mock(), Mock()) #Implicitly creates initial contexts",
"in cm.contexts.items(): assert(context_alias in cm.initial_contexts) assert(context) def test_basic_context_switching(self): \"\"\"Tests whether basic context switching",
"\"test1\") assert(cm.get_previous_context(\"test1\") == cm.fallback_context) cm.switch_to_context(\"test2\") assert(cm.current_context == \"test2\") assert(cm.get_previous_context(\"test2\") == \"test1\") cm.switch_to_context(\"test1\") assert(cm.current_context",
"def test_targetless_context_switching(self): \"\"\"Tests that switching to a target-less context fails\"\"\" cm = ContextManager()",
"cm.register_context_target(\"t2\", e2.wait) cm.switch_to_context(\"t1\") # Removing c1.set_target(None) del c1.thread c1.signal_finished = lambda: True c2.set_target(None)",
"run indefinitely # The exception thrown should protect from the latter raise KeyboardInterrupt",
"to match refresh interval r.set_refresh_interval(0.01) assert(r.refresh_interval == 0.01) assert(r.sleep_time == 0.01) assert(r.iterations_before_refresh ==",
"cm.register_context_target(\"t2\", e2.wait) cm.switch_to_context(\"t1\") # Fucking things up - since context objects are app-accessible,",
"e1.set() e2.set() assert(cm.current_context == cm.fallback_context) def test_failsafe_fallback_on_thread_fail(self): cm = ContextManager() cm.fallback_context = \"m\"",
"del c2.i # Both current and new contexts are fucked up cm.switch_to_context(\"t2\") #",
"since context objects are app-accessible, # we can't really rely on them staying",
"== 4 #should be refresh the display normally now def test_keymap_restore_on_resume(self): i =",
"== r.keymap assert \"KEY_LEFT\" in r.keymap r.pause() assert i.set_keymap.call_count == 1 #paused, so",
"0.1) # Back to normal assert(r.iterations_before_refresh == 100) def test_update_keymap(self): i = get_mock_input()",
"finished.set c.threaded = False # Need to set this flag, otherwise a validation",
"otherwise the keymap callbacks # are wrapped and we can't test equivalence with",
"exit finished.wait() assert(cm.current_context == cm.fallback_context) def test_targetless_context_switching(self): \"\"\"Tests that switching to a target-less",
"normal assert(r.iterations_before_refresh == 100) def test_update_keymap(self): i = get_mock_input() o = get_mock_output() r",
"== \"test2\") #Setting events so that threads exit e1.set() e2.set() def test_context_switching_on_context_finish(self): \"\"\"Tests",
"r.set_refresh_interval(0.1) assert(r.refresh_interval == 0.1) assert(r.sleep_time == 0.1) assert(r.iterations_before_refresh == 1) # Refresh intervals",
"try: c.activate() except ContextError: pass else: raise AssertionError # After marking context as",
"r.idle_loop.call_count == 1 assert o.display_data.called assert o.display_data.call_count == 2 #One in to_foreground, and",
"name=r_name, refresh_interval=1) assert(r.refresh_interval == 1) assert(r.sleep_time == 0.1) assert(r.iterations_before_refresh == 10) # Refresh",
"test failure, # or the idle loop will just run indefinitely # The",
"keyword arguments #and we don't want to mock that call return Mock() return",
"cm.initial_contexts = [\"m\"] cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) c1 = cm.create_context(\"t1\") c2 = cm.create_context(\"t2\") e1",
"r.pause() assert i.set_keymap.call_count == 1 #paused, so count shouldn't change i.set_keymap(None) assert i.set_keymap.call_args[0][0]",
"*args, **kwargs: None r.to_foreground() assert i.set_keymap.called assert i.set_keymap.call_count == 1 assert i.set_keymap.call_args[0][0] ==",
"r.idle_loop() assert o.display_data.call_count == 4 #should be refresh the display normally now def",
"assert o.display_data.called assert o.display_data.call_count == 2 #One in to_foreground, and one in patched",
"from context_manager import ContextManager, Context, ContextError class TestContext(unittest.TestCase): \"\"\"tests context class\"\"\" def test_constructor(self):",
"assert(cm.get_previous_context(\"test1\") == cm.fallback_context) cm.switch_to_context(\"test2\") assert(cm.current_context == \"test2\") assert(cm.get_previous_context(\"test2\") == \"test1\") cm.switch_to_context(\"test1\") assert(cm.current_context ==",
"Event() cm.register_context_target(\"test1\", e1.wait) cm.register_context_target(\"test2\", e2.wait) cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\") assert(cm.get_previous_context(\"test1\") == cm.fallback_context) cm.switch_to_context(\"test2\")",
"# Refresh intervals less than 0.1 change sleep_time to match refresh interval r.set_refresh_interval(0.01)",
"setting refresh_interval to a high value r.set_refresh_interval(10) assert(r.refresh_interval == 10) assert(r.sleep_time == 0.1)",
"test_left_key_exits(self): r = Refresher(lambda: \"Hello\", get_mock_input(), get_mock_output(), name=r_name) r.refresh = lambda *args, **kwargs:",
"Maybe use some kind of \"timeout\" library? def scenario(): r.keymap[\"KEY_LEFT\"]() assert not r.in_foreground",
"os import unittest from threading import Event from mock import patch, Mock try:",
"scenario(): r.refresh() r.deactivate() with patch.object(r, 'idle_loop', side_effect=scenario) as p: r.activate() #The scenario should",
"created\"\"\" cm = ContextManager() cm.init_io(Mock(), Mock()) #Implicitly creates initial contexts for context_alias, context",
"1 assert i.set_keymap.call_args[0][0] == r.keymap assert \"KEY_LEFT\" in r.keymap r.pause() assert i.set_keymap.call_count ==",
"== (\"Hello\", ) def test_pause_resume(self): i = get_mock_input() o = get_mock_output() r =",
"test_targetless_threaded_context(self): \"\"\"Tests whether a target-less threaded context fails to activate\"\"\" c = Context(\"test_context\",",
"r.idle_loop() assert o.display_data.call_count == 2 #paused, so count shouldn't change r.resume() assert o.display_data.call_count",
"Setting events so that threads exit e1.set() e2.set() assert(cm.current_context == cm.fallback_context) if __name__",
"1) # Refresh intervals less than 0.1 change sleep_time to match refresh interval",
"arguments #and we don't want to mock that call return Mock() return orig_import(name,",
"loop r.to_foreground() assert o.display_data.called assert o.display_data.call_count == 1 #to_foreground calls refresh() r.idle_loop() assert",
"r.keymap r.pause() assert i.set_keymap.call_count == 1 #paused, so count shouldn't change i.set_keymap(None) assert",
"= \"m\" cm.initial_contexts = [\"m\"] cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) c1 = cm.create_context(\"t1\") c2 =",
"assert will trigger a test failure, # or the idle loop will just",
"Event() e2 = Event() cm.register_context_target(\"t1\", e1.wait) cm.register_context_target(\"t2\", e2.wait) cm.switch_to_context(\"t1\") # Removing c1.set_target(None) del",
"and we can't test equivalence with patch.object(r, 'process_callback', side_effect=lambda keymap:keymap) as p: keymap1",
"tests whether the in_foreground attribute is set # Any ideas? Maybe use some",
"up context cm.switch_to_context(\"t2\") # Setting events so that threads exit e1.set() e2.set() assert(cm.current_context",
"things up - since context objects are app-accessible, # we can't really rely",
"o = get_mock_output() r = Refresher(lambda: \"Hello\", i, o, name=r_name, refresh_interval=0.1) #refresh_interval is",
"Need to set this flag, otherwise a validation check fails c.activate() assert(not e.isSet())",
"cm.fallback_context) def test_failsafe_fallback_on_io_fail(self): cm = ContextManager() cm.fallback_context = \"m\" cm.initial_contexts = [\"m\"] cm.init_io(Mock(),",
"change sleep_time to match refresh interval r.set_refresh_interval(0.01) assert(r.refresh_interval == 0.01) assert(r.sleep_time == 0.01)",
"always refreshes #Doing what an activate() would do, but without a loop r.to_foreground()",
"thread to exit finished.wait() assert(cm.current_context == cm.fallback_context) def test_targetless_context_switching(self): \"\"\"Tests that switching to",
"r.activate() #The scenario should only be called once assert r.idle_loop.called assert r.idle_loop.call_count ==",
"assert(r.sleep_time == 0.1) assert(r.iterations_before_refresh == 10) # Refresh intervals up until 0.1 don't",
"kwargs since there's a package in 'json' #that calls __builtins__.__import__ with keyword arguments",
"e2 = Event() cm.register_context_target(\"t1\", e1.wait) cm.register_context_target(\"t2\", e2.wait) cm.switch_to_context(\"t1\") # Removing c1.set_target(None) del c1.thread",
"but without a loop r.to_foreground() assert o.display_data.called assert o.display_data.call_count == 1 #to_foreground calls",
"e2 = Event() cm.register_context_target(\"test1\", e1.wait) cm.register_context_target(\"test2\", e2.wait) cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\") assert(cm.get_previous_context(\"test1\") ==",
"# Any ideas? Maybe use some kind of \"timeout\" library? def scenario(): r.keymap[\"KEY_LEFT\"]()",
"cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) c1 = cm.create_context(\"t1\") c2 = cm.create_context(\"t2\") e1 = Event() e2",
"match refresh interval r.set_refresh_interval(0.01) assert(r.refresh_interval == 0.01) assert(r.sleep_time == 0.01) assert(r.iterations_before_refresh == 1)",
"r.refresh = lambda *args, **kwargs: None # This test doesn't actually test whether",
"'signal_finished', side_effect=new_signal_finished) as p: e1.set() #Waiting for the thread to exit finished.wait() assert(cm.current_context",
"We need to patch \"process_callback\" because otherwise the keymap callbacks # are wrapped",
"cm = ContextManager() cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) cm.create_context(\"test1\") assert(cm.current_context == cm.fallback_context) cm.switch_to_context(\"test1\") assert(cm.current_context ==",
"r.resume() assert o.display_data.call_count == 3 #resume() refreshes the display r.idle_loop() assert o.display_data.call_count ==",
"cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) e1 = Event() c = cm.create_context(\"test1\") cm.register_context_target(\"test1\", e1.wait) cm.switch_to_context(\"test1\") assert(cm.current_context",
"test_shows_data_on_screen(self): i = get_mock_input() o = get_mock_output() r = Refresher(lambda: \"Hello\", i, o,",
"*args, **kwargs) with patch('__builtin__.__import__', side_effect=import_mock): from context_manager import ContextManager, Context, ContextError class TestContext(unittest.TestCase):",
"True) e = Event() finished = Event() c.signal_finished = finished.set c.threaded = False",
"up cm.switch_to_context(\"t2\") # Setting events so that threads exit e1.set() e2.set() assert(cm.current_context ==",
"assert(cm.current_context == cm.fallback_context) cm.switch_to_context(\"test1\") assert(cm.current_context == cm.fallback_context) def test_failsafe_fallback_on_io_fail(self): cm = ContextManager() cm.fallback_context",
"of \"timeout\" library? def scenario(): r.keymap[\"KEY_LEFT\"]() assert not r.in_foreground # If the test",
"c = Context(\"test_context\", lambda *a, **k: True) self.assertIsNotNone(c) def test_threading(self): \"\"\"Tests whether threaded",
"import ContextManager, Context, ContextError except ImportError: print(\"Absolute imports failed, trying relative imports\") os.sys.path.append(os.path.dirname(os.path.abspath('.')))",
"class and interaction between contexts\"\"\" def test_constructor(self): \"\"\"Tests constructor\"\"\" cm = ContextManager() self.assertIsNotNone(cm)",
"context switching works\"\"\" cm = ContextManager() cm.initial_contexts = [cm.fallback_context, \"test1\", \"test2\"] cm.init_io(Mock(), Mock())",
"== (\"Hello\", ) assert o.display_data.call_args_list[1][0] == (\"Hello\", ) def test_pause_resume(self): i = get_mock_input()",
"#paused, so count shouldn't change i.set_keymap(None) assert i.set_keymap.call_args[0][0] != r.keymap r.resume() assert i.set_keymap.call_count",
"if name in ['helpers'] and not kwargs: #Have to filter for kwargs since",
"set this flag, otherwise a validation check fails c.activate() assert(not e.isSet()) assert(not finished.isSet())",
"Event from mock import patch, Mock try: from context_manager import ContextManager, Context, ContextError",
"e2 = Event() cm.register_context_target(\"t1\", e1.wait) cm.register_context_target(\"t2\", e2.wait) cm.switch_to_context(\"t1\") # Fucking things up -",
"refresh_interval=1) assert(r.refresh_interval == 1) assert(r.sleep_time == 0.1) assert(r.iterations_before_refresh == 10) # Refresh intervals",
"assert i.set_keymap.called assert i.set_keymap.call_count == 1 assert i.set_keymap.call_args[0][0] == r.keymap assert \"KEY_LEFT\" in",
"__import__ orig_import = __import__ def import_mock(name, *args, **kwargs): if name in ['helpers'] and",
"assert(cm.current_context == cm.fallback_context) e1 = Event() e2 = Event() cm.register_context_target(\"test1\", e1.wait) cm.register_context_target(\"test2\", e2.wait)",
"Event() c = cm.create_context(\"test1\") cm.register_context_target(\"test1\", e1.wait) cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\") finished = Event()",
"some kind of \"timeout\" library? def scenario(): r.keymap[\"KEY_LEFT\"]() assert not r.in_foreground # If",
"use some kind of \"timeout\" library? def scenario(): r.keymap[\"KEY_LEFT\"]() assert not r.in_foreground #",
"keymap:keymap) as p: keymap1 = {\"KEY_LEFT\": lambda:1} r.update_keymap(keymap1) assert(r.keymap == keymap1) keymap2 =",
"getting created\"\"\" cm = ContextManager() cm.init_io(Mock(), Mock()) #Implicitly creates initial contexts for context_alias,",
"display normally now def test_keymap_restore_on_resume(self): i = get_mock_input() o = get_mock_output() r =",
"= Context(\"test_context\", lambda *a, **k: True) try: c.activate() except ContextError: pass else: raise",
"= lambda *args, **kwargs: None # We need to patch \"process_callback\" because otherwise",
"#The scenario should only be called once assert r.idle_loop.called assert r.idle_loop.call_count == 1",
"get_mock_input(), get_mock_output(), name=r_name) r.refresh = lambda *args, **kwargs: None # This test doesn't",
"a loop r.to_foreground() assert o.display_data.called assert o.display_data.call_count == 1 #to_foreground calls refresh() r.idle_loop()",
"0.1 so that _counter always stays 0 #and idle_loop always refreshes #Doing what",
"Refresher(lambda: \"Hello\", i, o, name=r_name, refresh_interval=1) assert(r.refresh_interval == 1) assert(r.sleep_time == 0.1) assert(r.iterations_before_refresh",
"class\"\"\" def test_constructor(self): \"\"\"Tests constructor\"\"\" c = Context(\"test_context\", lambda *a, **k: True) self.assertIsNotNone(c)",
"Event() cm.register_context_target(\"t1\", e1.wait) cm.register_context_target(\"t2\", e2.wait) cm.switch_to_context(\"t1\") # Removing c1.set_target(None) del c1.thread c1.signal_finished =",
"cm.switch_to_context(cm.fallback_context) e1 = Event() c = cm.create_context(\"test1\") cm.register_context_target(\"test1\", e1.wait) cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\")",
"import patch, Mock try: from context_manager import ContextManager, Context, ContextError except ImportError: print(\"Absolute",
"cm.initial_contexts = [cm.fallback_context, \"test1\", \"test2\"] cm.init_io(Mock(), Mock()) assert(cm.current_context is None) cm.switch_to_context(cm.fallback_context) assert(cm.current_context ==",
"threading import Event from mock import patch, Mock try: from context_manager import ContextManager,",
"unittest from threading import Event from mock import patch, Mock try: from context_manager",
"o, name=r_name, refresh_interval=0.1) r.refresh = lambda *args, **kwargs: None # We need to",
"context switching works\"\"\" cm = ContextManager() cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) e1 = Event() c",
"'process_callback', side_effect=lambda keymap:keymap) as p: keymap1 = {\"KEY_LEFT\": lambda:1} r.update_keymap(keymap1) assert(r.keymap == keymap1)",
"\"\"\"tests context manager class and interaction between contexts\"\"\" def test_constructor(self): \"\"\"Tests constructor\"\"\" cm",
"**kwargs: None r.to_foreground() assert i.set_keymap.called assert i.set_keymap.call_count == 1 assert i.set_keymap.call_args[0][0] == r.keymap",
"c.set_target(e.set) c.activate() finished.wait() assert(e.isSet()) def test_targetless_threaded_context(self): \"\"\"Tests whether a target-less threaded context fails",
"in r.keymap r.pause() assert i.set_keymap.call_count == 1 #paused, so count shouldn't change i.set_keymap(None)",
"else: raise AssertionError # After marking context as non-threaded, it should activate OK",
"get_mock_output() r = Refresher(lambda: \"Hello\", i, o, name=r_name, refresh_interval=0.1) r.refresh = lambda *args,",
"paused r.pause() r.idle_loop() assert o.display_data.call_count == 2 #paused, so count shouldn't change r.resume()",
"== \"test1\") finished = Event() def new_signal_finished(): c.event_cb(c.name, \"finished\") finished.set() with patch.object(c, 'signal_finished',",
"failure, # or the idle loop will just run indefinitely # The exception",
"== '__main__': unittest.main() \"\"\" def test_left_key_exits(self): r = Refresher(lambda: \"Hello\", get_mock_input(), get_mock_output(), name=r_name)",
"assert(r.refresh_interval == 10) assert(r.sleep_time == 0.1) # Back to normal assert(r.iterations_before_refresh == 100)",
"Mock()) cm.switch_to_context(cm.fallback_context) e1 = Event() c = cm.create_context(\"test1\") cm.register_context_target(\"test1\", e1.wait) cm.switch_to_context(\"test1\") assert(cm.current_context ==",
"explicitly done in the test right beforehand assert i.set_keymap.call_args[0][0] == r.keymap def test_set_interval(self):",
"False # Need to set this flag, otherwise a validation check fails c.activate()",
"contexts for context_alias, context in cm.contexts.items(): assert(context_alias in cm.initial_contexts) assert(context) def test_basic_context_switching(self): \"\"\"Tests",
"the test right beforehand assert i.set_keymap.call_args[0][0] == r.keymap def test_set_interval(self): i = get_mock_input()",
"test right beforehand assert i.set_keymap.call_args[0][0] == r.keymap def test_set_interval(self): i = get_mock_input() o",
"mock import patch, Mock try: from context_manager import ContextManager, Context, ContextError except ImportError:",
"Context(\"test_context\", lambda *a, **k: True) try: c.activate() except ContextError: pass else: raise AssertionError",
"otherwise a validation check fails c.activate() assert(not e.isSet()) assert(not finished.isSet()) c.threaded = True",
"100) def test_update_keymap(self): i = get_mock_input() o = get_mock_output() r = Refresher(lambda: \"Hello\",",
"0.1 change sleep_time to match refresh interval r.set_refresh_interval(0.01) assert(r.refresh_interval == 0.01) assert(r.sleep_time ==",
"between contexts\"\"\" def test_constructor(self): \"\"\"Tests constructor\"\"\" cm = ContextManager() self.assertIsNotNone(cm) def test_initial_contexts(self): \"\"\"Tests",
"\"test1\", \"test2\"] cm.init_io(Mock(), Mock()) assert(cm.current_context is None) cm.switch_to_context(cm.fallback_context) assert(cm.current_context == cm.fallback_context) e1 =",
"== 1 #paused, so count shouldn't change i.set_keymap(None) assert i.set_keymap.call_args[0][0] != r.keymap r.resume()",
"whether basic context switching works\"\"\" cm = ContextManager() cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) e1 =",
"should\"\"\" c = Context(\"test_context\", lambda *a, **k: True) e = Event() finished =",
"__builtins__.__import__ with keyword arguments #and we don't want to mock that call return",
"to set this flag, otherwise a validation check fails c.activate() assert(not e.isSet()) assert(not",
"sleep time r.set_refresh_interval(0.1) assert(r.refresh_interval == 0.1) assert(r.sleep_time == 0.1) assert(r.iterations_before_refresh == 1) #",
"c.threaded = True c.set_target(e.set) c.activate() finished.wait() assert(e.isSet()) def test_targetless_threaded_context(self): \"\"\"Tests whether a target-less",
"idle_loop always refreshes #Doing what an activate() would do, but without a loop",
"#one explicitly done in the test right beforehand assert i.set_keymap.call_args[0][0] == r.keymap def",
"context manager class and interaction between contexts\"\"\" def test_constructor(self): \"\"\"Tests constructor\"\"\" cm =",
"This test doesn't actually test whether the Refresher exits # It only tests",
"cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\") finished = Event() def new_signal_finished(): c.event_cb(c.name, \"finished\") finished.set() with",
"creates initial contexts for context_alias, context in cm.contexts.items(): assert(context_alias in cm.initial_contexts) assert(context) def",
"def test_initial_contexts(self): \"\"\"Tests whether initial contexts are getting created\"\"\" cm = ContextManager() cm.init_io(Mock(),",
"cm = ContextManager() self.assertIsNotNone(cm) def test_initial_contexts(self): \"\"\"Tests whether initial contexts are getting created\"\"\"",
"# or the idle loop will just run indefinitely # The exception thrown",
"threads exit e1.set() e2.set() assert(cm.current_context == cm.fallback_context) if __name__ == '__main__': unittest.main() \"\"\"",
"context class\"\"\" def test_constructor(self): \"\"\"Tests constructor\"\"\" c = Context(\"test_context\", lambda *a, **k: True)",
"cm = ContextManager() cm.fallback_context = \"m\" cm.initial_contexts = [\"m\"] cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) c1",
"test_failsafe_fallback_on_thread_fail(self): cm = ContextManager() cm.fallback_context = \"m\" cm.initial_contexts = [\"m\"] cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context)",
"call return Mock() return orig_import(name, *args, **kwargs) with patch('__builtin__.__import__', side_effect=import_mock): from context_manager import",
"= Refresher(lambda: \"Hello\", get_mock_input(), get_mock_output(), name=r_name) r.refresh = lambda *args, **kwargs: None #",
"# Again, switcing to the fucked up context cm.switch_to_context(\"t2\") # Setting events so",
"import_mock(name, *args, **kwargs): if name in ['helpers'] and not kwargs: #Have to filter",
"lambda: True c2.set_target(None) # Again, switcing to the fucked up context cm.switch_to_context(\"t2\") #",
"as p: r.activate() #The scenario should only be called once assert r.idle_loop.called assert",
"threaded and non-threaded contexts behave as they should\"\"\" c = Context(\"test_context\", lambda *a,",
"c.threaded = False # Need to set this flag, otherwise a validation check",
"e1.wait) cm.register_context_target(\"test2\", e2.wait) cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\") assert(cm.get_previous_context(\"test1\") == cm.fallback_context) cm.switch_to_context(\"test2\") assert(cm.current_context ==",
"**kwargs) with patch('__builtin__.__import__', side_effect=import_mock): from context_manager import ContextManager, Context, ContextError class TestContext(unittest.TestCase): \"\"\"tests",
"from the latter raise KeyboardInterrupt with patch.object(r, 'idle_loop', side_effect=scenario) as p: try: r.activate()",
"== cm.fallback_context) def test_failsafe_fallback_on_io_fail(self): cm = ContextManager() cm.fallback_context = \"m\" cm.initial_contexts = [\"m\"]",
"c.activate() finished.wait() assert(e.isSet()) def test_targetless_threaded_context(self): \"\"\"Tests whether a target-less threaded context fails to",
"target-less threaded context fails to activate\"\"\" c = Context(\"test_context\", lambda *a, **k: True)",
"o.display_data.call_count == 2 #not paused r.pause() r.idle_loop() assert o.display_data.call_count == 2 #paused, so",
"Refresher(lambda: \"Hello\", i, o, name=r_name) def scenario(): r.refresh() r.deactivate() with patch.object(r, 'idle_loop', side_effect=scenario)",
"idle_loop assert o.display_data.call_args_list[0][0] == (\"Hello\", ) assert o.display_data.call_args_list[1][0] == (\"Hello\", ) def test_pause_resume(self):",
"None # This test doesn't actually test whether the Refresher exits # It",
"fails to activate\"\"\" c = Context(\"test_context\", lambda *a, **k: True) try: c.activate() except",
"refresh() r.idle_loop() assert o.display_data.call_count == 2 #not paused r.pause() r.idle_loop() assert o.display_data.call_count ==",
"False try: c.activate() except: raise AssertionError else: pass class TestContextManager(unittest.TestCase): \"\"\"tests context manager",
"test_pause_resume(self): i = get_mock_input() o = get_mock_output() r = Refresher(lambda: \"Hello\", i, o,",
"Mock() return orig_import(name, *args, **kwargs) with patch('__builtin__.__import__', side_effect=import_mock): from context_manager import ContextManager, Context,",
"objects\"\"\" import os import unittest from threading import Event from mock import patch,",
"True) try: c.activate() except ContextError: pass else: raise AssertionError # After marking context",
"= cm.create_context(\"test1\") cm.register_context_target(\"test1\", e1.wait) cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\") finished = Event() def new_signal_finished():",
"cm.switch_to_context(\"test2\") assert(cm.current_context == \"test2\") assert(cm.get_previous_context(\"test2\") == \"test1\") cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\") assert(cm.get_previous_context(\"test1\") ==",
"o = get_mock_output() r = Refresher(lambda: \"Hello\", i, o, name=r_name, refresh_interval=1) assert(r.refresh_interval ==",
"= Refresher(lambda: \"Hello\", i, o, name=r_name, refresh_interval=0.1) #refresh_interval is 0.1 so that _counter",
"to a target-less context fails\"\"\" cm = ContextManager() cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) cm.create_context(\"test1\") assert(cm.current_context",
"except KeyboardInterrupt: pass #Test succeeded def test_shows_data_on_screen(self): i = get_mock_input() o = get_mock_output()",
"# After marking context as non-threaded, it should activate OK c.threaded = False",
"e1 = Event() e2 = Event() cm.register_context_target(\"t1\", e1.wait) cm.register_context_target(\"t2\", e2.wait) cm.switch_to_context(\"t1\") # Fucking",
"we can't test equivalence with patch.object(r, 'process_callback', side_effect=lambda keymap:keymap) as p: keymap1 =",
"as non-threaded, it should activate OK c.threaded = False try: c.activate() except: raise",
"2 #paused, so count shouldn't change r.resume() assert o.display_data.call_count == 3 #resume() refreshes",
"True c.set_target(e.set) c.activate() finished.wait() assert(e.isSet()) def test_targetless_threaded_context(self): \"\"\"Tests whether a target-less threaded context",
"i, o, name=r_name) def scenario(): r.refresh() r.deactivate() with patch.object(r, 'idle_loop', side_effect=scenario) as p:",
"self.assertIsNotNone(c) def test_threading(self): \"\"\"Tests whether threaded and non-threaded contexts behave as they should\"\"\"",
"count shouldn't change r.resume() assert o.display_data.call_count == 3 #resume() refreshes the display r.idle_loop()",
"cm.fallback_context) def test_failsafe_fallback_on_thread_fail(self): cm = ContextManager() cm.fallback_context = \"m\" cm.initial_contexts = [\"m\"] cm.init_io(Mock(),",
"def test_keymap_restore_on_resume(self): i = get_mock_input() o = get_mock_output() r = Refresher(lambda: \"Hello\", i,",
"so count shouldn't change i.set_keymap(None) assert i.set_keymap.call_args[0][0] != r.keymap r.resume() assert i.set_keymap.call_count ==",
"c1.set_target(None) del c1.thread c1.signal_finished = lambda: True c2.set_target(None) # Again, switcing to the",
"in patched idle_loop assert o.display_data.call_args_list[0][0] == (\"Hello\", ) assert o.display_data.call_args_list[1][0] == (\"Hello\", )",
"one in patched idle_loop assert o.display_data.call_args_list[0][0] == (\"Hello\", ) assert o.display_data.call_args_list[1][0] == (\"Hello\",",
"\"timeout\" library? def scenario(): r.keymap[\"KEY_LEFT\"]() assert not r.in_foreground # If the test fails,",
"they should\"\"\" c = Context(\"test_context\", lambda *a, **k: True) e = Event() finished",
"== cm.fallback_context) if __name__ == '__main__': unittest.main() \"\"\" def test_left_key_exits(self): r = Refresher(lambda:",
"#Setting events so that threads exit e1.set() e2.set() def test_context_switching_on_context_finish(self): \"\"\"Tests whether basic",
"def test_context_switching_on_context_finish(self): \"\"\"Tests whether basic context switching works\"\"\" cm = ContextManager() cm.init_io(Mock(), Mock())",
"cm.register_context_target(\"t1\", e1.wait) cm.register_context_target(\"t2\", e2.wait) cm.switch_to_context(\"t1\") # Fucking things up - since context objects",
"i, o, name=r_name, refresh_interval=0.1) r.refresh = lambda *args, **kwargs: None # We need",
"a target-less threaded context fails to activate\"\"\" c = Context(\"test_context\", lambda *a, **k:",
"for context_alias, context in cm.contexts.items(): assert(context_alias in cm.initial_contexts) assert(context) def test_basic_context_switching(self): \"\"\"Tests whether",
"without a loop r.to_foreground() assert o.display_data.called assert o.display_data.call_count == 1 #to_foreground calls refresh()",
"Event() e2 = Event() cm.register_context_target(\"t1\", e1.wait) cm.register_context_target(\"t2\", e2.wait) cm.switch_to_context(\"t1\") # Fucking things up",
"# If the test fails, either the assert will trigger a test failure,",
"finished.isSet()) c.threaded = True c.set_target(e.set) c.activate() finished.wait() assert(e.isSet()) def test_targetless_threaded_context(self): \"\"\"Tests whether a",
"change i.set_keymap(None) assert i.set_keymap.call_args[0][0] != r.keymap r.resume() assert i.set_keymap.call_count == 3 #one explicitly",
"assert(e.isSet()) def test_targetless_threaded_context(self): \"\"\"Tests whether a target-less threaded context fails to activate\"\"\" c",
"patch \"process_callback\" because otherwise the keymap callbacks # are wrapped and we can't",
"latter raise KeyboardInterrupt with patch.object(r, 'idle_loop', side_effect=scenario) as p: try: r.activate() except KeyboardInterrupt:",
"Context(\"test_context\", lambda *a, **k: True) e = Event() finished = Event() c.signal_finished =",
"r.refresh = lambda *args, **kwargs: None # We need to patch \"process_callback\" because",
"original __import__ orig_import = __import__ def import_mock(name, *args, **kwargs): if name in ['helpers']",
"because otherwise the keymap callbacks # are wrapped and we can't test equivalence",
"import Event from mock import patch, Mock try: from context_manager import ContextManager, Context,",
"activate\"\"\" c = Context(\"test_context\", lambda *a, **k: True) try: c.activate() except ContextError: pass",
"p: try: r.activate() except KeyboardInterrupt: pass #Test succeeded def test_shows_data_on_screen(self): i = get_mock_input()",
"than 0.1 change sleep_time to match refresh interval r.set_refresh_interval(0.01) assert(r.refresh_interval == 0.01) assert(r.sleep_time",
"patch, Mock try: from context_manager import ContextManager, Context, ContextError except ImportError: print(\"Absolute imports",
"whether threaded and non-threaded contexts behave as they should\"\"\" c = Context(\"test_context\", lambda",
"\"test2\") assert(cm.get_previous_context(\"test2\") == \"test1\") cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\") assert(cm.get_previous_context(\"test1\") == \"test2\") #Setting events",
"cm.register_context_target(\"test1\", e1.wait) cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\") finished = Event() def new_signal_finished(): c.event_cb(c.name, \"finished\")",
"\"\"\"Tests whether basic context switching works\"\"\" cm = ContextManager() cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) e1",
"actually test whether the Refresher exits # It only tests whether the in_foreground",
"refreshes #Doing what an activate() would do, but without a loop r.to_foreground() assert",
"= ContextManager() cm.init_io(Mock(), Mock()) #Implicitly creates initial contexts for context_alias, context in cm.contexts.items():",
"finished = Event() def new_signal_finished(): c.event_cb(c.name, \"finished\") finished.set() with patch.object(c, 'signal_finished', side_effect=new_signal_finished) as",
"e.isSet()) assert(not finished.isSet()) c.threaded = True c.set_target(e.set) c.activate() finished.wait() assert(e.isSet()) def test_targetless_threaded_context(self): \"\"\"Tests",
"doesn't actually test whether the Refresher exits # It only tests whether the",
"test whether the Refresher exits # It only tests whether the in_foreground attribute",
"test equivalence with patch.object(r, 'process_callback', side_effect=lambda keymap:keymap) as p: keymap1 = {\"KEY_LEFT\": lambda:1}",
"try: r.activate() except KeyboardInterrupt: pass #Test succeeded def test_shows_data_on_screen(self): i = get_mock_input() o",
"pass else: raise AssertionError # After marking context as non-threaded, it should activate",
"== 1 #to_foreground calls refresh() r.idle_loop() assert o.display_data.call_count == 2 #not paused r.pause()",
"def test_constructor(self): \"\"\"Tests constructor\"\"\" c = Context(\"test_context\", lambda *a, **k: True) self.assertIsNotNone(c) def",
"switching works\"\"\" cm = ContextManager() cm.initial_contexts = [cm.fallback_context, \"test1\", \"test2\"] cm.init_io(Mock(), Mock()) assert(cm.current_context",
"contexts are fucked up cm.switch_to_context(\"t2\") # Setting events so that threads exit e1.set()",
"kind of \"timeout\" library? def scenario(): r.keymap[\"KEY_LEFT\"]() assert not r.in_foreground # If the",
"o, name=r_name) def scenario(): r.refresh() r.deactivate() with patch.object(r, 'idle_loop', side_effect=scenario) as p: r.activate()",
"failed, trying relative imports\") os.sys.path.append(os.path.dirname(os.path.abspath('.'))) # Store original __import__ orig_import = __import__ def",
"import os import unittest from threading import Event from mock import patch, Mock",
"#should be refresh the display normally now def test_keymap_restore_on_resume(self): i = get_mock_input() o",
"== 1) # Now setting refresh_interval to a high value r.set_refresh_interval(10) assert(r.refresh_interval ==",
"= lambda: True c2.set_target(None) # Again, switcing to the fucked up context cm.switch_to_context(\"t2\")",
"\"Hello\", i, o, name=r_name) def scenario(): r.refresh() r.deactivate() with patch.object(r, 'idle_loop', side_effect=scenario) as",
"\"Hello\", i, o, name=r_name, refresh_interval=0.1) r.refresh = lambda *args, **kwargs: None r.to_foreground() assert",
"# The exception thrown should protect from the latter raise KeyboardInterrupt with patch.object(r,",
"name=r_name, refresh_interval=0.1) r.refresh = lambda *args, **kwargs: None r.to_foreground() assert i.set_keymap.called assert i.set_keymap.call_count",
"#Have to filter for kwargs since there's a package in 'json' #that calls",
"assert(r.iterations_before_refresh == 1) # Refresh intervals less than 0.1 change sleep_time to match",
"refresh_interval=0.1) r.refresh = lambda *args, **kwargs: None r.to_foreground() assert i.set_keymap.called assert i.set_keymap.call_count ==",
"**kwargs): if name in ['helpers'] and not kwargs: #Have to filter for kwargs",
"cm.create_context(\"t1\") c2 = cm.create_context(\"t2\") e1 = Event() e2 = Event() cm.register_context_target(\"t1\", e1.wait) cm.register_context_target(\"t2\",",
"!= r.keymap r.resume() assert i.set_keymap.call_count == 3 #one explicitly done in the test",
"fails, either the assert will trigger a test failure, # or the idle",
"intervals up until 0.1 don't change the sleep time r.set_refresh_interval(0.1) assert(r.refresh_interval == 0.1)",
"relative imports\") os.sys.path.append(os.path.dirname(os.path.abspath('.'))) # Store original __import__ orig_import = __import__ def import_mock(name, *args,",
"the Refresher exits # It only tests whether the in_foreground attribute is set",
"= Context(\"test_context\", lambda *a, **k: True) e = Event() finished = Event() c.signal_finished",
"fucked up context cm.switch_to_context(\"t2\") # Setting events so that threads exit e1.set() e2.set()",
"= Refresher(lambda: \"Hello\", i, o, name=r_name) def scenario(): r.refresh() r.deactivate() with patch.object(r, 'idle_loop',",
"to mock that call return Mock() return orig_import(name, *args, **kwargs) with patch('__builtin__.__import__', side_effect=import_mock):",
"o.display_data.call_args_list[1][0] == (\"Hello\", ) def test_pause_resume(self): i = get_mock_input() o = get_mock_output() r",
"time r.set_refresh_interval(0.1) assert(r.refresh_interval == 0.1) assert(r.sleep_time == 0.1) assert(r.iterations_before_refresh == 1) # Refresh",
"= Refresher(lambda: \"Hello\", i, o, name=r_name, refresh_interval=0.1) r.refresh = lambda *args, **kwargs: None",
"shouldn't change i.set_keymap(None) assert i.set_keymap.call_args[0][0] != r.keymap r.resume() assert i.set_keymap.call_count == 3 #one",
"for Context and ContextManager objects\"\"\" import os import unittest from threading import Event",
"1 assert o.display_data.called assert o.display_data.call_count == 2 #One in to_foreground, and one in",
"assert(cm.get_previous_context(\"test1\") == \"test2\") #Setting events so that threads exit e1.set() e2.set() def test_context_switching_on_context_finish(self):",
"get_mock_input() o = get_mock_output() r = Refresher(lambda: \"Hello\", i, o, name=r_name, refresh_interval=1) assert(r.refresh_interval",
"except: raise AssertionError else: pass class TestContextManager(unittest.TestCase): \"\"\"tests context manager class and interaction",
"Mock()) #Implicitly creates initial contexts for context_alias, context in cm.contexts.items(): assert(context_alias in cm.initial_contexts)",
"the display r.idle_loop() assert o.display_data.call_count == 4 #should be refresh the display normally",
"assert(r.refresh_interval == 0.1) assert(r.sleep_time == 0.1) assert(r.iterations_before_refresh == 1) # Refresh intervals less",
"== 3 #resume() refreshes the display r.idle_loop() assert o.display_data.call_count == 4 #should be",
"# Need to set this flag, otherwise a validation check fails c.activate() assert(not",
"4 #should be refresh the display normally now def test_keymap_restore_on_resume(self): i = get_mock_input()",
"assert i.set_keymap.call_args[0][0] == r.keymap assert \"KEY_LEFT\" in r.keymap r.pause() assert i.set_keymap.call_count == 1",
"get_mock_output(), name=r_name) r.refresh = lambda *args, **kwargs: None # This test doesn't actually",
"do, but without a loop r.to_foreground() assert o.display_data.called assert o.display_data.call_count == 1 #to_foreground",
"Mock()) cm.switch_to_context(cm.fallback_context) cm.create_context(\"test1\") assert(cm.current_context == cm.fallback_context) cm.switch_to_context(\"test1\") assert(cm.current_context == cm.fallback_context) def test_failsafe_fallback_on_io_fail(self): cm",
"with keyword arguments #and we don't want to mock that call return Mock()",
"threaded context fails to activate\"\"\" c = Context(\"test_context\", lambda *a, **k: True) try:",
"KeyboardInterrupt with patch.object(r, 'idle_loop', side_effect=scenario) as p: try: r.activate() except KeyboardInterrupt: pass #Test",
"== 1) # Refresh intervals less than 0.1 change sleep_time to match refresh",
"i = get_mock_input() o = get_mock_output() r = Refresher(lambda: \"Hello\", i, o, name=r_name,",
"get_mock_input() o = get_mock_output() r = Refresher(lambda: \"Hello\", i, o, name=r_name) def scenario():",
"context cm.switch_to_context(\"t2\") # Setting events so that threads exit e1.set() e2.set() assert(cm.current_context ==",
"# are wrapped and we can't test equivalence with patch.object(r, 'process_callback', side_effect=lambda keymap:keymap)",
"events so that threads exit e1.set() e2.set() assert(cm.current_context == cm.fallback_context) def test_failsafe_fallback_on_thread_fail(self): cm",
"target-less context fails\"\"\" cm = ContextManager() cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) cm.create_context(\"test1\") assert(cm.current_context == cm.fallback_context)",
"p: r.activate() #The scenario should only be called once assert r.idle_loop.called assert r.idle_loop.call_count",
"up - since context objects are app-accessible, # we can't really rely on",
"from mock import patch, Mock try: from context_manager import ContextManager, Context, ContextError except",
"imports\") os.sys.path.append(os.path.dirname(os.path.abspath('.'))) # Store original __import__ orig_import = __import__ def import_mock(name, *args, **kwargs):",
"test doesn't actually test whether the Refresher exits # It only tests whether",
"in to_foreground, and one in patched idle_loop assert o.display_data.call_args_list[0][0] == (\"Hello\", ) assert",
"activate() would do, but without a loop r.to_foreground() assert o.display_data.called assert o.display_data.call_count ==",
"refreshes the display r.idle_loop() assert o.display_data.call_count == 4 #should be refresh the display",
"patch.object(r, 'process_callback', side_effect=lambda keymap:keymap) as p: keymap1 = {\"KEY_LEFT\": lambda:1} r.update_keymap(keymap1) assert(r.keymap ==",
"= [\"m\"] cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) c1 = cm.create_context(\"t1\") c2 = cm.create_context(\"t2\") e1 =",
"= Event() c.signal_finished = finished.set c.threaded = False # Need to set this",
"package in 'json' #that calls __builtins__.__import__ with keyword arguments #and we don't want",
"lambda *a, **k: True) e = Event() finished = Event() c.signal_finished = finished.set",
"constructor\"\"\" cm = ContextManager() self.assertIsNotNone(cm) def test_initial_contexts(self): \"\"\"Tests whether initial contexts are getting",
"contexts behave as they should\"\"\" c = Context(\"test_context\", lambda *a, **k: True) e",
"protect from the latter raise KeyboardInterrupt with patch.object(r, 'idle_loop', side_effect=scenario) as p: try:",
"only be called once assert r.idle_loop.called assert r.idle_loop.call_count == 1 assert o.display_data.called assert",
"context objects are app-accessible, # we can't really rely on them staying the",
"if __name__ == '__main__': unittest.main() \"\"\" def test_left_key_exits(self): r = Refresher(lambda: \"Hello\", get_mock_input(),",
"attribute is set # Any ideas? Maybe use some kind of \"timeout\" library?",
"assert o.display_data.call_args_list[1][0] == (\"Hello\", ) def test_pause_resume(self): i = get_mock_input() o = get_mock_output()",
"<reponame>LouisPi/PiPortableRecorder \"\"\"tests for Context and ContextManager objects\"\"\" import os import unittest from threading",
"== 2 #One in to_foreground, and one in patched idle_loop assert o.display_data.call_args_list[0][0] ==",
"on them staying the same del c1.i c1.signal_finished = lambda: True del c2.i",
"Context, ContextError except ImportError: print(\"Absolute imports failed, trying relative imports\") os.sys.path.append(os.path.dirname(os.path.abspath('.'))) # Store",
"test_targetless_context_switching(self): \"\"\"Tests that switching to a target-less context fails\"\"\" cm = ContextManager() cm.init_io(Mock(),",
"the display normally now def test_keymap_restore_on_resume(self): i = get_mock_input() o = get_mock_output() r",
"def test_failsafe_fallback_on_thread_fail(self): cm = ContextManager() cm.fallback_context = \"m\" cm.initial_contexts = [\"m\"] cm.init_io(Mock(), Mock())",
"cm.contexts.items(): assert(context_alias in cm.initial_contexts) assert(context) def test_basic_context_switching(self): \"\"\"Tests whether basic context switching works\"\"\"",
"i.set_keymap.call_count == 1 assert i.set_keymap.call_args[0][0] == r.keymap assert \"KEY_LEFT\" in r.keymap r.pause() assert",
"should activate OK c.threaded = False try: c.activate() except: raise AssertionError else: pass",
"*a, **k: True) self.assertIsNotNone(c) def test_threading(self): \"\"\"Tests whether threaded and non-threaded contexts behave",
"Event() e2 = Event() cm.register_context_target(\"test1\", e1.wait) cm.register_context_target(\"test2\", e2.wait) cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\") assert(cm.get_previous_context(\"test1\")",
"Refresher(lambda: \"Hello\", i, o, name=r_name, refresh_interval=0.1) #refresh_interval is 0.1 so that _counter always",
"lambda:1} r.update_keymap(keymap1) assert(r.keymap == keymap1) keymap2 = {\"KEY_RIGHT\": lambda:2} r.update_keymap(keymap2) keymap2.update(keymap1) assert(r.keymap ==",
"trying relative imports\") os.sys.path.append(os.path.dirname(os.path.abspath('.'))) # Store original __import__ orig_import = __import__ def import_mock(name,",
"test_keymap_restore_on_resume(self): i = get_mock_input() o = get_mock_output() r = Refresher(lambda: \"Hello\", i, o,",
"wrapped and we can't test equivalence with patch.object(r, 'process_callback', side_effect=lambda keymap:keymap) as p:",
"ContextManager() cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) e1 = Event() c = cm.create_context(\"test1\") cm.register_context_target(\"test1\", e1.wait) cm.switch_to_context(\"test1\")",
"# Setting events so that threads exit e1.set() e2.set() assert(cm.current_context == cm.fallback_context) if",
"except ContextError: pass else: raise AssertionError # After marking context as non-threaded, it",
"\"Hello\", i, o, name=r_name, refresh_interval=1) assert(r.refresh_interval == 1) assert(r.sleep_time == 0.1) assert(r.iterations_before_refresh ==",
"assert i.set_keymap.call_count == 3 #one explicitly done in the test right beforehand assert",
"o = get_mock_output() r = Refresher(lambda: \"Hello\", i, o, name=r_name) def scenario(): r.refresh()",
"assert(r.sleep_time == 0.1) # Back to normal assert(r.iterations_before_refresh == 100) def test_update_keymap(self): i",
"the in_foreground attribute is set # Any ideas? Maybe use some kind of",
"lambda: True del c2.i # Both current and new contexts are fucked up",
"cm = ContextManager() cm.initial_contexts = [cm.fallback_context, \"test1\", \"test2\"] cm.init_io(Mock(), Mock()) assert(cm.current_context is None)",
"assert(cm.current_context == cm.fallback_context) if __name__ == '__main__': unittest.main() \"\"\" def test_left_key_exits(self): r =",
"either the assert will trigger a test failure, # or the idle loop",
"c = Context(\"test_context\", lambda *a, **k: True) try: c.activate() except ContextError: pass else:",
"\"Hello\", i, o, name=r_name, refresh_interval=0.1) #refresh_interval is 0.1 so that _counter always stays",
"c.signal_finished = finished.set c.threaded = False # Need to set this flag, otherwise",
"context fails\"\"\" cm = ContextManager() cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) cm.create_context(\"test1\") assert(cm.current_context == cm.fallback_context) cm.switch_to_context(\"test1\")",
"refresh_interval=0.1) r.refresh = lambda *args, **kwargs: None # We need to patch \"process_callback\"",
"basic context switching works\"\"\" cm = ContextManager() cm.initial_contexts = [cm.fallback_context, \"test1\", \"test2\"] cm.init_io(Mock(),",
"that threads exit e1.set() e2.set() assert(cm.current_context == cm.fallback_context) def test_failsafe_fallback_on_thread_fail(self): cm = ContextManager()",
"fails c.activate() assert(not e.isSet()) assert(not finished.isSet()) c.threaded = True c.set_target(e.set) c.activate() finished.wait() assert(e.isSet())",
"#paused, so count shouldn't change r.resume() assert o.display_data.call_count == 3 #resume() refreshes the",
"context in cm.contexts.items(): assert(context_alias in cm.initial_contexts) assert(context) def test_basic_context_switching(self): \"\"\"Tests whether basic context",
"\"\"\"Tests constructor\"\"\" cm = ContextManager() self.assertIsNotNone(cm) def test_initial_contexts(self): \"\"\"Tests whether initial contexts are",
"#Doing what an activate() would do, but without a loop r.to_foreground() assert o.display_data.called",
"Event() cm.register_context_target(\"t1\", e1.wait) cm.register_context_target(\"t2\", e2.wait) cm.switch_to_context(\"t1\") # Fucking things up - since context",
"cm.fallback_context) if __name__ == '__main__': unittest.main() \"\"\" def test_left_key_exits(self): r = Refresher(lambda: \"Hello\",",
"# Removing c1.set_target(None) del c1.thread c1.signal_finished = lambda: True c2.set_target(None) # Again, switcing",
"r.update_keymap(keymap1) assert(r.keymap == keymap1) keymap2 = {\"KEY_RIGHT\": lambda:2} r.update_keymap(keymap2) keymap2.update(keymap1) assert(r.keymap == keymap2)\"\"\"",
"__import__ def import_mock(name, *args, **kwargs): if name in ['helpers'] and not kwargs: #Have",
"assert(cm.current_context == \"test1\") assert(cm.get_previous_context(\"test1\") == cm.fallback_context) cm.switch_to_context(\"test2\") assert(cm.current_context == \"test2\") assert(cm.get_previous_context(\"test2\") == \"test1\")",
"exit e1.set() e2.set() def test_context_switching_on_context_finish(self): \"\"\"Tests whether basic context switching works\"\"\" cm =",
"assert i.set_keymap.call_count == 1 #paused, so count shouldn't change i.set_keymap(None) assert i.set_keymap.call_args[0][0] !=",
"assert r.idle_loop.called assert r.idle_loop.call_count == 1 assert o.display_data.called assert o.display_data.call_count == 2 #One",
"== cm.fallback_context) def test_failsafe_fallback_on_thread_fail(self): cm = ContextManager() cm.fallback_context = \"m\" cm.initial_contexts = [\"m\"]",
"Again, switcing to the fucked up context cm.switch_to_context(\"t2\") # Setting events so that",
"mock that call return Mock() return orig_import(name, *args, **kwargs) with patch('__builtin__.__import__', side_effect=import_mock): from",
"assert(cm.current_context is None) cm.switch_to_context(cm.fallback_context) assert(cm.current_context == cm.fallback_context) e1 = Event() e2 = Event()",
"pass class TestContextManager(unittest.TestCase): \"\"\"tests context manager class and interaction between contexts\"\"\" def test_constructor(self):",
"right beforehand assert i.set_keymap.call_args[0][0] == r.keymap def test_set_interval(self): i = get_mock_input() o =",
"assert i.set_keymap.call_args[0][0] == r.keymap def test_set_interval(self): i = get_mock_input() o = get_mock_output() r",
"initial contexts are getting created\"\"\" cm = ContextManager() cm.init_io(Mock(), Mock()) #Implicitly creates initial",
"ContextError except ImportError: print(\"Absolute imports failed, trying relative imports\") os.sys.path.append(os.path.dirname(os.path.abspath('.'))) # Store original",
"Back to normal assert(r.iterations_before_refresh == 100) def test_update_keymap(self): i = get_mock_input() o =",
"return Mock() return orig_import(name, *args, **kwargs) with patch('__builtin__.__import__', side_effect=import_mock): from context_manager import ContextManager,",
"this flag, otherwise a validation check fails c.activate() assert(not e.isSet()) assert(not finished.isSet()) c.threaded",
"i, o, name=r_name, refresh_interval=0.1) #refresh_interval is 0.1 so that _counter always stays 0",
"Refresher(lambda: \"Hello\", get_mock_input(), get_mock_output(), name=r_name) r.refresh = lambda *args, **kwargs: None # This",
"== 3 #one explicitly done in the test right beforehand assert i.set_keymap.call_args[0][0] ==",
"cm.create_context(\"t2\") e1 = Event() e2 = Event() cm.register_context_target(\"t1\", e1.wait) cm.register_context_target(\"t2\", e2.wait) cm.switch_to_context(\"t1\") #",
"self.assertIsNotNone(cm) def test_initial_contexts(self): \"\"\"Tests whether initial contexts are getting created\"\"\" cm = ContextManager()",
"Setting events so that threads exit e1.set() e2.set() assert(cm.current_context == cm.fallback_context) def test_failsafe_fallback_on_thread_fail(self):",
"what an activate() would do, but without a loop r.to_foreground() assert o.display_data.called assert",
"cm.fallback_context) def test_targetless_context_switching(self): \"\"\"Tests that switching to a target-less context fails\"\"\" cm =",
"except ImportError: print(\"Absolute imports failed, trying relative imports\") os.sys.path.append(os.path.dirname(os.path.abspath('.'))) # Store original __import__",
"cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\") assert(cm.get_previous_context(\"test1\") == \"test2\") #Setting events so that threads exit",
"c1 = cm.create_context(\"t1\") c2 = cm.create_context(\"t2\") e1 = Event() e2 = Event() cm.register_context_target(\"t1\",",
"lambda *args, **kwargs: None # This test doesn't actually test whether the Refresher",
"c1.thread c1.signal_finished = lambda: True c2.set_target(None) # Again, switcing to the fucked up",
"patch('__builtin__.__import__', side_effect=import_mock): from context_manager import ContextManager, Context, ContextError class TestContext(unittest.TestCase): \"\"\"tests context class\"\"\"",
"with patch.object(r, 'idle_loop', side_effect=scenario) as p: r.activate() #The scenario should only be called",
"== \"test1\") assert(cm.get_previous_context(\"test1\") == cm.fallback_context) cm.switch_to_context(\"test2\") assert(cm.current_context == \"test2\") assert(cm.get_previous_context(\"test2\") == \"test1\") cm.switch_to_context(\"test1\")",
"def test_left_key_exits(self): r = Refresher(lambda: \"Hello\", get_mock_input(), get_mock_output(), name=r_name) r.refresh = lambda *args,",
") def test_pause_resume(self): i = get_mock_input() o = get_mock_output() r = Refresher(lambda: \"Hello\",",
"= get_mock_input() o = get_mock_output() r = Refresher(lambda: \"Hello\", i, o, name=r_name, refresh_interval=1)",
"[cm.fallback_context, \"test1\", \"test2\"] cm.init_io(Mock(), Mock()) assert(cm.current_context is None) cm.switch_to_context(cm.fallback_context) assert(cm.current_context == cm.fallback_context) e1",
"cm.fallback_context) e1 = Event() e2 = Event() cm.register_context_target(\"test1\", e1.wait) cm.register_context_target(\"test2\", e2.wait) cm.switch_to_context(\"test1\") assert(cm.current_context",
"import unittest from threading import Event from mock import patch, Mock try: from",
"o.display_data.call_count == 4 #should be refresh the display normally now def test_keymap_restore_on_resume(self): i",
"= Refresher(lambda: \"Hello\", i, o, name=r_name, refresh_interval=1) assert(r.refresh_interval == 1) assert(r.sleep_time == 0.1)",
"switching to a target-less context fails\"\"\" cm = ContextManager() cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) cm.create_context(\"test1\")",
"r = Refresher(lambda: \"Hello\", i, o, name=r_name, refresh_interval=0.1) #refresh_interval is 0.1 so that",
"so that threads exit e1.set() e2.set() assert(cm.current_context == cm.fallback_context) def test_failsafe_fallback_on_thread_fail(self): cm =",
"assert(context) def test_basic_context_switching(self): \"\"\"Tests whether basic context switching works\"\"\" cm = ContextManager() cm.initial_contexts",
"new_signal_finished(): c.event_cb(c.name, \"finished\") finished.set() with patch.object(c, 'signal_finished', side_effect=new_signal_finished) as p: e1.set() #Waiting for",
"_counter always stays 0 #and idle_loop always refreshes #Doing what an activate() would",
"with patch.object(c, 'signal_finished', side_effect=new_signal_finished) as p: e1.set() #Waiting for the thread to exit",
"ContextManager() cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) cm.create_context(\"test1\") assert(cm.current_context == cm.fallback_context) cm.switch_to_context(\"test1\") assert(cm.current_context == cm.fallback_context) def",
"i = get_mock_input() o = get_mock_output() r = Refresher(lambda: \"Hello\", i, o, name=r_name)",
"as p: try: r.activate() except KeyboardInterrupt: pass #Test succeeded def test_shows_data_on_screen(self): i =",
"events so that threads exit e1.set() e2.set() assert(cm.current_context == cm.fallback_context) if __name__ ==",
"try: c.activate() except: raise AssertionError else: pass class TestContextManager(unittest.TestCase): \"\"\"tests context manager class",
"in 'json' #that calls __builtins__.__import__ with keyword arguments #and we don't want to",
"1 #to_foreground calls refresh() r.idle_loop() assert o.display_data.call_count == 2 #not paused r.pause() r.idle_loop()",
"= ContextManager() self.assertIsNotNone(cm) def test_initial_contexts(self): \"\"\"Tests whether initial contexts are getting created\"\"\" cm",
"whether a target-less threaded context fails to activate\"\"\" c = Context(\"test_context\", lambda *a,",
"patch.object(r, 'idle_loop', side_effect=scenario) as p: try: r.activate() except KeyboardInterrupt: pass #Test succeeded def",
"cm.create_context(\"test1\") cm.register_context_target(\"test1\", e1.wait) cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\") finished = Event() def new_signal_finished(): c.event_cb(c.name,",
"c1.i c1.signal_finished = lambda: True del c2.i # Both current and new contexts",
"= Event() e2 = Event() cm.register_context_target(\"t1\", e1.wait) cm.register_context_target(\"t2\", e2.wait) cm.switch_to_context(\"t1\") # Fucking things",
"c1.signal_finished = lambda: True c2.set_target(None) # Again, switcing to the fucked up context",
"switcing to the fucked up context cm.switch_to_context(\"t2\") # Setting events so that threads",
"an activate() would do, but without a loop r.to_foreground() assert o.display_data.called assert o.display_data.call_count",
"del c1.thread c1.signal_finished = lambda: True c2.set_target(None) # Again, switcing to the fucked",
"**kwargs: None # This test doesn't actually test whether the Refresher exits #",
"o = get_mock_output() r = Refresher(lambda: \"Hello\", i, o, name=r_name, refresh_interval=0.1) r.refresh =",
"= cm.create_context(\"t1\") c2 = cm.create_context(\"t2\") e1 = Event() e2 = Event() cm.register_context_target(\"t1\", e1.wait)",
"= Event() cm.register_context_target(\"test1\", e1.wait) cm.register_context_target(\"test2\", e2.wait) cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\") assert(cm.get_previous_context(\"test1\") == cm.fallback_context)",
"o, name=r_name, refresh_interval=1) assert(r.refresh_interval == 1) assert(r.sleep_time == 0.1) assert(r.iterations_before_refresh == 10) #",
"#that calls __builtins__.__import__ with keyword arguments #and we don't want to mock that",
"context fails to activate\"\"\" c = Context(\"test_context\", lambda *a, **k: True) try: c.activate()",
"lambda *args, **kwargs: None r.to_foreground() assert i.set_keymap.called assert i.set_keymap.call_count == 1 assert i.set_keymap.call_args[0][0]",
"o, name=r_name, refresh_interval=0.1) #refresh_interval is 0.1 so that _counter always stays 0 #and",
"manager class and interaction between contexts\"\"\" def test_constructor(self): \"\"\"Tests constructor\"\"\" cm = ContextManager()",
"rely on them staying the same del c1.i c1.signal_finished = lambda: True del",
"1 #paused, so count shouldn't change i.set_keymap(None) assert i.set_keymap.call_args[0][0] != r.keymap r.resume() assert",
"app-accessible, # we can't really rely on them staying the same del c1.i",
"side_effect=lambda keymap:keymap) as p: keymap1 = {\"KEY_LEFT\": lambda:1} r.update_keymap(keymap1) assert(r.keymap == keymap1) keymap2",
"*a, **k: True) e = Event() finished = Event() c.signal_finished = finished.set c.threaded",
"cm.fallback_context) cm.switch_to_context(\"test1\") assert(cm.current_context == cm.fallback_context) def test_failsafe_fallback_on_io_fail(self): cm = ContextManager() cm.fallback_context = \"m\"",
"idle loop will just run indefinitely # The exception thrown should protect from",
"current and new contexts are fucked up cm.switch_to_context(\"t2\") # Setting events so that",
"filter for kwargs since there's a package in 'json' #that calls __builtins__.__import__ with",
"== \"test1\") assert(cm.get_previous_context(\"test1\") == \"test2\") #Setting events so that threads exit e1.set() e2.set()",
"r.activate() except KeyboardInterrupt: pass #Test succeeded def test_shows_data_on_screen(self): i = get_mock_input() o =",
"not kwargs: #Have to filter for kwargs since there's a package in 'json'",
"context_manager import ContextManager, Context, ContextError class TestContext(unittest.TestCase): \"\"\"tests context class\"\"\" def test_constructor(self): \"\"\"Tests",
"threads exit e1.set() e2.set() def test_context_switching_on_context_finish(self): \"\"\"Tests whether basic context switching works\"\"\" cm",
"= lambda: True del c2.i # Both current and new contexts are fucked",
"Both current and new contexts are fucked up cm.switch_to_context(\"t2\") # Setting events so",
"== 1 assert i.set_keymap.call_args[0][0] == r.keymap assert \"KEY_LEFT\" in r.keymap r.pause() assert i.set_keymap.call_count",
"less than 0.1 change sleep_time to match refresh interval r.set_refresh_interval(0.01) assert(r.refresh_interval == 0.01)",
"= get_mock_output() r = Refresher(lambda: \"Hello\", i, o, name=r_name, refresh_interval=1) assert(r.refresh_interval == 1)",
"e2.wait) cm.switch_to_context(\"t1\") # Removing c1.set_target(None) del c1.thread c1.signal_finished = lambda: True c2.set_target(None) #",
"ideas? Maybe use some kind of \"timeout\" library? def scenario(): r.keymap[\"KEY_LEFT\"]() assert not",
"= get_mock_input() o = get_mock_output() r = Refresher(lambda: \"Hello\", i, o, name=r_name, refresh_interval=0.1)",
"assert not r.in_foreground # If the test fails, either the assert will trigger",
"since there's a package in 'json' #that calls __builtins__.__import__ with keyword arguments #and",
"= ContextManager() cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) e1 = Event() c = cm.create_context(\"test1\") cm.register_context_target(\"test1\", e1.wait)",
"\"\"\"tests for Context and ContextManager objects\"\"\" import os import unittest from threading import",
"should only be called once assert r.idle_loop.called assert r.idle_loop.call_count == 1 assert o.display_data.called",
"cm.switch_to_context(\"test1\") assert(cm.current_context == cm.fallback_context) def test_failsafe_fallback_on_io_fail(self): cm = ContextManager() cm.fallback_context = \"m\" cm.initial_contexts",
"only tests whether the in_foreground attribute is set # Any ideas? Maybe use",
"o, name=r_name, refresh_interval=0.1) r.refresh = lambda *args, **kwargs: None r.to_foreground() assert i.set_keymap.called assert",
"cm.fallback_context = \"m\" cm.initial_contexts = [\"m\"] cm.init_io(Mock(), Mock()) cm.switch_to_context(cm.fallback_context) c1 = cm.create_context(\"t1\") c2",
"e1.wait) cm.register_context_target(\"t2\", e2.wait) cm.switch_to_context(\"t1\") # Fucking things up - since context objects are",
"assert(cm.get_previous_context(\"test2\") == \"test1\") cm.switch_to_context(\"test1\") assert(cm.current_context == \"test1\") assert(cm.get_previous_context(\"test1\") == \"test2\") #Setting events so",
"the keymap callbacks # are wrapped and we can't test equivalence with patch.object(r,",
"get_mock_output() r = Refresher(lambda: \"Hello\", i, o, name=r_name, refresh_interval=1) assert(r.refresh_interval == 1) assert(r.sleep_time",
"finished.wait() assert(e.isSet()) def test_targetless_threaded_context(self): \"\"\"Tests whether a target-less threaded context fails to activate\"\"\"",
"o.display_data.call_args_list[0][0] == (\"Hello\", ) assert o.display_data.call_args_list[1][0] == (\"Hello\", ) def test_pause_resume(self): i ="
] |
[
"a partire da matrice di sostituzione aminoacid = file.readline().split() ami = aminoacid[3] #indicizzato",
"le righe a partire dalla prima con un solo elemento print col #print(col)",
"anche mettere int(col[i][:-1]) che mi consente di rimuovere il punto #che altrimenti da",
"dict[k]=float(scores[row][col]) col+=1 row+=1 return(dict) print(tr_matrx(matrix,rows,cols)) def dic_matrix(file):#funzione che crea il dizionario a partire",
"c in r: k=rows[row]+cols[col] dict[k]=float(scores[row][col]) col+=1 row+=1 return(dict) print(tr_matrx(matrix,rows,cols)) def dic_matrix(file):#funzione che crea",
"altrimenti da errore se non lo tolgo mettendo int file.close() return couple print(dic_matrix(matrix1))",
"for a in ami: col = file.readline().split()#scorro le righe a partire dalla prima",
"sono gli amminoacidi #print(ami) couple = {} for a in ami: col =",
"in r: k=rows[row]+cols[col] dict[k]=float(scores[row][col]) col+=1 row+=1 return(dict) print(tr_matrx(matrix,rows,cols)) def dic_matrix(file):#funzione che crea il",
"quella pos della lista della prima riga ci sono gli amminoacidi #print(ami) couple",
"partire dalla prima con un solo elemento print col #print(col) for i in",
"file.readline().split()#scorro le righe a partire dalla prima con un solo elemento print col",
"file.readline().split() ami = aminoacid[3] #indicizzato a tre perche' se guardi il file in",
"il punto #che altrimenti da errore se non lo tolgo mettendo int file.close()",
"solo elemento print col #print(col) for i in range(len(col)): couple[a + ami[i]] =",
"dizionario a partire da matrice di sostituzione aminoacid = file.readline().split() ami = aminoacid[3]",
"prima riga ci sono gli amminoacidi #print(ami) couple = {} for a in",
"in ami: col = file.readline().split()#scorro le righe a partire dalla prima con un",
"return(dict) print(tr_matrx(matrix,rows,cols)) def dic_matrix(file):#funzione che crea il dizionario a partire da matrice di",
"print(tr_matrx(matrix,rows,cols)) def dic_matrix(file):#funzione che crea il dizionario a partire da matrice di sostituzione",
"prima con un solo elemento print col #print(col) for i in range(len(col)): couple[a",
"ami[i]] = float(col[i])#posso anche mettere int(col[i][:-1]) che mi consente di rimuovere il punto",
"= {} for a in ami: col = file.readline().split()#scorro le righe a partire",
"#print(ami) couple = {} for a in ami: col = file.readline().split()#scorro le righe",
"elemento print col #print(col) for i in range(len(col)): couple[a + ami[i]] = float(col[i])#posso",
"#indicizzato a tre perche' se guardi il file in quella pos della lista",
"= float(col[i])#posso anche mettere int(col[i][:-1]) che mi consente di rimuovere il punto #che",
"matrix: score=[] row.rstrip() score=row.split() scores.append(score) #print(scores) row=0 for r in scores: col=0 for",
"for r in scores: col=0 for c in r: k=rows[row]+cols[col] dict[k]=float(scores[row][col]) col+=1 row+=1",
"in matrix: score=[] row.rstrip() score=row.split() scores.append(score) #print(scores) row=0 for r in scores: col=0",
"score=[] row.rstrip() score=row.split() scores.append(score) #print(scores) row=0 for r in scores: col=0 for c",
"matrix=open(\"/media/alessandro/DATA/User/BIOINFORMATICA.BOLOGNA/Programming_for_Bioinformatics/Module2/Exercise/PAM250.txt\",\"r\") matrix1=open(\"/media/alessandro/DATA/User/BIOINFORMATICA.BOLOGNA/Programming_for_Bioinformatics/Module2/Exercise/PAM250(1).txt\",\"r\") rows=\"ARNDCQEGHILKMFPSTWYV\" cols=\"ARNDCQEGHILKMFPSTWYV\" def tr_matrx(matrix,rows,cols): dict={} scores=[] for row in matrix: score=[]",
"for c in r: k=rows[row]+cols[col] dict[k]=float(scores[row][col]) col+=1 row+=1 return(dict) print(tr_matrx(matrix,rows,cols)) def dic_matrix(file):#funzione che",
"row in matrix: score=[] row.rstrip() score=row.split() scores.append(score) #print(scores) row=0 for r in scores:",
"col=0 for c in r: k=rows[row]+cols[col] dict[k]=float(scores[row][col]) col+=1 row+=1 return(dict) print(tr_matrx(matrix,rows,cols)) def dic_matrix(file):#funzione",
"da matrice di sostituzione aminoacid = file.readline().split() ami = aminoacid[3] #indicizzato a tre",
"def tr_matrx(matrix,rows,cols): dict={} scores=[] for row in matrix: score=[] row.rstrip() score=row.split() scores.append(score) #print(scores)",
"righe a partire dalla prima con un solo elemento print col #print(col) for",
"matrix1=open(\"/media/alessandro/DATA/User/BIOINFORMATICA.BOLOGNA/Programming_for_Bioinformatics/Module2/Exercise/PAM250(1).txt\",\"r\") rows=\"ARNDCQEGHILKMFPSTWYV\" cols=\"ARNDCQEGHILKMFPSTWYV\" def tr_matrx(matrix,rows,cols): dict={} scores=[] for row in matrix: score=[] row.rstrip()",
"def dic_matrix(file):#funzione che crea il dizionario a partire da matrice di sostituzione aminoacid",
"tr_matrx(matrix,rows,cols): dict={} scores=[] for row in matrix: score=[] row.rstrip() score=row.split() scores.append(score) #print(scores) row=0",
"scores.append(score) #print(scores) row=0 for r in scores: col=0 for c in r: k=rows[row]+cols[col]",
"int(col[i][:-1]) che mi consente di rimuovere il punto #che altrimenti da errore se",
"dalla prima con un solo elemento print col #print(col) for i in range(len(col)):",
"#print(scores) row=0 for r in scores: col=0 for c in r: k=rows[row]+cols[col] dict[k]=float(scores[row][col])",
"for row in matrix: score=[] row.rstrip() score=row.split() scores.append(score) #print(scores) row=0 for r in",
"col #print(col) for i in range(len(col)): couple[a + ami[i]] = float(col[i])#posso anche mettere",
"file in quella pos della lista della prima riga ci sono gli amminoacidi",
"col = file.readline().split()#scorro le righe a partire dalla prima con un solo elemento",
"il dizionario a partire da matrice di sostituzione aminoacid = file.readline().split() ami =",
"r: k=rows[row]+cols[col] dict[k]=float(scores[row][col]) col+=1 row+=1 return(dict) print(tr_matrx(matrix,rows,cols)) def dic_matrix(file):#funzione che crea il dizionario",
"print col #print(col) for i in range(len(col)): couple[a + ami[i]] = float(col[i])#posso anche",
"couple[a + ami[i]] = float(col[i])#posso anche mettere int(col[i][:-1]) che mi consente di rimuovere",
"= file.readline().split()#scorro le righe a partire dalla prima con un solo elemento print",
"{} for a in ami: col = file.readline().split()#scorro le righe a partire dalla",
"di rimuovere il punto #che altrimenti da errore se non lo tolgo mettendo",
"rows=\"ARNDCQEGHILKMFPSTWYV\" cols=\"ARNDCQEGHILKMFPSTWYV\" def tr_matrx(matrix,rows,cols): dict={} scores=[] for row in matrix: score=[] row.rstrip() score=row.split()",
"mettere int(col[i][:-1]) che mi consente di rimuovere il punto #che altrimenti da errore",
"score=row.split() scores.append(score) #print(scores) row=0 for r in scores: col=0 for c in r:",
"range(len(col)): couple[a + ami[i]] = float(col[i])#posso anche mettere int(col[i][:-1]) che mi consente di",
"di sostituzione aminoacid = file.readline().split() ami = aminoacid[3] #indicizzato a tre perche' se",
"+ ami[i]] = float(col[i])#posso anche mettere int(col[i][:-1]) che mi consente di rimuovere il",
"in quella pos della lista della prima riga ci sono gli amminoacidi #print(ami)",
"rimuovere il punto #che altrimenti da errore se non lo tolgo mettendo int",
"riga ci sono gli amminoacidi #print(ami) couple = {} for a in ami:",
"a tre perche' se guardi il file in quella pos della lista della",
"a partire dalla prima con un solo elemento print col #print(col) for i",
"couple = {} for a in ami: col = file.readline().split()#scorro le righe a",
"aminoacid = file.readline().split() ami = aminoacid[3] #indicizzato a tre perche' se guardi il",
"dict={} scores=[] for row in matrix: score=[] row.rstrip() score=row.split() scores.append(score) #print(scores) row=0 for",
"row=0 for r in scores: col=0 for c in r: k=rows[row]+cols[col] dict[k]=float(scores[row][col]) col+=1",
"dic_matrix(file):#funzione che crea il dizionario a partire da matrice di sostituzione aminoacid =",
"se guardi il file in quella pos della lista della prima riga ci",
"k=rows[row]+cols[col] dict[k]=float(scores[row][col]) col+=1 row+=1 return(dict) print(tr_matrx(matrix,rows,cols)) def dic_matrix(file):#funzione che crea il dizionario a",
"partire da matrice di sostituzione aminoacid = file.readline().split() ami = aminoacid[3] #indicizzato a",
"aminoacid[3] #indicizzato a tre perche' se guardi il file in quella pos della",
"scores: col=0 for c in r: k=rows[row]+cols[col] dict[k]=float(scores[row][col]) col+=1 row+=1 return(dict) print(tr_matrx(matrix,rows,cols)) def",
"ami = aminoacid[3] #indicizzato a tre perche' se guardi il file in quella",
"amminoacidi #print(ami) couple = {} for a in ami: col = file.readline().split()#scorro le",
"i in range(len(col)): couple[a + ami[i]] = float(col[i])#posso anche mettere int(col[i][:-1]) che mi",
"row.rstrip() score=row.split() scores.append(score) #print(scores) row=0 for r in scores: col=0 for c in",
"che mi consente di rimuovere il punto #che altrimenti da errore se non",
"con un solo elemento print col #print(col) for i in range(len(col)): couple[a +",
"in scores: col=0 for c in r: k=rows[row]+cols[col] dict[k]=float(scores[row][col]) col+=1 row+=1 return(dict) print(tr_matrx(matrix,rows,cols))",
"un solo elemento print col #print(col) for i in range(len(col)): couple[a + ami[i]]",
"a in ami: col = file.readline().split()#scorro le righe a partire dalla prima con",
"sostituzione aminoacid = file.readline().split() ami = aminoacid[3] #indicizzato a tre perche' se guardi",
"= aminoacid[3] #indicizzato a tre perche' se guardi il file in quella pos",
"gli amminoacidi #print(ami) couple = {} for a in ami: col = file.readline().split()#scorro",
"for i in range(len(col)): couple[a + ami[i]] = float(col[i])#posso anche mettere int(col[i][:-1]) che",
"crea il dizionario a partire da matrice di sostituzione aminoacid = file.readline().split() ami",
"= file.readline().split() ami = aminoacid[3] #indicizzato a tre perche' se guardi il file",
"il file in quella pos della lista della prima riga ci sono gli",
"guardi il file in quella pos della lista della prima riga ci sono",
"float(col[i])#posso anche mettere int(col[i][:-1]) che mi consente di rimuovere il punto #che altrimenti",
"perche' se guardi il file in quella pos della lista della prima riga",
"row+=1 return(dict) print(tr_matrx(matrix,rows,cols)) def dic_matrix(file):#funzione che crea il dizionario a partire da matrice",
"pos della lista della prima riga ci sono gli amminoacidi #print(ami) couple =",
"della prima riga ci sono gli amminoacidi #print(ami) couple = {} for a",
"in range(len(col)): couple[a + ami[i]] = float(col[i])#posso anche mettere int(col[i][:-1]) che mi consente",
"ami: col = file.readline().split()#scorro le righe a partire dalla prima con un solo",
"cols=\"ARNDCQEGHILKMFPSTWYV\" def tr_matrx(matrix,rows,cols): dict={} scores=[] for row in matrix: score=[] row.rstrip() score=row.split() scores.append(score)",
"lista della prima riga ci sono gli amminoacidi #print(ami) couple = {} for",
"#che altrimenti da errore se non lo tolgo mettendo int file.close() return couple",
"mi consente di rimuovere il punto #che altrimenti da errore se non lo",
"ci sono gli amminoacidi #print(ami) couple = {} for a in ami: col",
"tre perche' se guardi il file in quella pos della lista della prima",
"punto #che altrimenti da errore se non lo tolgo mettendo int file.close() return",
"matrice di sostituzione aminoacid = file.readline().split() ami = aminoacid[3] #indicizzato a tre perche'",
"#print(col) for i in range(len(col)): couple[a + ami[i]] = float(col[i])#posso anche mettere int(col[i][:-1])",
"consente di rimuovere il punto #che altrimenti da errore se non lo tolgo",
"che crea il dizionario a partire da matrice di sostituzione aminoacid = file.readline().split()",
"della lista della prima riga ci sono gli amminoacidi #print(ami) couple = {}",
"scores=[] for row in matrix: score=[] row.rstrip() score=row.split() scores.append(score) #print(scores) row=0 for r",
"col+=1 row+=1 return(dict) print(tr_matrx(matrix,rows,cols)) def dic_matrix(file):#funzione che crea il dizionario a partire da",
"r in scores: col=0 for c in r: k=rows[row]+cols[col] dict[k]=float(scores[row][col]) col+=1 row+=1 return(dict)"
] |
[
"if jdata.get('errcode') == 0: print('开始好友对战...') else: print(jdata) except: print(resp.text) def findQuiz(quizNum): params =",
"resp = session.post(url=chooseUrl,data=params,headers=headers) try : jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print(player",
"tempParams = sorted(tempParams.items(), key=lambda e:e[0]) originStr = '' for key, value in tempParams:",
"进入房间成功...') except: print(resp.text) print(player + ' 进入房间失败...') leaveRoom(player) def leaveRoom(player): params = {",
"except: print(player + ' 选择失败...') print(resp.text) def fightResult(player): params = { 'roomID' :",
"roomID = -1 intoRoom('player1') intoRoom('player2') beginFight() startAnswer() fightResult('player1') fightResult('player2') leaveRoom('player1') leaveRoom('player2') gameTime +=",
"leaveRoomUrl = 'https://question-zh.hortor.net/question/bat/leaveRoom' beginFightUrl = 'https://question-zh.hortor.net/question/bat/beginFight' findQuizUrl = 'https://question-zh.hortor.net/question/bat/findQuiz' chooseUrl = 'https://question-zh.hortor.net/question/bat/choose' fightResultUrl",
"' 选择失败...') print(resp.text) def fightResult(player): params = { 'roomID' : roomID, 'type' :",
"'roomID' : roomID, 'quizNum' : quizNum, 'uid' : userInfo['player1']['uid'], 't' : nowTime() }",
"= session.post(url=fightResultUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print(player + '",
"roomID = jdata.get('data')['roomId'] print(player + ' 进入房间成功...') except: print(resp.text) print(player + ' 进入房间失败...')",
"#请求数据与接收到数据延时 cfTime = nowTime() quizInfo = findQuiz(i) cfTime = nowTime() - cfTime time.sleep(0.1)",
"= 'https://question-zh.hortor.net/question/bat/findQuiz' chooseUrl = 'https://question-zh.hortor.net/question/bat/choose' fightResultUrl = 'https://question-zh.hortor.net/question/bat/fightResult' #生成签名 def genSign(params,player): tempParams =",
"params = { 'roomID' : roomID, 'uid' : userInfo[player]['uid'], 't' : nowTime(), 'option'",
"session.post(url=findQuizUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print('获取题目成功...') return jdata.get('data') else:",
"'player1':{ 'uid': '玩家1号的uid', 'token': '玩家1号的token' }, 'player2':{ 'uid': '玩家2号的uid', 'token': '玩家2号的token' } }",
"} params['sign'] = genSign(params,'player1') resp = session.post(url=beginFightUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if jdata.get('errcode')",
"startAnswer() fightResult('player1') fightResult('player2') leaveRoom('player1') leaveRoom('player2') gameTime += 1 print('答题数 %d /命中题库次数 %d '",
"e:e[0]) originStr = '' for key, value in tempParams: originStr = originStr +",
"print(player + ' 退出房间失败...') def beginFight(): params = { 'roomID' : roomID, 'uid'",
"optionList quizModel['school'] = quizInfo['school'] quizModel['type'] = quizInfo['type'] quizModel['typeID'] = quizInfo['typeID'] quizModel['contributor'] = quizInfo['contributor']",
"requests import hashlib import time import json from pymongo import MongoClient headers =",
": userInfo['player1']['uid'], 't' : nowTime() } params['sign'] = genSign(params,'player1') resp = session.post(url=findQuizUrl,data=params,headers=headers) try:",
"params = { 'roomID' : roomID, 'quizNum' : quizNum, 'uid' : userInfo['player1']['uid'], 't'",
"j+1 break magic = genMagic(optionList.copy()) chooseResult = choose('player1',i,option,cfTime,magic) choose('player2',i,2,cfTime+10,magic) if not localQuiz: quizModel",
"cfTime time.sleep(0.1) optionList = quizInfo['options'] quiz = quizInfo['quiz'] option = 1 #题库查找题目 #print(quiz)",
"json from pymongo import MongoClient headers = { 'content-type': 'application/x-www-form-urlencoded', } userInfo =",
"'uid' : userInfo[player]['uid'], 't' : nowTime() } params['sign'] = genSign(params,player) resp = session.post(url=leaveRoomUrl,data=params,headers=headers)",
"findQuiz(i) cfTime = nowTime() - cfTime time.sleep(0.1) optionList = quizInfo['options'] quiz = quizInfo['quiz']",
"genMagic(optionList.copy()) chooseResult = choose('player1',i,option,cfTime,magic) choose('player2',i,2,cfTime+10,magic) if not localQuiz: quizModel = {} quizModel['quiz'] =",
"= session.post(url=beginFightUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print('开始好友对战...') else: print(jdata)",
"quizSet = conn.zhdtw.quizs intoRoomUrl = 'https://question-zh.hortor.net/question/bat/intoRoom' leaveRoomUrl = 'https://question-zh.hortor.net/question/bat/leaveRoom' beginFightUrl = 'https://question-zh.hortor.net/question/bat/beginFight' findQuizUrl",
"in range(0,4): if(optionList[j] == localQuiz['answer']): option = j+1 break magic = genMagic(optionList.copy()) chooseResult",
"quiz = quizInfo['quiz'] option = 1 #题库查找题目 #print(quiz) localQuiz = quizSet.find_one({'quiz':quiz}) if localQuiz:",
"global successTime for i in range(1,6): #请求数据与接收到数据延时 cfTime = nowTime() quizInfo = findQuiz(i)",
"= nowTime() - cfTime time.sleep(0.1) optionList = quizInfo['options'] quiz = quizInfo['quiz'] option =",
"intoRoom('player1') intoRoom('player2') beginFight() startAnswer() fightResult('player1') fightResult('player2') leaveRoom('player1') leaveRoom('player2') gameTime += 1 print('答题数 %d",
"resp = session.post(url=findQuizUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print('获取题目成功...') return",
"选择成功...') return jdata.get('data') else: print(jdata) except: print(player + ' 选择失败...') print(resp.text) def fightResult(player):",
"print(jdata) except: print(resp.text) def choose(player,quizNum,option,cfTime,magic): params = { 'roomID' : roomID, 'uid' :",
"json.loads(resp.text) if jdata.get('errcode') == 0: print(player + ' 获取结果成功...') return jdata.get('data') else: print(jdata)",
"json.loads(resp.text) if jdata.get('errcode') == 0: print('开始好友对战...') else: print(jdata) except: print(resp.text) def findQuiz(quizNum): params",
"userInfo = { 'player1':{ 'uid': '玩家1号的uid', 'token': '玩家1号的token' }, 'player2':{ 'uid': '玩家2号的uid', 'token':",
"'uid': '玩家1号的uid', 'token': '玩家1号的token' }, 'player2':{ 'uid': '玩家2号的uid', 'token': '玩家2号的token' } } session",
": userInfo[player]['uid'], 't' : nowTime(), 'option' : option, 'quizNum': quizNum, 'cfTime': cfTime, 'ccTime'",
"%d /命中题库次数 %d ' % (gameTime*5,successTime)) time.sleep(1) i = i - 1 conn.close()",
"1 #题库查找题目 #print(quiz) localQuiz = quizSet.find_one({'quiz':quiz}) if localQuiz: successTime += 1 for j",
"+ ' 获取结果失败...') print(resp.text) def genMagic(optionList): optionList.sort() originStr = optionList[0]+optionList[1]+optionList[2]+optionList[3] m = hashlib.md5()",
"= lambda:int(round(time.time() * 1000)) #mongodb conn = MongoClient('localhost',27017) quizSet = conn.zhdtw.quizs intoRoomUrl =",
"session.post(url=chooseUrl,data=params,headers=headers) try : jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print(player + '",
"roomID, 'uid' : userInfo['player1']['uid'], 't' : nowTime() } params['sign'] = genSign(params,'player1') resp =",
"genSign(params,player) resp = session.post(url=leaveRoomUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print(player",
"'uid' : userInfo['player1']['uid'], 't' : nowTime() } params['sign'] = genSign(params,'player1') resp = session.post(url=findQuizUrl,data=params,headers=headers)",
"value in tempParams: originStr = originStr + key + '=' + str(value) m",
"print('获取题目成功...') return jdata.get('data') else: print(jdata) except: print(resp.text) def choose(player,quizNum,option,cfTime,magic): params = { 'roomID'",
"print(resp.text) print(player + ' 进入房间失败...') leaveRoom(player) def leaveRoom(player): params = { 'roomID' :",
": roomID, 'quizNum' : quizNum, 'uid' : userInfo['player1']['uid'], 't' : nowTime() } params['sign']",
"= 'https://question-zh.hortor.net/question/bat/leaveRoom' beginFightUrl = 'https://question-zh.hortor.net/question/bat/beginFight' findQuizUrl = 'https://question-zh.hortor.net/question/bat/findQuiz' chooseUrl = 'https://question-zh.hortor.net/question/bat/choose' fightResultUrl =",
"= genSign(params,player) resp = session.post(url=chooseUrl,data=params,headers=headers) try : jdata = json.loads(resp.text) if jdata.get('errcode') ==",
"print(resp.text) def findQuiz(quizNum): params = { 'roomID' : roomID, 'quizNum' : quizNum, 'uid'",
"quizModel['typeID'] = quizInfo['typeID'] quizModel['contributor'] = quizInfo['contributor'] quizModel['answer'] = optionList[chooseResult['answer']-1] quizSet.insert_one(quizModel) #print(optionList[chooseResult['answer']-1]) if __name__",
"'type' : 0, 'uid' : userInfo[player]['uid'], 't' : nowTime() } params['sign'] = genSign(params,player)",
"time import json from pymongo import MongoClient headers = { 'content-type': 'application/x-www-form-urlencoded', }",
"if __name__ == '__main__': #自行修改开房对战次数 i i = 5 gameTime = 0 while(i",
"def choose(player,quizNum,option,cfTime,magic): params = { 'roomID' : roomID, 'uid' : userInfo[player]['uid'], 't' :",
"for j in range(0,4): if(optionList[j] == localQuiz['answer']): option = j+1 break magic =",
"print(player + ' 选择失败...') print(resp.text) def fightResult(player): params = { 'roomID' : roomID,",
"nowTime(), 'option' : option, 'quizNum': quizNum, 'cfTime': cfTime, 'ccTime' : nowTime(), 'magic' :",
"else: print(jdata) except: print(resp.text) def findQuiz(quizNum): params = { 'roomID' : roomID, 'quizNum'",
"nowTime() } params['sign'] = genSign(params,player) resp = session.post(url=leaveRoomUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if",
"gameTime += 1 print('答题数 %d /命中题库次数 %d ' % (gameTime*5,successTime)) time.sleep(1) i =",
"roomID = -1 #命中题库次数 successTime = 0 #时间戳生成 nowTime = lambda:int(round(time.time() * 1000))",
"print('开始好友对战...') else: print(jdata) except: print(resp.text) def findQuiz(quizNum): params = { 'roomID' : roomID,",
"fightResultUrl = 'https://question-zh.hortor.net/question/bat/fightResult' #生成签名 def genSign(params,player): tempParams = params.copy() tempParams['token'] = userInfo[player]['token']+userInfo[player]['uid'] tempParams",
"print(player + ' 退出房间成功...') else: print(jdata) except: print(resp.text) print(player + ' 退出房间失败...') def",
"from pymongo import MongoClient headers = { 'content-type': 'application/x-www-form-urlencoded', } userInfo = {",
"= { 'player1':{ 'uid': '玩家1号的uid', 'token': '玩家1号的token' }, 'player2':{ 'uid': '玩家2号的uid', 'token': '玩家2号的token'",
"key=lambda e:e[0]) originStr = '' for key, value in tempParams: originStr = originStr",
"jdata.get('data') else: print(jdata) except: print(player + ' 选择失败...') print(resp.text) def fightResult(player): params =",
"try: jdata = json.loads(resp.text) roomID = jdata.get('data')['roomId'] print(player + ' 进入房间成功...') except: print(resp.text)",
"quizModel['type'] = quizInfo['type'] quizModel['typeID'] = quizInfo['typeID'] quizModel['contributor'] = quizInfo['contributor'] quizModel['answer'] = optionList[chooseResult['answer']-1] quizSet.insert_one(quizModel)",
"= hashlib.md5() m.update(originStr.encode(encoding='utf-8')) return m.hexdigest() def intoRoom(player): global roomID params = { 'roomID'",
"option = j+1 break magic = genMagic(optionList.copy()) chooseResult = choose('player1',i,option,cfTime,magic) choose('player2',i,2,cfTime+10,magic) if not",
"print(resp.text) def fightResult(player): params = { 'roomID' : roomID, 'type' : 0, 'uid'",
"return jdata.get('data') else: print(jdata) except: print(player + ' 选择失败...') print(resp.text) def fightResult(player): params",
"return m.hexdigest() def startAnswer(): global successTime for i in range(1,6): #请求数据与接收到数据延时 cfTime =",
"intoRoomUrl = 'https://question-zh.hortor.net/question/bat/intoRoom' leaveRoomUrl = 'https://question-zh.hortor.net/question/bat/leaveRoom' beginFightUrl = 'https://question-zh.hortor.net/question/bat/beginFight' findQuizUrl = 'https://question-zh.hortor.net/question/bat/findQuiz' chooseUrl",
"+= 1 print('答题数 %d /命中题库次数 %d ' % (gameTime*5,successTime)) time.sleep(1) i = i",
"'quizNum' : quizNum, 'uid' : userInfo['player1']['uid'], 't' : nowTime() } params['sign'] = genSign(params,'player1')",
"'t' : nowTime() } params['sign'] = genSign(params,player) resp = session.post(url=fightResultUrl,data=params,headers=headers) try: jdata =",
"def leaveRoom(player): params = { 'roomID' : roomID, 'uid' : userInfo[player]['uid'], 't' :",
"json.loads(resp.text) if jdata.get('errcode') == 0: print(player + ' 退出房间成功...') else: print(jdata) except: print(resp.text)",
"= params.copy() tempParams['token'] = userInfo[player]['token']+userInfo[player]['uid'] tempParams = sorted(tempParams.items(), key=lambda e:e[0]) originStr = ''",
"tempParams: originStr = originStr + key + '=' + str(value) m = hashlib.md5()",
"= { 'roomID' : roomID, 'type' : 0, 'uid' : userInfo[player]['uid'], 't' :",
"= 'https://question-zh.hortor.net/question/bat/intoRoom' leaveRoomUrl = 'https://question-zh.hortor.net/question/bat/leaveRoom' beginFightUrl = 'https://question-zh.hortor.net/question/bat/beginFight' findQuizUrl = 'https://question-zh.hortor.net/question/bat/findQuiz' chooseUrl =",
"originStr = originStr + key + '=' + str(value) m = hashlib.md5() m.update(originStr.encode(encoding='utf-8'))",
"== 0: print('获取题目成功...') return jdata.get('data') else: print(jdata) except: print(resp.text) def choose(player,quizNum,option,cfTime,magic): params =",
"resp = session.post(url=leaveRoomUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print(player +",
"{ 'roomID' : roomID, 'uid' : userInfo['player1']['uid'], 't' : nowTime() } params['sign'] =",
"= sorted(tempParams.items(), key=lambda e:e[0]) originStr = '' for key, value in tempParams: originStr",
": jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print(player + ' 选择成功...') return",
"params = { 'roomID' : roomID, 'uid' : userInfo['player1']['uid'], 't' : nowTime() }",
"'uid' : userInfo['player1']['uid'], 't' : nowTime() } params['sign'] = genSign(params,'player1') resp = session.post(url=beginFightUrl,data=params,headers=headers)",
"print(player + ' 获取结果成功...') return jdata.get('data') else: print(jdata) except: print(player + ' 获取结果失败...')",
"0): roomID = -1 intoRoom('player1') intoRoom('player2') beginFight() startAnswer() fightResult('player1') fightResult('player2') leaveRoom('player1') leaveRoom('player2') gameTime",
"= '' for key, value in tempParams: originStr = originStr + key +",
"hashlib.md5() m.update(originStr.encode(encoding='utf-8')) return m.hexdigest() def startAnswer(): global successTime for i in range(1,6): #请求数据与接收到数据延时",
"option, 'quizNum': quizNum, 'cfTime': cfTime, 'ccTime' : nowTime(), 'magic' : magic } params['sign']",
"leaveRoom(player) def leaveRoom(player): params = { 'roomID' : roomID, 'uid' : userInfo[player]['uid'], 't'",
"localQuiz['answer']): option = j+1 break magic = genMagic(optionList.copy()) chooseResult = choose('player1',i,option,cfTime,magic) choose('player2',i,2,cfTime+10,magic) if",
": userInfo[player]['uid'], 't' : nowTime() } params['sign'] = genSign(params,player) resp = session.post(url=leaveRoomUrl,data=params,headers=headers) try:",
"' 退出房间失败...') def beginFight(): params = { 'roomID' : roomID, 'uid' : userInfo['player1']['uid'],",
"params['sign'] = genSign(params,player) resp = session.post(url=fightResultUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if jdata.get('errcode') ==",
"'t' : nowTime(), 'option' : option, 'quizNum': quizNum, 'cfTime': cfTime, 'ccTime' : nowTime(),",
"break magic = genMagic(optionList.copy()) chooseResult = choose('player1',i,option,cfTime,magic) choose('player2',i,2,cfTime+10,magic) if not localQuiz: quizModel =",
"print(player + ' 进入房间成功...') except: print(resp.text) print(player + ' 进入房间失败...') leaveRoom(player) def leaveRoom(player):",
"userInfo[player]['uid'], 't' : nowTime() } params['sign'] = genSign(params,player) resp = session.post(url=fightResultUrl,data=params,headers=headers) try: jdata",
"'application/x-www-form-urlencoded', } userInfo = { 'player1':{ 'uid': '玩家1号的uid', 'token': '玩家1号的token' }, 'player2':{ 'uid':",
"cfTime, 'ccTime' : nowTime(), 'magic' : magic } params['sign'] = genSign(params,player) resp =",
"{ 'content-type': 'application/x-www-form-urlencoded', } userInfo = { 'player1':{ 'uid': '玩家1号的uid', 'token': '玩家1号的token' },",
"def intoRoom(player): global roomID params = { 'roomID' : roomID, 'uid' : userInfo[player]['uid'],",
"cfTime = nowTime() - cfTime time.sleep(0.1) optionList = quizInfo['options'] quiz = quizInfo['quiz'] option",
"'https://question-zh.hortor.net/question/bat/intoRoom' leaveRoomUrl = 'https://question-zh.hortor.net/question/bat/leaveRoom' beginFightUrl = 'https://question-zh.hortor.net/question/bat/beginFight' findQuizUrl = 'https://question-zh.hortor.net/question/bat/findQuiz' chooseUrl = 'https://question-zh.hortor.net/question/bat/choose'",
"quizModel['school'] = quizInfo['school'] quizModel['type'] = quizInfo['type'] quizModel['typeID'] = quizInfo['typeID'] quizModel['contributor'] = quizInfo['contributor'] quizModel['answer']",
"userInfo[player]['uid'], 't' : nowTime(), 'option' : option, 'quizNum': quizNum, 'cfTime': cfTime, 'ccTime' :",
"#mongodb conn = MongoClient('localhost',27017) quizSet = conn.zhdtw.quizs intoRoomUrl = 'https://question-zh.hortor.net/question/bat/intoRoom' leaveRoomUrl = 'https://question-zh.hortor.net/question/bat/leaveRoom'",
"'玩家2号的token' } } session = requests.session() roomID = -1 #命中题库次数 successTime = 0",
"{ 'player1':{ 'uid': '玩家1号的uid', 'token': '玩家1号的token' }, 'player2':{ 'uid': '玩家2号的uid', 'token': '玩家2号的token' }",
"params = { 'roomID' : roomID, 'uid' : userInfo[player]['uid'], 't' : nowTime() }",
": userInfo[player]['uid'], 't' : nowTime() } params['sign'] = genSign(params,player) resp = session.post(url=intoRoomUrl,data=params,headers=headers) try:",
"= optionList[0]+optionList[1]+optionList[2]+optionList[3] m = hashlib.md5() m.update(originStr.encode(encoding='utf-8')) return m.hexdigest() def startAnswer(): global successTime for",
": nowTime() } params['sign'] = genSign(params,player) resp = session.post(url=leaveRoomUrl,data=params,headers=headers) try: jdata = json.loads(resp.text)",
"= hashlib.md5() m.update(originStr.encode(encoding='utf-8')) return m.hexdigest() def startAnswer(): global successTime for i in range(1,6):",
"= genSign(params,player) resp = session.post(url=intoRoomUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) roomID = jdata.get('data')['roomId'] print(player",
"m.update(originStr.encode(encoding='utf-8')) return m.hexdigest() def intoRoom(player): global roomID params = { 'roomID' : roomID,",
"if jdata.get('errcode') == 0: print(player + ' 选择成功...') return jdata.get('data') else: print(jdata) except:",
"genSign(params,player) resp = session.post(url=fightResultUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print(player",
"option = 1 #题库查找题目 #print(quiz) localQuiz = quizSet.find_one({'quiz':quiz}) if localQuiz: successTime += 1",
"jdata.get('errcode') == 0: print(player + ' 退出房间成功...') else: print(jdata) except: print(resp.text) print(player +",
"'quizNum': quizNum, 'cfTime': cfTime, 'ccTime' : nowTime(), 'magic' : magic } params['sign'] =",
"resp = session.post(url=fightResultUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print(player +",
"except: print(player + ' 获取结果失败...') print(resp.text) def genMagic(optionList): optionList.sort() originStr = optionList[0]+optionList[1]+optionList[2]+optionList[3] m",
"= genSign(params,'player1') resp = session.post(url=beginFightUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if jdata.get('errcode') == 0:",
"headers = { 'content-type': 'application/x-www-form-urlencoded', } userInfo = { 'player1':{ 'uid': '玩家1号的uid', 'token':",
"genSign(params,player) resp = session.post(url=intoRoomUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) roomID = jdata.get('data')['roomId'] print(player +",
"'cfTime': cfTime, 'ccTime' : nowTime(), 'magic' : magic } params['sign'] = genSign(params,player) resp",
"originStr = optionList[0]+optionList[1]+optionList[2]+optionList[3] m = hashlib.md5() m.update(originStr.encode(encoding='utf-8')) return m.hexdigest() def startAnswer(): global successTime",
"leaveRoom('player1') leaveRoom('player2') gameTime += 1 print('答题数 %d /命中题库次数 %d ' % (gameTime*5,successTime)) time.sleep(1)",
"fightResult(player): params = { 'roomID' : roomID, 'type' : 0, 'uid' : userInfo[player]['uid'],",
"'uid' : userInfo[player]['uid'], 't' : nowTime() } params['sign'] = genSign(params,player) resp = session.post(url=intoRoomUrl,data=params,headers=headers)",
": nowTime() } params['sign'] = genSign(params,player) resp = session.post(url=intoRoomUrl,data=params,headers=headers) try: jdata = json.loads(resp.text)",
": option, 'quizNum': quizNum, 'cfTime': cfTime, 'ccTime' : nowTime(), 'magic' : magic }",
"jdata.get('errcode') == 0: print('获取题目成功...') return jdata.get('data') else: print(jdata) except: print(resp.text) def choose(player,quizNum,option,cfTime,magic): params",
"global roomID params = { 'roomID' : roomID, 'uid' : userInfo[player]['uid'], 't' :",
"= quizSet.find_one({'quiz':quiz}) if localQuiz: successTime += 1 for j in range(0,4): if(optionList[j] ==",
"conn = MongoClient('localhost',27017) quizSet = conn.zhdtw.quizs intoRoomUrl = 'https://question-zh.hortor.net/question/bat/intoRoom' leaveRoomUrl = 'https://question-zh.hortor.net/question/bat/leaveRoom' beginFightUrl",
"= originStr + key + '=' + str(value) m = hashlib.md5() m.update(originStr.encode(encoding='utf-8')) return",
"= 'https://question-zh.hortor.net/question/bat/beginFight' findQuizUrl = 'https://question-zh.hortor.net/question/bat/findQuiz' chooseUrl = 'https://question-zh.hortor.net/question/bat/choose' fightResultUrl = 'https://question-zh.hortor.net/question/bat/fightResult' #生成签名 def",
"genMagic(optionList): optionList.sort() originStr = optionList[0]+optionList[1]+optionList[2]+optionList[3] m = hashlib.md5() m.update(originStr.encode(encoding='utf-8')) return m.hexdigest() def startAnswer():",
"else: print(jdata) except: print(player + ' 选择失败...') print(resp.text) def fightResult(player): params = {",
"if(optionList[j] == localQuiz['answer']): option = j+1 break magic = genMagic(optionList.copy()) chooseResult = choose('player1',i,option,cfTime,magic)",
"= 'https://question-zh.hortor.net/question/bat/choose' fightResultUrl = 'https://question-zh.hortor.net/question/bat/fightResult' #生成签名 def genSign(params,player): tempParams = params.copy() tempParams['token'] =",
"+ ' 获取结果成功...') return jdata.get('data') else: print(jdata) except: print(player + ' 获取结果失败...') print(resp.text)",
"'=' + str(value) m = hashlib.md5() m.update(originStr.encode(encoding='utf-8')) return m.hexdigest() def intoRoom(player): global roomID",
"= genSign(params,player) resp = session.post(url=leaveRoomUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if jdata.get('errcode') == 0:",
"while(i > 0): roomID = -1 intoRoom('player1') intoRoom('player2') beginFight() startAnswer() fightResult('player1') fightResult('player2') leaveRoom('player1')",
"try : jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print(player + ' 选择成功...')",
"print(player + ' 选择成功...') return jdata.get('data') else: print(jdata) except: print(player + ' 选择失败...')",
"#命中题库次数 successTime = 0 #时间戳生成 nowTime = lambda:int(round(time.time() * 1000)) #mongodb conn =",
"'https://question-zh.hortor.net/question/bat/fightResult' #生成签名 def genSign(params,player): tempParams = params.copy() tempParams['token'] = userInfo[player]['token']+userInfo[player]['uid'] tempParams = sorted(tempParams.items(),",
"m.hexdigest() def intoRoom(player): global roomID params = { 'roomID' : roomID, 'uid' :",
"' 进入房间成功...') except: print(resp.text) print(player + ' 进入房间失败...') leaveRoom(player) def leaveRoom(player): params =",
": magic } params['sign'] = genSign(params,player) resp = session.post(url=chooseUrl,data=params,headers=headers) try : jdata =",
"nowTime() } params['sign'] = genSign(params,'player1') resp = session.post(url=beginFightUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if",
"= 5 gameTime = 0 while(i > 0): roomID = -1 intoRoom('player1') intoRoom('player2')",
"= 'https://question-zh.hortor.net/question/bat/fightResult' #生成签名 def genSign(params,player): tempParams = params.copy() tempParams['token'] = userInfo[player]['token']+userInfo[player]['uid'] tempParams =",
"print(player + ' 进入房间失败...') leaveRoom(player) def leaveRoom(player): params = { 'roomID' : roomID,",
"try: jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print(player + ' 退出房间成功...') else:",
"quizModel = {} quizModel['quiz'] = quiz quizModel['options'] = optionList quizModel['school'] = quizInfo['school'] quizModel['type']",
"pymongo import MongoClient headers = { 'content-type': 'application/x-www-form-urlencoded', } userInfo = { 'player1':{",
"beginFight() startAnswer() fightResult('player1') fightResult('player2') leaveRoom('player1') leaveRoom('player2') gameTime += 1 print('答题数 %d /命中题库次数 %d",
"json.loads(resp.text) if jdata.get('errcode') == 0: print(player + ' 选择成功...') return jdata.get('data') else: print(jdata)",
"选择失败...') print(resp.text) def fightResult(player): params = { 'roomID' : roomID, 'type' : 0,",
"= jdata.get('data')['roomId'] print(player + ' 进入房间成功...') except: print(resp.text) print(player + ' 进入房间失败...') leaveRoom(player)",
"print(resp.text) def genMagic(optionList): optionList.sort() originStr = optionList[0]+optionList[1]+optionList[2]+optionList[3] m = hashlib.md5() m.update(originStr.encode(encoding='utf-8')) return m.hexdigest()",
"= quizInfo['options'] quiz = quizInfo['quiz'] option = 1 #题库查找题目 #print(quiz) localQuiz = quizSet.find_one({'quiz':quiz})",
": roomID, 'type' : 0, 'uid' : userInfo[player]['uid'], 't' : nowTime() } params['sign']",
"= requests.session() roomID = -1 #命中题库次数 successTime = 0 #时间戳生成 nowTime = lambda:int(round(time.time()",
"0: print('开始好友对战...') else: print(jdata) except: print(resp.text) def findQuiz(quizNum): params = { 'roomID' :",
": roomID, 'uid' : userInfo[player]['uid'], 't' : nowTime() } params['sign'] = genSign(params,player) resp",
": nowTime(), 'option' : option, 'quizNum': quizNum, 'cfTime': cfTime, 'ccTime' : nowTime(), 'magic'",
"退出房间失败...') def beginFight(): params = { 'roomID' : roomID, 'uid' : userInfo['player1']['uid'], 't'",
"else: print(jdata) except: print(player + ' 获取结果失败...') print(resp.text) def genMagic(optionList): optionList.sort() originStr =",
"获取结果失败...') print(resp.text) def genMagic(optionList): optionList.sort() originStr = optionList[0]+optionList[1]+optionList[2]+optionList[3] m = hashlib.md5() m.update(originStr.encode(encoding='utf-8')) return",
"+ ' 选择成功...') return jdata.get('data') else: print(jdata) except: print(player + ' 选择失败...') print(resp.text)",
"import MongoClient headers = { 'content-type': 'application/x-www-form-urlencoded', } userInfo = { 'player1':{ 'uid':",
"m.update(originStr.encode(encoding='utf-8')) return m.hexdigest() def startAnswer(): global successTime for i in range(1,6): #请求数据与接收到数据延时 cfTime",
"+ ' 进入房间失败...') leaveRoom(player) def leaveRoom(player): params = { 'roomID' : roomID, 'uid'",
"'t' : nowTime() } params['sign'] = genSign(params,player) resp = session.post(url=leaveRoomUrl,data=params,headers=headers) try: jdata =",
"'roomID' : roomID, 'type' : 0, 'uid' : userInfo[player]['uid'], 't' : nowTime() }",
"'roomID' : roomID, 'uid' : userInfo[player]['uid'], 't' : nowTime() } params['sign'] = genSign(params,player)",
"roomID, 'uid' : userInfo[player]['uid'], 't' : nowTime() } params['sign'] = genSign(params,player) resp =",
"hashlib import time import json from pymongo import MongoClient headers = { 'content-type':",
"print(resp.text) print(player + ' 退出房间失败...') def beginFight(): params = { 'roomID' : roomID,",
"== 0: print(player + ' 获取结果成功...') return jdata.get('data') else: print(jdata) except: print(player +",
"+ str(value) m = hashlib.md5() m.update(originStr.encode(encoding='utf-8')) return m.hexdigest() def intoRoom(player): global roomID params",
"choose(player,quizNum,option,cfTime,magic): params = { 'roomID' : roomID, 'uid' : userInfo[player]['uid'], 't' : nowTime(),",
"0 while(i > 0): roomID = -1 intoRoom('player1') intoRoom('player2') beginFight() startAnswer() fightResult('player1') fightResult('player2')",
"conn.zhdtw.quizs intoRoomUrl = 'https://question-zh.hortor.net/question/bat/intoRoom' leaveRoomUrl = 'https://question-zh.hortor.net/question/bat/leaveRoom' beginFightUrl = 'https://question-zh.hortor.net/question/bat/beginFight' findQuizUrl = 'https://question-zh.hortor.net/question/bat/findQuiz'",
"resp = session.post(url=intoRoomUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) roomID = jdata.get('data')['roomId'] print(player + '",
"userInfo['player1']['uid'], 't' : nowTime() } params['sign'] = genSign(params,'player1') resp = session.post(url=beginFightUrl,data=params,headers=headers) try: jdata",
"= j+1 break magic = genMagic(optionList.copy()) chooseResult = choose('player1',i,option,cfTime,magic) choose('player2',i,2,cfTime+10,magic) if not localQuiz:",
"- cfTime time.sleep(0.1) optionList = quizInfo['options'] quiz = quizInfo['quiz'] option = 1 #题库查找题目",
"quizModel['quiz'] = quiz quizModel['options'] = optionList quizModel['school'] = quizInfo['school'] quizModel['type'] = quizInfo['type'] quizModel['typeID']",
"#生成签名 def genSign(params,player): tempParams = params.copy() tempParams['token'] = userInfo[player]['token']+userInfo[player]['uid'] tempParams = sorted(tempParams.items(), key=lambda",
": nowTime(), 'magic' : magic } params['sign'] = genSign(params,player) resp = session.post(url=chooseUrl,data=params,headers=headers) try",
"MongoClient('localhost',27017) quizSet = conn.zhdtw.quizs intoRoomUrl = 'https://question-zh.hortor.net/question/bat/intoRoom' leaveRoomUrl = 'https://question-zh.hortor.net/question/bat/leaveRoom' beginFightUrl = 'https://question-zh.hortor.net/question/bat/beginFight'",
"import time import json from pymongo import MongoClient headers = { 'content-type': 'application/x-www-form-urlencoded',",
"= { 'roomID' : roomID, 'uid' : userInfo['player1']['uid'], 't' : nowTime() } params['sign']",
"'玩家1号的token' }, 'player2':{ 'uid': '玩家2号的uid', 'token': '玩家2号的token' } } session = requests.session() roomID",
"key, value in tempParams: originStr = originStr + key + '=' + str(value)",
"m.hexdigest() def startAnswer(): global successTime for i in range(1,6): #请求数据与接收到数据延时 cfTime = nowTime()",
"+ ' 选择失败...') print(resp.text) def fightResult(player): params = { 'roomID' : roomID, 'type'",
": 0, 'uid' : userInfo[player]['uid'], 't' : nowTime() } params['sign'] = genSign(params,player) resp",
"print(jdata) except: print(resp.text) def findQuiz(quizNum): params = { 'roomID' : roomID, 'quizNum' :",
"= session.post(url=leaveRoomUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print(player + '",
"= userInfo[player]['token']+userInfo[player]['uid'] tempParams = sorted(tempParams.items(), key=lambda e:e[0]) originStr = '' for key, value",
"quizModel['options'] = optionList quizModel['school'] = quizInfo['school'] quizModel['type'] = quizInfo['type'] quizModel['typeID'] = quizInfo['typeID'] quizModel['contributor']",
"localQuiz: successTime += 1 for j in range(0,4): if(optionList[j] == localQuiz['answer']): option =",
"except: print(resp.text) print(player + ' 退出房间失败...') def beginFight(): params = { 'roomID' :",
"#时间戳生成 nowTime = lambda:int(round(time.time() * 1000)) #mongodb conn = MongoClient('localhost',27017) quizSet = conn.zhdtw.quizs",
"'uid': '玩家2号的uid', 'token': '玩家2号的token' } } session = requests.session() roomID = -1 #命中题库次数",
"userInfo[player]['token']+userInfo[player]['uid'] tempParams = sorted(tempParams.items(), key=lambda e:e[0]) originStr = '' for key, value in",
"获取结果成功...') return jdata.get('data') else: print(jdata) except: print(player + ' 获取结果失败...') print(resp.text) def genMagic(optionList):",
": roomID, 'uid' : userInfo[player]['uid'], 't' : nowTime(), 'option' : option, 'quizNum': quizNum,",
"except: print(resp.text) print(player + ' 进入房间失败...') leaveRoom(player) def leaveRoom(player): params = { 'roomID'",
"def fightResult(player): params = { 'roomID' : roomID, 'type' : 0, 'uid' :",
"jdata.get('errcode') == 0: print('开始好友对战...') else: print(jdata) except: print(resp.text) def findQuiz(quizNum): params = {",
"= json.loads(resp.text) if jdata.get('errcode') == 0: print(player + ' 选择成功...') return jdata.get('data') else:",
"in tempParams: originStr = originStr + key + '=' + str(value) m =",
"'https://question-zh.hortor.net/question/bat/findQuiz' chooseUrl = 'https://question-zh.hortor.net/question/bat/choose' fightResultUrl = 'https://question-zh.hortor.net/question/bat/fightResult' #生成签名 def genSign(params,player): tempParams = params.copy()",
"= genSign(params,player) resp = session.post(url=fightResultUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if jdata.get('errcode') == 0:",
"choose('player2',i,2,cfTime+10,magic) if not localQuiz: quizModel = {} quizModel['quiz'] = quiz quizModel['options'] = optionList",
"i = 5 gameTime = 0 while(i > 0): roomID = -1 intoRoom('player1')",
"optionList[0]+optionList[1]+optionList[2]+optionList[3] m = hashlib.md5() m.update(originStr.encode(encoding='utf-8')) return m.hexdigest() def startAnswer(): global successTime for i",
"startAnswer(): global successTime for i in range(1,6): #请求数据与接收到数据延时 cfTime = nowTime() quizInfo =",
"beginFight(): params = { 'roomID' : roomID, 'uid' : userInfo['player1']['uid'], 't' : nowTime()",
"cfTime = nowTime() quizInfo = findQuiz(i) cfTime = nowTime() - cfTime time.sleep(0.1) optionList",
"= choose('player1',i,option,cfTime,magic) choose('player2',i,2,cfTime+10,magic) if not localQuiz: quizModel = {} quizModel['quiz'] = quiz quizModel['options']",
"-1 intoRoom('player1') intoRoom('player2') beginFight() startAnswer() fightResult('player1') fightResult('player2') leaveRoom('player1') leaveRoom('player2') gameTime += 1 print('答题数",
"leaveRoom(player): params = { 'roomID' : roomID, 'uid' : userInfo[player]['uid'], 't' : nowTime()",
"= quizInfo['quiz'] option = 1 #题库查找题目 #print(quiz) localQuiz = quizSet.find_one({'quiz':quiz}) if localQuiz: successTime",
"quizSet.insert_one(quizModel) #print(optionList[chooseResult['answer']-1]) if __name__ == '__main__': #自行修改开房对战次数 i i = 5 gameTime =",
"if jdata.get('errcode') == 0: print('获取题目成功...') return jdata.get('data') else: print(jdata) except: print(resp.text) def choose(player,quizNum,option,cfTime,magic):",
"print('答题数 %d /命中题库次数 %d ' % (gameTime*5,successTime)) time.sleep(1) i = i - 1",
"optionList.sort() originStr = optionList[0]+optionList[1]+optionList[2]+optionList[3] m = hashlib.md5() m.update(originStr.encode(encoding='utf-8')) return m.hexdigest() def startAnswer(): global",
"= genSign(params,'player1') resp = session.post(url=findQuizUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if jdata.get('errcode') == 0:",
"try: jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print(player + ' 获取结果成功...') return",
"'t' : nowTime() } params['sign'] = genSign(params,player) resp = session.post(url=intoRoomUrl,data=params,headers=headers) try: jdata =",
"params.copy() tempParams['token'] = userInfo[player]['token']+userInfo[player]['uid'] tempParams = sorted(tempParams.items(), key=lambda e:e[0]) originStr = '' for",
"roomID, 'uid' : userInfo[player]['uid'], 't' : nowTime(), 'option' : option, 'quizNum': quizNum, 'cfTime':",
"choose('player1',i,option,cfTime,magic) choose('player2',i,2,cfTime+10,magic) if not localQuiz: quizModel = {} quizModel['quiz'] = quiz quizModel['options'] =",
"findQuiz(quizNum): params = { 'roomID' : roomID, 'quizNum' : quizNum, 'uid' : userInfo['player1']['uid'],",
"return jdata.get('data') else: print(jdata) except: print(resp.text) def choose(player,quizNum,option,cfTime,magic): params = { 'roomID' :",
"+ ' 退出房间成功...') else: print(jdata) except: print(resp.text) print(player + ' 退出房间失败...') def beginFight():",
"findQuizUrl = 'https://question-zh.hortor.net/question/bat/findQuiz' chooseUrl = 'https://question-zh.hortor.net/question/bat/choose' fightResultUrl = 'https://question-zh.hortor.net/question/bat/fightResult' #生成签名 def genSign(params,player): tempParams",
"= genMagic(optionList.copy()) chooseResult = choose('player1',i,option,cfTime,magic) choose('player2',i,2,cfTime+10,magic) if not localQuiz: quizModel = {} quizModel['quiz']",
"resp = session.post(url=beginFightUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print('开始好友对战...') else:",
"nowTime() } params['sign'] = genSign(params,'player1') resp = session.post(url=findQuizUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if",
"jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print(player + ' 退出房间成功...') else: print(jdata)",
"quizInfo['options'] quiz = quizInfo['quiz'] option = 1 #题库查找题目 #print(quiz) localQuiz = quizSet.find_one({'quiz':quiz}) if",
"= -1 #命中题库次数 successTime = 0 #时间戳生成 nowTime = lambda:int(round(time.time() * 1000)) #mongodb",
"params['sign'] = genSign(params,player) resp = session.post(url=intoRoomUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) roomID = jdata.get('data')['roomId']",
"== 0: print(player + ' 退出房间成功...') else: print(jdata) except: print(resp.text) print(player + '",
"params = { 'roomID' : roomID, 'type' : 0, 'uid' : userInfo[player]['uid'], 't'",
"* 1000)) #mongodb conn = MongoClient('localhost',27017) quizSet = conn.zhdtw.quizs intoRoomUrl = 'https://question-zh.hortor.net/question/bat/intoRoom' leaveRoomUrl",
"1 print('答题数 %d /命中题库次数 %d ' % (gameTime*5,successTime)) time.sleep(1) i = i -",
"userInfo[player]['uid'], 't' : nowTime() } params['sign'] = genSign(params,player) resp = session.post(url=leaveRoomUrl,data=params,headers=headers) try: jdata",
"0: print(player + ' 选择成功...') return jdata.get('data') else: print(jdata) except: print(player + '",
"#题库查找题目 #print(quiz) localQuiz = quizSet.find_one({'quiz':quiz}) if localQuiz: successTime += 1 for j in",
"return m.hexdigest() def intoRoom(player): global roomID params = { 'roomID' : roomID, 'uid'",
"'玩家1号的uid', 'token': '玩家1号的token' }, 'player2':{ 'uid': '玩家2号的uid', 'token': '玩家2号的token' } } session =",
": quizNum, 'uid' : userInfo['player1']['uid'], 't' : nowTime() } params['sign'] = genSign(params,'player1') resp",
"genSign(params,'player1') resp = session.post(url=findQuizUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print('获取题目成功...')",
"'uid' : userInfo[player]['uid'], 't' : nowTime() } params['sign'] = genSign(params,player) resp = session.post(url=fightResultUrl,data=params,headers=headers)",
"i i = 5 gameTime = 0 while(i > 0): roomID = -1",
"+ key + '=' + str(value) m = hashlib.md5() m.update(originStr.encode(encoding='utf-8')) return m.hexdigest() def",
"chooseResult = choose('player1',i,option,cfTime,magic) choose('player2',i,2,cfTime+10,magic) if not localQuiz: quizModel = {} quizModel['quiz'] = quiz",
"str(value) m = hashlib.md5() m.update(originStr.encode(encoding='utf-8')) return m.hexdigest() def intoRoom(player): global roomID params =",
"j in range(0,4): if(optionList[j] == localQuiz['answer']): option = j+1 break magic = genMagic(optionList.copy())",
"jdata.get('data') else: print(jdata) except: print(resp.text) def choose(player,quizNum,option,cfTime,magic): params = { 'roomID' : roomID,",
"= json.loads(resp.text) if jdata.get('errcode') == 0: print('开始好友对战...') else: print(jdata) except: print(resp.text) def findQuiz(quizNum):",
"+ ' 进入房间成功...') except: print(resp.text) print(player + ' 进入房间失败...') leaveRoom(player) def leaveRoom(player): params",
"0: print('获取题目成功...') return jdata.get('data') else: print(jdata) except: print(resp.text) def choose(player,quizNum,option,cfTime,magic): params = {",
"= 0 while(i > 0): roomID = -1 intoRoom('player1') intoRoom('player2') beginFight() startAnswer() fightResult('player1')",
"'content-type': 'application/x-www-form-urlencoded', } userInfo = { 'player1':{ 'uid': '玩家1号的uid', 'token': '玩家1号的token' }, 'player2':{",
"json.loads(resp.text) roomID = jdata.get('data')['roomId'] print(player + ' 进入房间成功...') except: print(resp.text) print(player + '",
"params['sign'] = genSign(params,'player1') resp = session.post(url=beginFightUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if jdata.get('errcode') ==",
"quizNum, 'uid' : userInfo['player1']['uid'], 't' : nowTime() } params['sign'] = genSign(params,'player1') resp =",
"optionList = quizInfo['options'] quiz = quizInfo['quiz'] option = 1 #题库查找题目 #print(quiz) localQuiz =",
"try: jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print('获取题目成功...') return jdata.get('data') else: print(jdata)",
"#print(optionList[chooseResult['answer']-1]) if __name__ == '__main__': #自行修改开房对战次数 i i = 5 gameTime = 0",
"} session = requests.session() roomID = -1 #命中题库次数 successTime = 0 #时间戳生成 nowTime",
"} params['sign'] = genSign(params,player) resp = session.post(url=fightResultUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if jdata.get('errcode')",
"= session.post(url=findQuizUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print('获取题目成功...') return jdata.get('data')",
"'player2':{ 'uid': '玩家2号的uid', 'token': '玩家2号的token' } } session = requests.session() roomID = -1",
"= quizInfo['typeID'] quizModel['contributor'] = quizInfo['contributor'] quizModel['answer'] = optionList[chooseResult['answer']-1] quizSet.insert_one(quizModel) #print(optionList[chooseResult['answer']-1]) if __name__ ==",
"== 0: print('开始好友对战...') else: print(jdata) except: print(resp.text) def findQuiz(quizNum): params = { 'roomID'",
"} params['sign'] = genSign(params,player) resp = session.post(url=intoRoomUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) roomID =",
"i in range(1,6): #请求数据与接收到数据延时 cfTime = nowTime() quizInfo = findQuiz(i) cfTime = nowTime()",
"'玩家2号的uid', 'token': '玩家2号的token' } } session = requests.session() roomID = -1 #命中题库次数 successTime",
"= optionList quizModel['school'] = quizInfo['school'] quizModel['type'] = quizInfo['type'] quizModel['typeID'] = quizInfo['typeID'] quizModel['contributor'] =",
"gameTime = 0 while(i > 0): roomID = -1 intoRoom('player1') intoRoom('player2') beginFight() startAnswer()",
"print(player + ' 获取结果失败...') print(resp.text) def genMagic(optionList): optionList.sort() originStr = optionList[0]+optionList[1]+optionList[2]+optionList[3] m =",
": roomID, 'uid' : userInfo['player1']['uid'], 't' : nowTime() } params['sign'] = genSign(params,'player1') resp",
"originStr + key + '=' + str(value) m = hashlib.md5() m.update(originStr.encode(encoding='utf-8')) return m.hexdigest()",
"} userInfo = { 'player1':{ 'uid': '玩家1号的uid', 'token': '玩家1号的token' }, 'player2':{ 'uid': '玩家2号的uid',",
"roomID params = { 'roomID' : roomID, 'uid' : userInfo[player]['uid'], 't' : nowTime()",
"= { 'content-type': 'application/x-www-form-urlencoded', } userInfo = { 'player1':{ 'uid': '玩家1号的uid', 'token': '玩家1号的token'",
"def startAnswer(): global successTime for i in range(1,6): #请求数据与接收到数据延时 cfTime = nowTime() quizInfo",
"key + '=' + str(value) m = hashlib.md5() m.update(originStr.encode(encoding='utf-8')) return m.hexdigest() def intoRoom(player):",
"print(jdata) except: print(resp.text) print(player + ' 退出房间失败...') def beginFight(): params = { 'roomID'",
"quizModel['answer'] = optionList[chooseResult['answer']-1] quizSet.insert_one(quizModel) #print(optionList[chooseResult['answer']-1]) if __name__ == '__main__': #自行修改开房对战次数 i i =",
"'t' : nowTime() } params['sign'] = genSign(params,'player1') resp = session.post(url=beginFightUrl,data=params,headers=headers) try: jdata =",
"userInfo['player1']['uid'], 't' : nowTime() } params['sign'] = genSign(params,'player1') resp = session.post(url=findQuizUrl,data=params,headers=headers) try: jdata",
"magic } params['sign'] = genSign(params,player) resp = session.post(url=chooseUrl,data=params,headers=headers) try : jdata = json.loads(resp.text)",
"'https://question-zh.hortor.net/question/bat/leaveRoom' beginFightUrl = 'https://question-zh.hortor.net/question/bat/beginFight' findQuizUrl = 'https://question-zh.hortor.net/question/bat/findQuiz' chooseUrl = 'https://question-zh.hortor.net/question/bat/choose' fightResultUrl = 'https://question-zh.hortor.net/question/bat/fightResult'",
"def beginFight(): params = { 'roomID' : roomID, 'uid' : userInfo['player1']['uid'], 't' :",
": userInfo[player]['uid'], 't' : nowTime() } params['sign'] = genSign(params,player) resp = session.post(url=fightResultUrl,data=params,headers=headers) try:",
"= session.post(url=chooseUrl,data=params,headers=headers) try : jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print(player +",
"'https://question-zh.hortor.net/question/bat/choose' fightResultUrl = 'https://question-zh.hortor.net/question/bat/fightResult' #生成签名 def genSign(params,player): tempParams = params.copy() tempParams['token'] = userInfo[player]['token']+userInfo[player]['uid']",
"params['sign'] = genSign(params,player) resp = session.post(url=chooseUrl,data=params,headers=headers) try : jdata = json.loads(resp.text) if jdata.get('errcode')",
"{ 'roomID' : roomID, 'uid' : userInfo[player]['uid'], 't' : nowTime() } params['sign'] =",
": nowTime() } params['sign'] = genSign(params,'player1') resp = session.post(url=beginFightUrl,data=params,headers=headers) try: jdata = json.loads(resp.text)",
"}, 'player2':{ 'uid': '玩家2号的uid', 'token': '玩家2号的token' } } session = requests.session() roomID =",
"not localQuiz: quizModel = {} quizModel['quiz'] = quiz quizModel['options'] = optionList quizModel['school'] =",
"sorted(tempParams.items(), key=lambda e:e[0]) originStr = '' for key, value in tempParams: originStr =",
"#print(quiz) localQuiz = quizSet.find_one({'quiz':quiz}) if localQuiz: successTime += 1 for j in range(0,4):",
"chooseUrl = 'https://question-zh.hortor.net/question/bat/choose' fightResultUrl = 'https://question-zh.hortor.net/question/bat/fightResult' #生成签名 def genSign(params,player): tempParams = params.copy() tempParams['token']",
"localQuiz: quizModel = {} quizModel['quiz'] = quiz quizModel['options'] = optionList quizModel['school'] = quizInfo['school']",
"import hashlib import time import json from pymongo import MongoClient headers = {",
"} params['sign'] = genSign(params,'player1') resp = session.post(url=findQuizUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if jdata.get('errcode')",
"for i in range(1,6): #请求数据与接收到数据延时 cfTime = nowTime() quizInfo = findQuiz(i) cfTime =",
"session.post(url=beginFightUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print('开始好友对战...') else: print(jdata) except:",
"except: print(resp.text) def choose(player,quizNum,option,cfTime,magic): params = { 'roomID' : roomID, 'uid' : userInfo[player]['uid'],",
"= quizInfo['type'] quizModel['typeID'] = quizInfo['typeID'] quizModel['contributor'] = quizInfo['contributor'] quizModel['answer'] = optionList[chooseResult['answer']-1] quizSet.insert_one(quizModel) #print(optionList[chooseResult['answer']-1])",
"roomID, 'type' : 0, 'uid' : userInfo[player]['uid'], 't' : nowTime() } params['sign'] =",
"'https://question-zh.hortor.net/question/bat/beginFight' findQuizUrl = 'https://question-zh.hortor.net/question/bat/findQuiz' chooseUrl = 'https://question-zh.hortor.net/question/bat/choose' fightResultUrl = 'https://question-zh.hortor.net/question/bat/fightResult' #生成签名 def genSign(params,player):",
"if jdata.get('errcode') == 0: print(player + ' 退出房间成功...') else: print(jdata) except: print(resp.text) print(player",
"' 进入房间失败...') leaveRoom(player) def leaveRoom(player): params = { 'roomID' : roomID, 'uid' :",
"'option' : option, 'quizNum': quizNum, 'cfTime': cfTime, 'ccTime' : nowTime(), 'magic' : magic",
"'magic' : magic } params['sign'] = genSign(params,player) resp = session.post(url=chooseUrl,data=params,headers=headers) try : jdata",
"'__main__': #自行修改开房对战次数 i i = 5 gameTime = 0 while(i > 0): roomID",
"quizNum, 'cfTime': cfTime, 'ccTime' : nowTime(), 'magic' : magic } params['sign'] = genSign(params,player)",
"quizInfo['quiz'] option = 1 #题库查找题目 #print(quiz) localQuiz = quizSet.find_one({'quiz':quiz}) if localQuiz: successTime +=",
"#自行修改开房对战次数 i i = 5 gameTime = 0 while(i > 0): roomID =",
"= { 'roomID' : roomID, 'uid' : userInfo[player]['uid'], 't' : nowTime() } params['sign']",
"' 退出房间成功...') else: print(jdata) except: print(resp.text) print(player + ' 退出房间失败...') def beginFight(): params",
"jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print('开始好友对战...') else: print(jdata) except: print(resp.text) def",
"import json from pymongo import MongoClient headers = { 'content-type': 'application/x-www-form-urlencoded', } userInfo",
"'uid' : userInfo[player]['uid'], 't' : nowTime(), 'option' : option, 'quizNum': quizNum, 'cfTime': cfTime,",
"quizInfo['typeID'] quizModel['contributor'] = quizInfo['contributor'] quizModel['answer'] = optionList[chooseResult['answer']-1] quizSet.insert_one(quizModel) #print(optionList[chooseResult['answer']-1]) if __name__ == '__main__':",
"m = hashlib.md5() m.update(originStr.encode(encoding='utf-8')) return m.hexdigest() def intoRoom(player): global roomID params = {",
"print(jdata) except: print(player + ' 选择失败...') print(resp.text) def fightResult(player): params = { 'roomID'",
"= json.loads(resp.text) if jdata.get('errcode') == 0: print(player + ' 退出房间成功...') else: print(jdata) except:",
"successTime += 1 for j in range(0,4): if(optionList[j] == localQuiz['answer']): option = j+1",
"magic = genMagic(optionList.copy()) chooseResult = choose('player1',i,option,cfTime,magic) choose('player2',i,2,cfTime+10,magic) if not localQuiz: quizModel = {}",
"quizModel['contributor'] = quizInfo['contributor'] quizModel['answer'] = optionList[chooseResult['answer']-1] quizSet.insert_one(quizModel) #print(optionList[chooseResult['answer']-1]) if __name__ == '__main__': #自行修改开房对战次数",
"fightResult('player1') fightResult('player2') leaveRoom('player1') leaveRoom('player2') gameTime += 1 print('答题数 %d /命中题库次数 %d ' %",
"'t' : nowTime() } params['sign'] = genSign(params,'player1') resp = session.post(url=findQuizUrl,data=params,headers=headers) try: jdata =",
"0: print(player + ' 退出房间成功...') else: print(jdata) except: print(resp.text) print(player + ' 退出房间失败...')",
"try: jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print('开始好友对战...') else: print(jdata) except: print(resp.text)",
"userInfo[player]['uid'], 't' : nowTime() } params['sign'] = genSign(params,player) resp = session.post(url=intoRoomUrl,data=params,headers=headers) try: jdata",
"+= 1 for j in range(0,4): if(optionList[j] == localQuiz['answer']): option = j+1 break",
"requests.session() roomID = -1 #命中题库次数 successTime = 0 #时间戳生成 nowTime = lambda:int(round(time.time() *",
"def genSign(params,player): tempParams = params.copy() tempParams['token'] = userInfo[player]['token']+userInfo[player]['uid'] tempParams = sorted(tempParams.items(), key=lambda e:e[0])",
"json.loads(resp.text) if jdata.get('errcode') == 0: print('获取题目成功...') return jdata.get('data') else: print(jdata) except: print(resp.text) def",
"} } session = requests.session() roomID = -1 #命中题库次数 successTime = 0 #时间戳生成",
"== '__main__': #自行修改开房对战次数 i i = 5 gameTime = 0 while(i > 0):",
"import requests import hashlib import time import json from pymongo import MongoClient headers",
"in range(1,6): #请求数据与接收到数据延时 cfTime = nowTime() quizInfo = findQuiz(i) cfTime = nowTime() -",
"print(jdata) except: print(player + ' 获取结果失败...') print(resp.text) def genMagic(optionList): optionList.sort() originStr = optionList[0]+optionList[1]+optionList[2]+optionList[3]",
"= quizInfo['contributor'] quizModel['answer'] = optionList[chooseResult['answer']-1] quizSet.insert_one(quizModel) #print(optionList[chooseResult['answer']-1]) if __name__ == '__main__': #自行修改开房对战次数 i",
"if not localQuiz: quizModel = {} quizModel['quiz'] = quiz quizModel['options'] = optionList quizModel['school']",
"0 #时间戳生成 nowTime = lambda:int(round(time.time() * 1000)) #mongodb conn = MongoClient('localhost',27017) quizSet =",
"params['sign'] = genSign(params,player) resp = session.post(url=leaveRoomUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if jdata.get('errcode') ==",
"退出房间成功...') else: print(jdata) except: print(resp.text) print(player + ' 退出房间失败...') def beginFight(): params =",
"genSign(params,player) resp = session.post(url=chooseUrl,data=params,headers=headers) try : jdata = json.loads(resp.text) if jdata.get('errcode') == 0:",
"successTime = 0 #时间戳生成 nowTime = lambda:int(round(time.time() * 1000)) #mongodb conn = MongoClient('localhost',27017)",
"localQuiz = quizSet.find_one({'quiz':quiz}) if localQuiz: successTime += 1 for j in range(0,4): if(optionList[j]",
"进入房间失败...') leaveRoom(player) def leaveRoom(player): params = { 'roomID' : roomID, 'uid' : userInfo[player]['uid'],",
"'token': '玩家1号的token' }, 'player2':{ 'uid': '玩家2号的uid', 'token': '玩家2号的token' } } session = requests.session()",
"nowTime = lambda:int(round(time.time() * 1000)) #mongodb conn = MongoClient('localhost',27017) quizSet = conn.zhdtw.quizs intoRoomUrl",
"= nowTime() quizInfo = findQuiz(i) cfTime = nowTime() - cfTime time.sleep(0.1) optionList =",
"+ '=' + str(value) m = hashlib.md5() m.update(originStr.encode(encoding='utf-8')) return m.hexdigest() def intoRoom(player): global",
"= MongoClient('localhost',27017) quizSet = conn.zhdtw.quizs intoRoomUrl = 'https://question-zh.hortor.net/question/bat/intoRoom' leaveRoomUrl = 'https://question-zh.hortor.net/question/bat/leaveRoom' beginFightUrl =",
"range(0,4): if(optionList[j] == localQuiz['answer']): option = j+1 break magic = genMagic(optionList.copy()) chooseResult =",
"def findQuiz(quizNum): params = { 'roomID' : roomID, 'quizNum' : quizNum, 'uid' :",
"def genMagic(optionList): optionList.sort() originStr = optionList[0]+optionList[1]+optionList[2]+optionList[3] m = hashlib.md5() m.update(originStr.encode(encoding='utf-8')) return m.hexdigest() def",
"jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print(player + ' 选择成功...') return jdata.get('data')",
"session.post(url=intoRoomUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) roomID = jdata.get('data')['roomId'] print(player + ' 进入房间成功...') except:",
"{} quizModel['quiz'] = quiz quizModel['options'] = optionList quizModel['school'] = quizInfo['school'] quizModel['type'] = quizInfo['type']",
"except: print(resp.text) def findQuiz(quizNum): params = { 'roomID' : roomID, 'quizNum' : quizNum,",
"= json.loads(resp.text) roomID = jdata.get('data')['roomId'] print(player + ' 进入房间成功...') except: print(resp.text) print(player +",
"__name__ == '__main__': #自行修改开房对战次数 i i = 5 gameTime = 0 while(i >",
"range(1,6): #请求数据与接收到数据延时 cfTime = nowTime() quizInfo = findQuiz(i) cfTime = nowTime() - cfTime",
"return jdata.get('data') else: print(jdata) except: print(player + ' 获取结果失败...') print(resp.text) def genMagic(optionList): optionList.sort()",
"roomID, 'quizNum' : quizNum, 'uid' : userInfo['player1']['uid'], 't' : nowTime() } params['sign'] =",
"originStr = '' for key, value in tempParams: originStr = originStr + key",
"beginFightUrl = 'https://question-zh.hortor.net/question/bat/beginFight' findQuizUrl = 'https://question-zh.hortor.net/question/bat/findQuiz' chooseUrl = 'https://question-zh.hortor.net/question/bat/choose' fightResultUrl = 'https://question-zh.hortor.net/question/bat/fightResult' #生成签名",
"quizInfo['type'] quizModel['typeID'] = quizInfo['typeID'] quizModel['contributor'] = quizInfo['contributor'] quizModel['answer'] = optionList[chooseResult['answer']-1] quizSet.insert_one(quizModel) #print(optionList[chooseResult['answer']-1]) if",
"'' for key, value in tempParams: originStr = originStr + key + '='",
"m = hashlib.md5() m.update(originStr.encode(encoding='utf-8')) return m.hexdigest() def startAnswer(): global successTime for i in",
"if jdata.get('errcode') == 0: print(player + ' 获取结果成功...') return jdata.get('data') else: print(jdata) except:",
"for key, value in tempParams: originStr = originStr + key + '=' +",
"== 0: print(player + ' 选择成功...') return jdata.get('data') else: print(jdata) except: print(player +",
"} params['sign'] = genSign(params,player) resp = session.post(url=leaveRoomUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if jdata.get('errcode')",
"quizInfo['school'] quizModel['type'] = quizInfo['type'] quizModel['typeID'] = quizInfo['typeID'] quizModel['contributor'] = quizInfo['contributor'] quizModel['answer'] = optionList[chooseResult['answer']-1]",
"= conn.zhdtw.quizs intoRoomUrl = 'https://question-zh.hortor.net/question/bat/intoRoom' leaveRoomUrl = 'https://question-zh.hortor.net/question/bat/leaveRoom' beginFightUrl = 'https://question-zh.hortor.net/question/bat/beginFight' findQuizUrl =",
"print(resp.text) def choose(player,quizNum,option,cfTime,magic): params = { 'roomID' : roomID, 'uid' : userInfo[player]['uid'], 't'",
"jdata = json.loads(resp.text) roomID = jdata.get('data')['roomId'] print(player + ' 进入房间成功...') except: print(resp.text) print(player",
"= -1 intoRoom('player1') intoRoom('player2') beginFight() startAnswer() fightResult('player1') fightResult('player2') leaveRoom('player1') leaveRoom('player2') gameTime += 1",
"else: print(jdata) except: print(resp.text) print(player + ' 退出房间失败...') def beginFight(): params = {",
"' 获取结果成功...') return jdata.get('data') else: print(jdata) except: print(player + ' 获取结果失败...') print(resp.text) def",
"= session.post(url=intoRoomUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) roomID = jdata.get('data')['roomId'] print(player + ' 进入房间成功...')",
"} params['sign'] = genSign(params,player) resp = session.post(url=chooseUrl,data=params,headers=headers) try : jdata = json.loads(resp.text) if",
"1 for j in range(0,4): if(optionList[j] == localQuiz['answer']): option = j+1 break magic",
"nowTime() quizInfo = findQuiz(i) cfTime = nowTime() - cfTime time.sleep(0.1) optionList = quizInfo['options']",
"optionList[chooseResult['answer']-1] quizSet.insert_one(quizModel) #print(optionList[chooseResult['answer']-1]) if __name__ == '__main__': #自行修改开房对战次数 i i = 5 gameTime",
"' 选择成功...') return jdata.get('data') else: print(jdata) except: print(player + ' 选择失败...') print(resp.text) def",
"0: print(player + ' 获取结果成功...') return jdata.get('data') else: print(jdata) except: print(player + '",
"jdata.get('data')['roomId'] print(player + ' 进入房间成功...') except: print(resp.text) print(player + ' 进入房间失败...') leaveRoom(player) def",
"'roomID' : roomID, 'uid' : userInfo[player]['uid'], 't' : nowTime(), 'option' : option, 'quizNum':",
"time.sleep(0.1) optionList = quizInfo['options'] quiz = quizInfo['quiz'] option = 1 #题库查找题目 #print(quiz) localQuiz",
"quizInfo['contributor'] quizModel['answer'] = optionList[chooseResult['answer']-1] quizSet.insert_one(quizModel) #print(optionList[chooseResult['answer']-1]) if __name__ == '__main__': #自行修改开房对战次数 i i",
"else: print(jdata) except: print(resp.text) def choose(player,quizNum,option,cfTime,magic): params = { 'roomID' : roomID, 'uid'",
"session.post(url=leaveRoomUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print(player + ' 退出房间成功...')",
"genSign(params,player): tempParams = params.copy() tempParams['token'] = userInfo[player]['token']+userInfo[player]['uid'] tempParams = sorted(tempParams.items(), key=lambda e:e[0]) originStr",
"fightResult('player2') leaveRoom('player1') leaveRoom('player2') gameTime += 1 print('答题数 %d /命中题库次数 %d ' % (gameTime*5,successTime))",
"= 1 #题库查找题目 #print(quiz) localQuiz = quizSet.find_one({'quiz':quiz}) if localQuiz: successTime += 1 for",
"1000)) #mongodb conn = MongoClient('localhost',27017) quizSet = conn.zhdtw.quizs intoRoomUrl = 'https://question-zh.hortor.net/question/bat/intoRoom' leaveRoomUrl =",
"= findQuiz(i) cfTime = nowTime() - cfTime time.sleep(0.1) optionList = quizInfo['options'] quiz =",
"{ 'roomID' : roomID, 'type' : 0, 'uid' : userInfo[player]['uid'], 't' : nowTime()",
"' 获取结果失败...') print(resp.text) def genMagic(optionList): optionList.sort() originStr = optionList[0]+optionList[1]+optionList[2]+optionList[3] m = hashlib.md5() m.update(originStr.encode(encoding='utf-8'))",
"+ ' 退出房间失败...') def beginFight(): params = { 'roomID' : roomID, 'uid' :",
"'ccTime' : nowTime(), 'magic' : magic } params['sign'] = genSign(params,player) resp = session.post(url=chooseUrl,data=params,headers=headers)",
"'roomID' : roomID, 'uid' : userInfo['player1']['uid'], 't' : nowTime() } params['sign'] = genSign(params,'player1')",
"genSign(params,'player1') resp = session.post(url=beginFightUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print('开始好友对战...')",
"jdata.get('errcode') == 0: print(player + ' 获取结果成功...') return jdata.get('data') else: print(jdata) except: print(player",
"-1 #命中题库次数 successTime = 0 #时间戳生成 nowTime = lambda:int(round(time.time() * 1000)) #mongodb conn",
"nowTime(), 'magic' : magic } params['sign'] = genSign(params,player) resp = session.post(url=chooseUrl,data=params,headers=headers) try :",
": userInfo['player1']['uid'], 't' : nowTime() } params['sign'] = genSign(params,'player1') resp = session.post(url=beginFightUrl,data=params,headers=headers) try:",
"jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print(player + ' 获取结果成功...') return jdata.get('data')",
": nowTime() } params['sign'] = genSign(params,player) resp = session.post(url=fightResultUrl,data=params,headers=headers) try: jdata = json.loads(resp.text)",
"session = requests.session() roomID = -1 #命中题库次数 successTime = 0 #时间戳生成 nowTime =",
"leaveRoom('player2') gameTime += 1 print('答题数 %d /命中题库次数 %d ' % (gameTime*5,successTime)) time.sleep(1) i",
"{ 'roomID' : roomID, 'quizNum' : quizNum, 'uid' : userInfo['player1']['uid'], 't' : nowTime()",
"= 0 #时间戳生成 nowTime = lambda:int(round(time.time() * 1000)) #mongodb conn = MongoClient('localhost',27017) quizSet",
"= { 'roomID' : roomID, 'uid' : userInfo[player]['uid'], 't' : nowTime(), 'option' :",
"> 0): roomID = -1 intoRoom('player1') intoRoom('player2') beginFight() startAnswer() fightResult('player1') fightResult('player2') leaveRoom('player1') leaveRoom('player2')",
"intoRoom(player): global roomID params = { 'roomID' : roomID, 'uid' : userInfo[player]['uid'], 't'",
"tempParams['token'] = userInfo[player]['token']+userInfo[player]['uid'] tempParams = sorted(tempParams.items(), key=lambda e:e[0]) originStr = '' for key,",
"quiz quizModel['options'] = optionList quizModel['school'] = quizInfo['school'] quizModel['type'] = quizInfo['type'] quizModel['typeID'] = quizInfo['typeID']",
"quizInfo = findQuiz(i) cfTime = nowTime() - cfTime time.sleep(0.1) optionList = quizInfo['options'] quiz",
"jdata.get('data') else: print(jdata) except: print(player + ' 获取结果失败...') print(resp.text) def genMagic(optionList): optionList.sort() originStr",
"= json.loads(resp.text) if jdata.get('errcode') == 0: print('获取题目成功...') return jdata.get('data') else: print(jdata) except: print(resp.text)",
"quizSet.find_one({'quiz':quiz}) if localQuiz: successTime += 1 for j in range(0,4): if(optionList[j] == localQuiz['answer']):",
"= quizInfo['school'] quizModel['type'] = quizInfo['type'] quizModel['typeID'] = quizInfo['typeID'] quizModel['contributor'] = quizInfo['contributor'] quizModel['answer'] =",
"if localQuiz: successTime += 1 for j in range(0,4): if(optionList[j] == localQuiz['answer']): option",
"= optionList[chooseResult['answer']-1] quizSet.insert_one(quizModel) #print(optionList[chooseResult['answer']-1]) if __name__ == '__main__': #自行修改开房对战次数 i i = 5",
"jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print('获取题目成功...') return jdata.get('data') else: print(jdata) except:",
"nowTime() - cfTime time.sleep(0.1) optionList = quizInfo['options'] quiz = quizInfo['quiz'] option = 1",
"nowTime() } params['sign'] = genSign(params,player) resp = session.post(url=intoRoomUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) roomID",
": nowTime() } params['sign'] = genSign(params,'player1') resp = session.post(url=findQuizUrl,data=params,headers=headers) try: jdata = json.loads(resp.text)",
"hashlib.md5() m.update(originStr.encode(encoding='utf-8')) return m.hexdigest() def intoRoom(player): global roomID params = { 'roomID' :",
"'token': '玩家2号的token' } } session = requests.session() roomID = -1 #命中题库次数 successTime =",
"lambda:int(round(time.time() * 1000)) #mongodb conn = MongoClient('localhost',27017) quizSet = conn.zhdtw.quizs intoRoomUrl = 'https://question-zh.hortor.net/question/bat/intoRoom'",
"jdata.get('errcode') == 0: print(player + ' 选择成功...') return jdata.get('data') else: print(jdata) except: print(player",
"params['sign'] = genSign(params,'player1') resp = session.post(url=findQuizUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if jdata.get('errcode') ==",
"= {} quizModel['quiz'] = quiz quizModel['options'] = optionList quizModel['school'] = quizInfo['school'] quizModel['type'] =",
"successTime for i in range(1,6): #请求数据与接收到数据延时 cfTime = nowTime() quizInfo = findQuiz(i) cfTime",
"tempParams = params.copy() tempParams['token'] = userInfo[player]['token']+userInfo[player]['uid'] tempParams = sorted(tempParams.items(), key=lambda e:e[0]) originStr =",
"0, 'uid' : userInfo[player]['uid'], 't' : nowTime() } params['sign'] = genSign(params,player) resp =",
"5 gameTime = 0 while(i > 0): roomID = -1 intoRoom('player1') intoRoom('player2') beginFight()",
"intoRoom('player2') beginFight() startAnswer() fightResult('player1') fightResult('player2') leaveRoom('player1') leaveRoom('player2') gameTime += 1 print('答题数 %d /命中题库次数",
"session.post(url=fightResultUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if jdata.get('errcode') == 0: print(player + ' 获取结果成功...')",
"{ 'roomID' : roomID, 'uid' : userInfo[player]['uid'], 't' : nowTime(), 'option' : option,",
"= quiz quizModel['options'] = optionList quizModel['school'] = quizInfo['school'] quizModel['type'] = quizInfo['type'] quizModel['typeID'] =",
"nowTime() } params['sign'] = genSign(params,player) resp = session.post(url=fightResultUrl,data=params,headers=headers) try: jdata = json.loads(resp.text) if",
"== localQuiz['answer']): option = j+1 break magic = genMagic(optionList.copy()) chooseResult = choose('player1',i,option,cfTime,magic) choose('player2',i,2,cfTime+10,magic)",
"MongoClient headers = { 'content-type': 'application/x-www-form-urlencoded', } userInfo = { 'player1':{ 'uid': '玩家1号的uid',",
"= json.loads(resp.text) if jdata.get('errcode') == 0: print(player + ' 获取结果成功...') return jdata.get('data') else:",
"= { 'roomID' : roomID, 'quizNum' : quizNum, 'uid' : userInfo['player1']['uid'], 't' :"
] |
[
"adc0 = ADC(Pin(26)) # create ADC object on ADC pin adc1 = ADC(Pin(27))",
"adc1 = ADC(Pin(27)) # create ADC object on ADC pin #adc=None, Vref=3.3, R=10000,",
") ntc0=NTC(adc=ADC(Pin(26)), R=3300, Ro=47000, beta=3740) ntc1=NTC(adc=ADC(Pin(27)), R=3300, Ro=47000, beta=3740) print (\"{} V\".format(ntc0.in_volt())) print",
"Pin from ntc import * adc0 = ADC(Pin(26)) # create ADC object on",
"from ntc import * adc0 = ADC(Pin(26)) # create ADC object on ADC",
"ntc import * adc0 = ADC(Pin(26)) # create ADC object on ADC pin",
"on ADC pin adc1 = ADC(Pin(27)) # create ADC object on ADC pin",
"machine import ADC, Pin from ntc import * adc0 = ADC(Pin(26)) # create",
"* adc0 = ADC(Pin(26)) # create ADC object on ADC pin adc1 =",
"Ro=10000.0, To=25.0, beta=3950.0, V=5 ) ntc0=NTC(adc=ADC(Pin(26)), R=3300, Ro=47000, beta=3740) ntc1=NTC(adc=ADC(Pin(27)), R=3300, Ro=47000, beta=3740)",
"beta=3740) print (\"{} V\".format(ntc0.in_volt())) print (\"{} V\".format(ntc1.in_volt())) print(\"{} ohm\".format(ntc0.r_UP())) print(\"{} ohm\".format(ntc1.r_UP())) print(\"{} C\".format(ntc0.to_temp(ntc0.r_UP())))",
"ADC(Pin(27)) # create ADC object on ADC pin #adc=None, Vref=3.3, R=10000, Ro=10000.0, To=25.0,",
"object on ADC pin #adc=None, Vref=3.3, R=10000, Ro=10000.0, To=25.0, beta=3950.0, V=5 ) ntc0=NTC(adc=ADC(Pin(26)),",
"pin #adc=None, Vref=3.3, R=10000, Ro=10000.0, To=25.0, beta=3950.0, V=5 ) ntc0=NTC(adc=ADC(Pin(26)), R=3300, Ro=47000, beta=3740)",
"ntc1=NTC(adc=ADC(Pin(27)), R=3300, Ro=47000, beta=3740) print (\"{} V\".format(ntc0.in_volt())) print (\"{} V\".format(ntc1.in_volt())) print(\"{} ohm\".format(ntc0.r_UP())) print(\"{}",
"pin adc1 = ADC(Pin(27)) # create ADC object on ADC pin #adc=None, Vref=3.3,",
"ADC pin #adc=None, Vref=3.3, R=10000, Ro=10000.0, To=25.0, beta=3950.0, V=5 ) ntc0=NTC(adc=ADC(Pin(26)), R=3300, Ro=47000,",
"#adc=None, Vref=3.3, R=10000, Ro=10000.0, To=25.0, beta=3950.0, V=5 ) ntc0=NTC(adc=ADC(Pin(26)), R=3300, Ro=47000, beta=3740) ntc1=NTC(adc=ADC(Pin(27)),",
"import * adc0 = ADC(Pin(26)) # create ADC object on ADC pin adc1",
"ADC pin adc1 = ADC(Pin(27)) # create ADC object on ADC pin #adc=None,",
"<gh_stars>0 from machine import ADC, Pin from ntc import * adc0 = ADC(Pin(26))",
"ntc0=NTC(adc=ADC(Pin(26)), R=3300, Ro=47000, beta=3740) ntc1=NTC(adc=ADC(Pin(27)), R=3300, Ro=47000, beta=3740) print (\"{} V\".format(ntc0.in_volt())) print (\"{}",
"beta=3950.0, V=5 ) ntc0=NTC(adc=ADC(Pin(26)), R=3300, Ro=47000, beta=3740) ntc1=NTC(adc=ADC(Pin(27)), R=3300, Ro=47000, beta=3740) print (\"{}",
"ADC, Pin from ntc import * adc0 = ADC(Pin(26)) # create ADC object",
"Vref=3.3, R=10000, Ro=10000.0, To=25.0, beta=3950.0, V=5 ) ntc0=NTC(adc=ADC(Pin(26)), R=3300, Ro=47000, beta=3740) ntc1=NTC(adc=ADC(Pin(27)), R=3300,",
"beta=3740) ntc1=NTC(adc=ADC(Pin(27)), R=3300, Ro=47000, beta=3740) print (\"{} V\".format(ntc0.in_volt())) print (\"{} V\".format(ntc1.in_volt())) print(\"{} ohm\".format(ntc0.r_UP()))",
"R=3300, Ro=47000, beta=3740) ntc1=NTC(adc=ADC(Pin(27)), R=3300, Ro=47000, beta=3740) print (\"{} V\".format(ntc0.in_volt())) print (\"{} V\".format(ntc1.in_volt()))",
"= ADC(Pin(27)) # create ADC object on ADC pin #adc=None, Vref=3.3, R=10000, Ro=10000.0,",
"on ADC pin #adc=None, Vref=3.3, R=10000, Ro=10000.0, To=25.0, beta=3950.0, V=5 ) ntc0=NTC(adc=ADC(Pin(26)), R=3300,",
"# create ADC object on ADC pin #adc=None, Vref=3.3, R=10000, Ro=10000.0, To=25.0, beta=3950.0,",
"object on ADC pin adc1 = ADC(Pin(27)) # create ADC object on ADC",
"import ADC, Pin from ntc import * adc0 = ADC(Pin(26)) # create ADC",
"from machine import ADC, Pin from ntc import * adc0 = ADC(Pin(26)) #",
"V=5 ) ntc0=NTC(adc=ADC(Pin(26)), R=3300, Ro=47000, beta=3740) ntc1=NTC(adc=ADC(Pin(27)), R=3300, Ro=47000, beta=3740) print (\"{} V\".format(ntc0.in_volt()))",
"R=3300, Ro=47000, beta=3740) print (\"{} V\".format(ntc0.in_volt())) print (\"{} V\".format(ntc1.in_volt())) print(\"{} ohm\".format(ntc0.r_UP())) print(\"{} ohm\".format(ntc1.r_UP()))",
"= ADC(Pin(26)) # create ADC object on ADC pin adc1 = ADC(Pin(27)) #",
"To=25.0, beta=3950.0, V=5 ) ntc0=NTC(adc=ADC(Pin(26)), R=3300, Ro=47000, beta=3740) ntc1=NTC(adc=ADC(Pin(27)), R=3300, Ro=47000, beta=3740) print",
"R=10000, Ro=10000.0, To=25.0, beta=3950.0, V=5 ) ntc0=NTC(adc=ADC(Pin(26)), R=3300, Ro=47000, beta=3740) ntc1=NTC(adc=ADC(Pin(27)), R=3300, Ro=47000,",
"ADC object on ADC pin #adc=None, Vref=3.3, R=10000, Ro=10000.0, To=25.0, beta=3950.0, V=5 )",
"Ro=47000, beta=3740) ntc1=NTC(adc=ADC(Pin(27)), R=3300, Ro=47000, beta=3740) print (\"{} V\".format(ntc0.in_volt())) print (\"{} V\".format(ntc1.in_volt())) print(\"{}",
"Ro=47000, beta=3740) print (\"{} V\".format(ntc0.in_volt())) print (\"{} V\".format(ntc1.in_volt())) print(\"{} ohm\".format(ntc0.r_UP())) print(\"{} ohm\".format(ntc1.r_UP())) print(\"{}",
"ADC(Pin(26)) # create ADC object on ADC pin adc1 = ADC(Pin(27)) # create",
"(\"{} V\".format(ntc0.in_volt())) print (\"{} V\".format(ntc1.in_volt())) print(\"{} ohm\".format(ntc0.r_UP())) print(\"{} ohm\".format(ntc1.r_UP())) print(\"{} C\".format(ntc0.to_temp(ntc0.r_UP()))) print(\"{} C\".format(ntc1.to_temp(ntc1.r_UP())))",
"print (\"{} V\".format(ntc0.in_volt())) print (\"{} V\".format(ntc1.in_volt())) print(\"{} ohm\".format(ntc0.r_UP())) print(\"{} ohm\".format(ntc1.r_UP())) print(\"{} C\".format(ntc0.to_temp(ntc0.r_UP()))) print(\"{}",
"# create ADC object on ADC pin adc1 = ADC(Pin(27)) # create ADC",
"ADC object on ADC pin adc1 = ADC(Pin(27)) # create ADC object on",
"create ADC object on ADC pin adc1 = ADC(Pin(27)) # create ADC object",
"create ADC object on ADC pin #adc=None, Vref=3.3, R=10000, Ro=10000.0, To=25.0, beta=3950.0, V=5"
] |
[
"Bank Transfer \"\"\" k = int(input()) fee = 25 + k * 0.01",
"> 2000 else fee fee = 100 if fee < 100 else fee",
"2000 if fee > 2000 else fee fee = 100 if fee <",
"fee = 25 + k * 0.01 fee = 2000 if fee >",
"= 2000 if fee > 2000 else fee fee = 100 if fee",
"\"\"\" 백준 21633번 : Bank Transfer \"\"\" k = int(input()) fee = 25",
"0.01 fee = 2000 if fee > 2000 else fee fee = 100",
"k = int(input()) fee = 25 + k * 0.01 fee = 2000",
"int(input()) fee = 25 + k * 0.01 fee = 2000 if fee",
"fee = 2000 if fee > 2000 else fee fee = 100 if",
"\"\"\" k = int(input()) fee = 25 + k * 0.01 fee =",
"Transfer \"\"\" k = int(input()) fee = 25 + k * 0.01 fee",
"2000 else fee fee = 100 if fee < 100 else fee print(fee)",
"= 25 + k * 0.01 fee = 2000 if fee > 2000",
"21633번 : Bank Transfer \"\"\" k = int(input()) fee = 25 + k",
"if fee > 2000 else fee fee = 100 if fee < 100",
"fee > 2000 else fee fee = 100 if fee < 100 else",
"= int(input()) fee = 25 + k * 0.01 fee = 2000 if",
": Bank Transfer \"\"\" k = int(input()) fee = 25 + k *",
"k * 0.01 fee = 2000 if fee > 2000 else fee fee",
"+ k * 0.01 fee = 2000 if fee > 2000 else fee",
"25 + k * 0.01 fee = 2000 if fee > 2000 else",
"백준 21633번 : Bank Transfer \"\"\" k = int(input()) fee = 25 +",
"* 0.01 fee = 2000 if fee > 2000 else fee fee ="
] |
[
"dice_result = [] for i in range(0,1000): dice1 = random.randint(1,6) dice2 = random.randint(1,6)",
"= [] for i in range(0,1000): dice1 = random.randint(1,6) dice2 = random.randint(1,6) dice_result.append(dice1+dice2)",
"random.randint(1,6) dice2 = random.randint(1,6) dice_result.append(dice1+dice2) mean = sum(dice_result)/len(dice_result) print(\"mean of this data is",
"mode= statistics.mode(dice_result) print(\"mode of this data is {} \".format(mode)) std_deviation = statistics.stdev(dice_result) print(\"stdev",
"range(0,1000): dice1 = random.randint(1,6) dice2 = random.randint(1,6) dice_result.append(dice1+dice2) mean = sum(dice_result)/len(dice_result) print(\"mean of",
"data is {} \".format(mean)) median = statistics.median(dice_result) print(\"median of this data is {}",
"of this data is {} \".format(median)) mode= statistics.mode(dice_result) print(\"mode of this data is",
"dice2 = random.randint(1,6) dice_result.append(dice1+dice2) mean = sum(dice_result)/len(dice_result) print(\"mean of this data is {}",
"is {} \".format(mode)) std_deviation = statistics.stdev(dice_result) print(\"stdev : {}\".format(std_deviation) ) fig = ff.create_distplot([dice_result],[\"Result\"],",
"= sum(dice_result)/len(dice_result) print(\"mean of this data is {} \".format(mean)) median = statistics.median(dice_result) print(\"median",
"[] for i in range(0,1000): dice1 = random.randint(1,6) dice2 = random.randint(1,6) dice_result.append(dice1+dice2) mean",
"= statistics.median(dice_result) print(\"median of this data is {} \".format(median)) mode= statistics.mode(dice_result) print(\"mode of",
"plotly.express as px import plotly.figure_factory as ff import statistics dice_result = [] for",
"import random import plotly.express as px import plotly.figure_factory as ff import statistics dice_result",
"dice_result.append(dice1+dice2) mean = sum(dice_result)/len(dice_result) print(\"mean of this data is {} \".format(mean)) median =",
"i in range(0,1000): dice1 = random.randint(1,6) dice2 = random.randint(1,6) dice_result.append(dice1+dice2) mean = sum(dice_result)/len(dice_result)",
"= random.randint(1,6) dice_result.append(dice1+dice2) mean = sum(dice_result)/len(dice_result) print(\"mean of this data is {} \".format(mean))",
"\".format(median)) mode= statistics.mode(dice_result) print(\"mode of this data is {} \".format(mode)) std_deviation = statistics.stdev(dice_result)",
"mean = sum(dice_result)/len(dice_result) print(\"mean of this data is {} \".format(mean)) median = statistics.median(dice_result)",
"this data is {} \".format(mean)) median = statistics.median(dice_result) print(\"median of this data is",
"px import plotly.figure_factory as ff import statistics dice_result = [] for i in",
"\".format(mean)) median = statistics.median(dice_result) print(\"median of this data is {} \".format(median)) mode= statistics.mode(dice_result)",
"of this data is {} \".format(mean)) median = statistics.median(dice_result) print(\"median of this data",
"print(\"median of this data is {} \".format(median)) mode= statistics.mode(dice_result) print(\"mode of this data",
"of this data is {} \".format(mode)) std_deviation = statistics.stdev(dice_result) print(\"stdev : {}\".format(std_deviation) )",
"as ff import statistics dice_result = [] for i in range(0,1000): dice1 =",
"{} \".format(median)) mode= statistics.mode(dice_result) print(\"mode of this data is {} \".format(mode)) std_deviation =",
"sum(dice_result)/len(dice_result) print(\"mean of this data is {} \".format(mean)) median = statistics.median(dice_result) print(\"median of",
"data is {} \".format(mode)) std_deviation = statistics.stdev(dice_result) print(\"stdev : {}\".format(std_deviation) ) fig =",
"std_deviation = statistics.stdev(dice_result) print(\"stdev : {}\".format(std_deviation) ) fig = ff.create_distplot([dice_result],[\"Result\"], show_hist= False) fig.show()",
"this data is {} \".format(mode)) std_deviation = statistics.stdev(dice_result) print(\"stdev : {}\".format(std_deviation) ) fig",
"in range(0,1000): dice1 = random.randint(1,6) dice2 = random.randint(1,6) dice_result.append(dice1+dice2) mean = sum(dice_result)/len(dice_result) print(\"mean",
"import plotly.figure_factory as ff import statistics dice_result = [] for i in range(0,1000):",
"import statistics dice_result = [] for i in range(0,1000): dice1 = random.randint(1,6) dice2",
"is {} \".format(mean)) median = statistics.median(dice_result) print(\"median of this data is {} \".format(median))",
"= random.randint(1,6) dice2 = random.randint(1,6) dice_result.append(dice1+dice2) mean = sum(dice_result)/len(dice_result) print(\"mean of this data",
"{} \".format(mean)) median = statistics.median(dice_result) print(\"median of this data is {} \".format(median)) mode=",
"= statistics.stdev(dice_result) print(\"stdev : {}\".format(std_deviation) ) fig = ff.create_distplot([dice_result],[\"Result\"], show_hist= False) fig.show() fig.show()",
"for i in range(0,1000): dice1 = random.randint(1,6) dice2 = random.randint(1,6) dice_result.append(dice1+dice2) mean =",
"dice1 = random.randint(1,6) dice2 = random.randint(1,6) dice_result.append(dice1+dice2) mean = sum(dice_result)/len(dice_result) print(\"mean of this",
"statistics.median(dice_result) print(\"median of this data is {} \".format(median)) mode= statistics.mode(dice_result) print(\"mode of this",
"random import plotly.express as px import plotly.figure_factory as ff import statistics dice_result =",
"ff import statistics dice_result = [] for i in range(0,1000): dice1 = random.randint(1,6)",
"is {} \".format(median)) mode= statistics.mode(dice_result) print(\"mode of this data is {} \".format(mode)) std_deviation",
"median = statistics.median(dice_result) print(\"median of this data is {} \".format(median)) mode= statistics.mode(dice_result) print(\"mode",
"plotly.figure_factory as ff import statistics dice_result = [] for i in range(0,1000): dice1",
"statistics.mode(dice_result) print(\"mode of this data is {} \".format(mode)) std_deviation = statistics.stdev(dice_result) print(\"stdev :",
"import plotly.express as px import plotly.figure_factory as ff import statistics dice_result = []",
"data is {} \".format(median)) mode= statistics.mode(dice_result) print(\"mode of this data is {} \".format(mode))",
"print(\"mean of this data is {} \".format(mean)) median = statistics.median(dice_result) print(\"median of this",
"this data is {} \".format(median)) mode= statistics.mode(dice_result) print(\"mode of this data is {}",
"random.randint(1,6) dice_result.append(dice1+dice2) mean = sum(dice_result)/len(dice_result) print(\"mean of this data is {} \".format(mean)) median",
"\".format(mode)) std_deviation = statistics.stdev(dice_result) print(\"stdev : {}\".format(std_deviation) ) fig = ff.create_distplot([dice_result],[\"Result\"], show_hist= False)",
"as px import plotly.figure_factory as ff import statistics dice_result = [] for i",
"print(\"mode of this data is {} \".format(mode)) std_deviation = statistics.stdev(dice_result) print(\"stdev : {}\".format(std_deviation)",
"statistics dice_result = [] for i in range(0,1000): dice1 = random.randint(1,6) dice2 =",
"{} \".format(mode)) std_deviation = statistics.stdev(dice_result) print(\"stdev : {}\".format(std_deviation) ) fig = ff.create_distplot([dice_result],[\"Result\"], show_hist="
] |
[
"+ len(self.cert_data) uefi_subreg_authen_hdr = struct.pack( self._StructAuthInfoFormat, self.w_name, self.vendor_guid.bytes_le, self.w_revision, self.dw_length, self.cert_type.bytes_le, ) self._valid",
"typedef struct { # SUB_REGION_HEADER Hdr; // Certificate Header # UINT8 CertData[1]; //",
"# typedef struct { # SUB_REGION_HEADER Hdr; // Certificate Header # UINT8 CertData[1];",
"== 0: LOGGER.critical(\"size of {} subregion file must be greater than 0!\".format(sbrgn_file)) sys.exit(status)",
"# Get signing type information cert_info = CERT_TYPE.get(cl_inputs.signer_type) # Create openSSL command 1",
"-modulus -noout\", ], } # Check if openssl is installed path = utils.check_for_tool(\"openssl\",",
"\"The size of {} is {}. The {} size must not be greter",
"import subprocess import argparse import uuid import struct import re from pathlib import",
"= self._StructAuthInfoSize self.cert_type = cert_info[\"cert_type\"] self.cert_data = bytes() self.payload = bytes() def encode(self):",
"header and signature and original file build_subreg_signed_file(uefi_signed_data, str(outfile)) print( \"Signed {} sub-region({}) was",
"reserved. # SPDX-License-Identifier: BSD-2-Clause # \"\"\"A signing utility for creating and signing a",
"signed_file: signed_file.write(cert_struct) except ValueError: LOGGER.critical(\"\\nCannot write payload file: %s\", outfile) sys.exit(2) def read_file(inputfile):",
"self.w_name, self.vendor_guid.bytes_le, self.w_revision, self.dw_length, self.cert_type.bytes_le, ) self._valid = True return uefi_subreg_authen_hdr + self.cert_data",
"print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.dw_length = {dw_length:08X}\".format( dw_length=self.dw_length ) ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.w_revision = {w_revision:04X}\".format( w_revision=self.w_revision )",
"-keyform PEM -sha384 -sign\", \"rsa -pubout -modulus -noout\", ], } # Check if",
"Signature # } SUB_REGION_VERIFICATION; # typedef struct { # UINT32 Revision; // Revision",
"0-9 guidFormat = re.compile( r\"([a-f\\d]{8}[-][a-f\\d]{4}[-][a-f\\d]{4}[-][a-f\\d]{4}[-]{1}[a-f\\d]{12}$)\", re.I ) if guidFormat.match(guid) is None: raise argparse.ArgumentTypeError(",
"that needs to be signed.\" ) my_parser.add_argument( \"-o\", \"--output\", dest=\"signed_file\", help=\"Output capsule filename.\",",
"already in PATH.\", default=None, ) my_parser.add_argument( \"--show\", help=\"Shows information about the subregion_authentication structure",
") print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.w_revision = {w_revision:04X}\".format( w_revision=self.w_revision ) ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.wCertificateType = {Vendor_guid}\".format( Vendor_guid=str(self.vendor_guid).upper()",
"for openSSL sbrgn_file = Path(subregion_file).resolve() signer_file = Path(signer_file).resolve() outfile = Path(signed_file).resolve() filenames =",
"= get_certifcation_info(cl_inputs, signer_file) uefi_subreg_authen = UefiSubregAuthenClass(cert_info) # read input file to store into",
"self.payload def dump_info(self): \"\"\" dump the information of subregion authentication structure \"\"\" if",
"input=payload, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, check=True, ) signature = ssl_process.stdout except: LOGGER.warning(\"\\nCannot run openssl.\")",
"Structure # UINT32 Length; // Length of the Signature + Header # EFI_GUID",
"my_parser.add_argument( \"--toolpath\", dest=\"tool_path\", help=\"Path to signtool or OpenSSL tool. \" \" Optional if",
"Calculated Signature # } SUB_REGION_VERIFICATION; # typedef struct { # UINT32 Revision; //",
"for guid xxxxxxxx-xxxx-xxxx-xxx-xxxxxxxxxxxx where x can be A-F or 0-9 guidFormat = re.compile(",
"in correct format \\ (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx where x can be A-F or 0-9)\\ {}\".format(guid)",
"uefi_subreg_authen = UefiSubregAuthenClass(cert_info) # read input file to store into structure payload =",
"outfile): \"\"\" build output file \"\"\" try: with open(outfile, mode=\"wb\") as signed_file: signed_file.write(cert_struct)",
"uefi_subreg_authen.cert_data = cert_data # pack structure with signature and get update size of",
"different signature type supported by tool CERT_TYPE = { \"pkcs7\": [ \"4aafd29d-68df-49ee-8aa9-347d375665a7\", \"smime",
"0: sys.exit(status) if os.path.getsize(sbrgn_file) == 0: LOGGER.critical(\"size of {} subregion file must be",
"Tool\", action=\"version\", version=\"%(prog)s {version}\".format(version=__version__), ) return my_parser def chk_string_size(string): \"\"\"\"Check the size of",
"tool CERT_TYPE = { \"pkcs7\": [ \"4aafd29d-68df-49ee-8aa9-347d375665a7\", \"smime -sign -binary -outform DER -md",
"signature type supported by tool CERT_TYPE = { \"pkcs7\": [ \"4aafd29d-68df-49ee-8aa9-347d375665a7\", \"smime -sign",
"signature from STDOUT try: ssl_process = subprocess.run( openssl_cmd, input=payload, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, check=True,",
"= re.compile( r\"([a-f\\d]{8}[-][a-f\\d]{4}[-][a-f\\d]{4}[-][a-f\\d]{4}[-]{1}[a-f\\d]{12}$)\", re.I ) if guidFormat.match(guid) is None: raise argparse.ArgumentTypeError( \"File guild",
"successfully generated.\".format( subregion_name, outfile ) ) def main(): \"\"\"Entry to script.\"\"\" parser =",
"input file to bytes \"\"\" try: with open(inputfile, mode=\"rb\") as file: sign_file =",
"original file build_subreg_signed_file(uefi_signed_data, str(outfile)) print( \"Signed {} sub-region({}) was successfully generated.\".format( subregion_name, outfile",
"on subregion \"\"\" # different signature type supported by tool CERT_TYPE = {",
"path = utils.check_for_tool(\"openssl\", \"version\", cl_inputs.tool_path) # Get signing type information cert_info = CERT_TYPE.get(cl_inputs.signer_type)",
"cert_pub = generate_signature(cert_info[\"openssl_cmd2\"], payload) # convert public key from bytes to string cert_pub_string",
"outfile ) ) def main(): \"\"\"Entry to script.\"\"\" parser = create_arg_parser() args =",
"args.signerfile, args.signed_file, args.signer_type, args.name, args.vendor_guid, args.show, args.tool_path) if __name__ == \"__main__\": banner(TOOLNAME, __version__)",
"sign_file def generate_signature(openssl_cmd, payload): \"\"\" signed input file \"\"\" # Run OpenSSL command",
"// Signature type # } SUB_REGION_HEADER; # typedef struct { # UINT8 PublicKey[384];",
"cert_type=str(self.cert_type).upper() ) ) print( \"sizeof (EFI_SUBREGION_AUTHENTICATION.AuthInfo.cert_data) = {Size:08X}\".format( Size=len(self.cert_data) ) ) print( \"sizeof",
"ValueError: LOGGER.critical(\"\\nCannot read payload file: %s\", inputfile) sys.exit(2) return sign_file def generate_signature(openssl_cmd, payload):",
"Max size is 16 bytes The name is stored in signed file.\", type=chk_string_size,",
"\"\"\" try: with open(outfile, mode=\"wb\") as signed_file: signed_file.write(cert_struct) except ValueError: LOGGER.critical(\"\\nCannot write payload",
"// Name of the sub-region # EFI_GUID VendorGuid; // Vendor GUID # SUB_REGION_VERIFICATION",
"convert_arg_line_to_args(arg_line): for arg in arg_line.split(): if not arg.strip(): continue yield arg my_parser =",
"build output file \"\"\" try: with open(outfile, mode=\"wb\") as signed_file: signed_file.write(cert_struct) except ValueError:",
"{ \"revision\": 0x01, \"name\": cl_inputs.name.encode(\"utf-8\"), \"vendor_guid\": uuid.UUID(cl_inputs.vendor_guid), \"cert_type\": uuid.UUID(cert_info[0]), \"openssl_cmd\": cmd, \"openssl_cmd2\": cmd2,",
"\"--show\", help=\"Shows information about the subregion_authentication structure \" \" Optional but requires all",
"raise argparse.ArgumentTypeError( \"File guild value is not in correct format \\ (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx where",
"# } EFI_CERT_BLOCK_RSA3072_SHA384; _StructAuthInfoFormat = \"<16s16sLL16s\" _StructAuthInfoSize = struct.calcsize(_StructAuthInfoFormat) _StructSubRegionHdrFormat = \"<LL16s\" _StructSubRegionHdrSize",
"# pack structure with signature and get update size of header uefi_signed_data =",
"\"\"\"Entry to script.\"\"\" parser = create_arg_parser() args = parser.parse_args() sign_subregion(args.subregion_file, args.signerfile, args.signed_file, args.signer_type,",
"max_size ) if size > max_size: raise argparse.ArgumentTypeError(str(msg)) return string def chk_guid_format(guid): \"\"\"",
"public key and signature are packed back to back cert_data = cert_pubkey +",
") print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.cert_type = {cert_type}\".format( cert_type=str(self.cert_type).upper() ) ) print( \"sizeof (EFI_SUBREGION_AUTHENTICATION.AuthInfo.cert_data) = {Size:08X}\".format(",
"-sha384 -sign\", \"rsa -pubout -modulus -noout\", ], } # Check if openssl is",
"f'{path} {cert_info[1]} \"{signer}\"' # Create openSSL command 2 if cert_info[2] is not None:",
"dest=\"tool_path\", help=\"Path to signtool or OpenSSL tool. \" \" Optional if path to",
"0x01, \"name\": cl_inputs.name.encode(\"utf-8\"), \"vendor_guid\": uuid.UUID(cl_inputs.vendor_guid), \"cert_type\": uuid.UUID(cert_info[0]), \"openssl_cmd\": cmd, \"openssl_cmd2\": cmd2, } return",
"import struct import re from pathlib import Path sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from common.siip_constants import",
"file \"\"\" # Run OpenSSL command with the specified private key and capture",
"\"2ee9976f-9d4c-4442-a997-8cad1c875fa1\", \"dgst -binary -keyform PEM -sha384 -sign\", \"rsa -pubout -modulus -noout\", ], }",
"PEM -sha384 -sign\", \"rsa -pubout -modulus -noout\", ], } # Check if openssl",
"openssl.\") sys.exit(1) if ssl_process.returncode != 0: LOGGER.critical(\"\\nopenssl failed.\") sys.exit(1) return signature def create_arg_parser():",
"= uefi_subreg_authen.vendor_guid.bytes_le + payload # calculate the signature store in structure cert_data =",
"payload) if cert_info[\"openssl_cmd2\"]: # Read in the private key payload = read_file(signer_file) #",
"} EFI_SUB_REGION_AUTHENTICATION; # typedef struct { # SUB_REGION_HEADER Hdr; // Certificate Header #",
"and capture signature from STDOUT try: ssl_process = subprocess.run( openssl_cmd, input=payload, stdout=subprocess.PIPE, stderr=subprocess.PIPE,",
"{}. The {} size must not be greter than {}\".format( string, size, string,",
"parser.parse_args() sign_subregion(args.subregion_file, args.signerfile, args.signed_file, args.signer_type, args.name, args.vendor_guid, args.show, args.tool_path) if __name__ == \"__main__\":",
"for arg in arg_line.split(): if not arg.strip(): continue yield arg my_parser = argparse.ArgumentParser(",
"EFI_GUID VendorGuid; // Vendor GUID # SUB_REGION_VERIFICATION CertParam; // Sub-Region Certificate Parameters #",
"# Create openSSL command 1 cmd = f'{path} {cert_info[1]} \"{signer}\"' # Create openSSL",
"[ \"2ee9976f-9d4c-4442-a997-8cad1c875fa1\", \"dgst -binary -keyform PEM -sha384 -sign\", \"rsa -pubout -modulus -noout\", ],",
"format is '00000000-0000-0000-0000-000000000000'\", type=chk_guid_format, metavar=\"v_guid\", required=True, ) my_parser.add_argument( \"-t\", \"--signer_type\", metavar=\"sign_type\", required=True, help=\"Type",
"sys.exit(2) def read_file(inputfile): \"\"\" read input file to bytes \"\"\" try: with open(inputfile,",
"but requires all information in order to process.\", action=\"store_true\", ) my_parser.add_argument( \"-v\", \"--version\",",
"guid xxxxxxxx-xxxx-xxxx-xxx-xxxxxxxxxxxx where x can be A-F or 0-9 guidFormat = re.compile( r\"([a-f\\d]{8}[-][a-f\\d]{4}[-][a-f\\d]{4}[-][a-f\\d]{4}[-]{1}[a-f\\d]{12}$)\",",
"or 0-9)\\ {}\".format(guid) ) return guid def sign_subregion(subregion_file, signer_file, signed_file, signer_type, subregion_name, vendor_guid,",
"input file exist status = utils.file_exist(filenames, LOGGER) if status != 0: sys.exit(status) if",
"in arg_line.split(): if not arg.strip(): continue yield arg my_parser = argparse.ArgumentParser( prog=__prog__, description=__doc__,",
"filename.\", metavar=\"Filename\", default=\"SIGNED_OUT.bin\", ) my_parser.add_argument( \"-n\", \"--name\", help=\"The name of the subregion being",
"re.compile( r\"([a-f\\d]{8}[-][a-f\\d]{4}[-][a-f\\d]{4}[-][a-f\\d]{4}[-]{1}[a-f\\d]{12}$)\", re.I ) if guidFormat.match(guid) is None: raise argparse.ArgumentTypeError( \"File guild value",
"the BIOS Stitching Tool\", action=\"version\", version=\"%(prog)s {version}\".format(version=__version__), ) return my_parser def chk_string_size(string): \"\"\"\"Check",
"sys.exit(status) if os.path.getsize(sbrgn_file) == 0: LOGGER.critical(\"size of {} subregion file must be greater",
"create_arg_parser() args = parser.parse_args() sign_subregion(args.subregion_file, args.signerfile, args.signed_file, args.signer_type, args.name, args.vendor_guid, args.show, args.tool_path) if",
"= bytes.fromhex(cert_pubkey) # public key and signature are packed back to back cert_data",
"generate_signature(cert_info[\"openssl_cmd2\"], payload) # convert public key from bytes to string cert_pub_string = cert_pub.decode(\"utf-8\")",
"cert_info[\"cert_type\"] self.cert_data = bytes() self.payload = bytes() def encode(self): \"\"\" builds structure for",
"for structure \"\"\" self._valid = False self.w_name = cert_info[\"name\"] self.vendor_guid = cert_info[\"vendor_guid\"] self.w_revision",
"try: with open(inputfile, mode=\"rb\") as file: sign_file = file.read() except ValueError: LOGGER.critical(\"\\nCannot read",
"return string def chk_guid_format(guid): \"\"\" check for correct formate of GUID \"\"\" #",
"to process.\", action=\"store_true\", ) my_parser.add_argument( \"-v\", \"--version\", help=\"Shows the current version of the",
"self.w_name = cert_info[\"name\"] self.vendor_guid = cert_info[\"vendor_guid\"] self.w_revision = cert_info[\"revision\"] self.dw_length = self._StructAuthInfoSize self.cert_type",
"Revision; // Revision of Signature Structure # UINT32 Length; // Length of the",
"cert_pub_string.replace(\"Modulus=\", \"\") # remove end of line from public key cert_pubkey = cert_pubkey.rstrip()",
"= Path(signed_file).resolve() filenames = [str(sbrgn_file), str(signer_file)] # Verify file input file exist status",
"VERSION as __version__ from common.banner import banner import common.utilities as utils import common.logger",
"ssl_process.stdout except: LOGGER.warning(\"\\nCannot run openssl.\") sys.exit(1) if ssl_process.returncode != 0: LOGGER.critical(\"\\nopenssl failed.\") sys.exit(1)",
"= cert_pubkey + cert_data uefi_subreg_authen.cert_data = cert_data # pack structure with signature and",
"= cert_pub.decode(\"utf-8\") # remove word Moudlus= from the file cert_pubkey = cert_pub_string.replace(\"Modulus=\", \"\")",
"the sub-region # EFI_GUID VendorGuid; // Vendor GUID # SUB_REGION_VERIFICATION CertParam; // Sub-Region",
"the subregion_authentication structure \" \" Optional but requires all information in order to",
"{}\".format( string, size, string, max_size ) if size > max_size: raise argparse.ArgumentTypeError(str(msg)) return",
"guidFormat.match(guid) is None: raise argparse.ArgumentTypeError( \"File guild value is not in correct format",
"to hex bytes and add to signature cert_pubkey = bytes.fromhex(cert_pubkey) # public key",
"specified private key and capture signature from STDOUT try: ssl_process = subprocess.run( openssl_cmd,",
"// Calculated Signature # } SUB_REGION_VERIFICATION; # typedef struct { # UINT32 Revision;",
"file must be greater than 0!\".format(sbrgn_file)) sys.exit(status) status = utils.check_key(signer_file, signer_type, LOGGER) if",
"greater than 0!\".format(sbrgn_file)) sys.exit(status) status = utils.check_key(signer_file, signer_type, LOGGER) if status != 0:",
"is required. The format is '00000000-0000-0000-0000-000000000000'\", type=chk_guid_format, metavar=\"v_guid\", required=True, ) my_parser.add_argument( \"-t\", \"--signer_type\",",
"= ssl_process.stdout except: LOGGER.warning(\"\\nCannot run openssl.\") sys.exit(1) if ssl_process.returncode != 0: LOGGER.critical(\"\\nopenssl failed.\")",
"def encode(self): \"\"\" builds structure for subregion authentication header \"\"\" self.dw_length = self._StructSubRegionHdrSize",
"struct { # SUB_REGION_HEADER Hdr; // Certificate Header # UINT8 CertData[1]; // Calculated",
"from __future__ import print_function import os import sys import subprocess import argparse import",
"class UefiSubregAuthenClass: \"\"\" Class define EFI subreation Authentication class \"\"\" # typedef struct",
"subregion authentication structure \"\"\" if not self._valid: raise ValueError print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.dw_length = {dw_length:08X}\".format(",
"get_certifcation_info(cl_inputs, signer): \"\"\" returns the certifcate type passed on subregion \"\"\" # different",
"-nodetach -signer\", None, ], \"rsa\": [ \"2ee9976f-9d4c-4442-a997-8cad1c875fa1\", \"dgst -binary -keyform PEM -sha384 -sign\",",
"\"\"\" # different signature type supported by tool CERT_TYPE = { \"pkcs7\": [",
"\"dgst -binary -keyform PEM -sha384 -sign\", \"rsa -pubout -modulus -noout\", ], } #",
"sys import subprocess import argparse import uuid import struct import re from pathlib",
"\"rsa\": [ \"2ee9976f-9d4c-4442-a997-8cad1c875fa1\", \"dgst -binary -keyform PEM -sha384 -sign\", \"rsa -pubout -modulus -noout\",",
"shell=True, check=True, ) signature = ssl_process.stdout except: LOGGER.warning(\"\\nCannot run openssl.\") sys.exit(1) if ssl_process.returncode",
"help=\"sub region data that needs to be signed.\" ) my_parser.add_argument( \"-o\", \"--output\", dest=\"signed_file\",",
"signing a BIOS sub-region for UEFI \"\"\" from __future__ import print_function import os",
"Create output EFI subregion authentication header and signature and original file build_subreg_signed_file(uefi_signed_data, str(outfile))",
"All rights reserved. # SPDX-License-Identifier: BSD-2-Clause # \"\"\"A signing utility for creating and",
"= {w_revision:04X}\".format( w_revision=self.w_revision ) ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.wCertificateType = {Vendor_guid}\".format( Vendor_guid=str(self.vendor_guid).upper() ) ) print(",
"\"subregion_sign\" TOOLNAME = \"Sub-Region Signing Tool\" if sys.version_info < (3, 6): raise Exception(\"Python",
"LOGGER.critical(\"\\nCannot write payload file: %s\", outfile) sys.exit(2) def read_file(inputfile): \"\"\" read input file",
"of the subregion being signed. Max size is 16 bytes The name is",
"signed input file \"\"\" # Run OpenSSL command with the specified private key",
"{} size must not be greter than {}\".format( string, size, string, max_size )",
"\"sizeof (payload) = {Size:08X}\".format( Size=len(self.payload) ) ) def get_certifcation_info(cl_inputs, signer): \"\"\" returns the",
"with open(outfile, mode=\"wb\") as signed_file: signed_file.write(cert_struct) except ValueError: LOGGER.critical(\"\\nCannot write payload file: %s\",",
"store in structure cert_data = generate_signature(cert_info[\"openssl_cmd\"], payload) if cert_info[\"openssl_cmd2\"]: # Read in the",
"EFI subregion authentication header and signature and original file build_subreg_signed_file(uefi_signed_data, str(outfile)) print( \"Signed",
"cert_pubkey = cert_pubkey.rstrip() # Conert to hex bytes and add to signature cert_pubkey",
"generate_signature(openssl_cmd, payload): \"\"\" signed input file \"\"\" # Run OpenSSL command with the",
"\"\"\"\"Check the size of the string\"\"\" max_size = 16 size = len(string.encode(\"utf-8\")) msg",
"the Signing Key # UINT8 Signature[384]; // SHA384-RSA3K Signature # } EFI_CERT_BLOCK_RSA3072_SHA384; _StructAuthInfoFormat",
"payload): \"\"\" signed input file \"\"\" # Run OpenSSL command with the specified",
"Optional if path to tools are already in PATH.\", default=None, ) my_parser.add_argument( \"--show\",",
"where x can be A-F or 0-9 guidFormat = re.compile( r\"([a-f\\d]{8}[-][a-f\\d]{4}[-][a-f\\d]{4}[-][a-f\\d]{4}[-]{1}[a-f\\d]{12}$)\", re.I )",
"# EFI_GUID CertType; // Signature type # } SUB_REGION_HEADER; # typedef struct {",
"signed.\\ This is required. The format is '00000000-0000-0000-0000-000000000000'\", type=chk_guid_format, metavar=\"v_guid\", required=True, ) my_parser.add_argument(",
"Get signing type information cert_info = CERT_TYPE.get(cl_inputs.signer_type) # Create openSSL command 1 cmd",
"# Extract the public key modulus from private key cert_pub = generate_signature(cert_info[\"openssl_cmd2\"], payload)",
"arguments.\"\"\" def convert_arg_line_to_args(arg_line): for arg in arg_line.split(): if not arg.strip(): continue yield arg",
"absolute path for openSSL sbrgn_file = Path(subregion_file).resolve() signer_file = Path(signer_file).resolve() outfile = Path(signed_file).resolve()",
"size > max_size: raise argparse.ArgumentTypeError(str(msg)) return string def chk_guid_format(guid): \"\"\" check for correct",
"read payload file: %s\", inputfile) sys.exit(2) return sign_file def generate_signature(openssl_cmd, payload): \"\"\" signed",
"This is required. The format is '00000000-0000-0000-0000-000000000000'\", type=chk_guid_format, metavar=\"v_guid\", required=True, ) my_parser.add_argument( \"-t\",",
"Revision of Signature Structure # UINT32 Length; // Length of the Signature +",
"create_arg_parser(): \"\"\" Parsing and validating input arguments.\"\"\" def convert_arg_line_to_args(arg_line): for arg in arg_line.split():",
"signed file.\", type=chk_string_size, metavar=\"subregion\", required=True, ) my_parser.add_argument( \"-vg\", \"--vendor-guid\", help=\"Vender GUID is one",
"Create openSSL command 2 if cert_info[2] is not None: cmd2 = f\"{path} {cert_info[2]}\"",
"input file \"\"\" # Run OpenSSL command with the specified private key and",
"re.I ) if guidFormat.match(guid) is None: raise argparse.ArgumentTypeError( \"File guild value is not",
"# } SUB_REGION_VERIFICATION; # typedef struct { # UINT32 Revision; // Revision of",
"arg in arg_line.split(): if not arg.strip(): continue yield arg my_parser = argparse.ArgumentParser( prog=__prog__,",
"if not arg.strip(): continue yield arg my_parser = argparse.ArgumentParser( prog=__prog__, description=__doc__, conflict_handler=\"resolve\", fromfile_prefix_chars=\"@\",",
"\"-o\", \"--output\", dest=\"signed_file\", help=\"Output capsule filename.\", metavar=\"Filename\", default=\"SIGNED_OUT.bin\", ) my_parser.add_argument( \"-n\", \"--name\", help=\"The",
"= read_file(sbrgn_file) uefi_subreg_authen.payload = payload # add Vendor Guid to Payload payload =",
"or 0-9 guidFormat = re.compile( r\"([a-f\\d]{8}[-][a-f\\d]{4}[-][a-f\\d]{4}[-][a-f\\d]{4}[-]{1}[a-f\\d]{12}$)\", re.I ) if guidFormat.match(guid) is None: raise",
"show: uefi_subreg_authen.dump_info() # Create output EFI subregion authentication header and signature and original",
"Parsing and validating input arguments.\"\"\" def convert_arg_line_to_args(arg_line): for arg in arg_line.split(): if not",
"read_file(signer_file) # Extract the public key modulus from private key cert_pub = generate_signature(cert_info[\"openssl_cmd2\"],",
"payload # add Vendor Guid to Payload payload = uefi_subreg_authen.vendor_guid.bytes_le + payload #",
"(3, 6): raise Exception(\"Python 3.6 is the minimal version required\") class UefiSubregAuthenClass: \"\"\"",
"if cert_info[\"openssl_cmd2\"]: # Read in the private key payload = read_file(signer_file) # Extract",
"Name of the sub-region # EFI_GUID VendorGuid; // Vendor GUID # SUB_REGION_VERIFICATION CertParam;",
"\\ (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx where x can be A-F or 0-9)\\ {}\".format(guid) ) return guid",
"the file cert_pubkey = cert_pub_string.replace(\"Modulus=\", \"\") # remove end of line from public",
"was successfully generated.\".format( subregion_name, outfile ) ) def main(): \"\"\"Entry to script.\"\"\" parser",
"0!\".format(sbrgn_file)) sys.exit(status) status = utils.check_key(signer_file, signer_type, LOGGER) if status != 0: sys.exit(status) outfile",
"file.\", type=chk_string_size, metavar=\"subregion\", required=True, ) my_parser.add_argument( \"-vg\", \"--vendor-guid\", help=\"Vender GUID is one specific",
"command with the specified private key and capture signature from STDOUT try: ssl_process",
"class \"\"\" # typedef struct { # char Name[16 bytes]; // Name of",
"stored in signed file.\", type=chk_string_size, metavar=\"subregion\", required=True, ) my_parser.add_argument( \"-vg\", \"--vendor-guid\", help=\"Vender GUID",
"help=\"The name of the subregion being signed. Max size is 16 bytes The",
"= \"subregion_sign\" TOOLNAME = \"Sub-Region Signing Tool\" if sys.version_info < (3, 6): raise",
"back to back cert_data = cert_pubkey + cert_data uefi_subreg_authen.cert_data = cert_data # pack",
"to bytes \"\"\" try: with open(inputfile, mode=\"rb\") as file: sign_file = file.read() except",
"\"smime -sign -binary -outform DER -md sha256 -nodetach -signer\", None, ], \"rsa\": [",
"\"revision\": 0x01, \"name\": cl_inputs.name.encode(\"utf-8\"), \"vendor_guid\": uuid.UUID(cl_inputs.vendor_guid), \"cert_type\": uuid.UUID(cert_info[0]), \"openssl_cmd\": cmd, \"openssl_cmd2\": cmd2, }",
"my_parser.convert_arg_line_to_args = convert_arg_line_to_args my_parser.add_argument( \"subregion_file\", help=\"sub region data that needs to be signed.\"",
"authentication header and signature and original file build_subreg_signed_file(uefi_signed_data, str(outfile)) print( \"Signed {} sub-region({})",
"payload) # convert public key from bytes to string cert_pub_string = cert_pub.decode(\"utf-8\") #",
"= 16 size = len(string.encode(\"utf-8\")) msg = \"The size of {} is {}.",
"from common.siip_constants import VERSION as __version__ from common.banner import banner import common.utilities as",
"EFI_CERT_BLOCK_RSA3072_SHA384; _StructAuthInfoFormat = \"<16s16sLL16s\" _StructAuthInfoSize = struct.calcsize(_StructAuthInfoFormat) _StructSubRegionHdrFormat = \"<LL16s\" _StructSubRegionHdrSize = struct.calcsize(_StructSubRegionHdrFormat)",
"of GUID \"\"\" # format for guid xxxxxxxx-xxxx-xxxx-xxx-xxxxxxxxxxxx where x can be A-F",
"self._valid: raise ValueError print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.dw_length = {dw_length:08X}\".format( dw_length=self.dw_length ) ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.w_revision =",
"format \\ (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx where x can be A-F or 0-9)\\ {}\".format(guid) ) return",
"= cert_data # pack structure with signature and get update size of header",
"= { \"revision\": 0x01, \"name\": cl_inputs.name.encode(\"utf-8\"), \"vendor_guid\": uuid.UUID(cl_inputs.vendor_guid), \"cert_type\": uuid.UUID(cert_info[0]), \"openssl_cmd\": cmd, \"openssl_cmd2\":",
"-binary -outform DER -md sha256 -nodetach -signer\", None, ], \"rsa\": [ \"2ee9976f-9d4c-4442-a997-8cad1c875fa1\", \"dgst",
"metavar=\"v_guid\", required=True, ) my_parser.add_argument( \"-t\", \"--signer_type\", metavar=\"sign_type\", required=True, help=\"Type of Signing pkcs7 or",
"3.6 is the minimal version required\") class UefiSubregAuthenClass: \"\"\" Class define EFI subreation",
") self._valid = True return uefi_subreg_authen_hdr + self.cert_data + self.payload def dump_info(self): \"\"\"",
"# typedef struct { # UINT32 Revision; // Revision of Signature Structure #",
"outfile) sys.exit(2) def read_file(inputfile): \"\"\" read input file to bytes \"\"\" try: with",
"logging LOGGER = logging.getLogger(\"subregion_sign\") __prog__ = \"subregion_sign\" TOOLNAME = \"Sub-Region Signing Tool\" if",
"cert_data = cert_pubkey + cert_data uefi_subreg_authen.cert_data = cert_data # pack structure with signature",
"= False self.w_name = cert_info[\"name\"] self.vendor_guid = cert_info[\"vendor_guid\"] self.w_revision = cert_info[\"revision\"] self.dw_length =",
"try: with open(outfile, mode=\"wb\") as signed_file: signed_file.write(cert_struct) except ValueError: LOGGER.critical(\"\\nCannot write payload file:",
"utils.check_for_tool(\"openssl\", \"version\", cl_inputs.tool_path) # Get signing type information cert_info = CERT_TYPE.get(cl_inputs.signer_type) # Create",
"Read in the private key payload = read_file(signer_file) # Extract the public key",
"structure \"\"\" self._valid = False self.w_name = cert_info[\"name\"] self.vendor_guid = cert_info[\"vendor_guid\"] self.w_revision =",
"# add Vendor Guid to Payload payload = uefi_subreg_authen.vendor_guid.bytes_le + payload # calculate",
"in the private key payload = read_file(signer_file) # Extract the public key modulus",
"inputfile) sys.exit(2) return sign_file def generate_signature(openssl_cmd, payload): \"\"\" signed input file \"\"\" #",
"tool_path, signer_type\") cl_inputs = parser.parse_args(['name={}'.format(subregion_name)]) cl_inputs.name = subregion_name cl_inputs.vendor_guid = vendor_guid cl_inputs.tool_path =",
"to signature cert_pubkey = bytes.fromhex(cert_pubkey) # public key and signature are packed back",
"BIOS sub-region for UEFI \"\"\" from __future__ import print_function import os import sys",
"not be greter than {}\".format( string, size, string, max_size ) if size >",
"add to signature cert_pubkey = bytes.fromhex(cert_pubkey) # public key and signature are packed",
"header uefi_signed_data = uefi_subreg_authen.encode() if show: uefi_subreg_authen.dump_info() # Create output EFI subregion authentication",
"stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, check=True, ) signature = ssl_process.stdout except: LOGGER.warning(\"\\nCannot run openssl.\") sys.exit(1)",
"except ValueError: LOGGER.critical(\"\\nCannot read payload file: %s\", inputfile) sys.exit(2) return sign_file def generate_signature(openssl_cmd,",
"guidFormat = re.compile( r\"([a-f\\d]{8}[-][a-f\\d]{4}[-][a-f\\d]{4}[-][a-f\\d]{4}[-]{1}[a-f\\d]{12}$)\", re.I ) if guidFormat.match(guid) is None: raise argparse.ArgumentTypeError( \"File",
"stderr=subprocess.PIPE, shell=True, check=True, ) signature = ssl_process.stdout except: LOGGER.warning(\"\\nCannot run openssl.\") sys.exit(1) if",
"required\") class UefiSubregAuthenClass: \"\"\" Class define EFI subreation Authentication class \"\"\" # typedef",
"self.dw_length = self._StructAuthInfoSize self.cert_type = cert_info[\"cert_type\"] self.cert_data = bytes() self.payload = bytes() def",
"conflict_handler=\"resolve\", fromfile_prefix_chars=\"@\", ) my_parser.convert_arg_line_to_args = convert_arg_line_to_args my_parser.add_argument( \"subregion_file\", help=\"sub region data that needs",
"output EFI subregion authentication header and signature and original file build_subreg_signed_file(uefi_signed_data, str(outfile)) print(",
"A-F or 0-9)\\ {}\".format(guid) ) return guid def sign_subregion(subregion_file, signer_file, signed_file, signer_type, subregion_name,",
"\"--signer_type\", metavar=\"sign_type\", required=True, help=\"Type of Signing pkcs7 or rsa.\", choices=[\"pkcs7\", \"rsa\"], ) my_parser.add_argument(",
"TOOLNAME = \"Sub-Region Signing Tool\" if sys.version_info < (3, 6): raise Exception(\"Python 3.6",
"file: %s\", inputfile) sys.exit(2) return sign_file def generate_signature(openssl_cmd, payload): \"\"\" signed input file",
"\"\"\" check for correct formate of GUID \"\"\" # format for guid xxxxxxxx-xxxx-xxxx-xxx-xxxxxxxxxxxx",
"from the file cert_pubkey = cert_pub_string.replace(\"Modulus=\", \"\") # remove end of line from",
"= [str(sbrgn_file), str(signer_file)] # Verify file input file exist status = utils.file_exist(filenames, LOGGER)",
"exist status = utils.file_exist(filenames, LOGGER) if status != 0: sys.exit(status) if os.path.getsize(sbrgn_file) ==",
"minimal version required\") class UefiSubregAuthenClass: \"\"\" Class define EFI subreation Authentication class \"\"\"",
"if not self._valid: raise ValueError print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.dw_length = {dw_length:08X}\".format( dw_length=self.dw_length ) ) print(",
"uuid import struct import re from pathlib import Path sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from common.siip_constants",
"# SUB_REGION_VERIFICATION CertParam; // Sub-Region Certificate Parameters # } EFI_SUB_REGION_AUTHENTICATION; # typedef struct",
"type information cert_info = CERT_TYPE.get(cl_inputs.signer_type) # Create openSSL command 1 cmd = f'{path}",
"\"\"\" signed input file \"\"\" # Run OpenSSL command with the specified private",
"return signature def create_arg_parser(): \"\"\" Parsing and validating input arguments.\"\"\" def convert_arg_line_to_args(arg_line): for",
"script.\"\"\" parser = create_arg_parser() args = parser.parse_args() sign_subregion(args.subregion_file, args.signerfile, args.signed_file, args.signer_type, args.name, args.vendor_guid,",
"sign_subregion(args.subregion_file, args.signerfile, args.signed_file, args.signer_type, args.name, args.vendor_guid, args.show, args.tool_path) if __name__ == \"__main__\": banner(TOOLNAME,",
"of line from public key cert_pubkey = cert_pubkey.rstrip() # Conert to hex bytes",
"= { \"pkcs7\": [ \"4aafd29d-68df-49ee-8aa9-347d375665a7\", \"smime -sign -binary -outform DER -md sha256 -nodetach",
") my_parser.add_argument( \"-t\", \"--signer_type\", metavar=\"sign_type\", required=True, help=\"Type of Signing pkcs7 or rsa.\", choices=[\"pkcs7\",",
") print( \"sizeof (EFI_SUBREGION_AUTHENTICATION.AuthInfo.cert_data) = {Size:08X}\".format( Size=len(self.cert_data) ) ) print( \"sizeof (payload) =",
"PATH.\", default=None, ) my_parser.add_argument( \"--show\", help=\"Shows information about the subregion_authentication structure \" \"",
"# format for guid xxxxxxxx-xxxx-xxxx-xxx-xxxxxxxxxxxx where x can be A-F or 0-9 guidFormat",
"# typedef struct { # UINT8 PublicKey[384]; // Public Key pair of the",
"# } EFI_SUB_REGION_AUTHENTICATION; # typedef struct { # SUB_REGION_HEADER Hdr; // Certificate Header",
"if openssl is installed path = utils.check_for_tool(\"openssl\", \"version\", cl_inputs.tool_path) # Get signing type",
"struct { # char Name[16 bytes]; // Name of the sub-region # EFI_GUID",
"structure payload = read_file(sbrgn_file) uefi_subreg_authen.payload = payload # add Vendor Guid to Payload",
"bytes]; // Name of the sub-region # EFI_GUID VendorGuid; // Vendor GUID #",
"description=__doc__, conflict_handler=\"resolve\", fromfile_prefix_chars=\"@\", ) my_parser.convert_arg_line_to_args = convert_arg_line_to_args my_parser.add_argument( \"subregion_file\", help=\"sub region data that",
"uuid.UUID(cl_inputs.vendor_guid), \"cert_type\": uuid.UUID(cert_info[0]), \"openssl_cmd\": cmd, \"openssl_cmd2\": cmd2, } return certification_info def build_subreg_signed_file(cert_struct, outfile):",
") ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.wCertificateType = {Vendor_guid}\".format( Vendor_guid=str(self.vendor_guid).upper() ) ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.cert_type = {cert_type}\".format(",
"payload = read_file(sbrgn_file) uefi_subreg_authen.payload = payload # add Vendor Guid to Payload payload",
"\"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.w_revision = {w_revision:04X}\".format( w_revision=self.w_revision ) ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.wCertificateType = {Vendor_guid}\".format( Vendor_guid=str(self.vendor_guid).upper() ) )",
"cl_inputs.tool_path = tool_path cl_inputs.signer_type = signer_type cert_info = get_certifcation_info(cl_inputs, signer_file) uefi_subreg_authen = UefiSubregAuthenClass(cert_info)",
"returns the certifcate type passed on subregion \"\"\" # different signature type supported",
"# Create output EFI subregion authentication header and signature and original file build_subreg_signed_file(uefi_signed_data,",
"bytes The name is stored in signed file.\", type=chk_string_size, metavar=\"subregion\", required=True, ) my_parser.add_argument(",
"print( \"sizeof (EFI_SUBREGION_AUTHENTICATION.AuthInfo.cert_data) = {Size:08X}\".format( Size=len(self.cert_data) ) ) print( \"sizeof (payload) = {Size:08X}\".format(",
") ) def main(): \"\"\"Entry to script.\"\"\" parser = create_arg_parser() args = parser.parse_args()",
"where x can be A-F or 0-9)\\ {}\".format(guid) ) return guid def sign_subregion(subregion_file,",
"0: LOGGER.critical(\"\\nopenssl failed.\") sys.exit(1) return signature def create_arg_parser(): \"\"\" Parsing and validating input",
"vendor_guid, show = False, tool_path = None): # Use absolute path for openSSL",
"the vendor for the sub-region being signed.\\ This is required. The format is",
"about the subregion_authentication structure \" \" Optional but requires all information in order",
"information in order to process.\", action=\"store_true\", ) my_parser.add_argument( \"-v\", \"--version\", help=\"Shows the current",
"sha256 -nodetach -signer\", None, ], \"rsa\": [ \"2ee9976f-9d4c-4442-a997-8cad1c875fa1\", \"dgst -binary -keyform PEM -sha384",
"parser.add_argument(\"name, vendor_guid, tool_path, signer_type\") cl_inputs = parser.parse_args(['name={}'.format(subregion_name)]) cl_inputs.name = subregion_name cl_inputs.vendor_guid = vendor_guid",
"UINT32 Revision; // Revision of Signature Structure # UINT32 Length; // Length of",
"string\"\"\" max_size = 16 size = len(string.encode(\"utf-8\")) msg = \"The size of {}",
"to string cert_pub_string = cert_pub.decode(\"utf-8\") # remove word Moudlus= from the file cert_pubkey",
"\"-s\", \"--signer\", dest=\"signerfile\", required=True, help=\"OpenSSL signer private certificate filename.\", ) my_parser.add_argument( \"--toolpath\", dest=\"tool_path\",",
"bytes \"\"\" try: with open(inputfile, mode=\"rb\") as file: sign_file = file.read() except ValueError:",
"\"subregion_file\", help=\"sub region data that needs to be signed.\" ) my_parser.add_argument( \"-o\", \"--output\",",
"action=\"store_true\", ) my_parser.add_argument( \"-v\", \"--version\", help=\"Shows the current version of the BIOS Stitching",
"size of the string\"\"\" max_size = 16 size = len(string.encode(\"utf-8\")) msg = \"The",
"my_parser.add_argument( \"subregion_file\", help=\"sub region data that needs to be signed.\" ) my_parser.add_argument( \"-o\",",
"or rsa.\", choices=[\"pkcs7\", \"rsa\"], ) my_parser.add_argument( \"-s\", \"--signer\", dest=\"signerfile\", required=True, help=\"OpenSSL signer private",
"Sub-Region Certificate Parameters # } EFI_SUB_REGION_AUTHENTICATION; # typedef struct { # SUB_REGION_HEADER Hdr;",
"typedef struct { # UINT8 PublicKey[384]; // Public Key pair of the Signing",
"rsa.\", choices=[\"pkcs7\", \"rsa\"], ) my_parser.add_argument( \"-s\", \"--signer\", dest=\"signerfile\", required=True, help=\"OpenSSL signer private certificate",
"return guid def sign_subregion(subregion_file, signer_file, signed_file, signer_type, subregion_name, vendor_guid, show = False, tool_path",
"6): raise Exception(\"Python 3.6 is the minimal version required\") class UefiSubregAuthenClass: \"\"\" Class",
"= cert_info[\"cert_type\"] self.cert_data = bytes() self.payload = bytes() def encode(self): \"\"\" builds structure",
"+ cert_data uefi_subreg_authen.cert_data = cert_data # pack structure with signature and get update",
"\"4aafd29d-68df-49ee-8aa9-347d375665a7\", \"smime -sign -binary -outform DER -md sha256 -nodetach -signer\", None, ], \"rsa\":",
"default=\"SIGNED_OUT.bin\", ) my_parser.add_argument( \"-n\", \"--name\", help=\"The name of the subregion being signed. Max",
"16 bytes The name is stored in signed file.\", type=chk_string_size, metavar=\"subregion\", required=True, )",
"status = utils.file_exist(filenames, LOGGER) if status != 0: sys.exit(status) if os.path.getsize(sbrgn_file) == 0:",
"Path(signer_file).resolve() outfile = Path(signed_file).resolve() filenames = [str(sbrgn_file), str(signer_file)] # Verify file input file",
"os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from common.siip_constants import VERSION as __version__ from common.banner import banner import common.utilities",
"cl_inputs.signer_type = signer_type cert_info = get_certifcation_info(cl_inputs, signer_file) uefi_subreg_authen = UefiSubregAuthenClass(cert_info) # read input",
"__version__ from common.banner import banner import common.utilities as utils import common.logger as logging",
"the size of the string\"\"\" max_size = 16 size = len(string.encode(\"utf-8\")) msg =",
") return guid def sign_subregion(subregion_file, signer_file, signed_file, signer_type, subregion_name, vendor_guid, show = False,",
"key cert_pubkey = cert_pubkey.rstrip() # Conert to hex bytes and add to signature",
"Hdr; // Certificate Header # UINT8 CertData[1]; // Calculated Signature # } SUB_REGION_VERIFICATION;",
"UefiSubregAuthenClass: \"\"\" Class define EFI subreation Authentication class \"\"\" # typedef struct {",
"data that needs to be signed.\" ) my_parser.add_argument( \"-o\", \"--output\", dest=\"signed_file\", help=\"Output capsule",
"size of {} is {}. The {} size must not be greter than",
"= logging.getLogger(\"subregion_sign\") __prog__ = \"subregion_sign\" TOOLNAME = \"Sub-Region Signing Tool\" if sys.version_info <",
"authentication structure \"\"\" if not self._valid: raise ValueError print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.dw_length = {dw_length:08X}\".format( dw_length=self.dw_length",
"key and capture signature from STDOUT try: ssl_process = subprocess.run( openssl_cmd, input=payload, stdout=subprocess.PIPE,",
") ) def get_certifcation_info(cl_inputs, signer): \"\"\" returns the certifcate type passed on subregion",
") ) print( \"sizeof (EFI_SUBREGION_AUTHENTICATION.AuthInfo.cert_data) = {Size:08X}\".format( Size=len(self.cert_data) ) ) print( \"sizeof (payload)",
"= subprocess.run( openssl_cmd, input=payload, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, check=True, ) signature = ssl_process.stdout except:",
"Authentication class \"\"\" # typedef struct { # char Name[16 bytes]; // Name",
"be A-F or 0-9 guidFormat = re.compile( r\"([a-f\\d]{8}[-][a-f\\d]{4}[-][a-f\\d]{4}[-][a-f\\d]{4}[-]{1}[a-f\\d]{12}$)\", re.I ) if guidFormat.match(guid) is",
"{ \"pkcs7\": [ \"4aafd29d-68df-49ee-8aa9-347d375665a7\", \"smime -sign -binary -outform DER -md sha256 -nodetach -signer\",",
"subprocess.run( openssl_cmd, input=payload, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, check=True, ) signature = ssl_process.stdout except: LOGGER.warning(\"\\nCannot",
"argparse.ArgumentParser( prog=__prog__, description=__doc__, conflict_handler=\"resolve\", fromfile_prefix_chars=\"@\", ) my_parser.convert_arg_line_to_args = convert_arg_line_to_args my_parser.add_argument( \"subregion_file\", help=\"sub region",
"subprocess import argparse import uuid import struct import re from pathlib import Path",
"UINT8 CertData[1]; // Calculated Signature # } SUB_REGION_VERIFICATION; # typedef struct { #",
"= vendor_guid cl_inputs.tool_path = tool_path cl_inputs.signer_type = signer_type cert_info = get_certifcation_info(cl_inputs, signer_file) uefi_subreg_authen",
"\"\") # remove end of line from public key cert_pubkey = cert_pubkey.rstrip() #",
"is installed path = utils.check_for_tool(\"openssl\", \"version\", cl_inputs.tool_path) # Get signing type information cert_info",
"def generate_signature(openssl_cmd, payload): \"\"\" signed input file \"\"\" # Run OpenSSL command with",
"= \"<16s16sLL16s\" _StructAuthInfoSize = struct.calcsize(_StructAuthInfoFormat) _StructSubRegionHdrFormat = \"<LL16s\" _StructSubRegionHdrSize = struct.calcsize(_StructSubRegionHdrFormat) def __init__(self,",
"// Sub-Region Certificate Parameters # } EFI_SUB_REGION_AUTHENTICATION; # typedef struct { # SUB_REGION_HEADER",
") ) print( \"sizeof (payload) = {Size:08X}\".format( Size=len(self.payload) ) ) def get_certifcation_info(cl_inputs, signer):",
"cert_pub.decode(\"utf-8\") # remove word Moudlus= from the file cert_pubkey = cert_pub_string.replace(\"Modulus=\", \"\") #",
"uuid.UUID(cert_info[0]), \"openssl_cmd\": cmd, \"openssl_cmd2\": cmd2, } return certification_info def build_subreg_signed_file(cert_struct, outfile): \"\"\" build",
"w_revision=self.w_revision ) ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.wCertificateType = {Vendor_guid}\".format( Vendor_guid=str(self.vendor_guid).upper() ) ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.cert_type =",
"from private key cert_pub = generate_signature(cert_info[\"openssl_cmd2\"], payload) # convert public key from bytes",
"# Copyright (c) 2020, Intel Corporation. All rights reserved. # SPDX-License-Identifier: BSD-2-Clause #",
"if size > max_size: raise argparse.ArgumentTypeError(str(msg)) return string def chk_guid_format(guid): \"\"\" check for",
"= signer_type cert_info = get_certifcation_info(cl_inputs, signer_file) uefi_subreg_authen = UefiSubregAuthenClass(cert_info) # read input file",
"key cert_pub = generate_signature(cert_info[\"openssl_cmd2\"], payload) # convert public key from bytes to string",
"LOGGER) if status != 0: sys.exit(status) outfile = utils.file_not_exist(outfile, LOGGER) parser = argparse.ArgumentParser()",
"2020, Intel Corporation. All rights reserved. # SPDX-License-Identifier: BSD-2-Clause # \"\"\"A signing utility",
"sys.exit(1) return signature def create_arg_parser(): \"\"\" Parsing and validating input arguments.\"\"\" def convert_arg_line_to_args(arg_line):",
"cmd, \"openssl_cmd2\": cmd2, } return certification_info def build_subreg_signed_file(cert_struct, outfile): \"\"\" build output file",
"\"--signer\", dest=\"signerfile\", required=True, help=\"OpenSSL signer private certificate filename.\", ) my_parser.add_argument( \"--toolpath\", dest=\"tool_path\", help=\"Path",
"cert_data # pack structure with signature and get update size of header uefi_signed_data",
"# Create openSSL command 2 if cert_info[2] is not None: cmd2 = f\"{path}",
"information of subregion authentication structure \"\"\" if not self._valid: raise ValueError print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.dw_length",
"= f\"{path} {cert_info[2]}\" else: cmd2 = cert_info[2] certification_info = { \"revision\": 0x01, \"name\":",
"guid def sign_subregion(subregion_file, signer_file, signed_file, signer_type, subregion_name, vendor_guid, show = False, tool_path =",
"sbrgn_file = Path(subregion_file).resolve() signer_file = Path(signer_file).resolve() outfile = Path(signed_file).resolve() filenames = [str(sbrgn_file), str(signer_file)]",
"cert_info = get_certifcation_info(cl_inputs, signer_file) uefi_subreg_authen = UefiSubregAuthenClass(cert_info) # read input file to store",
"signature store in structure cert_data = generate_signature(cert_info[\"openssl_cmd\"], payload) if cert_info[\"openssl_cmd2\"]: # Read in",
"argparse import uuid import struct import re from pathlib import Path sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))",
"# EFI_GUID VendorGuid; // Vendor GUID # SUB_REGION_VERIFICATION CertParam; // Sub-Region Certificate Parameters",
"Intel Corporation. All rights reserved. # SPDX-License-Identifier: BSD-2-Clause # \"\"\"A signing utility for",
") print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.wCertificateType = {Vendor_guid}\".format( Vendor_guid=str(self.vendor_guid).upper() ) ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.cert_type = {cert_type}\".format( cert_type=str(self.cert_type).upper()",
"cert_info[\"vendor_guid\"] self.w_revision = cert_info[\"revision\"] self.dw_length = self._StructAuthInfoSize self.cert_type = cert_info[\"cert_type\"] self.cert_data = bytes()",
"payload # calculate the signature store in structure cert_data = generate_signature(cert_info[\"openssl_cmd\"], payload) if",
"= {cert_type}\".format( cert_type=str(self.cert_type).upper() ) ) print( \"sizeof (EFI_SUBREGION_AUTHENTICATION.AuthInfo.cert_data) = {Size:08X}\".format( Size=len(self.cert_data) ) )",
"def read_file(inputfile): \"\"\" read input file to bytes \"\"\" try: with open(inputfile, mode=\"rb\")",
"pack structure with signature and get update size of header uefi_signed_data = uefi_subreg_authen.encode()",
"UINT8 Signature[384]; // SHA384-RSA3K Signature # } EFI_CERT_BLOCK_RSA3072_SHA384; _StructAuthInfoFormat = \"<16s16sLL16s\" _StructAuthInfoSize =",
"_StructAuthInfoSize = struct.calcsize(_StructAuthInfoFormat) _StructSubRegionHdrFormat = \"<LL16s\" _StructSubRegionHdrSize = struct.calcsize(_StructSubRegionHdrFormat) def __init__(self, cert_info): \"\"\"",
"\"--version\", help=\"Shows the current version of the BIOS Stitching Tool\", action=\"version\", version=\"%(prog)s {version}\".format(version=__version__),",
"import print_function import os import sys import subprocess import argparse import uuid import",
") my_parser.add_argument( \"-o\", \"--output\", dest=\"signed_file\", help=\"Output capsule filename.\", metavar=\"Filename\", default=\"SIGNED_OUT.bin\", ) my_parser.add_argument( \"-n\",",
"self._valid = False self.w_name = cert_info[\"name\"] self.vendor_guid = cert_info[\"vendor_guid\"] self.w_revision = cert_info[\"revision\"] self.dw_length",
"__future__ import print_function import os import sys import subprocess import argparse import uuid",
"msg = \"The size of {} is {}. The {} size must not",
"key and signature are packed back to back cert_data = cert_pubkey + cert_data",
"-sign\", \"rsa -pubout -modulus -noout\", ], } # Check if openssl is installed",
"= read_file(signer_file) # Extract the public key modulus from private key cert_pub =",
"arg_line.split(): if not arg.strip(): continue yield arg my_parser = argparse.ArgumentParser( prog=__prog__, description=__doc__, conflict_handler=\"resolve\",",
"validating input arguments.\"\"\" def convert_arg_line_to_args(arg_line): for arg in arg_line.split(): if not arg.strip(): continue",
"common.banner import banner import common.utilities as utils import common.logger as logging LOGGER =",
"# convert public key from bytes to string cert_pub_string = cert_pub.decode(\"utf-8\") # remove",
"ssl_process = subprocess.run( openssl_cmd, input=payload, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, check=True, ) signature = ssl_process.stdout",
"# public key and signature are packed back to back cert_data = cert_pubkey",
") my_parser.convert_arg_line_to_args = convert_arg_line_to_args my_parser.add_argument( \"subregion_file\", help=\"sub region data that needs to be",
"_StructSubRegionHdrSize = struct.calcsize(_StructSubRegionHdrFormat) def __init__(self, cert_info): \"\"\" initialization of the variables for structure",
"build_subreg_signed_file(cert_struct, outfile): \"\"\" build output file \"\"\" try: with open(outfile, mode=\"wb\") as signed_file:",
"information about the subregion_authentication structure \" \" Optional but requires all information in",
"EFI_GUID CertType; // Signature type # } SUB_REGION_HEADER; # typedef struct { #",
"utils.file_not_exist(outfile, LOGGER) parser = argparse.ArgumentParser() parser.add_argument(\"name, vendor_guid, tool_path, signer_type\") cl_inputs = parser.parse_args(['name={}'.format(subregion_name)]) cl_inputs.name",
"if cert_info[2] is not None: cmd2 = f\"{path} {cert_info[2]}\" else: cmd2 = cert_info[2]",
"os import sys import subprocess import argparse import uuid import struct import re",
"utf-8 -*- # # Copyright (c) 2020, Intel Corporation. All rights reserved. #",
"# UINT8 Signature[384]; // SHA384-RSA3K Signature # } EFI_CERT_BLOCK_RSA3072_SHA384; _StructAuthInfoFormat = \"<16s16sLL16s\" _StructAuthInfoSize",
"Signature[384]; // SHA384-RSA3K Signature # } EFI_CERT_BLOCK_RSA3072_SHA384; _StructAuthInfoFormat = \"<16s16sLL16s\" _StructAuthInfoSize = struct.calcsize(_StructAuthInfoFormat)",
"\"cert_type\": uuid.UUID(cert_info[0]), \"openssl_cmd\": cmd, \"openssl_cmd2\": cmd2, } return certification_info def build_subreg_signed_file(cert_struct, outfile): \"\"\"",
"= \"Sub-Region Signing Tool\" if sys.version_info < (3, 6): raise Exception(\"Python 3.6 is",
"= uefi_subreg_authen.encode() if show: uefi_subreg_authen.dump_info() # Create output EFI subregion authentication header and",
"{w_revision:04X}\".format( w_revision=self.w_revision ) ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.wCertificateType = {Vendor_guid}\".format( Vendor_guid=str(self.vendor_guid).upper() ) ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.cert_type",
"check=True, ) signature = ssl_process.stdout except: LOGGER.warning(\"\\nCannot run openssl.\") sys.exit(1) if ssl_process.returncode !=",
"structure for subregion authentication header \"\"\" self.dw_length = self._StructSubRegionHdrSize + len(self.cert_data) uefi_subreg_authen_hdr =",
"command 1 cmd = f'{path} {cert_info[1]} \"{signer}\"' # Create openSSL command 2 if",
"certificate filename.\", ) my_parser.add_argument( \"--toolpath\", dest=\"tool_path\", help=\"Path to signtool or OpenSSL tool. \"",
"signer_type, subregion_name, vendor_guid, show = False, tool_path = None): # Use absolute path",
"= False, tool_path = None): # Use absolute path for openSSL sbrgn_file =",
"= subregion_name cl_inputs.vendor_guid = vendor_guid cl_inputs.tool_path = tool_path cl_inputs.signer_type = signer_type cert_info =",
"Signing pkcs7 or rsa.\", choices=[\"pkcs7\", \"rsa\"], ) my_parser.add_argument( \"-s\", \"--signer\", dest=\"signerfile\", required=True, help=\"OpenSSL",
"subregion_name cl_inputs.vendor_guid = vendor_guid cl_inputs.tool_path = tool_path cl_inputs.signer_type = signer_type cert_info = get_certifcation_info(cl_inputs,",
"print( \"sizeof (payload) = {Size:08X}\".format( Size=len(self.payload) ) ) def get_certifcation_info(cl_inputs, signer): \"\"\" returns",
"= parser.parse_args(['name={}'.format(subregion_name)]) cl_inputs.name = subregion_name cl_inputs.vendor_guid = vendor_guid cl_inputs.tool_path = tool_path cl_inputs.signer_type =",
"filename.\", ) my_parser.add_argument( \"--toolpath\", dest=\"tool_path\", help=\"Path to signtool or OpenSSL tool. \" \"",
"choices=[\"pkcs7\", \"rsa\"], ) my_parser.add_argument( \"-s\", \"--signer\", dest=\"signerfile\", required=True, help=\"OpenSSL signer private certificate filename.\",",
"in PATH.\", default=None, ) my_parser.add_argument( \"--show\", help=\"Shows information about the subregion_authentication structure \"",
"0: sys.exit(status) outfile = utils.file_not_exist(outfile, LOGGER) parser = argparse.ArgumentParser() parser.add_argument(\"name, vendor_guid, tool_path, signer_type\")",
"OpenSSL command with the specified private key and capture signature from STDOUT try:",
"= {Size:08X}\".format( Size=len(self.cert_data) ) ) print( \"sizeof (payload) = {Size:08X}\".format( Size=len(self.payload) ) )",
"# UINT32 Revision; // Revision of Signature Structure # UINT32 Length; // Length",
"Create openSSL command 1 cmd = f'{path} {cert_info[1]} \"{signer}\"' # Create openSSL command",
"subregion \"\"\" # different signature type supported by tool CERT_TYPE = { \"pkcs7\":",
"= generate_signature(cert_info[\"openssl_cmd\"], payload) if cert_info[\"openssl_cmd2\"]: # Read in the private key payload =",
"raise Exception(\"Python 3.6 is the minimal version required\") class UefiSubregAuthenClass: \"\"\" Class define",
"char Name[16 bytes]; // Name of the sub-region # EFI_GUID VendorGuid; // Vendor",
"dw_length=self.dw_length ) ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.w_revision = {w_revision:04X}\".format( w_revision=self.w_revision ) ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.wCertificateType =",
"\"EFI_SUBREGION_AUTHENTICATION.AuthInfo.cert_type = {cert_type}\".format( cert_type=str(self.cert_type).upper() ) ) print( \"sizeof (EFI_SUBREGION_AUTHENTICATION.AuthInfo.cert_data) = {Size:08X}\".format( Size=len(self.cert_data) )",
"not arg.strip(): continue yield arg my_parser = argparse.ArgumentParser( prog=__prog__, description=__doc__, conflict_handler=\"resolve\", fromfile_prefix_chars=\"@\", )",
"signing type information cert_info = CERT_TYPE.get(cl_inputs.signer_type) # Create openSSL command 1 cmd =",
"< (3, 6): raise Exception(\"Python 3.6 is the minimal version required\") class UefiSubregAuthenClass:",
"given by the vendor for the sub-region being signed.\\ This is required. The",
"\"rsa\"], ) my_parser.add_argument( \"-s\", \"--signer\", dest=\"signerfile\", required=True, help=\"OpenSSL signer private certificate filename.\", )",
"add Vendor Guid to Payload payload = uefi_subreg_authen.vendor_guid.bytes_le + payload # calculate the",
"key from bytes to string cert_pub_string = cert_pub.decode(\"utf-8\") # remove word Moudlus= from",
"1 cmd = f'{path} {cert_info[1]} \"{signer}\"' # Create openSSL command 2 if cert_info[2]",
"-binary -keyform PEM -sha384 -sign\", \"rsa -pubout -modulus -noout\", ], } # Check",
"= utils.file_not_exist(outfile, LOGGER) parser = argparse.ArgumentParser() parser.add_argument(\"name, vendor_guid, tool_path, signer_type\") cl_inputs = parser.parse_args(['name={}'.format(subregion_name)])",
"pathlib import Path sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from common.siip_constants import VERSION as __version__ from common.banner",
"cl_inputs.vendor_guid = vendor_guid cl_inputs.tool_path = tool_path cl_inputs.signer_type = signer_type cert_info = get_certifcation_info(cl_inputs, signer_file)",
"help=\"Shows information about the subregion_authentication structure \" \" Optional but requires all information",
"False self.w_name = cert_info[\"name\"] self.vendor_guid = cert_info[\"vendor_guid\"] self.w_revision = cert_info[\"revision\"] self.dw_length = self._StructAuthInfoSize",
"size must not be greter than {}\".format( string, size, string, max_size ) if",
"of the variables for structure \"\"\" self._valid = False self.w_name = cert_info[\"name\"] self.vendor_guid",
"parser.parse_args(['name={}'.format(subregion_name)]) cl_inputs.name = subregion_name cl_inputs.vendor_guid = vendor_guid cl_inputs.tool_path = tool_path cl_inputs.signer_type = signer_type",
"calculate the signature store in structure cert_data = generate_signature(cert_info[\"openssl_cmd\"], payload) if cert_info[\"openssl_cmd2\"]: #",
"as __version__ from common.banner import banner import common.utilities as utils import common.logger as",
"\"Sub-Region Signing Tool\" if sys.version_info < (3, 6): raise Exception(\"Python 3.6 is the",
"help=\"Path to signtool or OpenSSL tool. \" \" Optional if path to tools",
"filenames = [str(sbrgn_file), str(signer_file)] # Verify file input file exist status = utils.file_exist(filenames,",
"structure \" \" Optional but requires all information in order to process.\", action=\"store_true\",",
"public key modulus from private key cert_pub = generate_signature(cert_info[\"openssl_cmd2\"], payload) # convert public",
") my_parser.add_argument( \"-v\", \"--version\", help=\"Shows the current version of the BIOS Stitching Tool\",",
"status = utils.check_key(signer_file, signer_type, LOGGER) if status != 0: sys.exit(status) outfile = utils.file_not_exist(outfile,",
"Vendor GUID # SUB_REGION_VERIFICATION CertParam; // Sub-Region Certificate Parameters # } EFI_SUB_REGION_AUTHENTICATION; #",
"common.logger as logging LOGGER = logging.getLogger(\"subregion_sign\") __prog__ = \"subregion_sign\" TOOLNAME = \"Sub-Region Signing",
"if os.path.getsize(sbrgn_file) == 0: LOGGER.critical(\"size of {} subregion file must be greater than",
"Conert to hex bytes and add to signature cert_pubkey = bytes.fromhex(cert_pubkey) # public",
"def chk_guid_format(guid): \"\"\" check for correct formate of GUID \"\"\" # format for",
"open(outfile, mode=\"wb\") as signed_file: signed_file.write(cert_struct) except ValueError: LOGGER.critical(\"\\nCannot write payload file: %s\", outfile)",
"else: cmd2 = cert_info[2] certification_info = { \"revision\": 0x01, \"name\": cl_inputs.name.encode(\"utf-8\"), \"vendor_guid\": uuid.UUID(cl_inputs.vendor_guid),",
"\"\"\" build output file \"\"\" try: with open(outfile, mode=\"wb\") as signed_file: signed_file.write(cert_struct) except",
"command 2 if cert_info[2] is not None: cmd2 = f\"{path} {cert_info[2]}\" else: cmd2",
"Vendor_guid=str(self.vendor_guid).upper() ) ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.cert_type = {cert_type}\".format( cert_type=str(self.cert_type).upper() ) ) print( \"sizeof (EFI_SUBREGION_AUTHENTICATION.AuthInfo.cert_data)",
"\"\"\" dump the information of subregion authentication structure \"\"\" if not self._valid: raise",
"to store into structure payload = read_file(sbrgn_file) uefi_subreg_authen.payload = payload # add Vendor",
"Run OpenSSL command with the specified private key and capture signature from STDOUT",
"# UINT32 Length; // Length of the Signature + Header # EFI_GUID CertType;",
"the variables for structure \"\"\" self._valid = False self.w_name = cert_info[\"name\"] self.vendor_guid =",
"BSD-2-Clause # \"\"\"A signing utility for creating and signing a BIOS sub-region for",
"typedef struct { # UINT32 Revision; // Revision of Signature Structure # UINT32",
"self.dw_length, self.cert_type.bytes_le, ) self._valid = True return uefi_subreg_authen_hdr + self.cert_data + self.payload def",
"\"File guild value is not in correct format \\ (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx where x can",
"of {} is {}. The {} size must not be greter than {}\".format(",
"with signature and get update size of header uefi_signed_data = uefi_subreg_authen.encode() if show:",
"get update size of header uefi_signed_data = uefi_subreg_authen.encode() if show: uefi_subreg_authen.dump_info() # Create",
"utils.file_exist(filenames, LOGGER) if status != 0: sys.exit(status) if os.path.getsize(sbrgn_file) == 0: LOGGER.critical(\"size of",
"parser = argparse.ArgumentParser() parser.add_argument(\"name, vendor_guid, tool_path, signer_type\") cl_inputs = parser.parse_args(['name={}'.format(subregion_name)]) cl_inputs.name = subregion_name",
"cert_data = generate_signature(cert_info[\"openssl_cmd\"], payload) if cert_info[\"openssl_cmd2\"]: # Read in the private key payload",
"pkcs7 or rsa.\", choices=[\"pkcs7\", \"rsa\"], ) my_parser.add_argument( \"-s\", \"--signer\", dest=\"signerfile\", required=True, help=\"OpenSSL signer",
"must be greater than 0!\".format(sbrgn_file)) sys.exit(status) status = utils.check_key(signer_file, signer_type, LOGGER) if status",
"to back cert_data = cert_pubkey + cert_data uefi_subreg_authen.cert_data = cert_data # pack structure",
"needs to be signed.\" ) my_parser.add_argument( \"-o\", \"--output\", dest=\"signed_file\", help=\"Output capsule filename.\", metavar=\"Filename\",",
"self.payload = bytes() def encode(self): \"\"\" builds structure for subregion authentication header \"\"\"",
"= Path(subregion_file).resolve() signer_file = Path(signer_file).resolve() outfile = Path(signed_file).resolve() filenames = [str(sbrgn_file), str(signer_file)] #",
"self.dw_length = self._StructSubRegionHdrSize + len(self.cert_data) uefi_subreg_authen_hdr = struct.pack( self._StructAuthInfoFormat, self.w_name, self.vendor_guid.bytes_le, self.w_revision, self.dw_length,",
"\"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.dw_length = {dw_length:08X}\".format( dw_length=self.dw_length ) ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.w_revision = {w_revision:04X}\".format( w_revision=self.w_revision ) )",
"{cert_type}\".format( cert_type=str(self.cert_type).upper() ) ) print( \"sizeof (EFI_SUBREGION_AUTHENTICATION.AuthInfo.cert_data) = {Size:08X}\".format( Size=len(self.cert_data) ) ) print(",
"Optional but requires all information in order to process.\", action=\"store_true\", ) my_parser.add_argument( \"-v\",",
"Path(signed_file).resolve() filenames = [str(sbrgn_file), str(signer_file)] # Verify file input file exist status =",
"and get update size of header uefi_signed_data = uefi_subreg_authen.encode() if show: uefi_subreg_authen.dump_info() #",
"argparse.ArgumentParser() parser.add_argument(\"name, vendor_guid, tool_path, signer_type\") cl_inputs = parser.parse_args(['name={}'.format(subregion_name)]) cl_inputs.name = subregion_name cl_inputs.vendor_guid =",
"tool. \" \" Optional if path to tools are already in PATH.\", default=None,",
"Key pair of the Signing Key # UINT8 Signature[384]; // SHA384-RSA3K Signature #",
"is None: raise argparse.ArgumentTypeError( \"File guild value is not in correct format \\",
"\"\"\" try: with open(inputfile, mode=\"rb\") as file: sign_file = file.read() except ValueError: LOGGER.critical(\"\\nCannot",
"{} is {}. The {} size must not be greter than {}\".format( string,",
"file exist status = utils.file_exist(filenames, LOGGER) if status != 0: sys.exit(status) if os.path.getsize(sbrgn_file)",
"as file: sign_file = file.read() except ValueError: LOGGER.critical(\"\\nCannot read payload file: %s\", inputfile)",
"structure with signature and get update size of header uefi_signed_data = uefi_subreg_authen.encode() if",
"= len(string.encode(\"utf-8\")) msg = \"The size of {} is {}. The {} size",
"public key cert_pubkey = cert_pubkey.rstrip() # Conert to hex bytes and add to",
"cert_pubkey = cert_pub_string.replace(\"Modulus=\", \"\") # remove end of line from public key cert_pubkey",
"of header uefi_signed_data = uefi_subreg_authen.encode() if show: uefi_subreg_authen.dump_info() # Create output EFI subregion",
"back cert_data = cert_pubkey + cert_data uefi_subreg_authen.cert_data = cert_data # pack structure with",
"Path(subregion_file).resolve() signer_file = Path(signer_file).resolve() outfile = Path(signed_file).resolve() filenames = [str(sbrgn_file), str(signer_file)] # Verify",
"__init__(self, cert_info): \"\"\" initialization of the variables for structure \"\"\" self._valid = False",
"(payload) = {Size:08X}\".format( Size=len(self.payload) ) ) def get_certifcation_info(cl_inputs, signer): \"\"\" returns the certifcate",
"help=\"Shows the current version of the BIOS Stitching Tool\", action=\"version\", version=\"%(prog)s {version}\".format(version=__version__), )",
"of Signing pkcs7 or rsa.\", choices=[\"pkcs7\", \"rsa\"], ) my_parser.add_argument( \"-s\", \"--signer\", dest=\"signerfile\", required=True,",
"prog=__prog__, description=__doc__, conflict_handler=\"resolve\", fromfile_prefix_chars=\"@\", ) my_parser.convert_arg_line_to_args = convert_arg_line_to_args my_parser.add_argument( \"subregion_file\", help=\"sub region data",
"utility for creating and signing a BIOS sub-region for UEFI \"\"\" from __future__",
"cert_info[2] is not None: cmd2 = f\"{path} {cert_info[2]}\" else: cmd2 = cert_info[2] certification_info",
"my_parser.add_argument( \"-o\", \"--output\", dest=\"signed_file\", help=\"Output capsule filename.\", metavar=\"Filename\", default=\"SIGNED_OUT.bin\", ) my_parser.add_argument( \"-n\", \"--name\",",
"is '00000000-0000-0000-0000-000000000000'\", type=chk_guid_format, metavar=\"v_guid\", required=True, ) my_parser.add_argument( \"-t\", \"--signer_type\", metavar=\"sign_type\", required=True, help=\"Type of",
"value is not in correct format \\ (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx where x can be A-F",
"CertParam; // Sub-Region Certificate Parameters # } EFI_SUB_REGION_AUTHENTICATION; # typedef struct { #",
"if show: uefi_subreg_authen.dump_info() # Create output EFI subregion authentication header and signature and",
"(EFI_SUBREGION_AUTHENTICATION.AuthInfo.cert_data) = {Size:08X}\".format( Size=len(self.cert_data) ) ) print( \"sizeof (payload) = {Size:08X}\".format( Size=len(self.payload) )",
"uefi_subreg_authen.vendor_guid.bytes_le + payload # calculate the signature store in structure cert_data = generate_signature(cert_info[\"openssl_cmd\"],",
"my_parser.add_argument( \"-v\", \"--version\", help=\"Shows the current version of the BIOS Stitching Tool\", action=\"version\",",
"required=True, ) my_parser.add_argument( \"-t\", \"--signer_type\", metavar=\"sign_type\", required=True, help=\"Type of Signing pkcs7 or rsa.\",",
"dest=\"signed_file\", help=\"Output capsule filename.\", metavar=\"Filename\", default=\"SIGNED_OUT.bin\", ) my_parser.add_argument( \"-n\", \"--name\", help=\"The name of",
"= utils.file_exist(filenames, LOGGER) if status != 0: sys.exit(status) if os.path.getsize(sbrgn_file) == 0: LOGGER.critical(\"size",
"of subregion authentication structure \"\"\" if not self._valid: raise ValueError print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.dw_length =",
"A-F or 0-9 guidFormat = re.compile( r\"([a-f\\d]{8}[-][a-f\\d]{4}[-][a-f\\d]{4}[-][a-f\\d]{4}[-]{1}[a-f\\d]{12}$)\", re.I ) if guidFormat.match(guid) is None:",
"utils import common.logger as logging LOGGER = logging.getLogger(\"subregion_sign\") __prog__ = \"subregion_sign\" TOOLNAME =",
"struct { # UINT32 Revision; // Revision of Signature Structure # UINT32 Length;",
"path for openSSL sbrgn_file = Path(subregion_file).resolve() signer_file = Path(signer_file).resolve() outfile = Path(signed_file).resolve() filenames",
"+ payload # calculate the signature store in structure cert_data = generate_signature(cert_info[\"openssl_cmd\"], payload)",
"Signing Key # UINT8 Signature[384]; // SHA384-RSA3K Signature # } EFI_CERT_BLOCK_RSA3072_SHA384; _StructAuthInfoFormat =",
"self._StructAuthInfoFormat, self.w_name, self.vendor_guid.bytes_le, self.w_revision, self.dw_length, self.cert_type.bytes_le, ) self._valid = True return uefi_subreg_authen_hdr +",
"Signing Tool\" if sys.version_info < (3, 6): raise Exception(\"Python 3.6 is the minimal",
"import common.utilities as utils import common.logger as logging LOGGER = logging.getLogger(\"subregion_sign\") __prog__ =",
"} SUB_REGION_VERIFICATION; # typedef struct { # UINT32 Revision; // Revision of Signature",
"\"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.wCertificateType = {Vendor_guid}\".format( Vendor_guid=str(self.vendor_guid).upper() ) ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.cert_type = {cert_type}\".format( cert_type=str(self.cert_type).upper() ) )",
"action=\"version\", version=\"%(prog)s {version}\".format(version=__version__), ) return my_parser def chk_string_size(string): \"\"\"\"Check the size of the",
"// Length of the Signature + Header # EFI_GUID CertType; // Signature type",
"formate of GUID \"\"\" # format for guid xxxxxxxx-xxxx-xxxx-xxx-xxxxxxxxxxxx where x can be",
"import argparse import uuid import struct import re from pathlib import Path sys.path.insert(0,",
"// Revision of Signature Structure # UINT32 Length; // Length of the Signature",
"= cert_info[\"revision\"] self.dw_length = self._StructAuthInfoSize self.cert_type = cert_info[\"cert_type\"] self.cert_data = bytes() self.payload =",
"0-9)\\ {}\".format(guid) ) return guid def sign_subregion(subregion_file, signer_file, signed_file, signer_type, subregion_name, vendor_guid, show",
"type # } SUB_REGION_HEADER; # typedef struct { # UINT8 PublicKey[384]; // Public",
"metavar=\"subregion\", required=True, ) my_parser.add_argument( \"-vg\", \"--vendor-guid\", help=\"Vender GUID is one specific value given",
"than 0!\".format(sbrgn_file)) sys.exit(status) status = utils.check_key(signer_file, signer_type, LOGGER) if status != 0: sys.exit(status)",
"signer_type\") cl_inputs = parser.parse_args(['name={}'.format(subregion_name)]) cl_inputs.name = subregion_name cl_inputs.vendor_guid = vendor_guid cl_inputs.tool_path = tool_path",
"UEFI \"\"\" from __future__ import print_function import os import sys import subprocess import",
"authentication header \"\"\" self.dw_length = self._StructSubRegionHdrSize + len(self.cert_data) uefi_subreg_authen_hdr = struct.pack( self._StructAuthInfoFormat, self.w_name,",
"passed on subregion \"\"\" # different signature type supported by tool CERT_TYPE =",
"'00000000-0000-0000-0000-000000000000'\", type=chk_guid_format, metavar=\"v_guid\", required=True, ) my_parser.add_argument( \"-t\", \"--signer_type\", metavar=\"sign_type\", required=True, help=\"Type of Signing",
"tools are already in PATH.\", default=None, ) my_parser.add_argument( \"--show\", help=\"Shows information about the",
"subregion file must be greater than 0!\".format(sbrgn_file)) sys.exit(status) status = utils.check_key(signer_file, signer_type, LOGGER)",
"= struct.calcsize(_StructSubRegionHdrFormat) def __init__(self, cert_info): \"\"\" initialization of the variables for structure \"\"\"",
"None: cmd2 = f\"{path} {cert_info[2]}\" else: cmd2 = cert_info[2] certification_info = { \"revision\":",
"def __init__(self, cert_info): \"\"\" initialization of the variables for structure \"\"\" self._valid =",
"!= 0: sys.exit(status) outfile = utils.file_not_exist(outfile, LOGGER) parser = argparse.ArgumentParser() parser.add_argument(\"name, vendor_guid, tool_path,",
"all information in order to process.\", action=\"store_true\", ) my_parser.add_argument( \"-v\", \"--version\", help=\"Shows the",
"signer_type cert_info = get_certifcation_info(cl_inputs, signer_file) uefi_subreg_authen = UefiSubregAuthenClass(cert_info) # read input file to",
"outfile = Path(signed_file).resolve() filenames = [str(sbrgn_file), str(signer_file)] # Verify file input file exist",
") def get_certifcation_info(cl_inputs, signer): \"\"\" returns the certifcate type passed on subregion \"\"\"",
"__prog__ = \"subregion_sign\" TOOLNAME = \"Sub-Region Signing Tool\" if sys.version_info < (3, 6):",
"UINT32 Length; // Length of the Signature + Header # EFI_GUID CertType; //",
"-sign -binary -outform DER -md sha256 -nodetach -signer\", None, ], \"rsa\": [ \"2ee9976f-9d4c-4442-a997-8cad1c875fa1\",",
"def chk_string_size(string): \"\"\"\"Check the size of the string\"\"\" max_size = 16 size =",
"} return certification_info def build_subreg_signed_file(cert_struct, outfile): \"\"\" build output file \"\"\" try: with",
"# \"\"\"A signing utility for creating and signing a BIOS sub-region for UEFI",
"subreation Authentication class \"\"\" # typedef struct { # char Name[16 bytes]; //",
"= struct.pack( self._StructAuthInfoFormat, self.w_name, self.vendor_guid.bytes_le, self.w_revision, self.dw_length, self.cert_type.bytes_le, ) self._valid = True return",
"dump the information of subregion authentication structure \"\"\" if not self._valid: raise ValueError",
"xxxxxxxx-xxxx-xxxx-xxx-xxxxxxxxxxxx where x can be A-F or 0-9 guidFormat = re.compile( r\"([a-f\\d]{8}[-][a-f\\d]{4}[-][a-f\\d]{4}[-][a-f\\d]{4}[-]{1}[a-f\\d]{12}$)\", re.I",
"if status != 0: sys.exit(status) outfile = utils.file_not_exist(outfile, LOGGER) parser = argparse.ArgumentParser() parser.add_argument(\"name,",
"True return uefi_subreg_authen_hdr + self.cert_data + self.payload def dump_info(self): \"\"\" dump the information",
"the specified private key and capture signature from STDOUT try: ssl_process = subprocess.run(",
"and validating input arguments.\"\"\" def convert_arg_line_to_args(arg_line): for arg in arg_line.split(): if not arg.strip():",
"Stitching Tool\", action=\"version\", version=\"%(prog)s {version}\".format(version=__version__), ) return my_parser def chk_string_size(string): \"\"\"\"Check the size",
"read_file(inputfile): \"\"\" read input file to bytes \"\"\" try: with open(inputfile, mode=\"rb\") as",
") signature = ssl_process.stdout except: LOGGER.warning(\"\\nCannot run openssl.\") sys.exit(1) if ssl_process.returncode != 0:",
"\"\"\" # typedef struct { # char Name[16 bytes]; // Name of the",
"the signature store in structure cert_data = generate_signature(cert_info[\"openssl_cmd\"], payload) if cert_info[\"openssl_cmd2\"]: # Read",
"Corporation. All rights reserved. # SPDX-License-Identifier: BSD-2-Clause # \"\"\"A signing utility for creating",
"creating and signing a BIOS sub-region for UEFI \"\"\" from __future__ import print_function",
"file.read() except ValueError: LOGGER.critical(\"\\nCannot read payload file: %s\", inputfile) sys.exit(2) return sign_file def",
"len(string.encode(\"utf-8\")) msg = \"The size of {} is {}. The {} size must",
"import re from pathlib import Path sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from common.siip_constants import VERSION as",
"VendorGuid; // Vendor GUID # SUB_REGION_VERIFICATION CertParam; // Sub-Region Certificate Parameters # }",
"in order to process.\", action=\"store_true\", ) my_parser.add_argument( \"-v\", \"--version\", help=\"Shows the current version",
"# Use absolute path for openSSL sbrgn_file = Path(subregion_file).resolve() signer_file = Path(signer_file).resolve() outfile",
"re from pathlib import Path sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from common.siip_constants import VERSION as __version__",
"\"\"\" self.dw_length = self._StructSubRegionHdrSize + len(self.cert_data) uefi_subreg_authen_hdr = struct.pack( self._StructAuthInfoFormat, self.w_name, self.vendor_guid.bytes_le, self.w_revision,",
"= file.read() except ValueError: LOGGER.critical(\"\\nCannot read payload file: %s\", inputfile) sys.exit(2) return sign_file",
"Path sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from common.siip_constants import VERSION as __version__ from common.banner import banner",
"dest=\"signerfile\", required=True, help=\"OpenSSL signer private certificate filename.\", ) my_parser.add_argument( \"--toolpath\", dest=\"tool_path\", help=\"Path to",
"are packed back to back cert_data = cert_pubkey + cert_data uefi_subreg_authen.cert_data = cert_data",
"the public key modulus from private key cert_pub = generate_signature(cert_info[\"openssl_cmd2\"], payload) # convert",
"Exception(\"Python 3.6 is the minimal version required\") class UefiSubregAuthenClass: \"\"\" Class define EFI",
"status != 0: sys.exit(status) outfile = utils.file_not_exist(outfile, LOGGER) parser = argparse.ArgumentParser() parser.add_argument(\"name, vendor_guid,",
"or OpenSSL tool. \" \" Optional if path to tools are already in",
"openssl_cmd, input=payload, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, check=True, ) signature = ssl_process.stdout except: LOGGER.warning(\"\\nCannot run",
"\"version\", cl_inputs.tool_path) # Get signing type information cert_info = CERT_TYPE.get(cl_inputs.signer_type) # Create openSSL",
"input arguments.\"\"\" def convert_arg_line_to_args(arg_line): for arg in arg_line.split(): if not arg.strip(): continue yield",
"requires all information in order to process.\", action=\"store_true\", ) my_parser.add_argument( \"-v\", \"--version\", help=\"Shows",
"from common.banner import banner import common.utilities as utils import common.logger as logging LOGGER",
"my_parser.add_argument( \"-vg\", \"--vendor-guid\", help=\"Vender GUID is one specific value given by the vendor",
"subregion authentication header \"\"\" self.dw_length = self._StructSubRegionHdrSize + len(self.cert_data) uefi_subreg_authen_hdr = struct.pack( self._StructAuthInfoFormat,",
"LOGGER.critical(\"\\nCannot read payload file: %s\", inputfile) sys.exit(2) return sign_file def generate_signature(openssl_cmd, payload): \"\"\"",
"The format is '00000000-0000-0000-0000-000000000000'\", type=chk_guid_format, metavar=\"v_guid\", required=True, ) my_parser.add_argument( \"-t\", \"--signer_type\", metavar=\"sign_type\", required=True,",
"\"-t\", \"--signer_type\", metavar=\"sign_type\", required=True, help=\"Type of Signing pkcs7 or rsa.\", choices=[\"pkcs7\", \"rsa\"], )",
"Vendor Guid to Payload payload = uefi_subreg_authen.vendor_guid.bytes_le + payload # calculate the signature",
"sub-region({}) was successfully generated.\".format( subregion_name, outfile ) ) def main(): \"\"\"Entry to script.\"\"\"",
"as logging LOGGER = logging.getLogger(\"subregion_sign\") __prog__ = \"subregion_sign\" TOOLNAME = \"Sub-Region Signing Tool\"",
"uefi_subreg_authen_hdr = struct.pack( self._StructAuthInfoFormat, self.w_name, self.vendor_guid.bytes_le, self.w_revision, self.dw_length, self.cert_type.bytes_le, ) self._valid = True",
"the string\"\"\" max_size = 16 size = len(string.encode(\"utf-8\")) msg = \"The size of",
"# Verify file input file exist status = utils.file_exist(filenames, LOGGER) if status !=",
"try: ssl_process = subprocess.run( openssl_cmd, input=payload, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, check=True, ) signature =",
"update size of header uefi_signed_data = uefi_subreg_authen.encode() if show: uefi_subreg_authen.dump_info() # Create output",
"builds structure for subregion authentication header \"\"\" self.dw_length = self._StructSubRegionHdrSize + len(self.cert_data) uefi_subreg_authen_hdr",
"process.\", action=\"store_true\", ) my_parser.add_argument( \"-v\", \"--version\", help=\"Shows the current version of the BIOS",
"], \"rsa\": [ \"2ee9976f-9d4c-4442-a997-8cad1c875fa1\", \"dgst -binary -keyform PEM -sha384 -sign\", \"rsa -pubout -modulus",
"my_parser.add_argument( \"--show\", help=\"Shows information about the subregion_authentication structure \" \" Optional but requires",
"information cert_info = CERT_TYPE.get(cl_inputs.signer_type) # Create openSSL command 1 cmd = f'{path} {cert_info[1]}",
"import os import sys import subprocess import argparse import uuid import struct import",
"\"\"\"A signing utility for creating and signing a BIOS sub-region for UEFI \"\"\"",
"\"\"\" self._valid = False self.w_name = cert_info[\"name\"] self.vendor_guid = cert_info[\"vendor_guid\"] self.w_revision = cert_info[\"revision\"]",
"type=chk_string_size, metavar=\"subregion\", required=True, ) my_parser.add_argument( \"-vg\", \"--vendor-guid\", help=\"Vender GUID is one specific value",
"max_size: raise argparse.ArgumentTypeError(str(msg)) return string def chk_guid_format(guid): \"\"\" check for correct formate of",
"struct.pack( self._StructAuthInfoFormat, self.w_name, self.vendor_guid.bytes_le, self.w_revision, self.dw_length, self.cert_type.bytes_le, ) self._valid = True return uefi_subreg_authen_hdr",
"read input file to bytes \"\"\" try: with open(inputfile, mode=\"rb\") as file: sign_file",
"the Signature + Header # EFI_GUID CertType; // Signature type # } SUB_REGION_HEADER;",
"convert_arg_line_to_args my_parser.add_argument( \"subregion_file\", help=\"sub region data that needs to be signed.\" ) my_parser.add_argument(",
"def convert_arg_line_to_args(arg_line): for arg in arg_line.split(): if not arg.strip(): continue yield arg my_parser",
"name of the subregion being signed. Max size is 16 bytes The name",
"Certificate Header # UINT8 CertData[1]; // Calculated Signature # } SUB_REGION_VERIFICATION; # typedef",
"default=None, ) my_parser.add_argument( \"--show\", help=\"Shows information about the subregion_authentication structure \" \" Optional",
"LOGGER) if status != 0: sys.exit(status) if os.path.getsize(sbrgn_file) == 0: LOGGER.critical(\"size of {}",
"UINT8 PublicKey[384]; // Public Key pair of the Signing Key # UINT8 Signature[384];",
"%s\", inputfile) sys.exit(2) return sign_file def generate_signature(openssl_cmd, payload): \"\"\" signed input file \"\"\"",
"be greter than {}\".format( string, size, string, max_size ) if size > max_size:",
"for creating and signing a BIOS sub-region for UEFI \"\"\" from __future__ import",
"= None): # Use absolute path for openSSL sbrgn_file = Path(subregion_file).resolve() signer_file =",
"str(signer_file)] # Verify file input file exist status = utils.file_exist(filenames, LOGGER) if status",
"os.path.getsize(sbrgn_file) == 0: LOGGER.critical(\"size of {} subregion file must be greater than 0!\".format(sbrgn_file))",
"show = False, tool_path = None): # Use absolute path for openSSL sbrgn_file",
"cert_info[\"revision\"] self.dw_length = self._StructAuthInfoSize self.cert_type = cert_info[\"cert_type\"] self.cert_data = bytes() self.payload = bytes()",
"CERT_TYPE = { \"pkcs7\": [ \"4aafd29d-68df-49ee-8aa9-347d375665a7\", \"smime -sign -binary -outform DER -md sha256",
"], } # Check if openssl is installed path = utils.check_for_tool(\"openssl\", \"version\", cl_inputs.tool_path)",
"capsule filename.\", metavar=\"Filename\", default=\"SIGNED_OUT.bin\", ) my_parser.add_argument( \"-n\", \"--name\", help=\"The name of the subregion",
"private key cert_pub = generate_signature(cert_info[\"openssl_cmd2\"], payload) # convert public key from bytes to",
"= utils.check_for_tool(\"openssl\", \"version\", cl_inputs.tool_path) # Get signing type information cert_info = CERT_TYPE.get(cl_inputs.signer_type) #",
"if ssl_process.returncode != 0: LOGGER.critical(\"\\nopenssl failed.\") sys.exit(1) return signature def create_arg_parser(): \"\"\" Parsing",
"type supported by tool CERT_TYPE = { \"pkcs7\": [ \"4aafd29d-68df-49ee-8aa9-347d375665a7\", \"smime -sign -binary",
"def sign_subregion(subregion_file, signer_file, signed_file, signer_type, subregion_name, vendor_guid, show = False, tool_path = None):",
"[ \"4aafd29d-68df-49ee-8aa9-347d375665a7\", \"smime -sign -binary -outform DER -md sha256 -nodetach -signer\", None, ],",
"= CERT_TYPE.get(cl_inputs.signer_type) # Create openSSL command 1 cmd = f'{path} {cert_info[1]} \"{signer}\"' #",
"get_certifcation_info(cl_inputs, signer_file) uefi_subreg_authen = UefiSubregAuthenClass(cert_info) # read input file to store into structure",
"# remove word Moudlus= from the file cert_pubkey = cert_pub_string.replace(\"Modulus=\", \"\") # remove",
"= tool_path cl_inputs.signer_type = signer_type cert_info = get_certifcation_info(cl_inputs, signer_file) uefi_subreg_authen = UefiSubregAuthenClass(cert_info) #",
"capture signature from STDOUT try: ssl_process = subprocess.run( openssl_cmd, input=payload, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True,",
"cert_info[\"name\"] self.vendor_guid = cert_info[\"vendor_guid\"] self.w_revision = cert_info[\"revision\"] self.dw_length = self._StructAuthInfoSize self.cert_type = cert_info[\"cert_type\"]",
"-outform DER -md sha256 -nodetach -signer\", None, ], \"rsa\": [ \"2ee9976f-9d4c-4442-a997-8cad1c875fa1\", \"dgst -binary",
"# read input file to store into structure payload = read_file(sbrgn_file) uefi_subreg_authen.payload =",
"if sys.version_info < (3, 6): raise Exception(\"Python 3.6 is the minimal version required\")",
"return uefi_subreg_authen_hdr + self.cert_data + self.payload def dump_info(self): \"\"\" dump the information of",
"\"-n\", \"--name\", help=\"The name of the subregion being signed. Max size is 16",
"import VERSION as __version__ from common.banner import banner import common.utilities as utils import",
"file input file exist status = utils.file_exist(filenames, LOGGER) if status != 0: sys.exit(status)",
"of the Signing Key # UINT8 Signature[384]; // SHA384-RSA3K Signature # } EFI_CERT_BLOCK_RSA3072_SHA384;",
"value given by the vendor for the sub-region being signed.\\ This is required.",
"cl_inputs = parser.parse_args(['name={}'.format(subregion_name)]) cl_inputs.name = subregion_name cl_inputs.vendor_guid = vendor_guid cl_inputs.tool_path = tool_path cl_inputs.signer_type",
"= generate_signature(cert_info[\"openssl_cmd2\"], payload) # convert public key from bytes to string cert_pub_string =",
"\"vendor_guid\": uuid.UUID(cl_inputs.vendor_guid), \"cert_type\": uuid.UUID(cert_info[0]), \"openssl_cmd\": cmd, \"openssl_cmd2\": cmd2, } return certification_info def build_subreg_signed_file(cert_struct,",
"being signed. Max size is 16 bytes The name is stored in signed",
"LOGGER.critical(\"size of {} subregion file must be greater than 0!\".format(sbrgn_file)) sys.exit(status) status =",
"payload = read_file(signer_file) # Extract the public key modulus from private key cert_pub",
"vendor for the sub-region being signed.\\ This is required. The format is '00000000-0000-0000-0000-000000000000'\",",
"key payload = read_file(signer_file) # Extract the public key modulus from private key",
"required=True, help=\"OpenSSL signer private certificate filename.\", ) my_parser.add_argument( \"--toolpath\", dest=\"tool_path\", help=\"Path to signtool",
"subregion_name, vendor_guid, show = False, tool_path = None): # Use absolute path for",
"packed back to back cert_data = cert_pubkey + cert_data uefi_subreg_authen.cert_data = cert_data #",
"LOGGER = logging.getLogger(\"subregion_sign\") __prog__ = \"subregion_sign\" TOOLNAME = \"Sub-Region Signing Tool\" if sys.version_info",
"output file \"\"\" try: with open(outfile, mode=\"wb\") as signed_file: signed_file.write(cert_struct) except ValueError: LOGGER.critical(\"\\nCannot",
"sys.exit(status) outfile = utils.file_not_exist(outfile, LOGGER) parser = argparse.ArgumentParser() parser.add_argument(\"name, vendor_guid, tool_path, signer_type\") cl_inputs",
"LOGGER) parser = argparse.ArgumentParser() parser.add_argument(\"name, vendor_guid, tool_path, signer_type\") cl_inputs = parser.parse_args(['name={}'.format(subregion_name)]) cl_inputs.name =",
"uefi_subreg_authen.encode() if show: uefi_subreg_authen.dump_info() # Create output EFI subregion authentication header and signature",
"= cert_pubkey.rstrip() # Conert to hex bytes and add to signature cert_pubkey =",
"-noout\", ], } # Check if openssl is installed path = utils.check_for_tool(\"openssl\", \"version\",",
"\"name\": cl_inputs.name.encode(\"utf-8\"), \"vendor_guid\": uuid.UUID(cl_inputs.vendor_guid), \"cert_type\": uuid.UUID(cert_info[0]), \"openssl_cmd\": cmd, \"openssl_cmd2\": cmd2, } return certification_info",
"OpenSSL tool. \" \" Optional if path to tools are already in PATH.\",",
"the information of subregion authentication structure \"\"\" if not self._valid: raise ValueError print(",
"structure \"\"\" if not self._valid: raise ValueError print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.dw_length = {dw_length:08X}\".format( dw_length=self.dw_length )",
"not None: cmd2 = f\"{path} {cert_info[2]}\" else: cmd2 = cert_info[2] certification_info = {",
"%s\", outfile) sys.exit(2) def read_file(inputfile): \"\"\" read input file to bytes \"\"\" try:",
"not in correct format \\ (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx where x can be A-F or 0-9)\\",
"read input file to store into structure payload = read_file(sbrgn_file) uefi_subreg_authen.payload = payload",
"hex bytes and add to signature cert_pubkey = bytes.fromhex(cert_pubkey) # public key and",
"signature are packed back to back cert_data = cert_pubkey + cert_data uefi_subreg_authen.cert_data =",
"of {} subregion file must be greater than 0!\".format(sbrgn_file)) sys.exit(status) status = utils.check_key(signer_file,",
"can be A-F or 0-9)\\ {}\".format(guid) ) return guid def sign_subregion(subregion_file, signer_file, signed_file,",
"private key and capture signature from STDOUT try: ssl_process = subprocess.run( openssl_cmd, input=payload,",
"{ # char Name[16 bytes]; // Name of the sub-region # EFI_GUID VendorGuid;",
"# -*- coding: utf-8 -*- # # Copyright (c) 2020, Intel Corporation. All",
"vendor_guid cl_inputs.tool_path = tool_path cl_inputs.signer_type = signer_type cert_info = get_certifcation_info(cl_inputs, signer_file) uefi_subreg_authen =",
"Tool\" if sys.version_info < (3, 6): raise Exception(\"Python 3.6 is the minimal version",
"self.cert_type.bytes_le, ) self._valid = True return uefi_subreg_authen_hdr + self.cert_data + self.payload def dump_info(self):",
"Signature Structure # UINT32 Length; // Length of the Signature + Header #",
"raise ValueError print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.dw_length = {dw_length:08X}\".format( dw_length=self.dw_length ) ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.w_revision = {w_revision:04X}\".format(",
"= {dw_length:08X}\".format( dw_length=self.dw_length ) ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.w_revision = {w_revision:04X}\".format( w_revision=self.w_revision ) ) print(",
") return my_parser def chk_string_size(string): \"\"\"\"Check the size of the string\"\"\" max_size =",
"\"-vg\", \"--vendor-guid\", help=\"Vender GUID is one specific value given by the vendor for",
"not self._valid: raise ValueError print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.dw_length = {dw_length:08X}\".format( dw_length=self.dw_length ) ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.w_revision",
"except: LOGGER.warning(\"\\nCannot run openssl.\") sys.exit(1) if ssl_process.returncode != 0: LOGGER.critical(\"\\nopenssl failed.\") sys.exit(1) return",
"signature and get update size of header uefi_signed_data = uefi_subreg_authen.encode() if show: uefi_subreg_authen.dump_info()",
"and signing a BIOS sub-region for UEFI \"\"\" from __future__ import print_function import",
"vendor_guid, tool_path, signer_type\") cl_inputs = parser.parse_args(['name={}'.format(subregion_name)]) cl_inputs.name = subregion_name cl_inputs.vendor_guid = vendor_guid cl_inputs.tool_path",
"region data that needs to be signed.\" ) my_parser.add_argument( \"-o\", \"--output\", dest=\"signed_file\", help=\"Output",
"\"Signed {} sub-region({}) was successfully generated.\".format( subregion_name, outfile ) ) def main(): \"\"\"Entry",
"EFI_SUB_REGION_AUTHENTICATION; # typedef struct { # SUB_REGION_HEADER Hdr; // Certificate Header # UINT8",
"= bytes() def encode(self): \"\"\" builds structure for subregion authentication header \"\"\" self.dw_length",
"\"\"\" builds structure for subregion authentication header \"\"\" self.dw_length = self._StructSubRegionHdrSize + len(self.cert_data)",
"cl_inputs.name.encode(\"utf-8\"), \"vendor_guid\": uuid.UUID(cl_inputs.vendor_guid), \"cert_type\": uuid.UUID(cert_info[0]), \"openssl_cmd\": cmd, \"openssl_cmd2\": cmd2, } return certification_info def",
"help=\"Vender GUID is one specific value given by the vendor for the sub-region",
"\" \" Optional if path to tools are already in PATH.\", default=None, )",
"SPDX-License-Identifier: BSD-2-Clause # \"\"\"A signing utility for creating and signing a BIOS sub-region",
"cert_data uefi_subreg_authen.cert_data = cert_data # pack structure with signature and get update size",
"store into structure payload = read_file(sbrgn_file) uefi_subreg_authen.payload = payload # add Vendor Guid",
"except ValueError: LOGGER.critical(\"\\nCannot write payload file: %s\", outfile) sys.exit(2) def read_file(inputfile): \"\"\" read",
"Size=len(self.payload) ) ) def get_certifcation_info(cl_inputs, signer): \"\"\" returns the certifcate type passed on",
"SUB_REGION_HEADER Hdr; // Certificate Header # UINT8 CertData[1]; // Calculated Signature # }",
"(c) 2020, Intel Corporation. All rights reserved. # SPDX-License-Identifier: BSD-2-Clause # \"\"\"A signing",
"self._StructAuthInfoSize self.cert_type = cert_info[\"cert_type\"] self.cert_data = bytes() self.payload = bytes() def encode(self): \"\"\"",
"Public Key pair of the Signing Key # UINT8 Signature[384]; // SHA384-RSA3K Signature",
"x can be A-F or 0-9 guidFormat = re.compile( r\"([a-f\\d]{8}[-][a-f\\d]{4}[-][a-f\\d]{4}[-][a-f\\d]{4}[-]{1}[a-f\\d]{12}$)\", re.I ) if",
"The name is stored in signed file.\", type=chk_string_size, metavar=\"subregion\", required=True, ) my_parser.add_argument( \"-vg\",",
"cl_inputs.tool_path) # Get signing type information cert_info = CERT_TYPE.get(cl_inputs.signer_type) # Create openSSL command",
"CertType; // Signature type # } SUB_REGION_HEADER; # typedef struct { # UINT8",
"the subregion being signed. Max size is 16 bytes The name is stored",
"\"\"\" initialization of the variables for structure \"\"\" self._valid = False self.w_name =",
"signing utility for creating and signing a BIOS sub-region for UEFI \"\"\" from",
"signed_file.write(cert_struct) except ValueError: LOGGER.critical(\"\\nCannot write payload file: %s\", outfile) sys.exit(2) def read_file(inputfile): \"\"\"",
"cert_info): \"\"\" initialization of the variables for structure \"\"\" self._valid = False self.w_name",
") my_parser.add_argument( \"-n\", \"--name\", help=\"The name of the subregion being signed. Max size",
"= payload # add Vendor Guid to Payload payload = uefi_subreg_authen.vendor_guid.bytes_le + payload",
"string cert_pub_string = cert_pub.decode(\"utf-8\") # remove word Moudlus= from the file cert_pubkey =",
"tool_path = None): # Use absolute path for openSSL sbrgn_file = Path(subregion_file).resolve() signer_file",
"ssl_process.returncode != 0: LOGGER.critical(\"\\nopenssl failed.\") sys.exit(1) return signature def create_arg_parser(): \"\"\" Parsing and",
"string, max_size ) if size > max_size: raise argparse.ArgumentTypeError(str(msg)) return string def chk_guid_format(guid):",
"print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.cert_type = {cert_type}\".format( cert_type=str(self.cert_type).upper() ) ) print( \"sizeof (EFI_SUBREGION_AUTHENTICATION.AuthInfo.cert_data) = {Size:08X}\".format( Size=len(self.cert_data)",
"supported by tool CERT_TYPE = { \"pkcs7\": [ \"4aafd29d-68df-49ee-8aa9-347d375665a7\", \"smime -sign -binary -outform",
"if path to tools are already in PATH.\", default=None, ) my_parser.add_argument( \"--show\", help=\"Shows",
"Length of the Signature + Header # EFI_GUID CertType; // Signature type #",
"{ # UINT32 Revision; // Revision of Signature Structure # UINT32 Length; //",
"file: sign_file = file.read() except ValueError: LOGGER.critical(\"\\nCannot read payload file: %s\", inputfile) sys.exit(2)",
"{}\".format(guid) ) return guid def sign_subregion(subregion_file, signer_file, signed_file, signer_type, subregion_name, vendor_guid, show =",
"into structure payload = read_file(sbrgn_file) uefi_subreg_authen.payload = payload # add Vendor Guid to",
"signed.\" ) my_parser.add_argument( \"-o\", \"--output\", dest=\"signed_file\", help=\"Output capsule filename.\", metavar=\"Filename\", default=\"SIGNED_OUT.bin\", ) my_parser.add_argument(",
"-signer\", None, ], \"rsa\": [ \"2ee9976f-9d4c-4442-a997-8cad1c875fa1\", \"dgst -binary -keyform PEM -sha384 -sign\", \"rsa",
"Signature + Header # EFI_GUID CertType; // Signature type # } SUB_REGION_HEADER; #",
"= {Vendor_guid}\".format( Vendor_guid=str(self.vendor_guid).upper() ) ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.cert_type = {cert_type}\".format( cert_type=str(self.cert_type).upper() ) ) print(",
"version required\") class UefiSubregAuthenClass: \"\"\" Class define EFI subreation Authentication class \"\"\" #",
"common.siip_constants import VERSION as __version__ from common.banner import banner import common.utilities as utils",
"mode=\"wb\") as signed_file: signed_file.write(cert_struct) except ValueError: LOGGER.critical(\"\\nCannot write payload file: %s\", outfile) sys.exit(2)",
"metavar=\"Filename\", default=\"SIGNED_OUT.bin\", ) my_parser.add_argument( \"-n\", \"--name\", help=\"The name of the subregion being signed.",
"# # Copyright (c) 2020, Intel Corporation. All rights reserved. # SPDX-License-Identifier: BSD-2-Clause",
"CertData[1]; // Calculated Signature # } SUB_REGION_VERIFICATION; # typedef struct { # UINT32",
"the certifcate type passed on subregion \"\"\" # different signature type supported by",
"Use absolute path for openSSL sbrgn_file = Path(subregion_file).resolve() signer_file = Path(signer_file).resolve() outfile =",
"the current version of the BIOS Stitching Tool\", action=\"version\", version=\"%(prog)s {version}\".format(version=__version__), ) return",
"\"-v\", \"--version\", help=\"Shows the current version of the BIOS Stitching Tool\", action=\"version\", version=\"%(prog)s",
"\"--output\", dest=\"signed_file\", help=\"Output capsule filename.\", metavar=\"Filename\", default=\"SIGNED_OUT.bin\", ) my_parser.add_argument( \"-n\", \"--name\", help=\"The name",
"DER -md sha256 -nodetach -signer\", None, ], \"rsa\": [ \"2ee9976f-9d4c-4442-a997-8cad1c875fa1\", \"dgst -binary -keyform",
"self._valid = True return uefi_subreg_authen_hdr + self.cert_data + self.payload def dump_info(self): \"\"\" dump",
"if status != 0: sys.exit(status) if os.path.getsize(sbrgn_file) == 0: LOGGER.critical(\"size of {} subregion",
"Key # UINT8 Signature[384]; // SHA384-RSA3K Signature # } EFI_CERT_BLOCK_RSA3072_SHA384; _StructAuthInfoFormat = \"<16s16sLL16s\"",
"raise argparse.ArgumentTypeError(str(msg)) return string def chk_guid_format(guid): \"\"\" check for correct formate of GUID",
"size of header uefi_signed_data = uefi_subreg_authen.encode() if show: uefi_subreg_authen.dump_info() # Create output EFI",
"{} sub-region({}) was successfully generated.\".format( subregion_name, outfile ) ) def main(): \"\"\"Entry to",
"openssl is installed path = utils.check_for_tool(\"openssl\", \"version\", cl_inputs.tool_path) # Get signing type information",
"cmd = f'{path} {cert_info[1]} \"{signer}\"' # Create openSSL command 2 if cert_info[2] is",
"help=\"Output capsule filename.\", metavar=\"Filename\", default=\"SIGNED_OUT.bin\", ) my_parser.add_argument( \"-n\", \"--name\", help=\"The name of the",
"common.utilities as utils import common.logger as logging LOGGER = logging.getLogger(\"subregion_sign\") __prog__ = \"subregion_sign\"",
"\" Optional but requires all information in order to process.\", action=\"store_true\", ) my_parser.add_argument(",
"uefi_subreg_authen.payload = payload # add Vendor Guid to Payload payload = uefi_subreg_authen.vendor_guid.bytes_le +",
"version=\"%(prog)s {version}\".format(version=__version__), ) return my_parser def chk_string_size(string): \"\"\"\"Check the size of the string\"\"\"",
"{ # SUB_REGION_HEADER Hdr; // Certificate Header # UINT8 CertData[1]; // Calculated Signature",
"= UefiSubregAuthenClass(cert_info) # read input file to store into structure payload = read_file(sbrgn_file)",
"SHA384-RSA3K Signature # } EFI_CERT_BLOCK_RSA3072_SHA384; _StructAuthInfoFormat = \"<16s16sLL16s\" _StructAuthInfoSize = struct.calcsize(_StructAuthInfoFormat) _StructSubRegionHdrFormat =",
"UefiSubregAuthenClass(cert_info) # read input file to store into structure payload = read_file(sbrgn_file) uefi_subreg_authen.payload",
"STDOUT try: ssl_process = subprocess.run( openssl_cmd, input=payload, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, check=True, ) signature",
"typedef struct { # char Name[16 bytes]; // Name of the sub-region #",
"The {} size must not be greter than {}\".format( string, size, string, max_size",
"sub-region for UEFI \"\"\" from __future__ import print_function import os import sys import",
"return certification_info def build_subreg_signed_file(cert_struct, outfile): \"\"\" build output file \"\"\" try: with open(outfile,",
"banner import common.utilities as utils import common.logger as logging LOGGER = logging.getLogger(\"subregion_sign\") __prog__",
"# typedef struct { # char Name[16 bytes]; // Name of the sub-region",
"for subregion authentication header \"\"\" self.dw_length = self._StructSubRegionHdrSize + len(self.cert_data) uefi_subreg_authen_hdr = struct.pack(",
"print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.w_revision = {w_revision:04X}\".format( w_revision=self.w_revision ) ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.wCertificateType = {Vendor_guid}\".format( Vendor_guid=str(self.vendor_guid).upper() )",
"Name[16 bytes]; // Name of the sub-region # EFI_GUID VendorGuid; // Vendor GUID",
"cmd2 = cert_info[2] certification_info = { \"revision\": 0x01, \"name\": cl_inputs.name.encode(\"utf-8\"), \"vendor_guid\": uuid.UUID(cl_inputs.vendor_guid), \"cert_type\":",
"self.w_revision = cert_info[\"revision\"] self.dw_length = self._StructAuthInfoSize self.cert_type = cert_info[\"cert_type\"] self.cert_data = bytes() self.payload",
"name is stored in signed file.\", type=chk_string_size, metavar=\"subregion\", required=True, ) my_parser.add_argument( \"-vg\", \"--vendor-guid\",",
"LOGGER.warning(\"\\nCannot run openssl.\") sys.exit(1) if ssl_process.returncode != 0: LOGGER.critical(\"\\nopenssl failed.\") sys.exit(1) return signature",
"\"openssl_cmd2\": cmd2, } return certification_info def build_subreg_signed_file(cert_struct, outfile): \"\"\" build output file \"\"\"",
"sign_file = file.read() except ValueError: LOGGER.critical(\"\\nCannot read payload file: %s\", inputfile) sys.exit(2) return",
"uefi_subreg_authen.dump_info() # Create output EFI subregion authentication header and signature and original file",
"type=chk_guid_format, metavar=\"v_guid\", required=True, ) my_parser.add_argument( \"-t\", \"--signer_type\", metavar=\"sign_type\", required=True, help=\"Type of Signing pkcs7",
"\" Optional if path to tools are already in PATH.\", default=None, ) my_parser.add_argument(",
"= cert_info[\"name\"] self.vendor_guid = cert_info[\"vendor_guid\"] self.w_revision = cert_info[\"revision\"] self.dw_length = self._StructAuthInfoSize self.cert_type =",
"self.vendor_guid = cert_info[\"vendor_guid\"] self.w_revision = cert_info[\"revision\"] self.dw_length = self._StructAuthInfoSize self.cert_type = cert_info[\"cert_type\"] self.cert_data",
"-pubout -modulus -noout\", ], } # Check if openssl is installed path =",
"certifcate type passed on subregion \"\"\" # different signature type supported by tool",
"payload file: %s\", outfile) sys.exit(2) def read_file(inputfile): \"\"\" read input file to bytes",
"my_parser.add_argument( \"-n\", \"--name\", help=\"The name of the subregion being signed. Max size is",
") my_parser.add_argument( \"-vg\", \"--vendor-guid\", help=\"Vender GUID is one specific value given by the",
"= utils.check_key(signer_file, signer_type, LOGGER) if status != 0: sys.exit(status) outfile = utils.file_not_exist(outfile, LOGGER)",
"signer_file) uefi_subreg_authen = UefiSubregAuthenClass(cert_info) # read input file to store into structure payload",
"= create_arg_parser() args = parser.parse_args() sign_subregion(args.subregion_file, args.signerfile, args.signed_file, args.signer_type, args.name, args.vendor_guid, args.show, args.tool_path)",
"print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.wCertificateType = {Vendor_guid}\".format( Vendor_guid=str(self.vendor_guid).upper() ) ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.cert_type = {cert_type}\".format( cert_type=str(self.cert_type).upper() )",
"print_function import os import sys import subprocess import argparse import uuid import struct",
"end of line from public key cert_pubkey = cert_pubkey.rstrip() # Conert to hex",
"# UINT8 CertData[1]; // Calculated Signature # } SUB_REGION_VERIFICATION; # typedef struct {",
"# } SUB_REGION_HEADER; # typedef struct { # UINT8 PublicKey[384]; // Public Key",
"cert_info[2] certification_info = { \"revision\": 0x01, \"name\": cl_inputs.name.encode(\"utf-8\"), \"vendor_guid\": uuid.UUID(cl_inputs.vendor_guid), \"cert_type\": uuid.UUID(cert_info[0]), \"openssl_cmd\":",
"{ # UINT8 PublicKey[384]; // Public Key pair of the Signing Key #",
"from bytes to string cert_pub_string = cert_pub.decode(\"utf-8\") # remove word Moudlus= from the",
"payload = uefi_subreg_authen.vendor_guid.bytes_le + payload # calculate the signature store in structure cert_data",
"argparse.ArgumentTypeError(str(msg)) return string def chk_guid_format(guid): \"\"\" check for correct formate of GUID \"\"\"",
"signtool or OpenSSL tool. \" \" Optional if path to tools are already",
"signed_file, signer_type, subregion_name, vendor_guid, show = False, tool_path = None): # Use absolute",
"= argparse.ArgumentParser() parser.add_argument(\"name, vendor_guid, tool_path, signer_type\") cl_inputs = parser.parse_args(['name={}'.format(subregion_name)]) cl_inputs.name = subregion_name cl_inputs.vendor_guid",
"# calculate the signature store in structure cert_data = generate_signature(cert_info[\"openssl_cmd\"], payload) if cert_info[\"openssl_cmd2\"]:",
"\"\"\" # format for guid xxxxxxxx-xxxx-xxxx-xxx-xxxxxxxxxxxx where x can be A-F or 0-9",
"x can be A-F or 0-9)\\ {}\".format(guid) ) return guid def sign_subregion(subregion_file, signer_file,",
"Extract the public key modulus from private key cert_pub = generate_signature(cert_info[\"openssl_cmd2\"], payload) #",
"(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx where x can be A-F or 0-9)\\ {}\".format(guid) ) return guid def",
"cert_pubkey + cert_data uefi_subreg_authen.cert_data = cert_data # pack structure with signature and get",
"\"\"\" from __future__ import print_function import os import sys import subprocess import argparse",
"struct.calcsize(_StructAuthInfoFormat) _StructSubRegionHdrFormat = \"<LL16s\" _StructSubRegionHdrSize = struct.calcsize(_StructSubRegionHdrFormat) def __init__(self, cert_info): \"\"\" initialization of",
"signer): \"\"\" returns the certifcate type passed on subregion \"\"\" # different signature",
"sys.exit(2) return sign_file def generate_signature(openssl_cmd, payload): \"\"\" signed input file \"\"\" # Run",
"\"--vendor-guid\", help=\"Vender GUID is one specific value given by the vendor for the",
"required=True, help=\"Type of Signing pkcs7 or rsa.\", choices=[\"pkcs7\", \"rsa\"], ) my_parser.add_argument( \"-s\", \"--signer\",",
"file to store into structure payload = read_file(sbrgn_file) uefi_subreg_authen.payload = payload # add",
"bytes and add to signature cert_pubkey = bytes.fromhex(cert_pubkey) # public key and signature",
"{version}\".format(version=__version__), ) return my_parser def chk_string_size(string): \"\"\"\"Check the size of the string\"\"\" max_size",
"None: raise argparse.ArgumentTypeError( \"File guild value is not in correct format \\ (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"remove end of line from public key cert_pubkey = cert_pubkey.rstrip() # Conert to",
"uefi_subreg_authen_hdr + self.cert_data + self.payload def dump_info(self): \"\"\" dump the information of subregion",
"# Conert to hex bytes and add to signature cert_pubkey = bytes.fromhex(cert_pubkey) #",
"certification_info = { \"revision\": 0x01, \"name\": cl_inputs.name.encode(\"utf-8\"), \"vendor_guid\": uuid.UUID(cl_inputs.vendor_guid), \"cert_type\": uuid.UUID(cert_info[0]), \"openssl_cmd\": cmd,",
"metavar=\"sign_type\", required=True, help=\"Type of Signing pkcs7 or rsa.\", choices=[\"pkcs7\", \"rsa\"], ) my_parser.add_argument( \"-s\",",
"bytes to string cert_pub_string = cert_pub.decode(\"utf-8\") # remove word Moudlus= from the file",
"self.cert_data + self.payload def dump_info(self): \"\"\" dump the information of subregion authentication structure",
"\"--name\", help=\"The name of the subregion being signed. Max size is 16 bytes",
"path to tools are already in PATH.\", default=None, ) my_parser.add_argument( \"--show\", help=\"Shows information",
"def create_arg_parser(): \"\"\" Parsing and validating input arguments.\"\"\" def convert_arg_line_to_args(arg_line): for arg in",
"be signed.\" ) my_parser.add_argument( \"-o\", \"--output\", dest=\"signed_file\", help=\"Output capsule filename.\", metavar=\"Filename\", default=\"SIGNED_OUT.bin\", )",
"is stored in signed file.\", type=chk_string_size, metavar=\"subregion\", required=True, ) my_parser.add_argument( \"-vg\", \"--vendor-guid\", help=\"Vender",
"# Read in the private key payload = read_file(signer_file) # Extract the public",
"\"\"\" if not self._valid: raise ValueError print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.dw_length = {dw_length:08X}\".format( dw_length=self.dw_length ) )",
"to script.\"\"\" parser = create_arg_parser() args = parser.parse_args() sign_subregion(args.subregion_file, args.signerfile, args.signed_file, args.signer_type, args.name,",
"type passed on subregion \"\"\" # different signature type supported by tool CERT_TYPE",
"ValueError: LOGGER.critical(\"\\nCannot write payload file: %s\", outfile) sys.exit(2) def read_file(inputfile): \"\"\" read input",
"= convert_arg_line_to_args my_parser.add_argument( \"subregion_file\", help=\"sub region data that needs to be signed.\" )",
"file to bytes \"\"\" try: with open(inputfile, mode=\"rb\") as file: sign_file = file.read()",
"{cert_info[1]} \"{signer}\"' # Create openSSL command 2 if cert_info[2] is not None: cmd2",
"can be A-F or 0-9 guidFormat = re.compile( r\"([a-f\\d]{8}[-][a-f\\d]{4}[-][a-f\\d]{4}[-][a-f\\d]{4}[-]{1}[a-f\\d]{12}$)\", re.I ) if guidFormat.match(guid)",
"\"pkcs7\": [ \"4aafd29d-68df-49ee-8aa9-347d375665a7\", \"smime -sign -binary -outform DER -md sha256 -nodetach -signer\", None,",
"uefi_signed_data = uefi_subreg_authen.encode() if show: uefi_subreg_authen.dump_info() # Create output EFI subregion authentication header",
"-*- # # Copyright (c) 2020, Intel Corporation. All rights reserved. # SPDX-License-Identifier:",
"payload file: %s\", inputfile) sys.exit(2) return sign_file def generate_signature(openssl_cmd, payload): \"\"\" signed input",
"remove word Moudlus= from the file cert_pubkey = cert_pub_string.replace(\"Modulus=\", \"\") # remove end",
"size is 16 bytes The name is stored in signed file.\", type=chk_string_size, metavar=\"subregion\",",
"parser = create_arg_parser() args = parser.parse_args() sign_subregion(args.subregion_file, args.signerfile, args.signed_file, args.signer_type, args.name, args.vendor_guid, args.show,",
"// Certificate Header # UINT8 CertData[1]; // Calculated Signature # } SUB_REGION_VERIFICATION; #",
"of Signature Structure # UINT32 Length; // Length of the Signature + Header",
"structure cert_data = generate_signature(cert_info[\"openssl_cmd\"], payload) if cert_info[\"openssl_cmd2\"]: # Read in the private key",
"public key from bytes to string cert_pub_string = cert_pub.decode(\"utf-8\") # remove word Moudlus=",
"a BIOS sub-region for UEFI \"\"\" from __future__ import print_function import os import",
"sub-region being signed.\\ This is required. The format is '00000000-0000-0000-0000-000000000000'\", type=chk_guid_format, metavar=\"v_guid\", required=True,",
"Parameters # } EFI_SUB_REGION_AUTHENTICATION; # typedef struct { # SUB_REGION_HEADER Hdr; // Certificate",
"struct.calcsize(_StructSubRegionHdrFormat) def __init__(self, cert_info): \"\"\" initialization of the variables for structure \"\"\" self._valid",
"_StructAuthInfoFormat = \"<16s16sLL16s\" _StructAuthInfoSize = struct.calcsize(_StructAuthInfoFormat) _StructSubRegionHdrFormat = \"<LL16s\" _StructSubRegionHdrSize = struct.calcsize(_StructSubRegionHdrFormat) def",
"encode(self): \"\"\" builds structure for subregion authentication header \"\"\" self.dw_length = self._StructSubRegionHdrSize +",
"{cert_info[2]}\" else: cmd2 = cert_info[2] certification_info = { \"revision\": 0x01, \"name\": cl_inputs.name.encode(\"utf-8\"), \"vendor_guid\":",
"None): # Use absolute path for openSSL sbrgn_file = Path(subregion_file).resolve() signer_file = Path(signer_file).resolve()",
"r\"([a-f\\d]{8}[-][a-f\\d]{4}[-][a-f\\d]{4}[-][a-f\\d]{4}[-]{1}[a-f\\d]{12}$)\", re.I ) if guidFormat.match(guid) is None: raise argparse.ArgumentTypeError( \"File guild value is",
"subregion authentication header and signature and original file build_subreg_signed_file(uefi_signed_data, str(outfile)) print( \"Signed {}",
"ValueError print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.dw_length = {dw_length:08X}\".format( dw_length=self.dw_length ) ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.w_revision = {w_revision:04X}\".format( w_revision=self.w_revision",
"args.signed_file, args.signer_type, args.name, args.vendor_guid, args.show, args.tool_path) if __name__ == \"__main__\": banner(TOOLNAME, __version__) main()",
"be A-F or 0-9)\\ {}\".format(guid) ) return guid def sign_subregion(subregion_file, signer_file, signed_file, signer_type,",
"version of the BIOS Stitching Tool\", action=\"version\", version=\"%(prog)s {version}\".format(version=__version__), ) return my_parser def",
"\"\"\" Parsing and validating input arguments.\"\"\" def convert_arg_line_to_args(arg_line): for arg in arg_line.split(): if",
"# SPDX-License-Identifier: BSD-2-Clause # \"\"\"A signing utility for creating and signing a BIOS",
"is the minimal version required\") class UefiSubregAuthenClass: \"\"\" Class define EFI subreation Authentication",
"Copyright (c) 2020, Intel Corporation. All rights reserved. # SPDX-License-Identifier: BSD-2-Clause # \"\"\"A",
"struct { # UINT8 PublicKey[384]; // Public Key pair of the Signing Key",
"signature = ssl_process.stdout except: LOGGER.warning(\"\\nCannot run openssl.\") sys.exit(1) if ssl_process.returncode != 0: LOGGER.critical(\"\\nopenssl",
"status != 0: sys.exit(status) if os.path.getsize(sbrgn_file) == 0: LOGGER.critical(\"size of {} subregion file",
"self.vendor_guid.bytes_le, self.w_revision, self.dw_length, self.cert_type.bytes_le, ) self._valid = True return uefi_subreg_authen_hdr + self.cert_data +",
"struct import re from pathlib import Path sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from common.siip_constants import VERSION",
"\"\"\" read input file to bytes \"\"\" try: with open(inputfile, mode=\"rb\") as file:",
"of the string\"\"\" max_size = 16 size = len(string.encode(\"utf-8\")) msg = \"The size",
"continue yield arg my_parser = argparse.ArgumentParser( prog=__prog__, description=__doc__, conflict_handler=\"resolve\", fromfile_prefix_chars=\"@\", ) my_parser.convert_arg_line_to_args =",
"\" \" Optional but requires all information in order to process.\", action=\"store_true\", )",
"openSSL command 1 cmd = f'{path} {cert_info[1]} \"{signer}\"' # Create openSSL command 2",
"subregion_authentication structure \" \" Optional but requires all information in order to process.\",",
") ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.cert_type = {cert_type}\".format( cert_type=str(self.cert_type).upper() ) ) print( \"sizeof (EFI_SUBREGION_AUTHENTICATION.AuthInfo.cert_data) =",
"# SUB_REGION_HEADER Hdr; // Certificate Header # UINT8 CertData[1]; // Calculated Signature #",
"SUB_REGION_VERIFICATION CertParam; // Sub-Region Certificate Parameters # } EFI_SUB_REGION_AUTHENTICATION; # typedef struct {",
"Size=len(self.cert_data) ) ) print( \"sizeof (payload) = {Size:08X}\".format( Size=len(self.payload) ) ) def get_certifcation_info(cl_inputs,",
"max_size = 16 size = len(string.encode(\"utf-8\")) msg = \"The size of {} is",
"by tool CERT_TYPE = { \"pkcs7\": [ \"4aafd29d-68df-49ee-8aa9-347d375665a7\", \"smime -sign -binary -outform DER",
"Verify file input file exist status = utils.file_exist(filenames, LOGGER) if status != 0:",
"input file to store into structure payload = read_file(sbrgn_file) uefi_subreg_authen.payload = payload #",
"SUB_REGION_HEADER; # typedef struct { # UINT8 PublicKey[384]; // Public Key pair of",
"key modulus from private key cert_pub = generate_signature(cert_info[\"openssl_cmd2\"], payload) # convert public key",
"certification_info def build_subreg_signed_file(cert_struct, outfile): \"\"\" build output file \"\"\" try: with open(outfile, mode=\"wb\")",
"line from public key cert_pubkey = cert_pubkey.rstrip() # Conert to hex bytes and",
"{dw_length:08X}\".format( dw_length=self.dw_length ) ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.w_revision = {w_revision:04X}\".format( w_revision=self.w_revision ) ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.wCertificateType",
"GUID \"\"\" # format for guid xxxxxxxx-xxxx-xxxx-xxx-xxxxxxxxxxxx where x can be A-F or",
"open(inputfile, mode=\"rb\") as file: sign_file = file.read() except ValueError: LOGGER.critical(\"\\nCannot read payload file:",
"the minimal version required\") class UefiSubregAuthenClass: \"\"\" Class define EFI subreation Authentication class",
"PublicKey[384]; // Public Key pair of the Signing Key # UINT8 Signature[384]; //",
"# char Name[16 bytes]; // Name of the sub-region # EFI_GUID VendorGuid; //",
"= True return uefi_subreg_authen_hdr + self.cert_data + self.payload def dump_info(self): \"\"\" dump the",
"import Path sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from common.siip_constants import VERSION as __version__ from common.banner import",
"SUB_REGION_VERIFICATION; # typedef struct { # UINT32 Revision; // Revision of Signature Structure",
"# UINT8 PublicKey[384]; // Public Key pair of the Signing Key # UINT8",
"signed. Max size is 16 bytes The name is stored in signed file.\",",
"specific value given by the vendor for the sub-region being signed.\\ This is",
"private certificate filename.\", ) my_parser.add_argument( \"--toolpath\", dest=\"tool_path\", help=\"Path to signtool or OpenSSL tool.",
"GUID is one specific value given by the vendor for the sub-region being",
"file \"\"\" try: with open(outfile, mode=\"wb\") as signed_file: signed_file.write(cert_struct) except ValueError: LOGGER.critical(\"\\nCannot write",
"+ Header # EFI_GUID CertType; // Signature type # } SUB_REGION_HEADER; # typedef",
"Header # EFI_GUID CertType; // Signature type # } SUB_REGION_HEADER; # typedef struct",
"is not None: cmd2 = f\"{path} {cert_info[2]}\" else: cmd2 = cert_info[2] certification_info =",
"size = len(string.encode(\"utf-8\")) msg = \"The size of {} is {}. The {}",
"logging.getLogger(\"subregion_sign\") __prog__ = \"subregion_sign\" TOOLNAME = \"Sub-Region Signing Tool\" if sys.version_info < (3,",
"\"--toolpath\", dest=\"tool_path\", help=\"Path to signtool or OpenSSL tool. \" \" Optional if path",
"self.cert_type = cert_info[\"cert_type\"] self.cert_data = bytes() self.payload = bytes() def encode(self): \"\"\" builds",
"signer_file, signed_file, signer_type, subregion_name, vendor_guid, show = False, tool_path = None): # Use",
"convert public key from bytes to string cert_pub_string = cert_pub.decode(\"utf-8\") # remove word",
"cert_pubkey = bytes.fromhex(cert_pubkey) # public key and signature are packed back to back",
"is one specific value given by the vendor for the sub-region being signed.\\",
"Length; // Length of the Signature + Header # EFI_GUID CertType; // Signature",
"is 16 bytes The name is stored in signed file.\", type=chk_string_size, metavar=\"subregion\", required=True,",
"and original file build_subreg_signed_file(uefi_signed_data, str(outfile)) print( \"Signed {} sub-region({}) was successfully generated.\".format( subregion_name,",
"// SHA384-RSA3K Signature # } EFI_CERT_BLOCK_RSA3072_SHA384; _StructAuthInfoFormat = \"<16s16sLL16s\" _StructAuthInfoSize = struct.calcsize(_StructAuthInfoFormat) _StructSubRegionHdrFormat",
"string, size, string, max_size ) if size > max_size: raise argparse.ArgumentTypeError(str(msg)) return string",
"if guidFormat.match(guid) is None: raise argparse.ArgumentTypeError( \"File guild value is not in correct",
"import sys import subprocess import argparse import uuid import struct import re from",
"signature and original file build_subreg_signed_file(uefi_signed_data, str(outfile)) print( \"Signed {} sub-region({}) was successfully generated.\".format(",
"yield arg my_parser = argparse.ArgumentParser( prog=__prog__, description=__doc__, conflict_handler=\"resolve\", fromfile_prefix_chars=\"@\", ) my_parser.convert_arg_line_to_args = convert_arg_line_to_args",
"signer private certificate filename.\", ) my_parser.add_argument( \"--toolpath\", dest=\"tool_path\", help=\"Path to signtool or OpenSSL",
"and signature and original file build_subreg_signed_file(uefi_signed_data, str(outfile)) print( \"Signed {} sub-region({}) was successfully",
"help=\"Type of Signing pkcs7 or rsa.\", choices=[\"pkcs7\", \"rsa\"], ) my_parser.add_argument( \"-s\", \"--signer\", dest=\"signerfile\",",
"Certificate Parameters # } EFI_SUB_REGION_AUTHENTICATION; # typedef struct { # SUB_REGION_HEADER Hdr; //",
"the sub-region being signed.\\ This is required. The format is '00000000-0000-0000-0000-000000000000'\", type=chk_guid_format, metavar=\"v_guid\",",
"\"sizeof (EFI_SUBREGION_AUTHENTICATION.AuthInfo.cert_data) = {Size:08X}\".format( Size=len(self.cert_data) ) ) print( \"sizeof (payload) = {Size:08X}\".format( Size=len(self.payload)",
"define EFI subreation Authentication class \"\"\" # typedef struct { # char Name[16",
") ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.w_revision = {w_revision:04X}\".format( w_revision=self.w_revision ) ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.Hdr.wCertificateType = {Vendor_guid}\".format(",
"import uuid import struct import re from pathlib import Path sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from",
"// Vendor GUID # SUB_REGION_VERIFICATION CertParam; // Sub-Region Certificate Parameters # } EFI_SUB_REGION_AUTHENTICATION;",
"size, string, max_size ) if size > max_size: raise argparse.ArgumentTypeError(str(msg)) return string def",
"for correct formate of GUID \"\"\" # format for guid xxxxxxxx-xxxx-xxxx-xxx-xxxxxxxxxxxx where x",
"generated.\".format( subregion_name, outfile ) ) def main(): \"\"\"Entry to script.\"\"\" parser = create_arg_parser()",
"} EFI_CERT_BLOCK_RSA3072_SHA384; _StructAuthInfoFormat = \"<16s16sLL16s\" _StructAuthInfoSize = struct.calcsize(_StructAuthInfoFormat) _StructSubRegionHdrFormat = \"<LL16s\" _StructSubRegionHdrSize =",
"def dump_info(self): \"\"\" dump the information of subregion authentication structure \"\"\" if not",
"{Size:08X}\".format( Size=len(self.payload) ) ) def get_certifcation_info(cl_inputs, signer): \"\"\" returns the certifcate type passed",
"cmd2 = f\"{path} {cert_info[2]}\" else: cmd2 = cert_info[2] certification_info = { \"revision\": 0x01,",
"tool_path cl_inputs.signer_type = signer_type cert_info = get_certifcation_info(cl_inputs, signer_file) uefi_subreg_authen = UefiSubregAuthenClass(cert_info) # read",
"// Public Key pair of the Signing Key # UINT8 Signature[384]; // SHA384-RSA3K",
"in structure cert_data = generate_signature(cert_info[\"openssl_cmd\"], payload) if cert_info[\"openssl_cmd2\"]: # Read in the private",
"of the BIOS Stitching Tool\", action=\"version\", version=\"%(prog)s {version}\".format(version=__version__), ) return my_parser def chk_string_size(string):",
"# Run OpenSSL command with the specified private key and capture signature from",
"and add to signature cert_pubkey = bytes.fromhex(cert_pubkey) # public key and signature are",
") my_parser.add_argument( \"--show\", help=\"Shows information about the subregion_authentication structure \" \" Optional but",
"= cert_pub_string.replace(\"Modulus=\", \"\") # remove end of line from public key cert_pubkey =",
"my_parser = argparse.ArgumentParser( prog=__prog__, description=__doc__, conflict_handler=\"resolve\", fromfile_prefix_chars=\"@\", ) my_parser.convert_arg_line_to_args = convert_arg_line_to_args my_parser.add_argument( \"subregion_file\",",
"!= 0: sys.exit(status) if os.path.getsize(sbrgn_file) == 0: LOGGER.critical(\"size of {} subregion file must",
"being signed.\\ This is required. The format is '00000000-0000-0000-0000-000000000000'\", type=chk_guid_format, metavar=\"v_guid\", required=True, )",
"LOGGER.critical(\"\\nopenssl failed.\") sys.exit(1) return signature def create_arg_parser(): \"\"\" Parsing and validating input arguments.\"\"\"",
"private key payload = read_file(signer_file) # Extract the public key modulus from private",
"\"\"\" Class define EFI subreation Authentication class \"\"\" # typedef struct { #",
"by the vendor for the sub-region being signed.\\ This is required. The format",
"current version of the BIOS Stitching Tool\", action=\"version\", version=\"%(prog)s {version}\".format(version=__version__), ) return my_parser",
"format for guid xxxxxxxx-xxxx-xxxx-xxx-xxxxxxxxxxxx where x can be A-F or 0-9 guidFormat =",
"Signature type # } SUB_REGION_HEADER; # typedef struct { # UINT8 PublicKey[384]; //",
"must not be greter than {}\".format( string, size, string, max_size ) if size",
"from public key cert_pubkey = cert_pubkey.rstrip() # Conert to hex bytes and add",
") if size > max_size: raise argparse.ArgumentTypeError(str(msg)) return string def chk_guid_format(guid): \"\"\" check",
"file build_subreg_signed_file(uefi_signed_data, str(outfile)) print( \"Signed {} sub-region({}) was successfully generated.\".format( subregion_name, outfile )",
"Moudlus= from the file cert_pubkey = cert_pub_string.replace(\"Modulus=\", \"\") # remove end of line",
"= {Size:08X}\".format( Size=len(self.payload) ) ) def get_certifcation_info(cl_inputs, signer): \"\"\" returns the certifcate type",
"main(): \"\"\"Entry to script.\"\"\" parser = create_arg_parser() args = parser.parse_args() sign_subregion(args.subregion_file, args.signerfile, args.signed_file,",
"file cert_pubkey = cert_pub_string.replace(\"Modulus=\", \"\") # remove end of line from public key",
"is {}. The {} size must not be greter than {}\".format( string, size,",
") def main(): \"\"\"Entry to script.\"\"\" parser = create_arg_parser() args = parser.parse_args() sign_subregion(args.subregion_file,",
"cert_info[\"openssl_cmd2\"]: # Read in the private key payload = read_file(signer_file) # Extract the",
"with open(inputfile, mode=\"rb\") as file: sign_file = file.read() except ValueError: LOGGER.critical(\"\\nCannot read payload",
"mode=\"rb\") as file: sign_file = file.read() except ValueError: LOGGER.critical(\"\\nCannot read payload file: %s\",",
"16 size = len(string.encode(\"utf-8\")) msg = \"The size of {} is {}. The",
"bytes() def encode(self): \"\"\" builds structure for subregion authentication header \"\"\" self.dw_length =",
"Header # UINT8 CertData[1]; // Calculated Signature # } SUB_REGION_VERIFICATION; # typedef struct",
"bytes() self.payload = bytes() def encode(self): \"\"\" builds structure for subregion authentication header",
"fromfile_prefix_chars=\"@\", ) my_parser.convert_arg_line_to_args = convert_arg_line_to_args my_parser.add_argument( \"subregion_file\", help=\"sub region data that needs to",
"file: %s\", outfile) sys.exit(2) def read_file(inputfile): \"\"\" read input file to bytes \"\"\"",
"my_parser.add_argument( \"-s\", \"--signer\", dest=\"signerfile\", required=True, help=\"OpenSSL signer private certificate filename.\", ) my_parser.add_argument( \"--toolpath\",",
"openSSL sbrgn_file = Path(subregion_file).resolve() signer_file = Path(signer_file).resolve() outfile = Path(signed_file).resolve() filenames = [str(sbrgn_file),",
"to be signed.\" ) my_parser.add_argument( \"-o\", \"--output\", dest=\"signed_file\", help=\"Output capsule filename.\", metavar=\"Filename\", default=\"SIGNED_OUT.bin\",",
"build_subreg_signed_file(uefi_signed_data, str(outfile)) print( \"Signed {} sub-region({}) was successfully generated.\".format( subregion_name, outfile ) )",
"order to process.\", action=\"store_true\", ) my_parser.add_argument( \"-v\", \"--version\", help=\"Shows the current version of",
"= struct.calcsize(_StructAuthInfoFormat) _StructSubRegionHdrFormat = \"<LL16s\" _StructSubRegionHdrSize = struct.calcsize(_StructSubRegionHdrFormat) def __init__(self, cert_info): \"\"\" initialization",
"cert_info = CERT_TYPE.get(cl_inputs.signer_type) # Create openSSL command 1 cmd = f'{path} {cert_info[1]} \"{signer}\"'",
"generate_signature(cert_info[\"openssl_cmd\"], payload) if cert_info[\"openssl_cmd2\"]: # Read in the private key payload = read_file(signer_file)",
") my_parser.add_argument( \"--toolpath\", dest=\"tool_path\", help=\"Path to signtool or OpenSSL tool. \" \" Optional",
"Guid to Payload payload = uefi_subreg_authen.vendor_guid.bytes_le + payload # calculate the signature store",
"# remove end of line from public key cert_pubkey = cert_pubkey.rstrip() # Conert",
"from pathlib import Path sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from common.siip_constants import VERSION as __version__ from",
") print( \"sizeof (payload) = {Size:08X}\".format( Size=len(self.payload) ) ) def get_certifcation_info(cl_inputs, signer): \"\"\"",
"chk_guid_format(guid): \"\"\" check for correct formate of GUID \"\"\" # format for guid",
"\"<LL16s\" _StructSubRegionHdrSize = struct.calcsize(_StructSubRegionHdrFormat) def __init__(self, cert_info): \"\"\" initialization of the variables for",
"than {}\".format( string, size, string, max_size ) if size > max_size: raise argparse.ArgumentTypeError(str(msg))",
"correct formate of GUID \"\"\" # format for guid xxxxxxxx-xxxx-xxxx-xxx-xxxxxxxxxxxx where x can",
"installed path = utils.check_for_tool(\"openssl\", \"version\", cl_inputs.tool_path) # Get signing type information cert_info =",
"= argparse.ArgumentParser( prog=__prog__, description=__doc__, conflict_handler=\"resolve\", fromfile_prefix_chars=\"@\", ) my_parser.convert_arg_line_to_args = convert_arg_line_to_args my_parser.add_argument( \"subregion_file\", help=\"sub",
"\"openssl_cmd\": cmd, \"openssl_cmd2\": cmd2, } return certification_info def build_subreg_signed_file(cert_struct, outfile): \"\"\" build output",
"BIOS Stitching Tool\", action=\"version\", version=\"%(prog)s {version}\".format(version=__version__), ) return my_parser def chk_string_size(string): \"\"\"\"Check the",
") if guidFormat.match(guid) is None: raise argparse.ArgumentTypeError( \"File guild value is not in",
"f\"{path} {cert_info[2]}\" else: cmd2 = cert_info[2] certification_info = { \"revision\": 0x01, \"name\": cl_inputs.name.encode(\"utf-8\"),",
"} SUB_REGION_HEADER; # typedef struct { # UINT8 PublicKey[384]; // Public Key pair",
"> max_size: raise argparse.ArgumentTypeError(str(msg)) return string def chk_guid_format(guid): \"\"\" check for correct formate",
"self.cert_data = bytes() self.payload = bytes() def encode(self): \"\"\" builds structure for subregion",
"my_parser.add_argument( \"-t\", \"--signer_type\", metavar=\"sign_type\", required=True, help=\"Type of Signing pkcs7 or rsa.\", choices=[\"pkcs7\", \"rsa\"],",
"signature cert_pubkey = bytes.fromhex(cert_pubkey) # public key and signature are packed back to",
"= parser.parse_args() sign_subregion(args.subregion_file, args.signerfile, args.signed_file, args.signer_type, args.name, args.vendor_guid, args.show, args.tool_path) if __name__ ==",
"EFI subreation Authentication class \"\"\" # typedef struct { # char Name[16 bytes];",
"my_parser def chk_string_size(string): \"\"\"\"Check the size of the string\"\"\" max_size = 16 size",
"of the sub-region # EFI_GUID VendorGuid; // Vendor GUID # SUB_REGION_VERIFICATION CertParam; //",
"return sign_file def generate_signature(openssl_cmd, payload): \"\"\" signed input file \"\"\" # Run OpenSSL",
"rights reserved. # SPDX-License-Identifier: BSD-2-Clause # \"\"\"A signing utility for creating and signing",
"cert_pub_string = cert_pub.decode(\"utf-8\") # remove word Moudlus= from the file cert_pubkey = cert_pub_string.replace(\"Modulus=\",",
"as utils import common.logger as logging LOGGER = logging.getLogger(\"subregion_sign\") __prog__ = \"subregion_sign\" TOOLNAME",
"{Size:08X}\".format( Size=len(self.cert_data) ) ) print( \"sizeof (payload) = {Size:08X}\".format( Size=len(self.payload) ) ) def",
"= cert_info[\"vendor_guid\"] self.w_revision = cert_info[\"revision\"] self.dw_length = self._StructAuthInfoSize self.cert_type = cert_info[\"cert_type\"] self.cert_data =",
"read_file(sbrgn_file) uefi_subreg_authen.payload = payload # add Vendor Guid to Payload payload = uefi_subreg_authen.vendor_guid.bytes_le",
"#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2020, Intel",
"for UEFI \"\"\" from __future__ import print_function import os import sys import subprocess",
"self.w_revision, self.dw_length, self.cert_type.bytes_le, ) self._valid = True return uefi_subreg_authen_hdr + self.cert_data + self.payload",
"subregion being signed. Max size is 16 bytes The name is stored in",
"argparse.ArgumentTypeError( \"File guild value is not in correct format \\ (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx where x",
"coding: utf-8 -*- # # Copyright (c) 2020, Intel Corporation. All rights reserved.",
"modulus from private key cert_pub = generate_signature(cert_info[\"openssl_cmd2\"], payload) # convert public key from",
"False, tool_path = None): # Use absolute path for openSSL sbrgn_file = Path(subregion_file).resolve()",
"python # -*- coding: utf-8 -*- # # Copyright (c) 2020, Intel Corporation.",
"sys.version_info < (3, 6): raise Exception(\"Python 3.6 is the minimal version required\") class",
"= f'{path} {cert_info[1]} \"{signer}\"' # Create openSSL command 2 if cert_info[2] is not",
"utils.check_key(signer_file, signer_type, LOGGER) if status != 0: sys.exit(status) outfile = utils.file_not_exist(outfile, LOGGER) parser",
"bytes.fromhex(cert_pubkey) # public key and signature are packed back to back cert_data =",
"0: LOGGER.critical(\"size of {} subregion file must be greater than 0!\".format(sbrgn_file)) sys.exit(status) status",
"chk_string_size(string): \"\"\"\"Check the size of the string\"\"\" max_size = 16 size = len(string.encode(\"utf-8\"))",
"!= 0: LOGGER.critical(\"\\nopenssl failed.\") sys.exit(1) return signature def create_arg_parser(): \"\"\" Parsing and validating",
"from STDOUT try: ssl_process = subprocess.run( openssl_cmd, input=payload, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, check=True, )",
"+ self.cert_data + self.payload def dump_info(self): \"\"\" dump the information of subregion authentication",
"# Check if openssl is installed path = utils.check_for_tool(\"openssl\", \"version\", cl_inputs.tool_path) # Get",
"one specific value given by the vendor for the sub-region being signed.\\ This",
") my_parser.add_argument( \"-s\", \"--signer\", dest=\"signerfile\", required=True, help=\"OpenSSL signer private certificate filename.\", ) my_parser.add_argument(",
"sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from common.siip_constants import VERSION as __version__ from common.banner import banner import",
"def build_subreg_signed_file(cert_struct, outfile): \"\"\" build output file \"\"\" try: with open(outfile, mode=\"wb\") as",
"write payload file: %s\", outfile) sys.exit(2) def read_file(inputfile): \"\"\" read input file to",
"import banner import common.utilities as utils import common.logger as logging LOGGER = logging.getLogger(\"subregion_sign\")",
"in signed file.\", type=chk_string_size, metavar=\"subregion\", required=True, ) my_parser.add_argument( \"-vg\", \"--vendor-guid\", help=\"Vender GUID is",
"check for correct formate of GUID \"\"\" # format for guid xxxxxxxx-xxxx-xxxx-xxx-xxxxxxxxxxxx where",
"to tools are already in PATH.\", default=None, ) my_parser.add_argument( \"--show\", help=\"Shows information about",
"print( \"Signed {} sub-region({}) was successfully generated.\".format( subregion_name, outfile ) ) def main():",
"Payload payload = uefi_subreg_authen.vendor_guid.bytes_le + payload # calculate the signature store in structure",
"# different signature type supported by tool CERT_TYPE = { \"pkcs7\": [ \"4aafd29d-68df-49ee-8aa9-347d375665a7\",",
"\"rsa -pubout -modulus -noout\", ], } # Check if openssl is installed path",
"for the sub-region being signed.\\ This is required. The format is '00000000-0000-0000-0000-000000000000'\", type=chk_guid_format,",
"failed.\") sys.exit(1) return signature def create_arg_parser(): \"\"\" Parsing and validating input arguments.\"\"\" def",
"dump_info(self): \"\"\" dump the information of subregion authentication structure \"\"\" if not self._valid:",
"return my_parser def chk_string_size(string): \"\"\"\"Check the size of the string\"\"\" max_size = 16",
"[str(sbrgn_file), str(signer_file)] # Verify file input file exist status = utils.file_exist(filenames, LOGGER) if",
"{} subregion file must be greater than 0!\".format(sbrgn_file)) sys.exit(status) status = utils.check_key(signer_file, signer_type,",
"sys.exit(status) status = utils.check_key(signer_file, signer_type, LOGGER) if status != 0: sys.exit(status) outfile =",
"= bytes() self.payload = bytes() def encode(self): \"\"\" builds structure for subregion authentication",
"subregion_name, outfile ) ) def main(): \"\"\"Entry to script.\"\"\" parser = create_arg_parser() args",
"as signed_file: signed_file.write(cert_struct) except ValueError: LOGGER.critical(\"\\nCannot write payload file: %s\", outfile) sys.exit(2) def",
"correct format \\ (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx where x can be A-F or 0-9)\\ {}\".format(guid) )",
"def get_certifcation_info(cl_inputs, signer): \"\"\" returns the certifcate type passed on subregion \"\"\" #",
"outfile = utils.file_not_exist(outfile, LOGGER) parser = argparse.ArgumentParser() parser.add_argument(\"name, vendor_guid, tool_path, signer_type\") cl_inputs =",
"\"<16s16sLL16s\" _StructAuthInfoSize = struct.calcsize(_StructAuthInfoFormat) _StructSubRegionHdrFormat = \"<LL16s\" _StructSubRegionHdrSize = struct.calcsize(_StructSubRegionHdrFormat) def __init__(self, cert_info):",
"cert_pubkey.rstrip() # Conert to hex bytes and add to signature cert_pubkey = bytes.fromhex(cert_pubkey)",
"required. The format is '00000000-0000-0000-0000-000000000000'\", type=chk_guid_format, metavar=\"v_guid\", required=True, ) my_parser.add_argument( \"-t\", \"--signer_type\", metavar=\"sign_type\",",
"signer_file = Path(signer_file).resolve() outfile = Path(signed_file).resolve() filenames = [str(sbrgn_file), str(signer_file)] # Verify file",
"signer_type, LOGGER) if status != 0: sys.exit(status) outfile = utils.file_not_exist(outfile, LOGGER) parser =",
"and signature are packed back to back cert_data = cert_pubkey + cert_data uefi_subreg_authen.cert_data",
"\"\"\" # Run OpenSSL command with the specified private key and capture signature",
"arg my_parser = argparse.ArgumentParser( prog=__prog__, description=__doc__, conflict_handler=\"resolve\", fromfile_prefix_chars=\"@\", ) my_parser.convert_arg_line_to_args = convert_arg_line_to_args my_parser.add_argument(",
"signature def create_arg_parser(): \"\"\" Parsing and validating input arguments.\"\"\" def convert_arg_line_to_args(arg_line): for arg",
"arg.strip(): continue yield arg my_parser = argparse.ArgumentParser( prog=__prog__, description=__doc__, conflict_handler=\"resolve\", fromfile_prefix_chars=\"@\", ) my_parser.convert_arg_line_to_args",
"cmd2, } return certification_info def build_subreg_signed_file(cert_struct, outfile): \"\"\" build output file \"\"\" try:",
"string def chk_guid_format(guid): \"\"\" check for correct formate of GUID \"\"\" # format",
"guild value is not in correct format \\ (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx where x can be",
"to signtool or OpenSSL tool. \" \" Optional if path to tools are",
"None, ], \"rsa\": [ \"2ee9976f-9d4c-4442-a997-8cad1c875fa1\", \"dgst -binary -keyform PEM -sha384 -sign\", \"rsa -pubout",
"= cert_info[2] certification_info = { \"revision\": 0x01, \"name\": cl_inputs.name.encode(\"utf-8\"), \"vendor_guid\": uuid.UUID(cl_inputs.vendor_guid), \"cert_type\": uuid.UUID(cert_info[0]),",
"pair of the Signing Key # UINT8 Signature[384]; // SHA384-RSA3K Signature # }",
"-*- coding: utf-8 -*- # # Copyright (c) 2020, Intel Corporation. All rights",
"= self._StructSubRegionHdrSize + len(self.cert_data) uefi_subreg_authen_hdr = struct.pack( self._StructAuthInfoFormat, self.w_name, self.vendor_guid.bytes_le, self.w_revision, self.dw_length, self.cert_type.bytes_le,",
"= \"The size of {} is {}. The {} size must not be",
"args = parser.parse_args() sign_subregion(args.subregion_file, args.signerfile, args.signed_file, args.signer_type, args.name, args.vendor_guid, args.show, args.tool_path) if __name__",
"cl_inputs.name = subregion_name cl_inputs.vendor_guid = vendor_guid cl_inputs.tool_path = tool_path cl_inputs.signer_type = signer_type cert_info",
"def main(): \"\"\"Entry to script.\"\"\" parser = create_arg_parser() args = parser.parse_args() sign_subregion(args.subregion_file, args.signerfile,",
"= Path(signer_file).resolve() outfile = Path(signed_file).resolve() filenames = [str(sbrgn_file), str(signer_file)] # Verify file input",
"\"{signer}\"' # Create openSSL command 2 if cert_info[2] is not None: cmd2 =",
"2 if cert_info[2] is not None: cmd2 = f\"{path} {cert_info[2]}\" else: cmd2 =",
"run openssl.\") sys.exit(1) if ssl_process.returncode != 0: LOGGER.critical(\"\\nopenssl failed.\") sys.exit(1) return signature def",
"sys.exit(1) if ssl_process.returncode != 0: LOGGER.critical(\"\\nopenssl failed.\") sys.exit(1) return signature def create_arg_parser(): \"\"\"",
"word Moudlus= from the file cert_pubkey = cert_pub_string.replace(\"Modulus=\", \"\") # remove end of",
"GUID # SUB_REGION_VERIFICATION CertParam; // Sub-Region Certificate Parameters # } EFI_SUB_REGION_AUTHENTICATION; # typedef",
"len(self.cert_data) uefi_subreg_authen_hdr = struct.pack( self._StructAuthInfoFormat, self.w_name, self.vendor_guid.bytes_le, self.w_revision, self.dw_length, self.cert_type.bytes_le, ) self._valid =",
"with the specified private key and capture signature from STDOUT try: ssl_process =",
"str(outfile)) print( \"Signed {} sub-region({}) was successfully generated.\".format( subregion_name, outfile ) ) def",
"Check if openssl is installed path = utils.check_for_tool(\"openssl\", \"version\", cl_inputs.tool_path) # Get signing",
"sign_subregion(subregion_file, signer_file, signed_file, signer_type, subregion_name, vendor_guid, show = False, tool_path = None): #",
"sub-region # EFI_GUID VendorGuid; // Vendor GUID # SUB_REGION_VERIFICATION CertParam; // Sub-Region Certificate",
"are already in PATH.\", default=None, ) my_parser.add_argument( \"--show\", help=\"Shows information about the subregion_authentication",
"= \"<LL16s\" _StructSubRegionHdrSize = struct.calcsize(_StructSubRegionHdrFormat) def __init__(self, cert_info): \"\"\" initialization of the variables",
"} # Check if openssl is installed path = utils.check_for_tool(\"openssl\", \"version\", cl_inputs.tool_path) #",
"is not in correct format \\ (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx where x can be A-F or",
"+ self.payload def dump_info(self): \"\"\" dump the information of subregion authentication structure \"\"\"",
"greter than {}\".format( string, size, string, max_size ) if size > max_size: raise",
"header \"\"\" self.dw_length = self._StructSubRegionHdrSize + len(self.cert_data) uefi_subreg_authen_hdr = struct.pack( self._StructAuthInfoFormat, self.w_name, self.vendor_guid.bytes_le,",
"_StructSubRegionHdrFormat = \"<LL16s\" _StructSubRegionHdrSize = struct.calcsize(_StructSubRegionHdrFormat) def __init__(self, cert_info): \"\"\" initialization of the",
"import common.logger as logging LOGGER = logging.getLogger(\"subregion_sign\") __prog__ = \"subregion_sign\" TOOLNAME = \"Sub-Region",
"{Vendor_guid}\".format( Vendor_guid=str(self.vendor_guid).upper() ) ) print( \"EFI_SUBREGION_AUTHENTICATION.AuthInfo.cert_type = {cert_type}\".format( cert_type=str(self.cert_type).upper() ) ) print( \"sizeof",
"-md sha256 -nodetach -signer\", None, ], \"rsa\": [ \"2ee9976f-9d4c-4442-a997-8cad1c875fa1\", \"dgst -binary -keyform PEM",
"initialization of the variables for structure \"\"\" self._valid = False self.w_name = cert_info[\"name\"]",
"be greater than 0!\".format(sbrgn_file)) sys.exit(status) status = utils.check_key(signer_file, signer_type, LOGGER) if status !=",
"variables for structure \"\"\" self._valid = False self.w_name = cert_info[\"name\"] self.vendor_guid = cert_info[\"vendor_guid\"]",
"Signature # } EFI_CERT_BLOCK_RSA3072_SHA384; _StructAuthInfoFormat = \"<16s16sLL16s\" _StructAuthInfoSize = struct.calcsize(_StructAuthInfoFormat) _StructSubRegionHdrFormat = \"<LL16s\"",
"self._StructSubRegionHdrSize + len(self.cert_data) uefi_subreg_authen_hdr = struct.pack( self._StructAuthInfoFormat, self.w_name, self.vendor_guid.bytes_le, self.w_revision, self.dw_length, self.cert_type.bytes_le, )",
"openSSL command 2 if cert_info[2] is not None: cmd2 = f\"{path} {cert_info[2]}\" else:",
"help=\"OpenSSL signer private certificate filename.\", ) my_parser.add_argument( \"--toolpath\", dest=\"tool_path\", help=\"Path to signtool or",
"the private key payload = read_file(signer_file) # Extract the public key modulus from",
"CERT_TYPE.get(cl_inputs.signer_type) # Create openSSL command 1 cmd = f'{path} {cert_info[1]} \"{signer}\"' # Create",
"\"\"\" returns the certifcate type passed on subregion \"\"\" # different signature type",
"to Payload payload = uefi_subreg_authen.vendor_guid.bytes_le + payload # calculate the signature store in",
"of the Signature + Header # EFI_GUID CertType; // Signature type # }",
"Class define EFI subreation Authentication class \"\"\" # typedef struct { # char",
"required=True, ) my_parser.add_argument( \"-vg\", \"--vendor-guid\", help=\"Vender GUID is one specific value given by"
] |
[
"<gh_stars>1-10 # -*- coding: utf-8 -*- from django import template from django.conf import",
"import settings from vvcatalog.conf import CURRENCY, PAGINATION register = template.Library() @register.simple_tag def get_currency():",
"vvcatalog.conf import CURRENCY, PAGINATION register = template.Library() @register.simple_tag def get_currency(): return CURRENCY @register.simple_tag",
"# -*- coding: utf-8 -*- from django import template from django.conf import settings",
"coding: utf-8 -*- from django import template from django.conf import settings from vvcatalog.conf",
"template from django.conf import settings from vvcatalog.conf import CURRENCY, PAGINATION register = template.Library()",
"from django import template from django.conf import settings from vvcatalog.conf import CURRENCY, PAGINATION",
"-*- coding: utf-8 -*- from django import template from django.conf import settings from",
"from vvcatalog.conf import CURRENCY, PAGINATION register = template.Library() @register.simple_tag def get_currency(): return CURRENCY",
"from django.conf import settings from vvcatalog.conf import CURRENCY, PAGINATION register = template.Library() @register.simple_tag",
"settings from vvcatalog.conf import CURRENCY, PAGINATION register = template.Library() @register.simple_tag def get_currency(): return",
"django import template from django.conf import settings from vvcatalog.conf import CURRENCY, PAGINATION register",
"CURRENCY, PAGINATION register = template.Library() @register.simple_tag def get_currency(): return CURRENCY @register.simple_tag def get_pagination():",
"PAGINATION register = template.Library() @register.simple_tag def get_currency(): return CURRENCY @register.simple_tag def get_pagination(): return",
"register = template.Library() @register.simple_tag def get_currency(): return CURRENCY @register.simple_tag def get_pagination(): return PAGINATION",
"-*- from django import template from django.conf import settings from vvcatalog.conf import CURRENCY,",
"import template from django.conf import settings from vvcatalog.conf import CURRENCY, PAGINATION register =",
"django.conf import settings from vvcatalog.conf import CURRENCY, PAGINATION register = template.Library() @register.simple_tag def",
"utf-8 -*- from django import template from django.conf import settings from vvcatalog.conf import",
"import CURRENCY, PAGINATION register = template.Library() @register.simple_tag def get_currency(): return CURRENCY @register.simple_tag def"
] |
[
"str \"\"\" return self._url @url.setter def url(self, url: str): \"\"\"Sets the url of",
"accuracy: The accuracy of this DataUtility. :type accuracy: float \"\"\" if accuracy is",
"completeness @property def timeliness(self) -> float: \"\"\"Gets the timeliness of this DataUtility. :return:",
"completeness: float=None, timeliness: float=None): # noqa: E501 \"\"\"DataUtility - a model defined in",
"self._completeness = completeness @property def timeliness(self) -> float: \"\"\"Gets the timeliness of this",
"of this DataUtility. :param completeness: The completeness of this DataUtility. :type completeness: float",
"noqa: E501 :type url: str :param accuracy: The accuracy of this DataUtility. #",
"DataUtility. :param url: The url of this DataUtility. :type url: str \"\"\" if",
"completeness: The completeness of this DataUtility. # noqa: E501 :type completeness: float :param",
"'DataUtility': \"\"\"Returns the dict as a model :param dikt: A dict. :type: dict",
"E501 :type accuracy: float :param consistency: The consistency of this DataUtility. # noqa:",
"this DataUtility. :rtype: str \"\"\" return self._url @url.setter def url(self, url: str): \"\"\"Sets",
":return: The completeness of this DataUtility. :rtype: float \"\"\" return self._completeness @completeness.setter def",
"self.swagger_types = { 'url': str, 'accuracy': float, 'consistency': float, 'completeness': float, 'timeliness': float",
":type completeness: float :param timeliness: The timeliness of this DataUtility. # noqa: E501",
"is None: raise ValueError(\"Invalid value for `accuracy`, must not be `None`\") # noqa:",
"E501 :type completeness: float :param timeliness: The timeliness of this DataUtility. # noqa:",
"= accuracy self._consistency = consistency self._completeness = completeness self._timeliness = timeliness @classmethod def",
"DataUtility. :type timeliness: float \"\"\" if timeliness is None: raise ValueError(\"Invalid value for",
"absolute_import from datetime import date, datetime # noqa: F401 from typing import List,",
"str): \"\"\"Sets the url of this DataUtility. :param url: The url of this",
"this DataUtility. # noqa: E501 :type url: str :param accuracy: The accuracy of",
"\"\"\" return self._timeliness @timeliness.setter def timeliness(self, timeliness: float): \"\"\"Sets the timeliness of this",
"@consistency.setter def consistency(self, consistency: float): \"\"\"Sets the consistency of this DataUtility. :param consistency:",
"consistency @property def completeness(self) -> float: \"\"\"Gets the completeness of this DataUtility. :return:",
"return self._completeness @completeness.setter def completeness(self, completeness: float): \"\"\"Sets the completeness of this DataUtility.",
"\"\"\"Sets the timeliness of this DataUtility. :param timeliness: The timeliness of this DataUtility.",
"if accuracy is None: raise ValueError(\"Invalid value for `accuracy`, must not be `None`\")",
"timeliness of this DataUtility. # noqa: E501 :type timeliness: float \"\"\" self.swagger_types =",
"DataUtility. :rtype: float \"\"\" return self._consistency @consistency.setter def consistency(self, consistency: float): \"\"\"Sets the",
"the timeliness of this DataUtility. :param timeliness: The timeliness of this DataUtility. :type",
"value for `url`, must not be `None`\") # noqa: E501 self._url = url",
"of this DataUtility. :rtype: float \"\"\" return self._accuracy @accuracy.setter def accuracy(self, accuracy: float):",
"of this DataUtility. :param timeliness: The timeliness of this DataUtility. :type timeliness: float",
"a model :param dikt: A dict. :type: dict :return: The DataUtility of this",
"consistency(self) -> float: \"\"\"Gets the consistency of this DataUtility. :return: The consistency of",
"must not be `None`\") # noqa: E501 self._consistency = consistency @property def completeness(self)",
"Model from swagger_server import util class DataUtility(Model): \"\"\"NOTE: This class is auto generated",
"this DataUtility. # noqa: E501 :rtype: DataUtility \"\"\" return util.deserialize_model(dikt, cls) @property def",
"url of this DataUtility. :return: The url of this DataUtility. :rtype: str \"\"\"",
"`accuracy`, must not be `None`\") # noqa: E501 self._accuracy = accuracy @property def",
"= accuracy @property def consistency(self) -> float: \"\"\"Gets the consistency of this DataUtility.",
"@property def completeness(self) -> float: \"\"\"Gets the completeness of this DataUtility. :return: The",
"None: raise ValueError(\"Invalid value for `timeliness`, must not be `None`\") # noqa: E501",
":type accuracy: float :param consistency: The consistency of this DataUtility. # noqa: E501",
"\"\"\"Sets the accuracy of this DataUtility. :param accuracy: The accuracy of this DataUtility.",
"# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime #",
"accuracy(self) -> float: \"\"\"Gets the accuracy of this DataUtility. :return: The accuracy of",
"self._consistency = consistency self._completeness = completeness self._timeliness = timeliness @classmethod def from_dict(cls, dikt)",
"@property def accuracy(self) -> float: \"\"\"Gets the accuracy of this DataUtility. :return: The",
"float :param completeness: The completeness of this DataUtility. # noqa: E501 :type completeness:",
"for `accuracy`, must not be `None`\") # noqa: E501 self._accuracy = accuracy @property",
"# noqa: E501 self._url = url @property def accuracy(self) -> float: \"\"\"Gets the",
"url: str \"\"\" if url is None: raise ValueError(\"Invalid value for `url`, must",
"the completeness of this DataUtility. :return: The completeness of this DataUtility. :rtype: float",
"class DataUtility(Model): \"\"\"NOTE: This class is auto generated by the swagger code generator",
"-> float: \"\"\"Gets the consistency of this DataUtility. :return: The consistency of this",
"@property def url(self) -> str: \"\"\"Gets the url of this DataUtility. :return: The",
"import Model from swagger_server import util class DataUtility(Model): \"\"\"NOTE: This class is auto",
"The DataUtility of this DataUtility. # noqa: E501 :rtype: DataUtility \"\"\" return util.deserialize_model(dikt,",
"noqa: F401 from swagger_server.models.base_model_ import Model from swagger_server import util class DataUtility(Model): \"\"\"NOTE:",
"E501 self._url = url @property def accuracy(self) -> float: \"\"\"Gets the accuracy of",
"if consistency is None: raise ValueError(\"Invalid value for `consistency`, must not be `None`\")",
"datetime # noqa: F401 from typing import List, Dict # noqa: F401 from",
"cls) @property def url(self) -> str: \"\"\"Gets the url of this DataUtility. :return:",
"return util.deserialize_model(dikt, cls) @property def url(self) -> str: \"\"\"Gets the url of this",
"`url`, must not be `None`\") # noqa: E501 self._url = url @property def",
"timeliness of this DataUtility. :return: The timeliness of this DataUtility. :rtype: float \"\"\"",
":rtype: float \"\"\" return self._timeliness @timeliness.setter def timeliness(self, timeliness: float): \"\"\"Sets the timeliness",
"\"\"\"NOTE: This class is auto generated by the swagger code generator program. Do",
"completeness of this DataUtility. # noqa: E501 :type completeness: float :param timeliness: The",
"`None`\") # noqa: E501 self._completeness = completeness @property def timeliness(self) -> float: \"\"\"Gets",
"\"\"\"Gets the url of this DataUtility. :return: The url of this DataUtility. :rtype:",
"\"\"\"Gets the consistency of this DataUtility. :return: The consistency of this DataUtility. :rtype:",
"completeness of this DataUtility. :return: The completeness of this DataUtility. :rtype: float \"\"\"",
"manually. \"\"\" def __init__(self, url: str=None, accuracy: float=None, consistency: float=None, completeness: float=None, timeliness:",
"@property def timeliness(self) -> float: \"\"\"Gets the timeliness of this DataUtility. :return: The",
"-> str: \"\"\"Gets the url of this DataUtility. :return: The url of this",
":type completeness: float \"\"\" if completeness is None: raise ValueError(\"Invalid value for `completeness`,",
":param timeliness: The timeliness of this DataUtility. # noqa: E501 :type timeliness: float",
"DataUtility. :type accuracy: float \"\"\" if accuracy is None: raise ValueError(\"Invalid value for",
"be `None`\") # noqa: E501 self._accuracy = accuracy @property def consistency(self) -> float:",
"'url': 'URL', 'accuracy': 'accuracy', 'consistency': 'consistency', 'completeness': 'completeness', 'timeliness': 'timeliness' } self._url =",
"this DataUtility. # noqa: E501 :type consistency: float :param completeness: The completeness of",
"this DataUtility. :param completeness: The completeness of this DataUtility. :type completeness: float \"\"\"",
"accuracy(self, accuracy: float): \"\"\"Sets the accuracy of this DataUtility. :param accuracy: The accuracy",
"dikt) -> 'DataUtility': \"\"\"Returns the dict as a model :param dikt: A dict.",
"\"\"\" return self._accuracy @accuracy.setter def accuracy(self, accuracy: float): \"\"\"Sets the accuracy of this",
"consistency of this DataUtility. :return: The consistency of this DataUtility. :rtype: float \"\"\"",
"of this DataUtility. :type accuracy: float \"\"\" if accuracy is None: raise ValueError(\"Invalid",
":return: The accuracy of this DataUtility. :rtype: float \"\"\" return self._accuracy @accuracy.setter def",
":param url: The url of this DataUtility. # noqa: E501 :type url: str",
"The url of this DataUtility. # noqa: E501 :type url: str :param accuracy:",
"noqa: E501 :type timeliness: float \"\"\" self.swagger_types = { 'url': str, 'accuracy': float,",
"if timeliness is None: raise ValueError(\"Invalid value for `timeliness`, must not be `None`\")",
"url self._accuracy = accuracy self._consistency = consistency self._completeness = completeness self._timeliness = timeliness",
"a model defined in Swagger :param url: The url of this DataUtility. #",
"completeness is None: raise ValueError(\"Invalid value for `completeness`, must not be `None`\") #",
"consistency: The consistency of this DataUtility. # noqa: E501 :type consistency: float :param",
"the consistency of this DataUtility. :param consistency: The consistency of this DataUtility. :type",
"def __init__(self, url: str=None, accuracy: float=None, consistency: float=None, completeness: float=None, timeliness: float=None): #",
"List, Dict # noqa: F401 from swagger_server.models.base_model_ import Model from swagger_server import util",
"A dict. :type: dict :return: The DataUtility of this DataUtility. # noqa: E501",
"consistency(self, consistency: float): \"\"\"Sets the consistency of this DataUtility. :param consistency: The consistency",
"must not be `None`\") # noqa: E501 self._accuracy = accuracy @property def consistency(self)",
"E501 :type consistency: float :param completeness: The completeness of this DataUtility. # noqa:",
"# noqa: E501 self._consistency = consistency @property def completeness(self) -> float: \"\"\"Gets the",
"DataUtility. :param accuracy: The accuracy of this DataUtility. :type accuracy: float \"\"\" if",
"of this DataUtility. :type consistency: float \"\"\" if consistency is None: raise ValueError(\"Invalid",
"The accuracy of this DataUtility. # noqa: E501 :type accuracy: float :param consistency:",
"completeness of this DataUtility. :param completeness: The completeness of this DataUtility. :type completeness:",
"\"\"\"DataUtility - a model defined in Swagger :param url: The url of this",
"-> float: \"\"\"Gets the accuracy of this DataUtility. :return: The accuracy of this",
"def accuracy(self, accuracy: float): \"\"\"Sets the accuracy of this DataUtility. :param accuracy: The",
"self._timeliness @timeliness.setter def timeliness(self, timeliness: float): \"\"\"Sets the timeliness of this DataUtility. :param",
":param completeness: The completeness of this DataUtility. :type completeness: float \"\"\" if completeness",
"raise ValueError(\"Invalid value for `completeness`, must not be `None`\") # noqa: E501 self._completeness",
"def completeness(self, completeness: float): \"\"\"Sets the completeness of this DataUtility. :param completeness: The",
"in Swagger :param url: The url of this DataUtility. # noqa: E501 :type",
":type timeliness: float \"\"\" if timeliness is None: raise ValueError(\"Invalid value for `timeliness`,",
"The consistency of this DataUtility. :rtype: float \"\"\" return self._consistency @consistency.setter def consistency(self,",
"of this DataUtility. :rtype: str \"\"\" return self._url @url.setter def url(self, url: str):",
"} self._url = url self._accuracy = accuracy self._consistency = consistency self._completeness = completeness",
"ValueError(\"Invalid value for `timeliness`, must not be `None`\") # noqa: E501 self._timeliness =",
":return: The timeliness of this DataUtility. :rtype: float \"\"\" return self._timeliness @timeliness.setter def",
"the url of this DataUtility. :param url: The url of this DataUtility. :type",
"DataUtility. :return: The completeness of this DataUtility. :rtype: float \"\"\" return self._completeness @completeness.setter",
"url of this DataUtility. :rtype: str \"\"\" return self._url @url.setter def url(self, url:",
"E501 :type timeliness: float \"\"\" self.swagger_types = { 'url': str, 'accuracy': float, 'consistency':",
"def consistency(self) -> float: \"\"\"Gets the consistency of this DataUtility. :return: The consistency",
"completeness: float \"\"\" if completeness is None: raise ValueError(\"Invalid value for `completeness`, must",
"raise ValueError(\"Invalid value for `timeliness`, must not be `None`\") # noqa: E501 self._timeliness",
"of this DataUtility. :return: The consistency of this DataUtility. :rtype: float \"\"\" return",
"float :param timeliness: The timeliness of this DataUtility. # noqa: E501 :type timeliness:",
"The completeness of this DataUtility. :rtype: float \"\"\" return self._completeness @completeness.setter def completeness(self,",
"float \"\"\" return self._completeness @completeness.setter def completeness(self, completeness: float): \"\"\"Sets the completeness of",
"return self._accuracy @accuracy.setter def accuracy(self, accuracy: float): \"\"\"Sets the accuracy of this DataUtility.",
"def timeliness(self) -> float: \"\"\"Gets the timeliness of this DataUtility. :return: The timeliness",
"url: str): \"\"\"Sets the url of this DataUtility. :param url: The url of",
"completeness: float): \"\"\"Sets the completeness of this DataUtility. :param completeness: The completeness of",
"of this DataUtility. :rtype: float \"\"\" return self._consistency @consistency.setter def consistency(self, consistency: float):",
"\"\"\"Gets the timeliness of this DataUtility. :return: The timeliness of this DataUtility. :rtype:",
"float=None, completeness: float=None, timeliness: float=None): # noqa: E501 \"\"\"DataUtility - a model defined",
"float: \"\"\"Gets the timeliness of this DataUtility. :return: The timeliness of this DataUtility.",
"url is None: raise ValueError(\"Invalid value for `url`, must not be `None`\") #",
"datetime import date, datetime # noqa: F401 from typing import List, Dict #",
"@completeness.setter def completeness(self, completeness: float): \"\"\"Sets the completeness of this DataUtility. :param completeness:",
"of this DataUtility. # noqa: E501 :type url: str :param accuracy: The accuracy",
"value for `completeness`, must not be `None`\") # noqa: E501 self._completeness = completeness",
":type consistency: float \"\"\" if consistency is None: raise ValueError(\"Invalid value for `consistency`,",
"of this DataUtility. :return: The timeliness of this DataUtility. :rtype: float \"\"\" return",
"completeness: float :param timeliness: The timeliness of this DataUtility. # noqa: E501 :type",
"@accuracy.setter def accuracy(self, accuracy: float): \"\"\"Sets the accuracy of this DataUtility. :param accuracy:",
"as a model :param dikt: A dict. :type: dict :return: The DataUtility of",
"swagger_server import util class DataUtility(Model): \"\"\"NOTE: This class is auto generated by the",
"model :param dikt: A dict. :type: dict :return: The DataUtility of this DataUtility.",
"this DataUtility. :rtype: float \"\"\" return self._completeness @completeness.setter def completeness(self, completeness: float): \"\"\"Sets",
"be `None`\") # noqa: E501 self._url = url @property def accuracy(self) -> float:",
"\"\"\" return self._consistency @consistency.setter def consistency(self, consistency: float): \"\"\"Sets the consistency of this",
"completeness: The completeness of this DataUtility. :type completeness: float \"\"\" if completeness is",
"def from_dict(cls, dikt) -> 'DataUtility': \"\"\"Returns the dict as a model :param dikt:",
"DataUtility of this DataUtility. # noqa: E501 :rtype: DataUtility \"\"\" return util.deserialize_model(dikt, cls)",
"consistency of this DataUtility. # noqa: E501 :type consistency: float :param completeness: The",
"of this DataUtility. # noqa: E501 :type accuracy: float :param consistency: The consistency",
"def consistency(self, consistency: float): \"\"\"Sets the consistency of this DataUtility. :param consistency: The",
"dict. :type: dict :return: The DataUtility of this DataUtility. # noqa: E501 :rtype:",
"None: raise ValueError(\"Invalid value for `accuracy`, must not be `None`\") # noqa: E501",
":param accuracy: The accuracy of this DataUtility. # noqa: E501 :type accuracy: float",
"float): \"\"\"Sets the consistency of this DataUtility. :param consistency: The consistency of this",
"accuracy: float \"\"\" if accuracy is None: raise ValueError(\"Invalid value for `accuracy`, must",
"= url self._accuracy = accuracy self._consistency = consistency self._completeness = completeness self._timeliness =",
"DataUtility. :rtype: float \"\"\" return self._completeness @completeness.setter def completeness(self, completeness: float): \"\"\"Sets the",
"consistency self._completeness = completeness self._timeliness = timeliness @classmethod def from_dict(cls, dikt) -> 'DataUtility':",
"dict as a model :param dikt: A dict. :type: dict :return: The DataUtility",
"ValueError(\"Invalid value for `accuracy`, must not be `None`\") # noqa: E501 self._accuracy =",
"float): \"\"\"Sets the timeliness of this DataUtility. :param timeliness: The timeliness of this",
"self._accuracy = accuracy @property def consistency(self) -> float: \"\"\"Gets the consistency of this",
":rtype: float \"\"\" return self._accuracy @accuracy.setter def accuracy(self, accuracy: float): \"\"\"Sets the accuracy",
"'accuracy', 'consistency': 'consistency', 'completeness': 'completeness', 'timeliness': 'timeliness' } self._url = url self._accuracy =",
"\"\"\" if completeness is None: raise ValueError(\"Invalid value for `completeness`, must not be",
"import util class DataUtility(Model): \"\"\"NOTE: This class is auto generated by the swagger",
"the completeness of this DataUtility. :param completeness: The completeness of this DataUtility. :type",
"- a model defined in Swagger :param url: The url of this DataUtility.",
"str \"\"\" if url is None: raise ValueError(\"Invalid value for `url`, must not",
"the dict as a model :param dikt: A dict. :type: dict :return: The",
"of this DataUtility. :return: The url of this DataUtility. :rtype: str \"\"\" return",
"consistency of this DataUtility. :type consistency: float \"\"\" if consistency is None: raise",
"'consistency': 'consistency', 'completeness': 'completeness', 'timeliness': 'timeliness' } self._url = url self._accuracy = accuracy",
"the consistency of this DataUtility. :return: The consistency of this DataUtility. :rtype: float",
"DataUtility. :rtype: str \"\"\" return self._url @url.setter def url(self, url: str): \"\"\"Sets the",
"url: The url of this DataUtility. # noqa: E501 :type url: str :param",
"noqa: E501 :type accuracy: float :param consistency: The consistency of this DataUtility. #",
"float } self.attribute_map = { 'url': 'URL', 'accuracy': 'accuracy', 'consistency': 'consistency', 'completeness': 'completeness',",
"F401 from swagger_server.models.base_model_ import Model from swagger_server import util class DataUtility(Model): \"\"\"NOTE: This",
"# noqa: E501 :type consistency: float :param completeness: The completeness of this DataUtility.",
"The consistency of this DataUtility. :type consistency: float \"\"\" if consistency is None:",
"= timeliness @classmethod def from_dict(cls, dikt) -> 'DataUtility': \"\"\"Returns the dict as a",
"date, datetime # noqa: F401 from typing import List, Dict # noqa: F401",
"consistency of this DataUtility. :param consistency: The consistency of this DataUtility. :type consistency:",
"float): \"\"\"Sets the accuracy of this DataUtility. :param accuracy: The accuracy of this",
":param accuracy: The accuracy of this DataUtility. :type accuracy: float \"\"\" if accuracy",
"DataUtility \"\"\" return util.deserialize_model(dikt, cls) @property def url(self) -> str: \"\"\"Gets the url",
"accuracy @property def consistency(self) -> float: \"\"\"Gets the consistency of this DataUtility. :return:",
"noqa: E501 :type completeness: float :param timeliness: The timeliness of this DataUtility. #",
"def completeness(self) -> float: \"\"\"Gets the completeness of this DataUtility. :return: The completeness",
"by the swagger code generator program. Do not edit the class manually. \"\"\"",
"accuracy of this DataUtility. :return: The accuracy of this DataUtility. :rtype: float \"\"\"",
"'accuracy': 'accuracy', 'consistency': 'consistency', 'completeness': 'completeness', 'timeliness': 'timeliness' } self._url = url self._accuracy",
":rtype: float \"\"\" return self._consistency @consistency.setter def consistency(self, consistency: float): \"\"\"Sets the consistency",
"\"\"\"Sets the consistency of this DataUtility. :param consistency: The consistency of this DataUtility.",
"timeliness is None: raise ValueError(\"Invalid value for `timeliness`, must not be `None`\") #",
"completeness(self) -> float: \"\"\"Gets the completeness of this DataUtility. :return: The completeness of",
"'completeness': 'completeness', 'timeliness': 'timeliness' } self._url = url self._accuracy = accuracy self._consistency =",
"F401 from typing import List, Dict # noqa: F401 from swagger_server.models.base_model_ import Model",
":rtype: float \"\"\" return self._completeness @completeness.setter def completeness(self, completeness: float): \"\"\"Sets the completeness",
"def url(self) -> str: \"\"\"Gets the url of this DataUtility. :return: The url",
"float: \"\"\"Gets the accuracy of this DataUtility. :return: The accuracy of this DataUtility.",
"= completeness @property def timeliness(self) -> float: \"\"\"Gets the timeliness of this DataUtility.",
"url of this DataUtility. # noqa: E501 :type url: str :param accuracy: The",
"DataUtility(Model): \"\"\"NOTE: This class is auto generated by the swagger code generator program.",
"DataUtility. :type completeness: float \"\"\" if completeness is None: raise ValueError(\"Invalid value for",
"timeliness: The timeliness of this DataUtility. # noqa: E501 :type timeliness: float \"\"\"",
"`None`\") # noqa: E501 self._url = url @property def accuracy(self) -> float: \"\"\"Gets",
"# noqa: E501 \"\"\"DataUtility - a model defined in Swagger :param url: The",
"this DataUtility. :return: The completeness of this DataUtility. :rtype: float \"\"\" return self._completeness",
"self._accuracy @accuracy.setter def accuracy(self, accuracy: float): \"\"\"Sets the accuracy of this DataUtility. :param",
"accuracy: The accuracy of this DataUtility. # noqa: E501 :type accuracy: float :param",
"not be `None`\") # noqa: E501 self._accuracy = accuracy @property def consistency(self) ->",
"E501 \"\"\"DataUtility - a model defined in Swagger :param url: The url of",
"ValueError(\"Invalid value for `url`, must not be `None`\") # noqa: E501 self._url =",
":param completeness: The completeness of this DataUtility. # noqa: E501 :type completeness: float",
"this DataUtility. :param consistency: The consistency of this DataUtility. :type consistency: float \"\"\"",
"must not be `None`\") # noqa: E501 self._url = url @property def accuracy(self)",
"util class DataUtility(Model): \"\"\"NOTE: This class is auto generated by the swagger code",
"not be `None`\") # noqa: E501 self._url = url @property def accuracy(self) ->",
"accuracy is None: raise ValueError(\"Invalid value for `accuracy`, must not be `None`\") #",
"self._consistency @consistency.setter def consistency(self, consistency: float): \"\"\"Sets the consistency of this DataUtility. :param",
"is None: raise ValueError(\"Invalid value for `completeness`, must not be `None`\") # noqa:",
"consistency is None: raise ValueError(\"Invalid value for `consistency`, must not be `None`\") #",
"consistency: float \"\"\" if consistency is None: raise ValueError(\"Invalid value for `consistency`, must",
"noqa: E501 self._completeness = completeness @property def timeliness(self) -> float: \"\"\"Gets the timeliness",
"of this DataUtility. :param url: The url of this DataUtility. :type url: str",
"\"\"\" if url is None: raise ValueError(\"Invalid value for `url`, must not be",
"'consistency': float, 'completeness': float, 'timeliness': float } self.attribute_map = { 'url': 'URL', 'accuracy':",
":param consistency: The consistency of this DataUtility. :type consistency: float \"\"\" if consistency",
"for `completeness`, must not be `None`\") # noqa: E501 self._completeness = completeness @property",
"for `url`, must not be `None`\") # noqa: E501 self._url = url @property",
"of this DataUtility. :param accuracy: The accuracy of this DataUtility. :type accuracy: float",
":param url: The url of this DataUtility. :type url: str \"\"\" if url",
":param consistency: The consistency of this DataUtility. # noqa: E501 :type consistency: float",
"The consistency of this DataUtility. # noqa: E501 :type consistency: float :param completeness:",
"{ 'url': 'URL', 'accuracy': 'accuracy', 'consistency': 'consistency', 'completeness': 'completeness', 'timeliness': 'timeliness' } self._url",
"# noqa: F401 from swagger_server.models.base_model_ import Model from swagger_server import util class DataUtility(Model):",
"class manually. \"\"\" def __init__(self, url: str=None, accuracy: float=None, consistency: float=None, completeness: float=None,",
"float \"\"\" if timeliness is None: raise ValueError(\"Invalid value for `timeliness`, must not",
"\"\"\" return self._url @url.setter def url(self, url: str): \"\"\"Sets the url of this",
":type accuracy: float \"\"\" if accuracy is None: raise ValueError(\"Invalid value for `accuracy`,",
"{ 'url': str, 'accuracy': float, 'consistency': float, 'completeness': float, 'timeliness': float } self.attribute_map",
"raise ValueError(\"Invalid value for `url`, must not be `None`\") # noqa: E501 self._url",
"accuracy self._consistency = consistency self._completeness = completeness self._timeliness = timeliness @classmethod def from_dict(cls,",
"# noqa: E501 :type accuracy: float :param consistency: The consistency of this DataUtility.",
"of this DataUtility. :rtype: float \"\"\" return self._timeliness @timeliness.setter def timeliness(self, timeliness: float):",
"The completeness of this DataUtility. # noqa: E501 :type completeness: float :param timeliness:",
"float \"\"\" return self._accuracy @accuracy.setter def accuracy(self, accuracy: float): \"\"\"Sets the accuracy of",
"E501 self._completeness = completeness @property def timeliness(self) -> float: \"\"\"Gets the timeliness of",
"noqa: E501 :type consistency: float :param completeness: The completeness of this DataUtility. #",
"DataUtility. :return: The accuracy of this DataUtility. :rtype: float \"\"\" return self._accuracy @accuracy.setter",
"# noqa: E501 :type completeness: float :param timeliness: The timeliness of this DataUtility.",
"str: \"\"\"Gets the url of this DataUtility. :return: The url of this DataUtility.",
":rtype: DataUtility \"\"\" return util.deserialize_model(dikt, cls) @property def url(self) -> str: \"\"\"Gets the",
"this DataUtility. :type completeness: float \"\"\" if completeness is None: raise ValueError(\"Invalid value",
"generated by the swagger code generator program. Do not edit the class manually.",
"consistency: float): \"\"\"Sets the consistency of this DataUtility. :param consistency: The consistency of",
"this DataUtility. :return: The accuracy of this DataUtility. :rtype: float \"\"\" return self._accuracy",
":type consistency: float :param completeness: The completeness of this DataUtility. # noqa: E501",
"DataUtility. :rtype: float \"\"\" return self._timeliness @timeliness.setter def timeliness(self, timeliness: float): \"\"\"Sets the",
"# noqa: E501 self._accuracy = accuracy @property def consistency(self) -> float: \"\"\"Gets the",
"None: raise ValueError(\"Invalid value for `completeness`, must not be `None`\") # noqa: E501",
"consistency: float :param completeness: The completeness of this DataUtility. # noqa: E501 :type",
"swagger code generator program. Do not edit the class manually. \"\"\" def __init__(self,",
"import date, datetime # noqa: F401 from typing import List, Dict # noqa:",
"accuracy: float=None, consistency: float=None, completeness: float=None, timeliness: float=None): # noqa: E501 \"\"\"DataUtility -",
"for `consistency`, must not be `None`\") # noqa: E501 self._consistency = consistency @property",
"the url of this DataUtility. :return: The url of this DataUtility. :rtype: str",
"str=None, accuracy: float=None, consistency: float=None, completeness: float=None, timeliness: float=None): # noqa: E501 \"\"\"DataUtility",
":return: The url of this DataUtility. :rtype: str \"\"\" return self._url @url.setter def",
"must not be `None`\") # noqa: E501 self._completeness = completeness @property def timeliness(self)",
"'consistency', 'completeness': 'completeness', 'timeliness': 'timeliness' } self._url = url self._accuracy = accuracy self._consistency",
"self._consistency = consistency @property def completeness(self) -> float: \"\"\"Gets the completeness of this",
"DataUtility. :return: The consistency of this DataUtility. :rtype: float \"\"\" return self._consistency @consistency.setter",
":type url: str :param accuracy: The accuracy of this DataUtility. # noqa: E501",
":type url: str \"\"\" if url is None: raise ValueError(\"Invalid value for `url`,",
"DataUtility. # noqa: E501 :type completeness: float :param timeliness: The timeliness of this",
"timeliness(self, timeliness: float): \"\"\"Sets the timeliness of this DataUtility. :param timeliness: The timeliness",
"not edit the class manually. \"\"\" def __init__(self, url: str=None, accuracy: float=None, consistency:",
"-> float: \"\"\"Gets the timeliness of this DataUtility. :return: The timeliness of this",
"ValueError(\"Invalid value for `consistency`, must not be `None`\") # noqa: E501 self._consistency =",
"float \"\"\" if completeness is None: raise ValueError(\"Invalid value for `completeness`, must not",
"@property def consistency(self) -> float: \"\"\"Gets the consistency of this DataUtility. :return: The",
"float): \"\"\"Sets the completeness of this DataUtility. :param completeness: The completeness of this",
"The accuracy of this DataUtility. :rtype: float \"\"\" return self._accuracy @accuracy.setter def accuracy(self,",
"noqa: F401 from typing import List, Dict # noqa: F401 from swagger_server.models.base_model_ import",
"timeliness: The timeliness of this DataUtility. :type timeliness: float \"\"\" if timeliness is",
"return self._url @url.setter def url(self, url: str): \"\"\"Sets the url of this DataUtility.",
"completeness of this DataUtility. :type completeness: float \"\"\" if completeness is None: raise",
"this DataUtility. # noqa: E501 :type completeness: float :param timeliness: The timeliness of",
"float \"\"\" if consistency is None: raise ValueError(\"Invalid value for `consistency`, must not",
"This class is auto generated by the swagger code generator program. Do not",
"\"\"\"Returns the dict as a model :param dikt: A dict. :type: dict :return:",
"# noqa: F401 from typing import List, Dict # noqa: F401 from swagger_server.models.base_model_",
"\"\"\" if accuracy is None: raise ValueError(\"Invalid value for `accuracy`, must not be",
"this DataUtility. :return: The timeliness of this DataUtility. :rtype: float \"\"\" return self._timeliness",
"float \"\"\" if accuracy is None: raise ValueError(\"Invalid value for `accuracy`, must not",
"ValueError(\"Invalid value for `completeness`, must not be `None`\") # noqa: E501 self._completeness =",
"edit the class manually. \"\"\" def __init__(self, url: str=None, accuracy: float=None, consistency: float=None,",
"model defined in Swagger :param url: The url of this DataUtility. # noqa:",
"from_dict(cls, dikt) -> 'DataUtility': \"\"\"Returns the dict as a model :param dikt: A",
"this DataUtility. :param url: The url of this DataUtility. :type url: str \"\"\"",
"class is auto generated by the swagger code generator program. Do not edit",
"of this DataUtility. # noqa: E501 :type consistency: float :param completeness: The completeness",
"import absolute_import from datetime import date, datetime # noqa: F401 from typing import",
"program. Do not edit the class manually. \"\"\" def __init__(self, url: str=None, accuracy:",
"DataUtility. :type consistency: float \"\"\" if consistency is None: raise ValueError(\"Invalid value for",
"DataUtility. # noqa: E501 :type url: str :param accuracy: The accuracy of this",
"self._url @url.setter def url(self, url: str): \"\"\"Sets the url of this DataUtility. :param",
"float, 'consistency': float, 'completeness': float, 'timeliness': float } self.attribute_map = { 'url': 'URL',",
"value for `consistency`, must not be `None`\") # noqa: E501 self._consistency = consistency",
"accuracy of this DataUtility. # noqa: E501 :type accuracy: float :param consistency: The",
"code generator program. Do not edit the class manually. \"\"\" def __init__(self, url:",
"generator program. Do not edit the class manually. \"\"\" def __init__(self, url: str=None,",
"accuracy: float :param consistency: The consistency of this DataUtility. # noqa: E501 :type",
"timeliness(self) -> float: \"\"\"Gets the timeliness of this DataUtility. :return: The timeliness of",
"DataUtility. :param timeliness: The timeliness of this DataUtility. :type timeliness: float \"\"\" if",
":param dikt: A dict. :type: dict :return: The DataUtility of this DataUtility. #",
"DataUtility. :return: The timeliness of this DataUtility. :rtype: float \"\"\" return self._timeliness @timeliness.setter",
"timeliness: float \"\"\" self.swagger_types = { 'url': str, 'accuracy': float, 'consistency': float, 'completeness':",
"util.deserialize_model(dikt, cls) @property def url(self) -> str: \"\"\"Gets the url of this DataUtility.",
"__future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing",
"def url(self, url: str): \"\"\"Sets the url of this DataUtility. :param url: The",
"accuracy of this DataUtility. :param accuracy: The accuracy of this DataUtility. :type accuracy:",
"from datetime import date, datetime # noqa: F401 from typing import List, Dict",
"url: str=None, accuracy: float=None, consistency: float=None, completeness: float=None, timeliness: float=None): # noqa: E501",
"float=None): # noqa: E501 \"\"\"DataUtility - a model defined in Swagger :param url:",
"DataUtility. # noqa: E501 :type accuracy: float :param consistency: The consistency of this",
"this DataUtility. :type accuracy: float \"\"\" if accuracy is None: raise ValueError(\"Invalid value",
"'timeliness': float } self.attribute_map = { 'url': 'URL', 'accuracy': 'accuracy', 'consistency': 'consistency', 'completeness':",
":param timeliness: The timeliness of this DataUtility. :type timeliness: float \"\"\" if timeliness",
"\"\"\"Sets the completeness of this DataUtility. :param completeness: The completeness of this DataUtility.",
"timeliness @classmethod def from_dict(cls, dikt) -> 'DataUtility': \"\"\"Returns the dict as a model",
":type: dict :return: The DataUtility of this DataUtility. # noqa: E501 :rtype: DataUtility",
"this DataUtility. :param timeliness: The timeliness of this DataUtility. :type timeliness: float \"\"\"",
"this DataUtility. # noqa: E501 :type timeliness: float \"\"\" self.swagger_types = { 'url':",
"from typing import List, Dict # noqa: F401 from swagger_server.models.base_model_ import Model from",
"if url is None: raise ValueError(\"Invalid value for `url`, must not be `None`\")",
"\"\"\" self.swagger_types = { 'url': str, 'accuracy': float, 'consistency': float, 'completeness': float, 'timeliness':",
"= consistency @property def completeness(self) -> float: \"\"\"Gets the completeness of this DataUtility.",
"consistency: float=None, completeness: float=None, timeliness: float=None): # noqa: E501 \"\"\"DataUtility - a model",
"# noqa: E501 :type url: str :param accuracy: The accuracy of this DataUtility.",
"DataUtility. :param completeness: The completeness of this DataUtility. :type completeness: float \"\"\" if",
"float=None, timeliness: float=None): # noqa: E501 \"\"\"DataUtility - a model defined in Swagger",
"this DataUtility. :rtype: float \"\"\" return self._accuracy @accuracy.setter def accuracy(self, accuracy: float): \"\"\"Sets",
"\"\"\"Gets the accuracy of this DataUtility. :return: The accuracy of this DataUtility. :rtype:",
"url(self, url: str): \"\"\"Sets the url of this DataUtility. :param url: The url",
"utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401",
"'timeliness': 'timeliness' } self._url = url self._accuracy = accuracy self._consistency = consistency self._completeness",
"this DataUtility. :type url: str \"\"\" if url is None: raise ValueError(\"Invalid value",
"\"\"\" if timeliness is None: raise ValueError(\"Invalid value for `timeliness`, must not be",
"this DataUtility. :type consistency: float \"\"\" if consistency is None: raise ValueError(\"Invalid value",
"dikt: A dict. :type: dict :return: The DataUtility of this DataUtility. # noqa:",
"url of this DataUtility. :param url: The url of this DataUtility. :type url:",
"completeness(self, completeness: float): \"\"\"Sets the completeness of this DataUtility. :param completeness: The completeness",
"if completeness is None: raise ValueError(\"Invalid value for `completeness`, must not be `None`\")",
"The url of this DataUtility. :type url: str \"\"\" if url is None:",
"self._url = url @property def accuracy(self) -> float: \"\"\"Gets the accuracy of this",
"\"\"\" return util.deserialize_model(dikt, cls) @property def url(self) -> str: \"\"\"Gets the url of",
"of this DataUtility. :type url: str \"\"\" if url is None: raise ValueError(\"Invalid",
"'completeness': float, 'timeliness': float } self.attribute_map = { 'url': 'URL', 'accuracy': 'accuracy', 'consistency':",
"def timeliness(self, timeliness: float): \"\"\"Sets the timeliness of this DataUtility. :param timeliness: The",
"} self.attribute_map = { 'url': 'URL', 'accuracy': 'accuracy', 'consistency': 'consistency', 'completeness': 'completeness', 'timeliness':",
"swagger_server.models.base_model_ import Model from swagger_server import util class DataUtility(Model): \"\"\"NOTE: This class is",
"= consistency self._completeness = completeness self._timeliness = timeliness @classmethod def from_dict(cls, dikt) ->",
"float: \"\"\"Gets the consistency of this DataUtility. :return: The consistency of this DataUtility.",
"'url': str, 'accuracy': float, 'consistency': float, 'completeness': float, 'timeliness': float } self.attribute_map =",
":type timeliness: float \"\"\" self.swagger_types = { 'url': str, 'accuracy': float, 'consistency': float,",
"float, 'completeness': float, 'timeliness': float } self.attribute_map = { 'url': 'URL', 'accuracy': 'accuracy',",
"float :param consistency: The consistency of this DataUtility. # noqa: E501 :type consistency:",
"not be `None`\") # noqa: E501 self._completeness = completeness @property def timeliness(self) ->",
"from swagger_server.models.base_model_ import Model from swagger_server import util class DataUtility(Model): \"\"\"NOTE: This class",
"DataUtility. # noqa: E501 :type consistency: float :param completeness: The completeness of this",
"timeliness: float): \"\"\"Sets the timeliness of this DataUtility. :param timeliness: The timeliness of",
"noqa: E501 \"\"\"DataUtility - a model defined in Swagger :param url: The url",
"DataUtility. :type url: str \"\"\" if url is None: raise ValueError(\"Invalid value for",
"@url.setter def url(self, url: str): \"\"\"Sets the url of this DataUtility. :param url:",
"`None`\") # noqa: E501 self._consistency = consistency @property def completeness(self) -> float: \"\"\"Gets",
"str :param accuracy: The accuracy of this DataUtility. # noqa: E501 :type accuracy:",
"this DataUtility. :rtype: float \"\"\" return self._consistency @consistency.setter def consistency(self, consistency: float): \"\"\"Sets",
"E501 self._consistency = consistency @property def completeness(self) -> float: \"\"\"Gets the completeness of",
"The timeliness of this DataUtility. :type timeliness: float \"\"\" if timeliness is None:",
"value for `accuracy`, must not be `None`\") # noqa: E501 self._accuracy = accuracy",
"the timeliness of this DataUtility. :return: The timeliness of this DataUtility. :rtype: float",
"'URL', 'accuracy': 'accuracy', 'consistency': 'consistency', 'completeness': 'completeness', 'timeliness': 'timeliness' } self._url = url",
"this DataUtility. :param accuracy: The accuracy of this DataUtility. :type accuracy: float \"\"\"",
"= { 'url': 'URL', 'accuracy': 'accuracy', 'consistency': 'consistency', 'completeness': 'completeness', 'timeliness': 'timeliness' }",
"-> 'DataUtility': \"\"\"Returns the dict as a model :param dikt: A dict. :type:",
"value for `timeliness`, must not be `None`\") # noqa: E501 self._timeliness = timeliness",
"is None: raise ValueError(\"Invalid value for `url`, must not be `None`\") # noqa:",
"of this DataUtility. # noqa: E501 :type completeness: float :param timeliness: The timeliness",
"this DataUtility. :return: The url of this DataUtility. :rtype: str \"\"\" return self._url",
"the class manually. \"\"\" def __init__(self, url: str=None, accuracy: float=None, consistency: float=None, completeness:",
"from swagger_server import util class DataUtility(Model): \"\"\"NOTE: This class is auto generated by",
"timeliness: float=None): # noqa: E501 \"\"\"DataUtility - a model defined in Swagger :param",
"The timeliness of this DataUtility. # noqa: E501 :type timeliness: float \"\"\" self.swagger_types",
"Swagger :param url: The url of this DataUtility. # noqa: E501 :type url:",
"dict :return: The DataUtility of this DataUtility. # noqa: E501 :rtype: DataUtility \"\"\"",
"'timeliness' } self._url = url self._accuracy = accuracy self._consistency = consistency self._completeness =",
"float \"\"\" self.swagger_types = { 'url': str, 'accuracy': float, 'consistency': float, 'completeness': float,",
"consistency of this DataUtility. :rtype: float \"\"\" return self._consistency @consistency.setter def consistency(self, consistency:",
"accuracy: float): \"\"\"Sets the accuracy of this DataUtility. :param accuracy: The accuracy of",
"DataUtility. # noqa: E501 :type timeliness: float \"\"\" self.swagger_types = { 'url': str,",
"coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa:",
"consistency: The consistency of this DataUtility. :type consistency: float \"\"\" if consistency is",
"not be `None`\") # noqa: E501 self._consistency = consistency @property def completeness(self) ->",
"def accuracy(self) -> float: \"\"\"Gets the accuracy of this DataUtility. :return: The accuracy",
"The completeness of this DataUtility. :type completeness: float \"\"\" if completeness is None:",
"url: str :param accuracy: The accuracy of this DataUtility. # noqa: E501 :type",
"of this DataUtility. :return: The completeness of this DataUtility. :rtype: float \"\"\" return",
"the swagger code generator program. Do not edit the class manually. \"\"\" def",
"= { 'url': str, 'accuracy': float, 'consistency': float, 'completeness': float, 'timeliness': float }",
"E501 :type url: str :param accuracy: The accuracy of this DataUtility. # noqa:",
"is auto generated by the swagger code generator program. Do not edit the",
"float: \"\"\"Gets the completeness of this DataUtility. :return: The completeness of this DataUtility.",
"of this DataUtility. # noqa: E501 :rtype: DataUtility \"\"\" return util.deserialize_model(dikt, cls) @property",
"the accuracy of this DataUtility. :return: The accuracy of this DataUtility. :rtype: float",
"this DataUtility. :rtype: float \"\"\" return self._timeliness @timeliness.setter def timeliness(self, timeliness: float): \"\"\"Sets",
"timeliness of this DataUtility. :param timeliness: The timeliness of this DataUtility. :type timeliness:",
"of this DataUtility. # noqa: E501 :type timeliness: float \"\"\" self.swagger_types = {",
"of this DataUtility. :param consistency: The consistency of this DataUtility. :type consistency: float",
"of this DataUtility. :return: The accuracy of this DataUtility. :rtype: float \"\"\" return",
":rtype: str \"\"\" return self._url @url.setter def url(self, url: str): \"\"\"Sets the url",
"be `None`\") # noqa: E501 self._completeness = completeness @property def timeliness(self) -> float:",
"'accuracy': float, 'consistency': float, 'completeness': float, 'timeliness': float } self.attribute_map = { 'url':",
"= completeness self._timeliness = timeliness @classmethod def from_dict(cls, dikt) -> 'DataUtility': \"\"\"Returns the",
"of this DataUtility. :rtype: float \"\"\" return self._completeness @completeness.setter def completeness(self, completeness: float):",
"__init__(self, url: str=None, accuracy: float=None, consistency: float=None, completeness: float=None, timeliness: float=None): # noqa:",
"Dict # noqa: F401 from swagger_server.models.base_model_ import Model from swagger_server import util class",
"noqa: E501 self._url = url @property def accuracy(self) -> float: \"\"\"Gets the accuracy",
"is None: raise ValueError(\"Invalid value for `timeliness`, must not be `None`\") # noqa:",
"DataUtility. # noqa: E501 :rtype: DataUtility \"\"\" return util.deserialize_model(dikt, cls) @property def url(self)",
"url(self) -> str: \"\"\"Gets the url of this DataUtility. :return: The url of",
"this DataUtility. :type timeliness: float \"\"\" if timeliness is None: raise ValueError(\"Invalid value",
"self._completeness = completeness self._timeliness = timeliness @classmethod def from_dict(cls, dikt) -> 'DataUtility': \"\"\"Returns",
":return: The DataUtility of this DataUtility. # noqa: E501 :rtype: DataUtility \"\"\" return",
"auto generated by the swagger code generator program. Do not edit the class",
"\"\"\" if consistency is None: raise ValueError(\"Invalid value for `consistency`, must not be",
"accuracy of this DataUtility. :rtype: float \"\"\" return self._accuracy @accuracy.setter def accuracy(self, accuracy:",
"completeness self._timeliness = timeliness @classmethod def from_dict(cls, dikt) -> 'DataUtility': \"\"\"Returns the dict",
"self.attribute_map = { 'url': 'URL', 'accuracy': 'accuracy', 'consistency': 'consistency', 'completeness': 'completeness', 'timeliness': 'timeliness'",
"typing import List, Dict # noqa: F401 from swagger_server.models.base_model_ import Model from swagger_server",
"DataUtility. :return: The url of this DataUtility. :rtype: str \"\"\" return self._url @url.setter",
"self._accuracy = accuracy self._consistency = consistency self._completeness = completeness self._timeliness = timeliness @classmethod",
"DataUtility. :rtype: float \"\"\" return self._accuracy @accuracy.setter def accuracy(self, accuracy: float): \"\"\"Sets the",
"return self._timeliness @timeliness.setter def timeliness(self, timeliness: float): \"\"\"Sets the timeliness of this DataUtility.",
":return: The consistency of this DataUtility. :rtype: float \"\"\" return self._consistency @consistency.setter def",
"self._timeliness = timeliness @classmethod def from_dict(cls, dikt) -> 'DataUtility': \"\"\"Returns the dict as",
"@timeliness.setter def timeliness(self, timeliness: float): \"\"\"Sets the timeliness of this DataUtility. :param timeliness:",
"# noqa: E501 :type timeliness: float \"\"\" self.swagger_types = { 'url': str, 'accuracy':",
"float \"\"\" return self._timeliness @timeliness.setter def timeliness(self, timeliness: float): \"\"\"Sets the timeliness of",
"`completeness`, must not be `None`\") # noqa: E501 self._completeness = completeness @property def",
"None: raise ValueError(\"Invalid value for `consistency`, must not be `None`\") # noqa: E501",
"accuracy of this DataUtility. :type accuracy: float \"\"\" if accuracy is None: raise",
"self._url = url self._accuracy = accuracy self._consistency = consistency self._completeness = completeness self._timeliness",
"return self._consistency @consistency.setter def consistency(self, consistency: float): \"\"\"Sets the consistency of this DataUtility.",
"Do not edit the class manually. \"\"\" def __init__(self, url: str=None, accuracy: float=None,",
"defined in Swagger :param url: The url of this DataUtility. # noqa: E501",
"'completeness', 'timeliness': 'timeliness' } self._url = url self._accuracy = accuracy self._consistency = consistency",
"raise ValueError(\"Invalid value for `consistency`, must not be `None`\") # noqa: E501 self._consistency",
"self._completeness @completeness.setter def completeness(self, completeness: float): \"\"\"Sets the completeness of this DataUtility. :param",
"The url of this DataUtility. :rtype: str \"\"\" return self._url @url.setter def url(self,",
"noqa: E501 self._consistency = consistency @property def completeness(self) -> float: \"\"\"Gets the completeness",
"from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from",
"\"\"\" return self._completeness @completeness.setter def completeness(self, completeness: float): \"\"\"Sets the completeness of this",
"url @property def accuracy(self) -> float: \"\"\"Gets the accuracy of this DataUtility. :return:",
"be `None`\") # noqa: E501 self._consistency = consistency @property def completeness(self) -> float:",
"of this DataUtility. :type completeness: float \"\"\" if completeness is None: raise ValueError(\"Invalid",
"float, 'timeliness': float } self.attribute_map = { 'url': 'URL', 'accuracy': 'accuracy', 'consistency': 'consistency',",
"of this DataUtility. :type timeliness: float \"\"\" if timeliness is None: raise ValueError(\"Invalid",
"timeliness: float \"\"\" if timeliness is None: raise ValueError(\"Invalid value for `timeliness`, must",
"\"\"\"Sets the url of this DataUtility. :param url: The url of this DataUtility.",
"str, 'accuracy': float, 'consistency': float, 'completeness': float, 'timeliness': float } self.attribute_map = {",
"import List, Dict # noqa: F401 from swagger_server.models.base_model_ import Model from swagger_server import",
"-> float: \"\"\"Gets the completeness of this DataUtility. :return: The completeness of this",
"E501 :rtype: DataUtility \"\"\" return util.deserialize_model(dikt, cls) @property def url(self) -> str: \"\"\"Gets",
"url of this DataUtility. :type url: str \"\"\" if url is None: raise",
"is None: raise ValueError(\"Invalid value for `consistency`, must not be `None`\") # noqa:",
"\"\"\"Gets the completeness of this DataUtility. :return: The completeness of this DataUtility. :rtype:",
"timeliness of this DataUtility. :rtype: float \"\"\" return self._timeliness @timeliness.setter def timeliness(self, timeliness:",
"url: The url of this DataUtility. :type url: str \"\"\" if url is",
"# noqa: E501 :rtype: DataUtility \"\"\" return util.deserialize_model(dikt, cls) @property def url(self) ->",
"completeness of this DataUtility. :rtype: float \"\"\" return self._completeness @completeness.setter def completeness(self, completeness:",
"float \"\"\" return self._consistency @consistency.setter def consistency(self, consistency: float): \"\"\"Sets the consistency of",
"float=None, consistency: float=None, completeness: float=None, timeliness: float=None): # noqa: E501 \"\"\"DataUtility - a",
"this DataUtility. # noqa: E501 :type accuracy: float :param consistency: The consistency of",
"`consistency`, must not be `None`\") # noqa: E501 self._consistency = consistency @property def",
"`None`\") # noqa: E501 self._accuracy = accuracy @property def consistency(self) -> float: \"\"\"Gets",
"E501 self._accuracy = accuracy @property def consistency(self) -> float: \"\"\"Gets the consistency of",
"timeliness of this DataUtility. :type timeliness: float \"\"\" if timeliness is None: raise",
"raise ValueError(\"Invalid value for `accuracy`, must not be `None`\") # noqa: E501 self._accuracy",
"DataUtility. :param consistency: The consistency of this DataUtility. :type consistency: float \"\"\" if",
"The accuracy of this DataUtility. :type accuracy: float \"\"\" if accuracy is None:",
"noqa: E501 self._accuracy = accuracy @property def consistency(self) -> float: \"\"\"Gets the consistency",
"The timeliness of this DataUtility. :rtype: float \"\"\" return self._timeliness @timeliness.setter def timeliness(self,",
"\"\"\" def __init__(self, url: str=None, accuracy: float=None, consistency: float=None, completeness: float=None, timeliness: float=None):",
"# noqa: E501 self._completeness = completeness @property def timeliness(self) -> float: \"\"\"Gets the",
"this DataUtility. :return: The consistency of this DataUtility. :rtype: float \"\"\" return self._consistency",
"None: raise ValueError(\"Invalid value for `url`, must not be `None`\") # noqa: E501",
"@classmethod def from_dict(cls, dikt) -> 'DataUtility': \"\"\"Returns the dict as a model :param",
"= url @property def accuracy(self) -> float: \"\"\"Gets the accuracy of this DataUtility.",
"noqa: E501 :rtype: DataUtility \"\"\" return util.deserialize_model(dikt, cls) @property def url(self) -> str:",
"the accuracy of this DataUtility. :param accuracy: The accuracy of this DataUtility. :type"
] |
[
"torch.cuda.manual_seed_all(int(seed)) torch.backends.cudnn.deterministic = True def set_py_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed for python",
"elif not isinstance(int(seed), int): raise ValueError(f\"seed={seed} should be str or int\") random.seed(int(seed)) def",
"torch process's rand seed The rand seed of non-torch libs may duplicate in",
"worker processes. Use this function as dataloader's worker init function can solve this",
"as np import torch import random from typing import Union __all__ = ['set_numpy_rand_seed',",
"hashed to get int seed \"\"\" set_numpy_rand_seed(seed) set_py_rand_seed(seed) set_torch_rand_seed(seed) def set_rand_seed_according_torch(): \"\"\"Set rand",
"on both cpu, cuda and cudnn Args: seed (Union[int, str]): int seed or",
"\"\"\"Set rand seed for python Args: seed (Union[int, str]): int seed or str,",
"seed (Union[int, str]): int seed or str, which will be hashed to get",
"will be hashed to get int seed \"\"\" if isinstance(seed, str): seed =",
"to get int seed \"\"\" if isinstance(seed, str): seed = hash(seed) elif not",
"seed for torch on both cpu, cuda and cudnn Args: seed (Union[int, str]):",
"will be hashed to get int seed \"\"\" set_numpy_rand_seed(seed) set_py_rand_seed(seed) set_torch_rand_seed(seed) def set_rand_seed_according_torch():",
"set_numpy_rand_seed(seed) set_py_rand_seed(seed) set_torch_rand_seed(seed) def set_rand_seed_according_torch(): \"\"\"Set rand seed according to torch process's rand",
"True def set_py_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed for python Args: seed (Union[int,",
"np import torch import random from typing import Union __all__ = ['set_numpy_rand_seed', 'set_py_rand_seed',",
"torch on both cpu, cuda and cudnn Args: seed (Union[int, str]): int seed",
"seed or str, which will be hashed to get int seed \"\"\" if",
"'set_py_rand_seed', 'set_torch_rand_seed', 'set_rand_seed', 'set_rand_seed_according_torch'] def set_numpy_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed for numpy",
"\"\"\"Set rand seed for numpy, torch(cpu, cuda, cudnn), python Args: seed (Union[int, str]):",
"python # -*- coding: utf-8 -*- \"\"\" @author: <NAME> @contact: <EMAIL> @software: PyCharm",
"str]): \"\"\"Set rand seed for python Args: seed (Union[int, str]): int seed or",
"random from typing import Union __all__ = ['set_numpy_rand_seed', 'set_py_rand_seed', 'set_torch_rand_seed', 'set_rand_seed', 'set_rand_seed_according_torch'] def",
"seed for numpy Args: seed (Union[int, str]): int seed or str, which will",
"int\") random.seed(int(seed)) def set_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed for numpy, torch(cpu, cuda,",
"= True def set_py_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed for python Args: seed",
"set_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed for numpy, torch(cpu, cuda, cudnn), python Args:",
"hash(seed) elif not isinstance(int(seed), int): raise ValueError(f\"seed={seed} should be str or int\") seed",
"duplicate in several dataloader worker processes. Use this function as dataloader's worker init",
"function as dataloader's worker init function can solve this problem. \"\"\" seed =",
"The rand seed of non-torch libs may duplicate in several dataloader worker processes.",
"or int\") random.seed(int(seed)) def set_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed for numpy, torch(cpu,",
"seed or str, which will be hashed to get int seed \"\"\" set_numpy_rand_seed(seed)",
"be hashed to get int seed \"\"\" if isinstance(seed, str): seed = hash(seed)",
"raise ValueError(f\"seed={seed} should be str or int\") torch.manual_seed(int(seed)) if torch.cuda.is_available(): torch.cuda.manual_seed_all(int(seed)) torch.backends.cudnn.deterministic =",
"str, which will be hashed to get int seed \"\"\" set_numpy_rand_seed(seed) set_py_rand_seed(seed) set_torch_rand_seed(seed)",
"as dataloader's worker init function can solve this problem. \"\"\" seed = torch.initial_seed()",
"(Union[int, str]): int seed or str, which will be hashed to get int",
"torch.cuda.is_available(): torch.cuda.manual_seed_all(int(seed)) torch.backends.cudnn.deterministic = True def set_py_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed for",
"int seed \"\"\" if isinstance(seed, str): seed = hash(seed) elif not isinstance(int(seed), int):",
"numpy, torch(cpu, cuda, cudnn), python Args: seed (Union[int, str]): int seed or str,",
"cudnn), python Args: seed (Union[int, str]): int seed or str, which will be",
"or str, which will be hashed to get int seed \"\"\" set_numpy_rand_seed(seed) set_py_rand_seed(seed)",
"Union[int, str]): \"\"\"Set rand seed for numpy Args: seed (Union[int, str]): int seed",
"processes. Use this function as dataloader's worker init function can solve this problem.",
"not isinstance(int(seed), int): raise ValueError(f\"seed={seed} should be str or int\") torch.manual_seed(int(seed)) if torch.cuda.is_available():",
"which will be hashed to get int seed \"\"\" if isinstance(seed, str): seed",
"str]): int seed or str, which will be hashed to get int seed",
"get int seed \"\"\" set_numpy_rand_seed(seed) set_py_rand_seed(seed) set_torch_rand_seed(seed) def set_rand_seed_according_torch(): \"\"\"Set rand seed according",
"dataloader's worker init function can solve this problem. \"\"\" seed = torch.initial_seed() set_py_rand_seed(seed)",
"PyCharm @file: random.py @time: 2020/1/15 2:29 @desc: \"\"\" import numpy as np import",
"which will be hashed to get int seed \"\"\" set_numpy_rand_seed(seed) set_py_rand_seed(seed) set_torch_rand_seed(seed) def",
"\"\"\" if isinstance(seed, str): seed = hash(seed) elif not isinstance(int(seed), int): raise ValueError(f\"seed={seed}",
"get int seed \"\"\" if isinstance(seed, str): seed = hash(seed) elif not isinstance(int(seed),",
"Use this function as dataloader's worker init function can solve this problem. \"\"\"",
"\"\"\" import numpy as np import torch import random from typing import Union",
"dataloader worker processes. Use this function as dataloader's worker init function can solve",
"or int\") seed = seed % (2**32) np.random.seed(int(seed)) def set_torch_rand_seed(seed: Union[int, str]): \"\"\"Set",
"rand seed for torch on both cpu, cuda and cudnn Args: seed (Union[int,",
"Args: seed (Union[int, str]): int seed or str, which will be hashed to",
"Union[int, str]): \"\"\"Set rand seed for torch on both cpu, cuda and cudnn",
"cuda, cudnn), python Args: seed (Union[int, str]): int seed or str, which will",
"2:29 @desc: \"\"\" import numpy as np import torch import random from typing",
"@author: <NAME> @contact: <EMAIL> @software: PyCharm @file: random.py @time: 2020/1/15 2:29 @desc: \"\"\"",
"be str or int\") torch.manual_seed(int(seed)) if torch.cuda.is_available(): torch.cuda.manual_seed_all(int(seed)) torch.backends.cudnn.deterministic = True def set_py_rand_seed(seed:",
"-*- \"\"\" @author: <NAME> @contact: <EMAIL> @software: PyCharm @file: random.py @time: 2020/1/15 2:29",
"'set_rand_seed_according_torch'] def set_numpy_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed for numpy Args: seed (Union[int,",
"Union[int, str]): \"\"\"Set rand seed for python Args: seed (Union[int, str]): int seed",
"should be str or int\") random.seed(int(seed)) def set_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed",
"def set_rand_seed_according_torch(): \"\"\"Set rand seed according to torch process's rand seed The rand",
"seed The rand seed of non-torch libs may duplicate in several dataloader worker",
"\"\"\" set_numpy_rand_seed(seed) set_py_rand_seed(seed) set_torch_rand_seed(seed) def set_rand_seed_according_torch(): \"\"\"Set rand seed according to torch process's",
"= ['set_numpy_rand_seed', 'set_py_rand_seed', 'set_torch_rand_seed', 'set_rand_seed', 'set_rand_seed_according_torch'] def set_numpy_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed",
"cpu, cuda and cudnn Args: seed (Union[int, str]): int seed or str, which",
"for numpy, torch(cpu, cuda, cudnn), python Args: seed (Union[int, str]): int seed or",
"seed = seed % (2**32) np.random.seed(int(seed)) def set_torch_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed",
"(2**32) np.random.seed(int(seed)) def set_torch_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed for torch on both",
"elif not isinstance(int(seed), int): raise ValueError(f\"seed={seed} should be str or int\") torch.manual_seed(int(seed)) if",
"of non-torch libs may duplicate in several dataloader worker processes. Use this function",
"int): raise ValueError(f\"seed={seed} should be str or int\") torch.manual_seed(int(seed)) if torch.cuda.is_available(): torch.cuda.manual_seed_all(int(seed)) torch.backends.cudnn.deterministic",
"-*- coding: utf-8 -*- \"\"\" @author: <NAME> @contact: <EMAIL> @software: PyCharm @file: random.py",
"coding: utf-8 -*- \"\"\" @author: <NAME> @contact: <EMAIL> @software: PyCharm @file: random.py @time:",
"set_rand_seed_according_torch(): \"\"\"Set rand seed according to torch process's rand seed The rand seed",
"and cudnn Args: seed (Union[int, str]): int seed or str, which will be",
"if torch.cuda.is_available(): torch.cuda.manual_seed_all(int(seed)) torch.backends.cudnn.deterministic = True def set_py_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed",
"be str or int\") random.seed(int(seed)) def set_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed for",
"several dataloader worker processes. Use this function as dataloader's worker init function can",
"seed of non-torch libs may duplicate in several dataloader worker processes. Use this",
"% (2**32) np.random.seed(int(seed)) def set_torch_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed for torch on",
"'set_rand_seed', 'set_rand_seed_according_torch'] def set_numpy_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed for numpy Args: seed",
"\"\"\"Set rand seed for torch on both cpu, cuda and cudnn Args: seed",
"set_py_rand_seed(seed) set_torch_rand_seed(seed) def set_rand_seed_according_torch(): \"\"\"Set rand seed according to torch process's rand seed",
"__all__ = ['set_numpy_rand_seed', 'set_py_rand_seed', 'set_torch_rand_seed', 'set_rand_seed', 'set_rand_seed_according_torch'] def set_numpy_rand_seed(seed: Union[int, str]): \"\"\"Set rand",
"rand seed according to torch process's rand seed The rand seed of non-torch",
"worker init function can solve this problem. \"\"\" seed = torch.initial_seed() set_py_rand_seed(seed) set_numpy_rand_seed(seed)",
"random.py @time: 2020/1/15 2:29 @desc: \"\"\" import numpy as np import torch import",
"raise ValueError(f\"seed={seed} should be str or int\") seed = seed % (2**32) np.random.seed(int(seed))",
"set_py_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed for python Args: seed (Union[int, str]): int",
"for python Args: seed (Union[int, str]): int seed or str, which will be",
"torch import random from typing import Union __all__ = ['set_numpy_rand_seed', 'set_py_rand_seed', 'set_torch_rand_seed', 'set_rand_seed',",
"@desc: \"\"\" import numpy as np import torch import random from typing import",
"str): seed = hash(seed) elif not isinstance(int(seed), int): raise ValueError(f\"seed={seed} should be str",
"= seed % (2**32) np.random.seed(int(seed)) def set_torch_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed for",
"np.random.seed(int(seed)) def set_torch_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed for torch on both cpu,",
"str]): \"\"\"Set rand seed for torch on both cpu, cuda and cudnn Args:",
"or int\") torch.manual_seed(int(seed)) if torch.cuda.is_available(): torch.cuda.manual_seed_all(int(seed)) torch.backends.cudnn.deterministic = True def set_py_rand_seed(seed: Union[int, str]):",
"str or int\") random.seed(int(seed)) def set_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed for numpy,",
"according to torch process's rand seed The rand seed of non-torch libs may",
"from typing import Union __all__ = ['set_numpy_rand_seed', 'set_py_rand_seed', 'set_torch_rand_seed', 'set_rand_seed', 'set_rand_seed_according_torch'] def set_numpy_rand_seed(seed:",
"should be str or int\") torch.manual_seed(int(seed)) if torch.cuda.is_available(): torch.cuda.manual_seed_all(int(seed)) torch.backends.cudnn.deterministic = True def",
"int): raise ValueError(f\"seed={seed} should be str or int\") random.seed(int(seed)) def set_rand_seed(seed: Union[int, str]):",
"seed \"\"\" set_numpy_rand_seed(seed) set_py_rand_seed(seed) set_torch_rand_seed(seed) def set_rand_seed_according_torch(): \"\"\"Set rand seed according to torch",
"int\") torch.manual_seed(int(seed)) if torch.cuda.is_available(): torch.cuda.manual_seed_all(int(seed)) torch.backends.cudnn.deterministic = True def set_py_rand_seed(seed: Union[int, str]): \"\"\"Set",
"numpy as np import torch import random from typing import Union __all__ =",
"may duplicate in several dataloader worker processes. Use this function as dataloader's worker",
"seed = hash(seed) elif not isinstance(int(seed), int): raise ValueError(f\"seed={seed} should be str or",
"set_torch_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed for torch on both cpu, cuda and",
"str, which will be hashed to get int seed \"\"\" if isinstance(seed, str):",
"process's rand seed The rand seed of non-torch libs may duplicate in several",
"elif not isinstance(int(seed), int): raise ValueError(f\"seed={seed} should be str or int\") seed =",
"hash(seed) elif not isinstance(int(seed), int): raise ValueError(f\"seed={seed} should be str or int\") torch.manual_seed(int(seed))",
"not isinstance(int(seed), int): raise ValueError(f\"seed={seed} should be str or int\") random.seed(int(seed)) def set_rand_seed(seed:",
"isinstance(seed, str): seed = hash(seed) elif not isinstance(int(seed), int): raise ValueError(f\"seed={seed} should be",
"set_torch_rand_seed(seed) def set_rand_seed_according_torch(): \"\"\"Set rand seed according to torch process's rand seed The",
"rand seed The rand seed of non-torch libs may duplicate in several dataloader",
"isinstance(int(seed), int): raise ValueError(f\"seed={seed} should be str or int\") seed = seed %",
"raise ValueError(f\"seed={seed} should be str or int\") random.seed(int(seed)) def set_rand_seed(seed: Union[int, str]): \"\"\"Set",
"isinstance(int(seed), int): raise ValueError(f\"seed={seed} should be str or int\") random.seed(int(seed)) def set_rand_seed(seed: Union[int,",
"str]): \"\"\"Set rand seed for numpy, torch(cpu, cuda, cudnn), python Args: seed (Union[int,",
"hash(seed) elif not isinstance(int(seed), int): raise ValueError(f\"seed={seed} should be str or int\") random.seed(int(seed))",
"def set_torch_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed for torch on both cpu, cuda",
"seed \"\"\" if isinstance(seed, str): seed = hash(seed) elif not isinstance(int(seed), int): raise",
"\"\"\"Set rand seed according to torch process's rand seed The rand seed of",
"rand seed for numpy Args: seed (Union[int, str]): int seed or str, which",
"int seed or str, which will be hashed to get int seed \"\"\"",
"set_numpy_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed for numpy Args: seed (Union[int, str]): int",
"int\") seed = seed % (2**32) np.random.seed(int(seed)) def set_torch_rand_seed(seed: Union[int, str]): \"\"\"Set rand",
"in several dataloader worker processes. Use this function as dataloader's worker init function",
"@contact: <EMAIL> @software: PyCharm @file: random.py @time: 2020/1/15 2:29 @desc: \"\"\" import numpy",
"@time: 2020/1/15 2:29 @desc: \"\"\" import numpy as np import torch import random",
"int seed \"\"\" set_numpy_rand_seed(seed) set_py_rand_seed(seed) set_torch_rand_seed(seed) def set_rand_seed_according_torch(): \"\"\"Set rand seed according to",
"<NAME> @contact: <EMAIL> @software: PyCharm @file: random.py @time: 2020/1/15 2:29 @desc: \"\"\" import",
"seed for numpy, torch(cpu, cuda, cudnn), python Args: seed (Union[int, str]): int seed",
"'set_torch_rand_seed', 'set_rand_seed', 'set_rand_seed_according_torch'] def set_numpy_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed for numpy Args:",
"@software: PyCharm @file: random.py @time: 2020/1/15 2:29 @desc: \"\"\" import numpy as np",
"# -*- coding: utf-8 -*- \"\"\" @author: <NAME> @contact: <EMAIL> @software: PyCharm @file:",
"cuda and cudnn Args: seed (Union[int, str]): int seed or str, which will",
"def set_numpy_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed for numpy Args: seed (Union[int, str]):",
"isinstance(int(seed), int): raise ValueError(f\"seed={seed} should be str or int\") torch.manual_seed(int(seed)) if torch.cuda.is_available(): torch.cuda.manual_seed_all(int(seed))",
"be str or int\") seed = seed % (2**32) np.random.seed(int(seed)) def set_torch_rand_seed(seed: Union[int,",
"rand seed for python Args: seed (Union[int, str]): int seed or str, which",
"for numpy Args: seed (Union[int, str]): int seed or str, which will be",
"rand seed for numpy, torch(cpu, cuda, cudnn), python Args: seed (Union[int, str]): int",
"import numpy as np import torch import random from typing import Union __all__",
"\"\"\"Set rand seed for numpy Args: seed (Union[int, str]): int seed or str,",
"hashed to get int seed \"\"\" if isinstance(seed, str): seed = hash(seed) elif",
"this function as dataloader's worker init function can solve this problem. \"\"\" seed",
"\"\"\" @author: <NAME> @contact: <EMAIL> @software: PyCharm @file: random.py @time: 2020/1/15 2:29 @desc:",
"ValueError(f\"seed={seed} should be str or int\") torch.manual_seed(int(seed)) if torch.cuda.is_available(): torch.cuda.manual_seed_all(int(seed)) torch.backends.cudnn.deterministic = True",
"= hash(seed) elif not isinstance(int(seed), int): raise ValueError(f\"seed={seed} should be str or int\")",
"int): raise ValueError(f\"seed={seed} should be str or int\") seed = seed % (2**32)",
"str or int\") seed = seed % (2**32) np.random.seed(int(seed)) def set_torch_rand_seed(seed: Union[int, str]):",
"rand seed of non-torch libs may duplicate in several dataloader worker processes. Use",
"Union[int, str]): \"\"\"Set rand seed for numpy, torch(cpu, cuda, cudnn), python Args: seed",
"seed according to torch process's rand seed The rand seed of non-torch libs",
"typing import Union __all__ = ['set_numpy_rand_seed', 'set_py_rand_seed', 'set_torch_rand_seed', 'set_rand_seed', 'set_rand_seed_according_torch'] def set_numpy_rand_seed(seed: Union[int,",
"non-torch libs may duplicate in several dataloader worker processes. Use this function as",
"cudnn Args: seed (Union[int, str]): int seed or str, which will be hashed",
"def set_py_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed for python Args: seed (Union[int, str]):",
"str or int\") torch.manual_seed(int(seed)) if torch.cuda.is_available(): torch.cuda.manual_seed_all(int(seed)) torch.backends.cudnn.deterministic = True def set_py_rand_seed(seed: Union[int,",
"torch.manual_seed(int(seed)) if torch.cuda.is_available(): torch.cuda.manual_seed_all(int(seed)) torch.backends.cudnn.deterministic = True def set_py_rand_seed(seed: Union[int, str]): \"\"\"Set rand",
"random.seed(int(seed)) def set_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed for numpy, torch(cpu, cuda, cudnn),",
"to get int seed \"\"\" set_numpy_rand_seed(seed) set_py_rand_seed(seed) set_torch_rand_seed(seed) def set_rand_seed_according_torch(): \"\"\"Set rand seed",
"@file: random.py @time: 2020/1/15 2:29 @desc: \"\"\" import numpy as np import torch",
"seed for python Args: seed (Union[int, str]): int seed or str, which will",
"import torch import random from typing import Union __all__ = ['set_numpy_rand_seed', 'set_py_rand_seed', 'set_torch_rand_seed',",
"['set_numpy_rand_seed', 'set_py_rand_seed', 'set_torch_rand_seed', 'set_rand_seed', 'set_rand_seed_according_torch'] def set_numpy_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed for",
"utf-8 -*- \"\"\" @author: <NAME> @contact: <EMAIL> @software: PyCharm @file: random.py @time: 2020/1/15",
"both cpu, cuda and cudnn Args: seed (Union[int, str]): int seed or str,",
"should be str or int\") seed = seed % (2**32) np.random.seed(int(seed)) def set_torch_rand_seed(seed:",
"torch.backends.cudnn.deterministic = True def set_py_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed for python Args:",
"libs may duplicate in several dataloader worker processes. Use this function as dataloader's",
"seed % (2**32) np.random.seed(int(seed)) def set_torch_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed for torch",
"Union __all__ = ['set_numpy_rand_seed', 'set_py_rand_seed', 'set_torch_rand_seed', 'set_rand_seed', 'set_rand_seed_according_torch'] def set_numpy_rand_seed(seed: Union[int, str]): \"\"\"Set",
"to torch process's rand seed The rand seed of non-torch libs may duplicate",
"2020/1/15 2:29 @desc: \"\"\" import numpy as np import torch import random from",
"#!/usr/bin/env python # -*- coding: utf-8 -*- \"\"\" @author: <NAME> @contact: <EMAIL> @software:",
"str]): \"\"\"Set rand seed for numpy Args: seed (Union[int, str]): int seed or",
"ValueError(f\"seed={seed} should be str or int\") random.seed(int(seed)) def set_rand_seed(seed: Union[int, str]): \"\"\"Set rand",
"def set_rand_seed(seed: Union[int, str]): \"\"\"Set rand seed for numpy, torch(cpu, cuda, cudnn), python",
"<EMAIL> @software: PyCharm @file: random.py @time: 2020/1/15 2:29 @desc: \"\"\" import numpy as",
"not isinstance(int(seed), int): raise ValueError(f\"seed={seed} should be str or int\") seed = seed",
"if isinstance(seed, str): seed = hash(seed) elif not isinstance(int(seed), int): raise ValueError(f\"seed={seed} should",
"import random from typing import Union __all__ = ['set_numpy_rand_seed', 'set_py_rand_seed', 'set_torch_rand_seed', 'set_rand_seed', 'set_rand_seed_according_torch']",
"import Union __all__ = ['set_numpy_rand_seed', 'set_py_rand_seed', 'set_torch_rand_seed', 'set_rand_seed', 'set_rand_seed_according_torch'] def set_numpy_rand_seed(seed: Union[int, str]):",
"numpy Args: seed (Union[int, str]): int seed or str, which will be hashed",
"for torch on both cpu, cuda and cudnn Args: seed (Union[int, str]): int",
"ValueError(f\"seed={seed} should be str or int\") seed = seed % (2**32) np.random.seed(int(seed)) def",
"be hashed to get int seed \"\"\" set_numpy_rand_seed(seed) set_py_rand_seed(seed) set_torch_rand_seed(seed) def set_rand_seed_according_torch(): \"\"\"Set",
"torch(cpu, cuda, cudnn), python Args: seed (Union[int, str]): int seed or str, which",
"or str, which will be hashed to get int seed \"\"\" if isinstance(seed,",
"python Args: seed (Union[int, str]): int seed or str, which will be hashed"
] |
[
"socket.TCP_KEEPINTVL, 75) ftp.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 60) ftp = FTP_TLS() ftp.set_pasv(True) connect() ftp.voidcmd('TYPE I') dst_filesize",
"= True t.start() return stop return wrap return outer_wrap class PyFTPclient: def __init__(self,",
"ftp.voidcmd('TYPE I') dst_filesize = ftp.size(dst_filename) mon = monitor() while dst_filesize > f.tell(): try:",
"actual decorator, # with fixed interval and times parameter def outer_wrap(function): # This",
"# with fixed interval and times parameter def outer_wrap(function): # This will be",
"stop.wait(interval) function(*args, **kwargs) i += 1 t = threading.Timer(0, inner_wrap) t.daemon = True",
"where we were disconnected res = ftp.retrbinary('RETR %s' % dst_filename, f.write) if f.tell()",
"stop.isSet(): stop.wait(interval) function(*args, **kwargs) i += 1 t = threading.Timer(0, inner_wrap) t.daemon =",
"optimize socket params for download task ftp.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) ftp.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 75) ftp.sock.setsockopt(socket.IPPROTO_TCP,",
"threading import logging from ftplib import FTP_TLS import socket import time def setInterval(interval,",
"import FTP_TLS import socket import time def setInterval(interval, times = -1): # This",
"self.passwd) ftp.prot_p() if self.directory != None: ftp.cwd(self.directory) # optimize socket params for download",
"time.sleep(30) logging.info('reconnect') mon.set() #stop monitor ftp.close() if not res.startswith('226 Transfer complete'): logging.error('Downloaded file",
"1 t = threading.Timer(0, inner_wrap) t.daemon = True t.start() return stop return wrap",
"ftp.retrbinary('RETR %s' % dst_filename, f.write) if f.tell() == 0 else \\ ftp.retrbinary('RETR %s'",
"t.start() return stop return wrap return outer_wrap class PyFTPclient: def __init__(self, host, port,",
"\\ ftp.retrbinary('RETR %s' % dst_filename, f.write, rest=f.tell()) except: self.max_attempts -= 1 if self.max_attempts",
"FTP_TLS import socket import time def setInterval(interval, times = -1): # This will",
"host, port, login, passwd, monitor_interval = 30, directory = None): self.host = host",
"< i: logging.debug(\"%d - %0.1f Kb/s\" % (i, (i-self.ptr)/(1024*self.monitor_interval))) self.ptr = i os.system('clear')",
"connect() ftp.voidcmd('TYPE I') dst_filesize = ftp.size(dst_filename) mon = monitor() while dst_filesize > f.tell():",
"try: connect() self.waiting = False # retrieve file from position where we were",
"os import threading import logging from ftplib import FTP_TLS import socket import time",
"be # called def wrap(*args, **kwargs): stop = threading.Event() # This is another",
"we were disconnected res = ftp.retrbinary('RETR %s' % dst_filename, f.write) if f.tell() ==",
"f.tell() @setInterval(self.monitor_interval) def monitor(): if not self.waiting: i = f.tell() if self.ptr <",
"= False # retrieve file from position where we were disconnected res =",
"ftp.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) ftp.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 75) ftp.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 60) ftp = FTP_TLS() ftp.set_pasv(True)",
"None): self.host = host self.port = port self.login = login self.passwd = <PASSWORD>",
"= f.tell() @setInterval(self.monitor_interval) def monitor(): if not self.waiting: i = f.tell() if self.ptr",
"True logging.info('waiting 30 sec...') time.sleep(30) logging.info('reconnect') mon.set() #stop monitor ftp.close() if not res.startswith('226",
"not stop.isSet(): stop.wait(interval) function(*args, **kwargs) i += 1 t = threading.Timer(0, inner_wrap) t.daemon",
"stop = threading.Event() # This is another function to be executed # in",
"i = 0 while i != times and not stop.isSet(): stop.wait(interval) function(*args, **kwargs)",
"fixed interval and times parameter def outer_wrap(function): # This will be the function",
"i: logging.debug(\"%d - %0.1f Kb/s\" % (i, (i-self.ptr)/(1024*self.monitor_interval))) self.ptr = i os.system('clear') print(str(int((float(i)/float(dst_filesize))",
"def inner_wrap(): i = 0 while i != times and not stop.isSet(): stop.wait(interval)",
"-1): # This will be the actual decorator, # with fixed interval and",
"= monitor() while dst_filesize > f.tell(): try: connect() self.waiting = False # retrieve",
"ftp.close() if not res.startswith('226 Transfer complete'): logging.error('Downloaded file {0} is not full.'.format(dst_filename)) os.remove(local_filename)",
"= '' if local_filename is None: local_filename = dst_filename with open(local_filename, 'w+b') as",
"socket import time def setInterval(interval, times = -1): # This will be the",
"is another function to be executed # in a different thread to simulate",
"if self.max_attempts == 0: mon.set() logging.exception('') raise self.waiting = True logging.info('waiting 30 sec...')",
"logging.exception('') raise self.waiting = True logging.info('waiting 30 sec...') time.sleep(30) logging.info('reconnect') mon.set() #stop monitor",
"= True logging.info('waiting 30 sec...') time.sleep(30) logging.info('reconnect') mon.set() #stop monitor ftp.close() if not",
"**kwargs): stop = threading.Event() # This is another function to be executed #",
"res.startswith('226 Transfer complete'): logging.error('Downloaded file {0} is not full.'.format(dst_filename)) os.remove(local_filename) return None return",
"as f: self.ptr = f.tell() @setInterval(self.monitor_interval) def monitor(): if not self.waiting: i =",
"sec...') time.sleep(30) logging.info('reconnect') mon.set() #stop monitor ftp.close() if not res.startswith('226 Transfer complete'): logging.error('Downloaded",
"position where we were disconnected res = ftp.retrbinary('RETR %s' % dst_filename, f.write) if",
"host self.port = port self.login = login self.passwd = <PASSWORD> self.directory = directory",
"return outer_wrap class PyFTPclient: def __init__(self, host, port, login, passwd, monitor_interval = 30,",
"= i os.system('clear') print(str(int((float(i)/float(dst_filesize)) * 100)) + '%') else: ftp.close() def connect(): ftp.connect(self.host,",
"connect() self.waiting = False # retrieve file from position where we were disconnected",
"0: mon.set() logging.exception('') raise self.waiting = True logging.info('waiting 30 sec...') time.sleep(30) logging.info('reconnect') mon.set()",
"i = f.tell() if self.ptr < i: logging.debug(\"%d - %0.1f Kb/s\" % (i,",
"dst_filename, f.write, rest=f.tell()) except: self.max_attempts -= 1 if self.max_attempts == 0: mon.set() logging.exception('')",
"= monitor_interval self.ptr = None self.max_attempts = 15 self.waiting = True def DownloadFile(self,",
"interval and times parameter def outer_wrap(function): # This will be the function to",
"ftp.login(self.login, self.passwd) ftp.prot_p() if self.directory != None: ftp.cwd(self.directory) # optimize socket params for",
"local_filename = None): res = '' if local_filename is None: local_filename = dst_filename",
"= ftp.size(dst_filename) mon = monitor() while dst_filesize > f.tell(): try: connect() self.waiting =",
"login self.passwd = <PASSWORD> self.directory = directory self.monitor_interval = monitor_interval self.ptr = None",
"f: self.ptr = f.tell() @setInterval(self.monitor_interval) def monitor(): if not self.waiting: i = f.tell()",
"PyFTPclient: def __init__(self, host, port, login, passwd, monitor_interval = 30, directory = None):",
"== 0 else \\ ftp.retrbinary('RETR %s' % dst_filename, f.write, rest=f.tell()) except: self.max_attempts -=",
"def outer_wrap(function): # This will be the function to be # called def",
"if not self.waiting: i = f.tell() if self.ptr < i: logging.debug(\"%d - %0.1f",
"function(*args, **kwargs) i += 1 t = threading.Timer(0, inner_wrap) t.daemon = True t.start()",
"self.directory != None: ftp.cwd(self.directory) # optimize socket params for download task ftp.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE,",
"-= 1 if self.max_attempts == 0: mon.set() logging.exception('') raise self.waiting = True logging.info('waiting",
"if self.directory != None: ftp.cwd(self.directory) # optimize socket params for download task ftp.sock.setsockopt(socket.SOL_SOCKET,",
"if local_filename is None: local_filename = dst_filename with open(local_filename, 'w+b') as f: self.ptr",
"in a different thread to simulate setInterval def inner_wrap(): i = 0 while",
"params for download task ftp.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) ftp.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 75) ftp.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 60)",
"%0.1f Kb/s\" % (i, (i-self.ptr)/(1024*self.monitor_interval))) self.ptr = i os.system('clear') print(str(int((float(i)/float(dst_filesize)) * 100)) +",
"local_filename is None: local_filename = dst_filename with open(local_filename, 'w+b') as f: self.ptr =",
"raise self.waiting = True logging.info('waiting 30 sec...') time.sleep(30) logging.info('reconnect') mon.set() #stop monitor ftp.close()",
"15 self.waiting = True def DownloadFile(self, dst_filename, local_filename = None): res = ''",
"= host self.port = port self.login = login self.passwd = <PASSWORD> self.directory =",
"self.port = port self.login = login self.passwd = <PASSWORD> self.directory = directory self.monitor_interval",
"= threading.Event() # This is another function to be executed # in a",
"= threading.Timer(0, inner_wrap) t.daemon = True t.start() return stop return wrap return outer_wrap",
"wrap(*args, **kwargs): stop = threading.Event() # This is another function to be executed",
"for download task ftp.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) ftp.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 75) ftp.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 60) ftp",
"self.host = host self.port = port self.login = login self.passwd = <PASSWORD> self.directory",
"logging.info('waiting 30 sec...') time.sleep(30) logging.info('reconnect') mon.set() #stop monitor ftp.close() if not res.startswith('226 Transfer",
"function to be executed # in a different thread to simulate setInterval def",
"monitor() while dst_filesize > f.tell(): try: connect() self.waiting = False # retrieve file",
"logging.info('reconnect') mon.set() #stop monitor ftp.close() if not res.startswith('226 Transfer complete'): logging.error('Downloaded file {0}",
"= None): self.host = host self.port = port self.login = login self.passwd =",
"else: ftp.close() def connect(): ftp.connect(self.host, self.port) ftp.login(self.login, self.passwd) ftp.prot_p() if self.directory != None:",
"were disconnected res = ftp.retrbinary('RETR %s' % dst_filename, f.write) if f.tell() == 0",
"* 100)) + '%') else: ftp.close() def connect(): ftp.connect(self.host, self.port) ftp.login(self.login, self.passwd) ftp.prot_p()",
"def wrap(*args, **kwargs): stop = threading.Event() # This is another function to be",
"def __init__(self, host, port, login, passwd, monitor_interval = 30, directory = None): self.host",
"<PASSWORD> self.directory = directory self.monitor_interval = monitor_interval self.ptr = None self.max_attempts = 15",
"time def setInterval(interval, times = -1): # This will be the actual decorator,",
"threading.Timer(0, inner_wrap) t.daemon = True t.start() return stop return wrap return outer_wrap class",
"self.waiting = True logging.info('waiting 30 sec...') time.sleep(30) logging.info('reconnect') mon.set() #stop monitor ftp.close() if",
"FTP_TLS() ftp.set_pasv(True) connect() ftp.voidcmd('TYPE I') dst_filesize = ftp.size(dst_filename) mon = monitor() while dst_filesize",
"logging.debug(\"%d - %0.1f Kb/s\" % (i, (i-self.ptr)/(1024*self.monitor_interval))) self.ptr = i os.system('clear') print(str(int((float(i)/float(dst_filesize)) *",
"res = ftp.retrbinary('RETR %s' % dst_filename, f.write) if f.tell() == 0 else \\",
"is None: local_filename = dst_filename with open(local_filename, 'w+b') as f: self.ptr = f.tell()",
"retrieve file from position where we were disconnected res = ftp.retrbinary('RETR %s' %",
"= None self.max_attempts = 15 self.waiting = True def DownloadFile(self, dst_filename, local_filename =",
"self.waiting = True def DownloadFile(self, dst_filename, local_filename = None): res = '' if",
"None: local_filename = dst_filename with open(local_filename, 'w+b') as f: self.ptr = f.tell() @setInterval(self.monitor_interval)",
"self.waiting = False # retrieve file from position where we were disconnected res",
"# called def wrap(*args, **kwargs): stop = threading.Event() # This is another function",
"!= None: ftp.cwd(self.directory) # optimize socket params for download task ftp.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)",
"= 0 while i != times and not stop.isSet(): stop.wait(interval) function(*args, **kwargs) i",
"f.tell(): try: connect() self.waiting = False # retrieve file from position where we",
"executed # in a different thread to simulate setInterval def inner_wrap(): i =",
"I') dst_filesize = ftp.size(dst_filename) mon = monitor() while dst_filesize > f.tell(): try: connect()",
"threading.Event() # This is another function to be executed # in a different",
"dst_filename, f.write) if f.tell() == 0 else \\ ftp.retrbinary('RETR %s' % dst_filename, f.write,",
"'%') else: ftp.close() def connect(): ftp.connect(self.host, self.port) ftp.login(self.login, self.passwd) ftp.prot_p() if self.directory !=",
"ftp = FTP_TLS() ftp.set_pasv(True) connect() ftp.voidcmd('TYPE I') dst_filesize = ftp.size(dst_filename) mon = monitor()",
"wrap return outer_wrap class PyFTPclient: def __init__(self, host, port, login, passwd, monitor_interval =",
"socket.TCP_KEEPIDLE, 60) ftp = FTP_TLS() ftp.set_pasv(True) connect() ftp.voidcmd('TYPE I') dst_filesize = ftp.size(dst_filename) mon",
"f.write) if f.tell() == 0 else \\ ftp.retrbinary('RETR %s' % dst_filename, f.write, rest=f.tell())",
"open(local_filename, 'w+b') as f: self.ptr = f.tell() @setInterval(self.monitor_interval) def monitor(): if not self.waiting:",
"times parameter def outer_wrap(function): # This will be the function to be #",
"= port self.login = login self.passwd = <PASSWORD> self.directory = directory self.monitor_interval =",
"def monitor(): if not self.waiting: i = f.tell() if self.ptr < i: logging.debug(\"%d",
"if self.ptr < i: logging.debug(\"%d - %0.1f Kb/s\" % (i, (i-self.ptr)/(1024*self.monitor_interval))) self.ptr =",
"(i, (i-self.ptr)/(1024*self.monitor_interval))) self.ptr = i os.system('clear') print(str(int((float(i)/float(dst_filesize)) * 100)) + '%') else: ftp.close()",
"self.waiting: i = f.tell() if self.ptr < i: logging.debug(\"%d - %0.1f Kb/s\" %",
"parameter def outer_wrap(function): # This will be the function to be # called",
"download task ftp.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) ftp.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 75) ftp.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 60) ftp =",
"and times parameter def outer_wrap(function): # This will be the function to be",
"setInterval(interval, times = -1): # This will be the actual decorator, # with",
"with open(local_filename, 'w+b') as f: self.ptr = f.tell() @setInterval(self.monitor_interval) def monitor(): if not",
"t.daemon = True t.start() return stop return wrap return outer_wrap class PyFTPclient: def",
"= <PASSWORD> self.directory = directory self.monitor_interval = monitor_interval self.ptr = None self.max_attempts =",
"- %0.1f Kb/s\" % (i, (i-self.ptr)/(1024*self.monitor_interval))) self.ptr = i os.system('clear') print(str(int((float(i)/float(dst_filesize)) * 100))",
"False # retrieve file from position where we were disconnected res = ftp.retrbinary('RETR",
"% dst_filename, f.write) if f.tell() == 0 else \\ ftp.retrbinary('RETR %s' % dst_filename,",
"This is another function to be executed # in a different thread to",
"%s' % dst_filename, f.write, rest=f.tell()) except: self.max_attempts -= 1 if self.max_attempts == 0:",
"different thread to simulate setInterval def inner_wrap(): i = 0 while i !=",
"inner_wrap(): i = 0 while i != times and not stop.isSet(): stop.wait(interval) function(*args,",
"import threading import logging from ftplib import FTP_TLS import socket import time def",
"self.directory = directory self.monitor_interval = monitor_interval self.ptr = None self.max_attempts = 15 self.waiting",
"if not res.startswith('226 Transfer complete'): logging.error('Downloaded file {0} is not full.'.format(dst_filename)) os.remove(local_filename) return",
"to be # called def wrap(*args, **kwargs): stop = threading.Event() # This is",
"dst_filename, local_filename = None): res = '' if local_filename is None: local_filename =",
"%s' % dst_filename, f.write) if f.tell() == 0 else \\ ftp.retrbinary('RETR %s' %",
"% dst_filename, f.write, rest=f.tell()) except: self.max_attempts -= 1 if self.max_attempts == 0: mon.set()",
"decorator, # with fixed interval and times parameter def outer_wrap(function): # This will",
"= f.tell() if self.ptr < i: logging.debug(\"%d - %0.1f Kb/s\" % (i, (i-self.ptr)/(1024*self.monitor_interval)))",
"to be executed # in a different thread to simulate setInterval def inner_wrap():",
"def DownloadFile(self, dst_filename, local_filename = None): res = '' if local_filename is None:",
"This will be the actual decorator, # with fixed interval and times parameter",
"ftp.connect(self.host, self.port) ftp.login(self.login, self.passwd) ftp.prot_p() if self.directory != None: ftp.cwd(self.directory) # optimize socket",
"= FTP_TLS() ftp.set_pasv(True) connect() ftp.voidcmd('TYPE I') dst_filesize = ftp.size(dst_filename) mon = monitor() while",
"not res.startswith('226 Transfer complete'): logging.error('Downloaded file {0} is not full.'.format(dst_filename)) os.remove(local_filename) return None",
"def setInterval(interval, times = -1): # This will be the actual decorator, #",
"self.max_attempts = 15 self.waiting = True def DownloadFile(self, dst_filename, local_filename = None): res",
"= None): res = '' if local_filename is None: local_filename = dst_filename with",
"# This will be the function to be # called def wrap(*args, **kwargs):",
"be the function to be # called def wrap(*args, **kwargs): stop = threading.Event()",
"from position where we were disconnected res = ftp.retrbinary('RETR %s' % dst_filename, f.write)",
"inner_wrap) t.daemon = True t.start() return stop return wrap return outer_wrap class PyFTPclient:",
"the actual decorator, # with fixed interval and times parameter def outer_wrap(function): #",
"task ftp.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) ftp.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 75) ftp.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 60) ftp = FTP_TLS()",
"!= times and not stop.isSet(): stop.wait(interval) function(*args, **kwargs) i += 1 t =",
"return wrap return outer_wrap class PyFTPclient: def __init__(self, host, port, login, passwd, monitor_interval",
"self.login = login self.passwd = <PASSWORD> self.directory = directory self.monitor_interval = monitor_interval self.ptr",
"+ '%') else: ftp.close() def connect(): ftp.connect(self.host, self.port) ftp.login(self.login, self.passwd) ftp.prot_p() if self.directory",
"mon.set() logging.exception('') raise self.waiting = True logging.info('waiting 30 sec...') time.sleep(30) logging.info('reconnect') mon.set() #stop",
"ftp.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 60) ftp = FTP_TLS() ftp.set_pasv(True) connect() ftp.voidcmd('TYPE I') dst_filesize = ftp.size(dst_filename)",
"logging from ftplib import FTP_TLS import socket import time def setInterval(interval, times =",
"t = threading.Timer(0, inner_wrap) t.daemon = True t.start() return stop return wrap return",
"outer_wrap class PyFTPclient: def __init__(self, host, port, login, passwd, monitor_interval = 30, directory",
"'w+b') as f: self.ptr = f.tell() @setInterval(self.monitor_interval) def monitor(): if not self.waiting: i",
"ftp.retrbinary('RETR %s' % dst_filename, f.write, rest=f.tell()) except: self.max_attempts -= 1 if self.max_attempts ==",
"0 else \\ ftp.retrbinary('RETR %s' % dst_filename, f.write, rest=f.tell()) except: self.max_attempts -= 1",
"file from position where we were disconnected res = ftp.retrbinary('RETR %s' % dst_filename,",
"75) ftp.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 60) ftp = FTP_TLS() ftp.set_pasv(True) connect() ftp.voidcmd('TYPE I') dst_filesize =",
"= directory self.monitor_interval = monitor_interval self.ptr = None self.max_attempts = 15 self.waiting =",
"'' if local_filename is None: local_filename = dst_filename with open(local_filename, 'w+b') as f:",
"Kb/s\" % (i, (i-self.ptr)/(1024*self.monitor_interval))) self.ptr = i os.system('clear') print(str(int((float(i)/float(dst_filesize)) * 100)) + '%')",
"@setInterval(self.monitor_interval) def monitor(): if not self.waiting: i = f.tell() if self.ptr < i:",
"while i != times and not stop.isSet(): stop.wait(interval) function(*args, **kwargs) i += 1",
"self.ptr = i os.system('clear') print(str(int((float(i)/float(dst_filesize)) * 100)) + '%') else: ftp.close() def connect():",
"ftp.cwd(self.directory) # optimize socket params for download task ftp.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) ftp.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL,",
"disconnected res = ftp.retrbinary('RETR %s' % dst_filename, f.write) if f.tell() == 0 else",
"directory = None): self.host = host self.port = port self.login = login self.passwd",
"0 while i != times and not stop.isSet(): stop.wait(interval) function(*args, **kwargs) i +=",
"# optimize socket params for download task ftp.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) ftp.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 75)",
"rest=f.tell()) except: self.max_attempts -= 1 if self.max_attempts == 0: mon.set() logging.exception('') raise self.waiting",
"self.max_attempts -= 1 if self.max_attempts == 0: mon.set() logging.exception('') raise self.waiting = True",
"return stop return wrap return outer_wrap class PyFTPclient: def __init__(self, host, port, login,",
"monitor_interval self.ptr = None self.max_attempts = 15 self.waiting = True def DownloadFile(self, dst_filename,",
"# in a different thread to simulate setInterval def inner_wrap(): i = 0",
"f.write, rest=f.tell()) except: self.max_attempts -= 1 if self.max_attempts == 0: mon.set() logging.exception('') raise",
"import socket import time def setInterval(interval, times = -1): # This will be",
"import time def setInterval(interval, times = -1): # This will be the actual",
"not self.waiting: i = f.tell() if self.ptr < i: logging.debug(\"%d - %0.1f Kb/s\"",
"ftp.close() def connect(): ftp.connect(self.host, self.port) ftp.login(self.login, self.passwd) ftp.prot_p() if self.directory != None: ftp.cwd(self.directory)",
"= ftp.retrbinary('RETR %s' % dst_filename, f.write) if f.tell() == 0 else \\ ftp.retrbinary('RETR",
"class PyFTPclient: def __init__(self, host, port, login, passwd, monitor_interval = 30, directory =",
"def connect(): ftp.connect(self.host, self.port) ftp.login(self.login, self.passwd) ftp.prot_p() if self.directory != None: ftp.cwd(self.directory) #",
"self.port) ftp.login(self.login, self.passwd) ftp.prot_p() if self.directory != None: ftp.cwd(self.directory) # optimize socket params",
"and not stop.isSet(): stop.wait(interval) function(*args, **kwargs) i += 1 t = threading.Timer(0, inner_wrap)",
"function to be # called def wrap(*args, **kwargs): stop = threading.Event() # This",
"setInterval def inner_wrap(): i = 0 while i != times and not stop.isSet():",
"self.ptr = f.tell() @setInterval(self.monitor_interval) def monitor(): if not self.waiting: i = f.tell() if",
"self.ptr < i: logging.debug(\"%d - %0.1f Kb/s\" % (i, (i-self.ptr)/(1024*self.monitor_interval))) self.ptr = i",
"simulate setInterval def inner_wrap(): i = 0 while i != times and not",
"Transfer complete'): logging.error('Downloaded file {0} is not full.'.format(dst_filename)) os.remove(local_filename) return None return 1",
"dst_filesize = ftp.size(dst_filename) mon = monitor() while dst_filesize > f.tell(): try: connect() self.waiting",
"directory self.monitor_interval = monitor_interval self.ptr = None self.max_attempts = 15 self.waiting = True",
"f.tell() if self.ptr < i: logging.debug(\"%d - %0.1f Kb/s\" % (i, (i-self.ptr)/(1024*self.monitor_interval))) self.ptr",
"f.tell() == 0 else \\ ftp.retrbinary('RETR %s' % dst_filename, f.write, rest=f.tell()) except: self.max_attempts",
"monitor(): if not self.waiting: i = f.tell() if self.ptr < i: logging.debug(\"%d -",
"except: self.max_attempts -= 1 if self.max_attempts == 0: mon.set() logging.exception('') raise self.waiting =",
"another function to be executed # in a different thread to simulate setInterval",
"login, passwd, monitor_interval = 30, directory = None): self.host = host self.port =",
"monitor_interval = 30, directory = None): self.host = host self.port = port self.login",
"= 30, directory = None): self.host = host self.port = port self.login =",
"called def wrap(*args, **kwargs): stop = threading.Event() # This is another function to",
"self.passwd = <PASSWORD> self.directory = directory self.monitor_interval = monitor_interval self.ptr = None self.max_attempts",
"> f.tell(): try: connect() self.waiting = False # retrieve file from position where",
"to simulate setInterval def inner_wrap(): i = 0 while i != times and",
"import logging from ftplib import FTP_TLS import socket import time def setInterval(interval, times",
"times = -1): # This will be the actual decorator, # with fixed",
"self.ptr = None self.max_attempts = 15 self.waiting = True def DownloadFile(self, dst_filename, local_filename",
"+= 1 t = threading.Timer(0, inner_wrap) t.daemon = True t.start() return stop return",
"i os.system('clear') print(str(int((float(i)/float(dst_filesize)) * 100)) + '%') else: ftp.close() def connect(): ftp.connect(self.host, self.port)",
"**kwargs) i += 1 t = threading.Timer(0, inner_wrap) t.daemon = True t.start() return",
"i != times and not stop.isSet(): stop.wait(interval) function(*args, **kwargs) i += 1 t",
"a different thread to simulate setInterval def inner_wrap(): i = 0 while i",
"connect(): ftp.connect(self.host, self.port) ftp.login(self.login, self.passwd) ftp.prot_p() if self.directory != None: ftp.cwd(self.directory) # optimize",
"socket.SO_KEEPALIVE, 1) ftp.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 75) ftp.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 60) ftp = FTP_TLS() ftp.set_pasv(True) connect()",
"import os import threading import logging from ftplib import FTP_TLS import socket import",
"ftp.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 75) ftp.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 60) ftp = FTP_TLS() ftp.set_pasv(True) connect() ftp.voidcmd('TYPE I')",
"else \\ ftp.retrbinary('RETR %s' % dst_filename, f.write, rest=f.tell()) except: self.max_attempts -= 1 if",
"ftp.size(dst_filename) mon = monitor() while dst_filesize > f.tell(): try: connect() self.waiting = False",
"res = '' if local_filename is None: local_filename = dst_filename with open(local_filename, 'w+b')",
"1) ftp.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 75) ftp.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 60) ftp = FTP_TLS() ftp.set_pasv(True) connect() ftp.voidcmd('TYPE",
"100)) + '%') else: ftp.close() def connect(): ftp.connect(self.host, self.port) ftp.login(self.login, self.passwd) ftp.prot_p() if",
"i += 1 t = threading.Timer(0, inner_wrap) t.daemon = True t.start() return stop",
"None): res = '' if local_filename is None: local_filename = dst_filename with open(local_filename,",
"mon.set() #stop monitor ftp.close() if not res.startswith('226 Transfer complete'): logging.error('Downloaded file {0} is",
"while dst_filesize > f.tell(): try: connect() self.waiting = False # retrieve file from",
"os.system('clear') print(str(int((float(i)/float(dst_filesize)) * 100)) + '%') else: ftp.close() def connect(): ftp.connect(self.host, self.port) ftp.login(self.login,",
"# This is another function to be executed # in a different thread",
"This will be the function to be # called def wrap(*args, **kwargs): stop",
"= 15 self.waiting = True def DownloadFile(self, dst_filename, local_filename = None): res =",
"(i-self.ptr)/(1024*self.monitor_interval))) self.ptr = i os.system('clear') print(str(int((float(i)/float(dst_filesize)) * 100)) + '%') else: ftp.close() def",
"be the actual decorator, # with fixed interval and times parameter def outer_wrap(function):",
"stop return wrap return outer_wrap class PyFTPclient: def __init__(self, host, port, login, passwd,",
"__init__(self, host, port, login, passwd, monitor_interval = 30, directory = None): self.host =",
"thread to simulate setInterval def inner_wrap(): i = 0 while i != times",
"port, login, passwd, monitor_interval = 30, directory = None): self.host = host self.port",
"the function to be # called def wrap(*args, **kwargs): stop = threading.Event() #",
"self.monitor_interval = monitor_interval self.ptr = None self.max_attempts = 15 self.waiting = True def",
"True def DownloadFile(self, dst_filename, local_filename = None): res = '' if local_filename is",
"passwd, monitor_interval = 30, directory = None): self.host = host self.port = port",
"= dst_filename with open(local_filename, 'w+b') as f: self.ptr = f.tell() @setInterval(self.monitor_interval) def monitor():",
"% (i, (i-self.ptr)/(1024*self.monitor_interval))) self.ptr = i os.system('clear') print(str(int((float(i)/float(dst_filesize)) * 100)) + '%') else:",
"None self.max_attempts = 15 self.waiting = True def DownloadFile(self, dst_filename, local_filename = None):",
"ftp.set_pasv(True) connect() ftp.voidcmd('TYPE I') dst_filesize = ftp.size(dst_filename) mon = monitor() while dst_filesize >",
"mon = monitor() while dst_filesize > f.tell(): try: connect() self.waiting = False #",
"dst_filesize > f.tell(): try: connect() self.waiting = False # retrieve file from position",
"if f.tell() == 0 else \\ ftp.retrbinary('RETR %s' % dst_filename, f.write, rest=f.tell()) except:",
"monitor ftp.close() if not res.startswith('226 Transfer complete'): logging.error('Downloaded file {0} is not full.'.format(dst_filename))",
"= -1): # This will be the actual decorator, # with fixed interval",
"will be the actual decorator, # with fixed interval and times parameter def",
"ftp.prot_p() if self.directory != None: ftp.cwd(self.directory) # optimize socket params for download task",
"30 sec...') time.sleep(30) logging.info('reconnect') mon.set() #stop monitor ftp.close() if not res.startswith('226 Transfer complete'):",
"= login self.passwd = <PASSWORD> self.directory = directory self.monitor_interval = monitor_interval self.ptr =",
"outer_wrap(function): # This will be the function to be # called def wrap(*args,",
"with fixed interval and times parameter def outer_wrap(function): # This will be the",
"port self.login = login self.passwd = <PASSWORD> self.directory = directory self.monitor_interval = monitor_interval",
"60) ftp = FTP_TLS() ftp.set_pasv(True) connect() ftp.voidcmd('TYPE I') dst_filesize = ftp.size(dst_filename) mon =",
"will be the function to be # called def wrap(*args, **kwargs): stop =",
"ftplib import FTP_TLS import socket import time def setInterval(interval, times = -1): #",
"# This will be the actual decorator, # with fixed interval and times",
"be executed # in a different thread to simulate setInterval def inner_wrap(): i",
"from ftplib import FTP_TLS import socket import time def setInterval(interval, times = -1):",
"DownloadFile(self, dst_filename, local_filename = None): res = '' if local_filename is None: local_filename",
"print(str(int((float(i)/float(dst_filesize)) * 100)) + '%') else: ftp.close() def connect(): ftp.connect(self.host, self.port) ftp.login(self.login, self.passwd)",
"1 if self.max_attempts == 0: mon.set() logging.exception('') raise self.waiting = True logging.info('waiting 30",
"#stop monitor ftp.close() if not res.startswith('226 Transfer complete'): logging.error('Downloaded file {0} is not",
"# retrieve file from position where we were disconnected res = ftp.retrbinary('RETR %s'",
"= True def DownloadFile(self, dst_filename, local_filename = None): res = '' if local_filename",
"dst_filename with open(local_filename, 'w+b') as f: self.ptr = f.tell() @setInterval(self.monitor_interval) def monitor(): if",
"None: ftp.cwd(self.directory) # optimize socket params for download task ftp.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) ftp.sock.setsockopt(socket.IPPROTO_TCP,",
"== 0: mon.set() logging.exception('') raise self.waiting = True logging.info('waiting 30 sec...') time.sleep(30) logging.info('reconnect')",
"self.max_attempts == 0: mon.set() logging.exception('') raise self.waiting = True logging.info('waiting 30 sec...') time.sleep(30)",
"True t.start() return stop return wrap return outer_wrap class PyFTPclient: def __init__(self, host,",
"socket params for download task ftp.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) ftp.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 75) ftp.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE,",
"30, directory = None): self.host = host self.port = port self.login = login",
"times and not stop.isSet(): stop.wait(interval) function(*args, **kwargs) i += 1 t = threading.Timer(0,",
"local_filename = dst_filename with open(local_filename, 'w+b') as f: self.ptr = f.tell() @setInterval(self.monitor_interval) def"
] |
[
"logging.getLogger(\"Ingest\") logger.info(\"Ingesting data\") try: columns = getattr(column_constants, \"column_constants\") schema = StructType([StructField(columns[\"GENDER\"], StringType(), True),",
"input JSON file \"\"\" logger = logging.getLogger(\"Ingest\") logger.info(\"Ingesting data\") try: columns = getattr(column_constants,",
"def __init__(self, spark): self.spark = spark def ingest_json_data(self, file_path): \"\"\" This function reads",
"StructField, IntegerType from src.utils import column_constants class Ingest: logging.config.fileConfig(\"config/logging.conf\") def __init__(self, spark): self.spark",
"True), StructField(columns[\"WEIGHT_KG\"], IntegerType(), True)]) input_file = self.spark.read.option(\"multiLine\", \"true\").schema(schema).json(file_path) return input_file.persist() except Exception as",
"self.spark.read.option(\"multiLine\", \"true\").schema(schema).json(file_path) return input_file.persist() except Exception as exp: logger.error(\"An error occured while ingesting",
"project bmi_calculator # Created by @<NAME> at 9:06 AM 1/16/2022 using PyCharm \"\"\"",
"StringType, StructField, IntegerType from src.utils import column_constants class Ingest: logging.config.fileConfig(\"config/logging.conf\") def __init__(self, spark):",
"Ingest: logging.config.fileConfig(\"config/logging.conf\") def __init__(self, spark): self.spark = spark def ingest_json_data(self, file_path): \"\"\" This",
"StructField(columns[\"HEIGHT_CM\"], IntegerType(), True), StructField(columns[\"WEIGHT_KG\"], IntegerType(), True)]) input_file = self.spark.read.option(\"multiLine\", \"true\").schema(schema).json(file_path) return input_file.persist() except",
"self.spark = spark def ingest_json_data(self, file_path): \"\"\" This function reads the json file",
"AM 1/16/2022 using PyCharm \"\"\" import logging.config from pyspark.sql.types import StructType, StringType, StructField,",
"spark): self.spark = spark def ingest_json_data(self, file_path): \"\"\" This function reads the json",
"return input_file.persist() except Exception as exp: logger.error(\"An error occured while ingesting data >",
"\"\"\" # ingest.py for project bmi_calculator # Created by @<NAME> at 9:06 AM",
"where the data is available :return: dataframe from input JSON file \"\"\" logger",
"\"\"\" import logging.config from pyspark.sql.types import StructType, StringType, StructField, IntegerType from src.utils import",
"by @<NAME> at 9:06 AM 1/16/2022 using PyCharm \"\"\" import logging.config from pyspark.sql.types",
"try: columns = getattr(column_constants, \"column_constants\") schema = StructType([StructField(columns[\"GENDER\"], StringType(), True), StructField(columns[\"HEIGHT_CM\"], IntegerType(), True),",
"PyCharm \"\"\" import logging.config from pyspark.sql.types import StructType, StringType, StructField, IntegerType from src.utils",
"from input JSON file \"\"\" logger = logging.getLogger(\"Ingest\") logger.info(\"Ingesting data\") try: columns =",
"<gh_stars>0 \"\"\" # ingest.py for project bmi_calculator # Created by @<NAME> at 9:06",
"@<NAME> at 9:06 AM 1/16/2022 using PyCharm \"\"\" import logging.config from pyspark.sql.types import",
"file \"\"\" logger = logging.getLogger(\"Ingest\") logger.info(\"Ingesting data\") try: columns = getattr(column_constants, \"column_constants\") schema",
"spark: Spark session :param file_path: input file path where the data is available",
"schema = StructType([StructField(columns[\"GENDER\"], StringType(), True), StructField(columns[\"HEIGHT_CM\"], IntegerType(), True), StructField(columns[\"WEIGHT_KG\"], IntegerType(), True)]) input_file =",
"pyspark.sql.types import StructType, StringType, StructField, IntegerType from src.utils import column_constants class Ingest: logging.config.fileConfig(\"config/logging.conf\")",
"True), StructField(columns[\"HEIGHT_CM\"], IntegerType(), True), StructField(columns[\"WEIGHT_KG\"], IntegerType(), True)]) input_file = self.spark.read.option(\"multiLine\", \"true\").schema(schema).json(file_path) return input_file.persist()",
"import column_constants class Ingest: logging.config.fileConfig(\"config/logging.conf\") def __init__(self, spark): self.spark = spark def ingest_json_data(self,",
"True)]) input_file = self.spark.read.option(\"multiLine\", \"true\").schema(schema).json(file_path) return input_file.persist() except Exception as exp: logger.error(\"An error",
"= self.spark.read.option(\"multiLine\", \"true\").schema(schema).json(file_path) return input_file.persist() except Exception as exp: logger.error(\"An error occured while",
"except Exception as exp: logger.error(\"An error occured while ingesting data > \" +",
"data frame :param spark: Spark session :param file_path: input file path where the",
"import logging.config from pyspark.sql.types import StructType, StringType, StructField, IntegerType from src.utils import column_constants",
"\"\"\" This function reads the json file and returns a data frame :param",
"from pyspark.sql.types import StructType, StringType, StructField, IntegerType from src.utils import column_constants class Ingest:",
"using PyCharm \"\"\" import logging.config from pyspark.sql.types import StructType, StringType, StructField, IntegerType from",
"file and returns a data frame :param spark: Spark session :param file_path: input",
"input file path where the data is available :return: dataframe from input JSON",
"file_path): \"\"\" This function reads the json file and returns a data frame",
"spark def ingest_json_data(self, file_path): \"\"\" This function reads the json file and returns",
":param file_path: input file path where the data is available :return: dataframe from",
"StructType, StringType, StructField, IntegerType from src.utils import column_constants class Ingest: logging.config.fileConfig(\"config/logging.conf\") def __init__(self,",
"is available :return: dataframe from input JSON file \"\"\" logger = logging.getLogger(\"Ingest\") logger.info(\"Ingesting",
"bmi_calculator # Created by @<NAME> at 9:06 AM 1/16/2022 using PyCharm \"\"\" import",
"logger = logging.getLogger(\"Ingest\") logger.info(\"Ingesting data\") try: columns = getattr(column_constants, \"column_constants\") schema = StructType([StructField(columns[\"GENDER\"],",
"data is available :return: dataframe from input JSON file \"\"\" logger = logging.getLogger(\"Ingest\")",
"columns = getattr(column_constants, \"column_constants\") schema = StructType([StructField(columns[\"GENDER\"], StringType(), True), StructField(columns[\"HEIGHT_CM\"], IntegerType(), True), StructField(columns[\"WEIGHT_KG\"],",
"available :return: dataframe from input JSON file \"\"\" logger = logging.getLogger(\"Ingest\") logger.info(\"Ingesting data\")",
"9:06 AM 1/16/2022 using PyCharm \"\"\" import logging.config from pyspark.sql.types import StructType, StringType,",
"json file and returns a data frame :param spark: Spark session :param file_path:",
"for project bmi_calculator # Created by @<NAME> at 9:06 AM 1/16/2022 using PyCharm",
"Spark session :param file_path: input file path where the data is available :return:",
"= logging.getLogger(\"Ingest\") logger.info(\"Ingesting data\") try: columns = getattr(column_constants, \"column_constants\") schema = StructType([StructField(columns[\"GENDER\"], StringType(),",
"class Ingest: logging.config.fileConfig(\"config/logging.conf\") def __init__(self, spark): self.spark = spark def ingest_json_data(self, file_path): \"\"\"",
"IntegerType(), True), StructField(columns[\"WEIGHT_KG\"], IntegerType(), True)]) input_file = self.spark.read.option(\"multiLine\", \"true\").schema(schema).json(file_path) return input_file.persist() except Exception",
"IntegerType(), True)]) input_file = self.spark.read.option(\"multiLine\", \"true\").schema(schema).json(file_path) return input_file.persist() except Exception as exp: logger.error(\"An",
"the data is available :return: dataframe from input JSON file \"\"\" logger =",
"# Created by @<NAME> at 9:06 AM 1/16/2022 using PyCharm \"\"\" import logging.config",
"1/16/2022 using PyCharm \"\"\" import logging.config from pyspark.sql.types import StructType, StringType, StructField, IntegerType",
"src.utils import column_constants class Ingest: logging.config.fileConfig(\"config/logging.conf\") def __init__(self, spark): self.spark = spark def",
"data\") try: columns = getattr(column_constants, \"column_constants\") schema = StructType([StructField(columns[\"GENDER\"], StringType(), True), StructField(columns[\"HEIGHT_CM\"], IntegerType(),",
"\"column_constants\") schema = StructType([StructField(columns[\"GENDER\"], StringType(), True), StructField(columns[\"HEIGHT_CM\"], IntegerType(), True), StructField(columns[\"WEIGHT_KG\"], IntegerType(), True)]) input_file",
"function reads the json file and returns a data frame :param spark: Spark",
"input_file = self.spark.read.option(\"multiLine\", \"true\").schema(schema).json(file_path) return input_file.persist() except Exception as exp: logger.error(\"An error occured",
"StructField(columns[\"WEIGHT_KG\"], IntegerType(), True)]) input_file = self.spark.read.option(\"multiLine\", \"true\").schema(schema).json(file_path) return input_file.persist() except Exception as exp:",
"input_file.persist() except Exception as exp: logger.error(\"An error occured while ingesting data > \"",
"StructType([StructField(columns[\"GENDER\"], StringType(), True), StructField(columns[\"HEIGHT_CM\"], IntegerType(), True), StructField(columns[\"WEIGHT_KG\"], IntegerType(), True)]) input_file = self.spark.read.option(\"multiLine\", \"true\").schema(schema).json(file_path)",
"logging.config from pyspark.sql.types import StructType, StringType, StructField, IntegerType from src.utils import column_constants class",
"frame :param spark: Spark session :param file_path: input file path where the data",
"logger.info(\"Ingesting data\") try: columns = getattr(column_constants, \"column_constants\") schema = StructType([StructField(columns[\"GENDER\"], StringType(), True), StructField(columns[\"HEIGHT_CM\"],",
"dataframe from input JSON file \"\"\" logger = logging.getLogger(\"Ingest\") logger.info(\"Ingesting data\") try: columns",
"ingest.py for project bmi_calculator # Created by @<NAME> at 9:06 AM 1/16/2022 using",
"reads the json file and returns a data frame :param spark: Spark session",
"logging.config.fileConfig(\"config/logging.conf\") def __init__(self, spark): self.spark = spark def ingest_json_data(self, file_path): \"\"\" This function",
"getattr(column_constants, \"column_constants\") schema = StructType([StructField(columns[\"GENDER\"], StringType(), True), StructField(columns[\"HEIGHT_CM\"], IntegerType(), True), StructField(columns[\"WEIGHT_KG\"], IntegerType(), True)])",
"Exception as exp: logger.error(\"An error occured while ingesting data > \" + str(exp))",
"= getattr(column_constants, \"column_constants\") schema = StructType([StructField(columns[\"GENDER\"], StringType(), True), StructField(columns[\"HEIGHT_CM\"], IntegerType(), True), StructField(columns[\"WEIGHT_KG\"], IntegerType(),",
"the json file and returns a data frame :param spark: Spark session :param",
"ingest_json_data(self, file_path): \"\"\" This function reads the json file and returns a data",
"file_path: input file path where the data is available :return: dataframe from input",
"= StructType([StructField(columns[\"GENDER\"], StringType(), True), StructField(columns[\"HEIGHT_CM\"], IntegerType(), True), StructField(columns[\"WEIGHT_KG\"], IntegerType(), True)]) input_file = self.spark.read.option(\"multiLine\",",
"at 9:06 AM 1/16/2022 using PyCharm \"\"\" import logging.config from pyspark.sql.types import StructType,",
"path where the data is available :return: dataframe from input JSON file \"\"\"",
"session :param file_path: input file path where the data is available :return: dataframe",
"import StructType, StringType, StructField, IntegerType from src.utils import column_constants class Ingest: logging.config.fileConfig(\"config/logging.conf\") def",
"IntegerType from src.utils import column_constants class Ingest: logging.config.fileConfig(\"config/logging.conf\") def __init__(self, spark): self.spark =",
"# ingest.py for project bmi_calculator # Created by @<NAME> at 9:06 AM 1/16/2022",
"and returns a data frame :param spark: Spark session :param file_path: input file",
"column_constants class Ingest: logging.config.fileConfig(\"config/logging.conf\") def __init__(self, spark): self.spark = spark def ingest_json_data(self, file_path):",
"def ingest_json_data(self, file_path): \"\"\" This function reads the json file and returns a",
"This function reads the json file and returns a data frame :param spark:",
"file path where the data is available :return: dataframe from input JSON file",
"JSON file \"\"\" logger = logging.getLogger(\"Ingest\") logger.info(\"Ingesting data\") try: columns = getattr(column_constants, \"column_constants\")",
":param spark: Spark session :param file_path: input file path where the data is",
"\"\"\" logger = logging.getLogger(\"Ingest\") logger.info(\"Ingesting data\") try: columns = getattr(column_constants, \"column_constants\") schema =",
":return: dataframe from input JSON file \"\"\" logger = logging.getLogger(\"Ingest\") logger.info(\"Ingesting data\") try:",
"Created by @<NAME> at 9:06 AM 1/16/2022 using PyCharm \"\"\" import logging.config from",
"\"true\").schema(schema).json(file_path) return input_file.persist() except Exception as exp: logger.error(\"An error occured while ingesting data",
"returns a data frame :param spark: Spark session :param file_path: input file path",
"a data frame :param spark: Spark session :param file_path: input file path where",
"__init__(self, spark): self.spark = spark def ingest_json_data(self, file_path): \"\"\" This function reads the",
"StringType(), True), StructField(columns[\"HEIGHT_CM\"], IntegerType(), True), StructField(columns[\"WEIGHT_KG\"], IntegerType(), True)]) input_file = self.spark.read.option(\"multiLine\", \"true\").schema(schema).json(file_path) return",
"= spark def ingest_json_data(self, file_path): \"\"\" This function reads the json file and",
"from src.utils import column_constants class Ingest: logging.config.fileConfig(\"config/logging.conf\") def __init__(self, spark): self.spark = spark"
] |
[
"self.handler # ValueError becomes exceptions.Gone handler.kwargs = {'id': 'string'} self.assertRaises( exceptions.Gone, handler.get_data_item, )",
"users = mommy.make(User, 10) def test_get_data_item_single_field_selection(self): handler = self.handler self.assertEquals( handler.get_data_item(), None, )",
"handler.get_data_item(), User.objects.get(id=1), ) def test_get_data_item_double_field_selection(self): handler = self.handler # Item selection based on",
"self.handler # ObjectDoesNotExist becomes exceptions.Gone handler.kwargs = {'id': 1000} self.assertRaises( exceptions.Gone, handler.get_data_item, )",
"request, *args, **kwargs): # Mimicking the initialization of the handler instance handler.request =",
"Create some model instances users = mommy.make(User, 10) def test_get_working_set(self): # Testing ``ModelHandler.get_working_set``",
"self.assertEquals( handler.get_data(), user, ) def test_get_data_gone(self): handler = self.handler handler.kwargs = {'id': 1000}",
"= User.objects.get(id=1) handler.kwargs = {'id': user.id, 'first_name': user.first_name} self.assertEquals( handler.get_data(), user, ) def",
"{'id': {'key': 'value'}} self.assertRaises( exceptions.Gone, handler.get_data_item, ) class TestModelHandlerGetDataSet(TestCase): def setUp(self): request =",
"class TestModelHandlerGetData(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/') handler = init_handler(ModelHandler(), request) handler.model =",
"handler.kwargs = kwargs return handler class TestModelHandlerGetDataItem(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/') handler",
"handler = self.handler user = User.objects.get(id=1) handler.kwargs = {'id': user.id, 'first_name': user.first_name} self.assertEquals(",
"{'id': 1000} self.assertRaises( exceptions.Gone, handler.get_data, ) def test_get_data_method_not_allowed(self): # Plural DELETE method, raises",
"ValueError becomes exceptions.Gone handler.kwargs = {'id': 'string'} self.assertRaises( exceptions.Gone, handler.get_data_item, ) def test_get_data_item_type_error(self):",
"handler # Create some model instances users = mommy.make(User, 10) def test_get_data_item_single_field_selection(self): handler",
"selection based on 1 field handler.kwargs = {'id':1} self.assertEquals( handler.get_data_item(), User.objects.get(id=1), ) def",
"handler.kwargs = {'id': user.id, 'first_name': user.first_name} self.assertEquals( handler.get_data(), user, ) def test_get_data_gone(self): handler",
"test_get_data_method_not_allowed(self): # Plural DELETE method, raises ``MethodNotAllowed`` exception handler = self.handler handler.request =",
"return handler class TestModelHandlerGetDataItem(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/') handler = init_handler(ModelHandler(), request)",
"import mommy def init_handler(handler, request, *args, **kwargs): # Mimicking the initialization of the",
"handler.get_data_item, ) def test_get_data_item_type_error(self): handler = self.handler # TypeError becomes exceptions.Gone handler.kwargs =",
"exceptions.Gone handler.kwargs = {'id': {'key': 'value'}} self.assertRaises( exceptions.Gone, handler.get_data_item, ) class TestModelHandlerGetDataSet(TestCase): def",
") class TestModelHandlerGetDataSet(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/') handler = init_handler(ModelHandler(), request) handler.model",
"methods. \"\"\" from firestone.handlers import BaseHandler from firestone.handlers import ModelHandler from firestone import",
"TestModelHandlerGetData(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/') handler = init_handler(ModelHandler(), request) handler.model = User",
"``get_data_item``, ``get_data_set`` and ``get_working_set`` handler methods. \"\"\" from firestone.handlers import BaseHandler from firestone.handlers",
"``ModelHandler.get_data`` handler = self.handler self.assertItemsEqual( handler.get_data(), User.objects.all(), ) def test_get_data_single_field_selection(self): handler = self.handler",
"10) def test_get_working_set(self): # Testing ``ModelHandler.get_working_set`` handler = self.handler self.assertItemsEqual( handler.get_working_set(), User.objects.all(), )",
"from django.test import RequestFactory from django.contrib.auth.models import User from model_mommy import mommy def",
"self.assertEquals( handler.get_data_item(), user, ) def test_get_data_item_object_does_not_exist(self): handler = self.handler # ObjectDoesNotExist becomes exceptions.Gone",
"class TestModelHandlerGetDataItem(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/') handler = init_handler(ModelHandler(), request) handler.model =",
"= mommy.make(User, 10) def test_get_data(self): # Testing ``ModelHandler.get_data`` handler = self.handler self.assertItemsEqual( handler.get_data(),",
"mommy.make(User, 10) def test_get_data(self): # Testing ``ModelHandler.get_data`` handler = self.handler self.assertItemsEqual( handler.get_data(), User.objects.all(),",
"self.handler self.assertItemsEqual( handler.get_data_set(), User.objects.all(), ) class TestModelHandlerGetWorkingSet(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/') handler",
"10) def test_get_data(self): # Testing ``ModelHandler.get_data`` handler = self.handler self.assertItemsEqual( handler.get_data(), User.objects.all(), )",
"self.assertEquals( handler.get_data_item(), User.objects.get(id=1), ) def test_get_data_item_double_field_selection(self): handler = self.handler # Item selection based",
"mommy.make(User, 10) def test_get_data_item_single_field_selection(self): handler = self.handler self.assertEquals( handler.get_data_item(), None, ) # Item",
"the initialization of the handler instance handler.request = request handler.args = args handler.kwargs",
"handler.get_working_set(), User.objects.all(), ) class TestModelHandlerGetData(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/') handler = init_handler(ModelHandler(),",
"some model instances users = mommy.make(User, 10) def test_get_working_set(self): # Testing ``ModelHandler.get_working_set`` handler",
"handler = self.handler # ValueError becomes exceptions.Gone handler.kwargs = {'id': 'string'} self.assertRaises( exceptions.Gone,",
"handler.kwargs = {'id': 'string'} self.assertRaises( exceptions.Gone, handler.get_data_item, ) def test_get_data_item_type_error(self): handler = self.handler",
"RequestFactory from django.contrib.auth.models import User from model_mommy import mommy def init_handler(handler, request, *args,",
"self.assertRaises( exceptions.Gone, handler.get_data_item, ) def test_get_data_item_value_error(self): handler = self.handler # ValueError becomes exceptions.Gone",
"= self.handler # ObjectDoesNotExist becomes exceptions.Gone handler.kwargs = {'id': 1000} self.assertRaises( exceptions.Gone, handler.get_data_item,",
"TestModelHandlerGetWorkingSet(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/') handler = init_handler(ModelHandler(), request) handler.model = User",
"self.handler self.assertEquals( handler.get_data_item(), None, ) # Item selection based on 1 field handler.kwargs",
"**kwargs): # Mimicking the initialization of the handler instance handler.request = request handler.args",
"{'id': 1} self.assertEquals( handler.get_data(), User.objects.get(id=1), ) def test_get_data_double_field_selection(self): handler = self.handler user =",
"handler.args = args handler.kwargs = kwargs return handler class TestModelHandlerGetDataItem(TestCase): def setUp(self): request",
"on 2 fields user = User.objects.get(id=1) handler.kwargs = {'id': user.id, 'first_name': user.first_name} self.assertEquals(",
"instances users = mommy.make(User, 10) def test_get_data_set(self): # Testing ``ModelHandler.get_data_set`` handler = self.handler",
"init_handler(ModelHandler(), request) handler.model = User self.handler = handler # Create some model instances",
"user, ) def test_get_data_gone(self): handler = self.handler handler.kwargs = {'id': 1000} self.assertRaises( exceptions.Gone,",
"user.id, 'first_name': user.first_name} self.assertEquals( handler.get_data(), user, ) def test_get_data_gone(self): handler = self.handler handler.kwargs",
"Mimicking the initialization of the handler instance handler.request = request handler.args = args",
"self.assertItemsEqual( handler.get_data(), User.objects.all(), ) def test_get_data_single_field_selection(self): handler = self.handler handler.kwargs = {'id': 1}",
"self.handler self.assertItemsEqual( handler.get_working_set(), User.objects.all(), ) class TestModelHandlerGetData(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/') handler",
"handler = self.handler # Item selection based on 2 fields user = User.objects.get(id=1)",
"= {'id':1} self.assertEquals( handler.get_data_item(), User.objects.get(id=1), ) def test_get_data_item_double_field_selection(self): handler = self.handler # Item",
"django.contrib.auth.models import User from model_mommy import mommy def init_handler(handler, request, *args, **kwargs): #",
"exceptions.Gone, handler.get_data, ) def test_get_data_method_not_allowed(self): # Plural DELETE method, raises ``MethodNotAllowed`` exception handler",
"This module tests the ``get_data``, ``get_data_item``, ``get_data_set`` and ``get_working_set`` handler methods. \"\"\" from",
"handler instance handler.request = request handler.args = args handler.kwargs = kwargs return handler",
"handler.get_data_item(), None, ) # Item selection based on 1 field handler.kwargs = {'id':1}",
"self.handler self.assertItemsEqual( handler.get_data(), User.objects.all(), ) def test_get_data_single_field_selection(self): handler = self.handler handler.kwargs = {'id':",
"exceptions from django.test import TestCase from django.test import RequestFactory from django.contrib.auth.models import User",
"exceptions.Gone handler.kwargs = {'id': 'string'} self.assertRaises( exceptions.Gone, handler.get_data_item, ) def test_get_data_item_type_error(self): handler =",
") class TestModelHandlerGetWorkingSet(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/') handler = init_handler(ModelHandler(), request) handler.model",
"TestModelHandlerGetDataSet(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/') handler = init_handler(ModelHandler(), request) handler.model = User",
"None, ) # Item selection based on 1 field handler.kwargs = {'id':1} self.assertEquals(",
"based on 1 field handler.kwargs = {'id':1} self.assertEquals( handler.get_data_item(), User.objects.get(id=1), ) def test_get_data_item_double_field_selection(self):",
"mommy.make(User, 10) def test_get_working_set(self): # Testing ``ModelHandler.get_working_set`` handler = self.handler self.assertItemsEqual( handler.get_working_set(), User.objects.all(),",
"and ``get_working_set`` handler methods. \"\"\" from firestone.handlers import BaseHandler from firestone.handlers import ModelHandler",
"self.assertItemsEqual( handler.get_working_set(), User.objects.all(), ) class TestModelHandlerGetData(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/') handler =",
"instances users = mommy.make(User, 10) def test_get_working_set(self): # Testing ``ModelHandler.get_working_set`` handler = self.handler",
"def init_handler(handler, request, *args, **kwargs): # Mimicking the initialization of the handler instance",
"10) def test_get_data_item_single_field_selection(self): handler = self.handler self.assertEquals( handler.get_data_item(), None, ) # Item selection",
"handler.get_data(), User.objects.all(), ) def test_get_data_single_field_selection(self): handler = self.handler handler.kwargs = {'id': 1} self.assertEquals(",
"10) def test_get_data_set(self): # Testing ``ModelHandler.get_data_set`` handler = self.handler self.assertItemsEqual( handler.get_data_set(), User.objects.all(), )",
"{'id': 1000} self.assertRaises( exceptions.Gone, handler.get_data_item, ) def test_get_data_item_value_error(self): handler = self.handler # ValueError",
"def test_get_data_item_double_field_selection(self): handler = self.handler # Item selection based on 2 fields user",
"# Testing ``ModelHandler.get_working_set`` handler = self.handler self.assertItemsEqual( handler.get_working_set(), User.objects.all(), ) class TestModelHandlerGetData(TestCase): def",
"User self.handler = handler # Create some model instances users = mommy.make(User, 10)",
"def test_get_data_item_type_error(self): handler = self.handler # TypeError becomes exceptions.Gone handler.kwargs = {'id': {'key':",
"TypeError becomes exceptions.Gone handler.kwargs = {'id': {'key': 'value'}} self.assertRaises( exceptions.Gone, handler.get_data_item, ) class",
"Plural DELETE method, raises ``MethodNotAllowed`` exception handler = self.handler handler.request = RequestFactory().delete('/') self.assertRaises(",
"def test_get_working_set(self): # Testing ``ModelHandler.get_working_set`` handler = self.handler self.assertItemsEqual( handler.get_working_set(), User.objects.all(), ) class",
"# Plural DELETE method, raises ``MethodNotAllowed`` exception handler = self.handler handler.request = RequestFactory().delete('/')",
"from django.contrib.auth.models import User from model_mommy import mommy def init_handler(handler, request, *args, **kwargs):",
"# Item selection based on 1 field handler.kwargs = {'id':1} self.assertEquals( handler.get_data_item(), User.objects.get(id=1),",
"firestone import exceptions from django.test import TestCase from django.test import RequestFactory from django.contrib.auth.models",
"= self.handler self.assertItemsEqual( handler.get_data(), User.objects.all(), ) def test_get_data_single_field_selection(self): handler = self.handler handler.kwargs =",
"def test_get_data(self): # Testing ``ModelHandler.get_data`` handler = self.handler self.assertItemsEqual( handler.get_data(), User.objects.all(), ) def",
"= {'id': user.id, 'first_name': user.first_name} self.assertEquals( handler.get_data_item(), user, ) def test_get_data_item_object_does_not_exist(self): handler =",
"def setUp(self): request = RequestFactory().get('whateverpath/') handler = init_handler(ModelHandler(), request) handler.model = User self.handler",
"handler = self.handler self.assertItemsEqual( handler.get_data_set(), User.objects.all(), ) class TestModelHandlerGetWorkingSet(TestCase): def setUp(self): request =",
"kwargs return handler class TestModelHandlerGetDataItem(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/') handler = init_handler(ModelHandler(),",
"def test_get_data_item_object_does_not_exist(self): handler = self.handler # ObjectDoesNotExist becomes exceptions.Gone handler.kwargs = {'id': 1000}",
"self.assertEquals( handler.get_data_item(), None, ) # Item selection based on 1 field handler.kwargs =",
"model instances users = mommy.make(User, 10) def test_get_data_set(self): # Testing ``ModelHandler.get_data_set`` handler =",
"# Mimicking the initialization of the handler instance handler.request = request handler.args =",
"test_get_data_item_value_error(self): handler = self.handler # ValueError becomes exceptions.Gone handler.kwargs = {'id': 'string'} self.assertRaises(",
"import User from model_mommy import mommy def init_handler(handler, request, *args, **kwargs): # Mimicking",
"handler.get_data(), user, ) def test_get_data_gone(self): handler = self.handler handler.kwargs = {'id': 1000} self.assertRaises(",
"= args handler.kwargs = kwargs return handler class TestModelHandlerGetDataItem(TestCase): def setUp(self): request =",
"users = mommy.make(User, 10) def test_get_data_set(self): # Testing ``ModelHandler.get_data_set`` handler = self.handler self.assertItemsEqual(",
"= handler # Create some model instances users = mommy.make(User, 10) def test_get_data(self):",
"2 fields user = User.objects.get(id=1) handler.kwargs = {'id': user.id, 'first_name': user.first_name} self.assertEquals( handler.get_data_item(),",
"from firestone import exceptions from django.test import TestCase from django.test import RequestFactory from",
"\"\"\" This module tests the ``get_data``, ``get_data_item``, ``get_data_set`` and ``get_working_set`` handler methods. \"\"\"",
"= init_handler(ModelHandler(), request) handler.model = User self.handler = handler # Create some model",
"handler = self.handler handler.kwargs = {'id': 1000} self.assertRaises( exceptions.Gone, handler.get_data, ) def test_get_data_method_not_allowed(self):",
"TestCase from django.test import RequestFactory from django.contrib.auth.models import User from model_mommy import mommy",
"selection based on 2 fields user = User.objects.get(id=1) handler.kwargs = {'id': user.id, 'first_name':",
"method, raises ``MethodNotAllowed`` exception handler = self.handler handler.request = RequestFactory().delete('/') self.assertRaises( exceptions.MethodNotAllowed, handler.get_data,",
"# Testing ``ModelHandler.get_data_set`` handler = self.handler self.assertItemsEqual( handler.get_data_set(), User.objects.all(), ) class TestModelHandlerGetWorkingSet(TestCase): def",
"Create some model instances users = mommy.make(User, 10) def test_get_data_set(self): # Testing ``ModelHandler.get_data_set``",
"users = mommy.make(User, 10) def test_get_data(self): # Testing ``ModelHandler.get_data`` handler = self.handler self.assertItemsEqual(",
"becomes exceptions.Gone handler.kwargs = {'id': 1000} self.assertRaises( exceptions.Gone, handler.get_data_item, ) def test_get_data_item_value_error(self): handler",
"Testing ``ModelHandler.get_data`` handler = self.handler self.assertItemsEqual( handler.get_data(), User.objects.all(), ) def test_get_data_single_field_selection(self): handler =",
"= User.objects.get(id=1) handler.kwargs = {'id': user.id, 'first_name': user.first_name} self.assertEquals( handler.get_data_item(), user, ) def",
"test_get_data_item_object_does_not_exist(self): handler = self.handler # ObjectDoesNotExist becomes exceptions.Gone handler.kwargs = {'id': 1000} self.assertRaises(",
"User.objects.all(), ) def test_get_data_single_field_selection(self): handler = self.handler handler.kwargs = {'id': 1} self.assertEquals( handler.get_data(),",
"handler.kwargs = {'id': 1000} self.assertRaises( exceptions.Gone, handler.get_data_item, ) def test_get_data_item_value_error(self): handler = self.handler",
"``get_data_set`` and ``get_working_set`` handler methods. \"\"\" from firestone.handlers import BaseHandler from firestone.handlers import",
"= handler # Create some model instances users = mommy.make(User, 10) def test_get_working_set(self):",
"Create some model instances users = mommy.make(User, 10) def test_get_data(self): # Testing ``ModelHandler.get_data``",
"= self.handler handler.kwargs = {'id': 1000} self.assertRaises( exceptions.Gone, handler.get_data, ) def test_get_data_method_not_allowed(self): #",
"# Create some model instances users = mommy.make(User, 10) def test_get_data_set(self): # Testing",
"Item selection based on 1 field handler.kwargs = {'id':1} self.assertEquals( handler.get_data_item(), User.objects.get(id=1), )",
"based on 2 fields user = User.objects.get(id=1) handler.kwargs = {'id': user.id, 'first_name': user.first_name}",
"from model_mommy import mommy def init_handler(handler, request, *args, **kwargs): # Mimicking the initialization",
"= self.handler # TypeError becomes exceptions.Gone handler.kwargs = {'id': {'key': 'value'}} self.assertRaises( exceptions.Gone,",
"the handler instance handler.request = request handler.args = args handler.kwargs = kwargs return",
"Item selection based on 2 fields user = User.objects.get(id=1) handler.kwargs = {'id': user.id,",
"some model instances users = mommy.make(User, 10) def test_get_data_item_single_field_selection(self): handler = self.handler self.assertEquals(",
"handler.get_data_item, ) class TestModelHandlerGetDataSet(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/') handler = init_handler(ModelHandler(), request)",
"request handler.args = args handler.kwargs = kwargs return handler class TestModelHandlerGetDataItem(TestCase): def setUp(self):",
"{'id': user.id, 'first_name': user.first_name} self.assertEquals( handler.get_data(), user, ) def test_get_data_gone(self): handler = self.handler",
"model instances users = mommy.make(User, 10) def test_get_data(self): # Testing ``ModelHandler.get_data`` handler =",
") def test_get_data_double_field_selection(self): handler = self.handler user = User.objects.get(id=1) handler.kwargs = {'id': user.id,",
"= request handler.args = args handler.kwargs = kwargs return handler class TestModelHandlerGetDataItem(TestCase): def",
"handler.request = request handler.args = args handler.kwargs = kwargs return handler class TestModelHandlerGetDataItem(TestCase):",
"from django.test import TestCase from django.test import RequestFactory from django.contrib.auth.models import User from",
"becomes exceptions.Gone handler.kwargs = {'id': {'key': 'value'}} self.assertRaises( exceptions.Gone, handler.get_data_item, ) class TestModelHandlerGetDataSet(TestCase):",
"def test_get_data_double_field_selection(self): handler = self.handler user = User.objects.get(id=1) handler.kwargs = {'id': user.id, 'first_name':",
"def test_get_data_method_not_allowed(self): # Plural DELETE method, raises ``MethodNotAllowed`` exception handler = self.handler handler.request",
") def test_get_data_item_double_field_selection(self): handler = self.handler # Item selection based on 2 fields",
"handler.get_data, ) def test_get_data_method_not_allowed(self): # Plural DELETE method, raises ``MethodNotAllowed`` exception handler =",
"= self.handler handler.kwargs = {'id': 1} self.assertEquals( handler.get_data(), User.objects.get(id=1), ) def test_get_data_double_field_selection(self): handler",
"{'id': user.id, 'first_name': user.first_name} self.assertEquals( handler.get_data_item(), user, ) def test_get_data_item_object_does_not_exist(self): handler = self.handler",
"test_get_data_item_single_field_selection(self): handler = self.handler self.assertEquals( handler.get_data_item(), None, ) # Item selection based on",
"request) handler.model = User self.handler = handler # Create some model instances users",
"fields user = User.objects.get(id=1) handler.kwargs = {'id': user.id, 'first_name': user.first_name} self.assertEquals( handler.get_data_item(), user,",
"self.assertRaises( exceptions.Gone, handler.get_data_item, ) class TestModelHandlerGetDataSet(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/') handler =",
"test_get_data_set(self): # Testing ``ModelHandler.get_data_set`` handler = self.handler self.assertItemsEqual( handler.get_data_set(), User.objects.all(), ) class TestModelHandlerGetWorkingSet(TestCase):",
"{'id':1} self.assertEquals( handler.get_data_item(), User.objects.get(id=1), ) def test_get_data_item_double_field_selection(self): handler = self.handler # Item selection",
"= self.handler self.assertItemsEqual( handler.get_data_set(), User.objects.all(), ) class TestModelHandlerGetWorkingSet(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/')",
"# Item selection based on 2 fields user = User.objects.get(id=1) handler.kwargs = {'id':",
"User from model_mommy import mommy def init_handler(handler, request, *args, **kwargs): # Mimicking the",
"Testing ``ModelHandler.get_working_set`` handler = self.handler self.assertItemsEqual( handler.get_working_set(), User.objects.all(), ) class TestModelHandlerGetData(TestCase): def setUp(self):",
"BaseHandler from firestone.handlers import ModelHandler from firestone import exceptions from django.test import TestCase",
"raises ``MethodNotAllowed`` exception handler = self.handler handler.request = RequestFactory().delete('/') self.assertRaises( exceptions.MethodNotAllowed, handler.get_data, )",
"``get_data``, ``get_data_item``, ``get_data_set`` and ``get_working_set`` handler methods. \"\"\" from firestone.handlers import BaseHandler from",
"``get_working_set`` handler methods. \"\"\" from firestone.handlers import BaseHandler from firestone.handlers import ModelHandler from",
"TestModelHandlerGetDataItem(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/') handler = init_handler(ModelHandler(), request) handler.model = User",
"self.handler # Item selection based on 2 fields user = User.objects.get(id=1) handler.kwargs =",
"setUp(self): request = RequestFactory().get('whateverpath/') handler = init_handler(ModelHandler(), request) handler.model = User self.handler =",
"handler # Create some model instances users = mommy.make(User, 10) def test_get_data(self): #",
") def test_get_data_item_value_error(self): handler = self.handler # ValueError becomes exceptions.Gone handler.kwargs = {'id':",
"= self.handler user = User.objects.get(id=1) handler.kwargs = {'id': user.id, 'first_name': user.first_name} self.assertEquals( handler.get_data(),",
"handler.get_data_set(), User.objects.all(), ) class TestModelHandlerGetWorkingSet(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/') handler = init_handler(ModelHandler(),",
"mommy.make(User, 10) def test_get_data_set(self): # Testing ``ModelHandler.get_data_set`` handler = self.handler self.assertItemsEqual( handler.get_data_set(), User.objects.all(),",
"exceptions.Gone, handler.get_data_item, ) class TestModelHandlerGetDataSet(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/') handler = init_handler(ModelHandler(),",
"class TestModelHandlerGetWorkingSet(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/') handler = init_handler(ModelHandler(), request) handler.model =",
"user, ) def test_get_data_item_object_does_not_exist(self): handler = self.handler # ObjectDoesNotExist becomes exceptions.Gone handler.kwargs =",
"User.objects.all(), ) class TestModelHandlerGetData(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/') handler = init_handler(ModelHandler(), request)",
"{'id': 'string'} self.assertRaises( exceptions.Gone, handler.get_data_item, ) def test_get_data_item_type_error(self): handler = self.handler # TypeError",
"handler.kwargs = {'id':1} self.assertEquals( handler.get_data_item(), User.objects.get(id=1), ) def test_get_data_item_double_field_selection(self): handler = self.handler #",
"self.handler = handler # Create some model instances users = mommy.make(User, 10) def",
"{'key': 'value'}} self.assertRaises( exceptions.Gone, handler.get_data_item, ) class TestModelHandlerGetDataSet(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/')",
"tests the ``get_data``, ``get_data_item``, ``get_data_set`` and ``get_working_set`` handler methods. \"\"\" from firestone.handlers import",
"handler.get_data(), User.objects.get(id=1), ) def test_get_data_double_field_selection(self): handler = self.handler user = User.objects.get(id=1) handler.kwargs =",
"``ModelHandler.get_data_set`` handler = self.handler self.assertItemsEqual( handler.get_data_set(), User.objects.all(), ) class TestModelHandlerGetWorkingSet(TestCase): def setUp(self): request",
"self.handler handler.kwargs = {'id': 1000} self.assertRaises( exceptions.Gone, handler.get_data, ) def test_get_data_method_not_allowed(self): # Plural",
"self.assertEquals( handler.get_data(), User.objects.get(id=1), ) def test_get_data_double_field_selection(self): handler = self.handler user = User.objects.get(id=1) handler.kwargs",
"class TestModelHandlerGetDataSet(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/') handler = init_handler(ModelHandler(), request) handler.model =",
"field handler.kwargs = {'id':1} self.assertEquals( handler.get_data_item(), User.objects.get(id=1), ) def test_get_data_item_double_field_selection(self): handler = self.handler",
"*args, **kwargs): # Mimicking the initialization of the handler instance handler.request = request",
"handler.kwargs = {'id': user.id, 'first_name': user.first_name} self.assertEquals( handler.get_data_item(), user, ) def test_get_data_item_object_does_not_exist(self): handler",
"initialization of the handler instance handler.request = request handler.args = args handler.kwargs =",
"= mommy.make(User, 10) def test_get_working_set(self): # Testing ``ModelHandler.get_working_set`` handler = self.handler self.assertItemsEqual( handler.get_working_set(),",
"= self.handler self.assertItemsEqual( handler.get_working_set(), User.objects.all(), ) class TestModelHandlerGetData(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/')",
"handler methods. \"\"\" from firestone.handlers import BaseHandler from firestone.handlers import ModelHandler from firestone",
"= {'id': 1} self.assertEquals( handler.get_data(), User.objects.get(id=1), ) def test_get_data_double_field_selection(self): handler = self.handler user",
"test_get_data_item_double_field_selection(self): handler = self.handler # Item selection based on 2 fields user =",
"user.first_name} self.assertEquals( handler.get_data(), user, ) def test_get_data_gone(self): handler = self.handler handler.kwargs = {'id':",
"1000} self.assertRaises( exceptions.Gone, handler.get_data_item, ) def test_get_data_item_value_error(self): handler = self.handler # ValueError becomes",
"module tests the ``get_data``, ``get_data_item``, ``get_data_set`` and ``get_working_set`` handler methods. \"\"\" from firestone.handlers",
"init_handler(handler, request, *args, **kwargs): # Mimicking the initialization of the handler instance handler.request",
"the ``get_data``, ``get_data_item``, ``get_data_set`` and ``get_working_set`` handler methods. \"\"\" from firestone.handlers import BaseHandler",
"handler = self.handler self.assertEquals( handler.get_data_item(), None, ) # Item selection based on 1",
"model instances users = mommy.make(User, 10) def test_get_data_item_single_field_selection(self): handler = self.handler self.assertEquals( handler.get_data_item(),",
"import RequestFactory from django.contrib.auth.models import User from model_mommy import mommy def init_handler(handler, request,",
"handler.get_data_item, ) def test_get_data_item_value_error(self): handler = self.handler # ValueError becomes exceptions.Gone handler.kwargs =",
"user = User.objects.get(id=1) handler.kwargs = {'id': user.id, 'first_name': user.first_name} self.assertEquals( handler.get_data(), user, )",
"Create some model instances users = mommy.make(User, 10) def test_get_data_item_single_field_selection(self): handler = self.handler",
"'string'} self.assertRaises( exceptions.Gone, handler.get_data_item, ) def test_get_data_item_type_error(self): handler = self.handler # TypeError becomes",
"1000} self.assertRaises( exceptions.Gone, handler.get_data, ) def test_get_data_method_not_allowed(self): # Plural DELETE method, raises ``MethodNotAllowed``",
"model instances users = mommy.make(User, 10) def test_get_working_set(self): # Testing ``ModelHandler.get_working_set`` handler =",
"Testing ``ModelHandler.get_data_set`` handler = self.handler self.assertItemsEqual( handler.get_data_set(), User.objects.all(), ) class TestModelHandlerGetWorkingSet(TestCase): def setUp(self):",
"# ValueError becomes exceptions.Gone handler.kwargs = {'id': 'string'} self.assertRaises( exceptions.Gone, handler.get_data_item, ) def",
"user.first_name} self.assertEquals( handler.get_data_item(), user, ) def test_get_data_item_object_does_not_exist(self): handler = self.handler # ObjectDoesNotExist becomes",
"= self.handler # Item selection based on 2 fields user = User.objects.get(id=1) handler.kwargs",
"def test_get_data_item_single_field_selection(self): handler = self.handler self.assertEquals( handler.get_data_item(), None, ) # Item selection based",
"DELETE method, raises ``MethodNotAllowed`` exception handler = self.handler handler.request = RequestFactory().delete('/') self.assertRaises( exceptions.MethodNotAllowed,",
"request = RequestFactory().get('whateverpath/') handler = init_handler(ModelHandler(), request) handler.model = User self.handler = handler",
"import ModelHandler from firestone import exceptions from django.test import TestCase from django.test import",
"1} self.assertEquals( handler.get_data(), User.objects.get(id=1), ) def test_get_data_double_field_selection(self): handler = self.handler user = User.objects.get(id=1)",
"def test_get_data_single_field_selection(self): handler = self.handler handler.kwargs = {'id': 1} self.assertEquals( handler.get_data(), User.objects.get(id=1), )",
"handler.model = User self.handler = handler # Create some model instances users =",
"import TestCase from django.test import RequestFactory from django.contrib.auth.models import User from model_mommy import",
"= handler # Create some model instances users = mommy.make(User, 10) def test_get_data_item_single_field_selection(self):",
"= RequestFactory().get('whateverpath/') handler = init_handler(ModelHandler(), request) handler.model = User self.handler = handler #",
"= mommy.make(User, 10) def test_get_data_set(self): # Testing ``ModelHandler.get_data_set`` handler = self.handler self.assertItemsEqual( handler.get_data_set(),",
"exceptions.Gone, handler.get_data_item, ) def test_get_data_item_value_error(self): handler = self.handler # ValueError becomes exceptions.Gone handler.kwargs",
"1 field handler.kwargs = {'id':1} self.assertEquals( handler.get_data_item(), User.objects.get(id=1), ) def test_get_data_item_double_field_selection(self): handler =",
"RequestFactory().get('whateverpath/') handler = init_handler(ModelHandler(), request) handler.model = User self.handler = handler # Create",
"= {'id': 1000} self.assertRaises( exceptions.Gone, handler.get_data, ) def test_get_data_method_not_allowed(self): # Plural DELETE method,",
"self.handler handler.kwargs = {'id': 1} self.assertEquals( handler.get_data(), User.objects.get(id=1), ) def test_get_data_double_field_selection(self): handler =",
"User.objects.get(id=1), ) def test_get_data_item_double_field_selection(self): handler = self.handler # Item selection based on 2",
") class TestModelHandlerGetData(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/') handler = init_handler(ModelHandler(), request) handler.model",
"= handler # Create some model instances users = mommy.make(User, 10) def test_get_data_set(self):",
"= kwargs return handler class TestModelHandlerGetDataItem(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/') handler =",
"mommy def init_handler(handler, request, *args, **kwargs): # Mimicking the initialization of the handler",
"= {'id': 1000} self.assertRaises( exceptions.Gone, handler.get_data_item, ) def test_get_data_item_value_error(self): handler = self.handler #",
"firestone.handlers import ModelHandler from firestone import exceptions from django.test import TestCase from django.test",
"= {'id': user.id, 'first_name': user.first_name} self.assertEquals( handler.get_data(), user, ) def test_get_data_gone(self): handler =",
"handler # Create some model instances users = mommy.make(User, 10) def test_get_data_set(self): #",
"test_get_data_gone(self): handler = self.handler handler.kwargs = {'id': 1000} self.assertRaises( exceptions.Gone, handler.get_data, ) def",
"# Create some model instances users = mommy.make(User, 10) def test_get_data(self): # Testing",
"of the handler instance handler.request = request handler.args = args handler.kwargs = kwargs",
"self.handler user = User.objects.get(id=1) handler.kwargs = {'id': user.id, 'first_name': user.first_name} self.assertEquals( handler.get_data(), user,",
") def test_get_data_single_field_selection(self): handler = self.handler handler.kwargs = {'id': 1} self.assertEquals( handler.get_data(), User.objects.get(id=1),",
"handler.get_data_item(), user, ) def test_get_data_item_object_does_not_exist(self): handler = self.handler # ObjectDoesNotExist becomes exceptions.Gone handler.kwargs",
"test_get_working_set(self): # Testing ``ModelHandler.get_working_set`` handler = self.handler self.assertItemsEqual( handler.get_working_set(), User.objects.all(), ) class TestModelHandlerGetData(TestCase):",
") def test_get_data_item_type_error(self): handler = self.handler # TypeError becomes exceptions.Gone handler.kwargs = {'id':",
"test_get_data_double_field_selection(self): handler = self.handler user = User.objects.get(id=1) handler.kwargs = {'id': user.id, 'first_name': user.first_name}",
"instance handler.request = request handler.args = args handler.kwargs = kwargs return handler class",
"on 1 field handler.kwargs = {'id':1} self.assertEquals( handler.get_data_item(), User.objects.get(id=1), ) def test_get_data_item_double_field_selection(self): handler",
"self.assertRaises( exceptions.Gone, handler.get_data, ) def test_get_data_method_not_allowed(self): # Plural DELETE method, raises ``MethodNotAllowed`` exception",
"'value'}} self.assertRaises( exceptions.Gone, handler.get_data_item, ) class TestModelHandlerGetDataSet(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/') handler",
"<reponame>movermeyer/django-firestone<filename>testproject/testapp/tests/test_handlers_data_control.py \"\"\" This module tests the ``get_data``, ``get_data_item``, ``get_data_set`` and ``get_working_set`` handler methods.",
"handler = init_handler(ModelHandler(), request) handler.model = User self.handler = handler # Create some",
"exceptions.Gone, handler.get_data_item, ) def test_get_data_item_type_error(self): handler = self.handler # TypeError becomes exceptions.Gone handler.kwargs",
") # Item selection based on 1 field handler.kwargs = {'id':1} self.assertEquals( handler.get_data_item(),",
"ModelHandler from firestone import exceptions from django.test import TestCase from django.test import RequestFactory",
"user.id, 'first_name': user.first_name} self.assertEquals( handler.get_data_item(), user, ) def test_get_data_item_object_does_not_exist(self): handler = self.handler #",
"= {'id': {'key': 'value'}} self.assertRaises( exceptions.Gone, handler.get_data_item, ) class TestModelHandlerGetDataSet(TestCase): def setUp(self): request",
"handler class TestModelHandlerGetDataItem(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/') handler = init_handler(ModelHandler(), request) handler.model",
"= mommy.make(User, 10) def test_get_data_item_single_field_selection(self): handler = self.handler self.assertEquals( handler.get_data_item(), None, ) #",
"firestone.handlers import BaseHandler from firestone.handlers import ModelHandler from firestone import exceptions from django.test",
"import BaseHandler from firestone.handlers import ModelHandler from firestone import exceptions from django.test import",
"model_mommy import mommy def init_handler(handler, request, *args, **kwargs): # Mimicking the initialization of",
"ObjectDoesNotExist becomes exceptions.Gone handler.kwargs = {'id': 1000} self.assertRaises( exceptions.Gone, handler.get_data_item, ) def test_get_data_item_value_error(self):",
"User.objects.get(id=1) handler.kwargs = {'id': user.id, 'first_name': user.first_name} self.assertEquals( handler.get_data(), user, ) def test_get_data_gone(self):",
"import exceptions from django.test import TestCase from django.test import RequestFactory from django.contrib.auth.models import",
"# Create some model instances users = mommy.make(User, 10) def test_get_working_set(self): # Testing",
"handler # Create some model instances users = mommy.make(User, 10) def test_get_working_set(self): #",
"some model instances users = mommy.make(User, 10) def test_get_data_set(self): # Testing ``ModelHandler.get_data_set`` handler",
"'first_name': user.first_name} self.assertEquals( handler.get_data(), user, ) def test_get_data_gone(self): handler = self.handler handler.kwargs =",
"= {'id': 'string'} self.assertRaises( exceptions.Gone, handler.get_data_item, ) def test_get_data_item_type_error(self): handler = self.handler #",
"django.test import TestCase from django.test import RequestFactory from django.contrib.auth.models import User from model_mommy",
"= self.handler self.assertEquals( handler.get_data_item(), None, ) # Item selection based on 1 field",
"exceptions.Gone handler.kwargs = {'id': 1000} self.assertRaises( exceptions.Gone, handler.get_data_item, ) def test_get_data_item_value_error(self): handler =",
"handler = self.handler self.assertItemsEqual( handler.get_working_set(), User.objects.all(), ) class TestModelHandlerGetData(TestCase): def setUp(self): request =",
"= self.handler # ValueError becomes exceptions.Gone handler.kwargs = {'id': 'string'} self.assertRaises( exceptions.Gone, handler.get_data_item,",
"instances users = mommy.make(User, 10) def test_get_data_item_single_field_selection(self): handler = self.handler self.assertEquals( handler.get_data_item(), None,",
"users = mommy.make(User, 10) def test_get_working_set(self): # Testing ``ModelHandler.get_working_set`` handler = self.handler self.assertItemsEqual(",
"handler = self.handler self.assertItemsEqual( handler.get_data(), User.objects.all(), ) def test_get_data_single_field_selection(self): handler = self.handler handler.kwargs",
"# Create some model instances users = mommy.make(User, 10) def test_get_data_item_single_field_selection(self): handler =",
"becomes exceptions.Gone handler.kwargs = {'id': 'string'} self.assertRaises( exceptions.Gone, handler.get_data_item, ) def test_get_data_item_type_error(self): handler",
"# Testing ``ModelHandler.get_data`` handler = self.handler self.assertItemsEqual( handler.get_data(), User.objects.all(), ) def test_get_data_single_field_selection(self): handler",
"handler = self.handler handler.kwargs = {'id': 1} self.assertEquals( handler.get_data(), User.objects.get(id=1), ) def test_get_data_double_field_selection(self):",
"``ModelHandler.get_working_set`` handler = self.handler self.assertItemsEqual( handler.get_working_set(), User.objects.all(), ) class TestModelHandlerGetData(TestCase): def setUp(self): request",
"# TypeError becomes exceptions.Gone handler.kwargs = {'id': {'key': 'value'}} self.assertRaises( exceptions.Gone, handler.get_data_item, )",
"self.assertRaises( exceptions.Gone, handler.get_data_item, ) def test_get_data_item_type_error(self): handler = self.handler # TypeError becomes exceptions.Gone",
"= User self.handler = handler # Create some model instances users = mommy.make(User,",
"self.handler # TypeError becomes exceptions.Gone handler.kwargs = {'id': {'key': 'value'}} self.assertRaises( exceptions.Gone, handler.get_data_item,",
"User.objects.all(), ) class TestModelHandlerGetWorkingSet(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/') handler = init_handler(ModelHandler(), request)",
"def test_get_data_set(self): # Testing ``ModelHandler.get_data_set`` handler = self.handler self.assertItemsEqual( handler.get_data_set(), User.objects.all(), ) class",
"instances users = mommy.make(User, 10) def test_get_data(self): # Testing ``ModelHandler.get_data`` handler = self.handler",
"from firestone.handlers import BaseHandler from firestone.handlers import ModelHandler from firestone import exceptions from",
"args handler.kwargs = kwargs return handler class TestModelHandlerGetDataItem(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/')",
"'first_name': user.first_name} self.assertEquals( handler.get_data_item(), user, ) def test_get_data_item_object_does_not_exist(self): handler = self.handler # ObjectDoesNotExist",
"user = User.objects.get(id=1) handler.kwargs = {'id': user.id, 'first_name': user.first_name} self.assertEquals( handler.get_data_item(), user, )",
"User.objects.get(id=1), ) def test_get_data_double_field_selection(self): handler = self.handler user = User.objects.get(id=1) handler.kwargs = {'id':",
"handler = self.handler # TypeError becomes exceptions.Gone handler.kwargs = {'id': {'key': 'value'}} self.assertRaises(",
") def test_get_data_gone(self): handler = self.handler handler.kwargs = {'id': 1000} self.assertRaises( exceptions.Gone, handler.get_data,",
"def test_get_data_gone(self): handler = self.handler handler.kwargs = {'id': 1000} self.assertRaises( exceptions.Gone, handler.get_data, )",
"from firestone.handlers import ModelHandler from firestone import exceptions from django.test import TestCase from",
"test_get_data_item_type_error(self): handler = self.handler # TypeError becomes exceptions.Gone handler.kwargs = {'id': {'key': 'value'}}",
"test_get_data(self): # Testing ``ModelHandler.get_data`` handler = self.handler self.assertItemsEqual( handler.get_data(), User.objects.all(), ) def test_get_data_single_field_selection(self):",
") def test_get_data_method_not_allowed(self): # Plural DELETE method, raises ``MethodNotAllowed`` exception handler = self.handler",
"handler.kwargs = {'id': {'key': 'value'}} self.assertRaises( exceptions.Gone, handler.get_data_item, ) class TestModelHandlerGetDataSet(TestCase): def setUp(self):",
"\"\"\" from firestone.handlers import BaseHandler from firestone.handlers import ModelHandler from firestone import exceptions",
"handler.kwargs = {'id': 1} self.assertEquals( handler.get_data(), User.objects.get(id=1), ) def test_get_data_double_field_selection(self): handler = self.handler",
"handler.kwargs = {'id': 1000} self.assertRaises( exceptions.Gone, handler.get_data, ) def test_get_data_method_not_allowed(self): # Plural DELETE",
"def test_get_data_item_value_error(self): handler = self.handler # ValueError becomes exceptions.Gone handler.kwargs = {'id': 'string'}",
"# ObjectDoesNotExist becomes exceptions.Gone handler.kwargs = {'id': 1000} self.assertRaises( exceptions.Gone, handler.get_data_item, ) def",
"self.assertItemsEqual( handler.get_data_set(), User.objects.all(), ) class TestModelHandlerGetWorkingSet(TestCase): def setUp(self): request = RequestFactory().get('whateverpath/') handler =",
"User.objects.get(id=1) handler.kwargs = {'id': user.id, 'first_name': user.first_name} self.assertEquals( handler.get_data_item(), user, ) def test_get_data_item_object_does_not_exist(self):",
"test_get_data_single_field_selection(self): handler = self.handler handler.kwargs = {'id': 1} self.assertEquals( handler.get_data(), User.objects.get(id=1), ) def",
"django.test import RequestFactory from django.contrib.auth.models import User from model_mommy import mommy def init_handler(handler,",
"some model instances users = mommy.make(User, 10) def test_get_data(self): # Testing ``ModelHandler.get_data`` handler",
") def test_get_data_item_object_does_not_exist(self): handler = self.handler # ObjectDoesNotExist becomes exceptions.Gone handler.kwargs = {'id':",
"handler = self.handler # ObjectDoesNotExist becomes exceptions.Gone handler.kwargs = {'id': 1000} self.assertRaises( exceptions.Gone,"
] |
[
"(str): path+name of the tiff file we want to convert destination_geojson_path (str): path+name",
"\"__main__\": for file in os.listdir(\"asset/tiff\"): print(\"Conversion of \" + file + \" starting",
"(str): path+name of the targeted geojson band (int): tiff band you want to",
"geopandas as gpd def convert_tiff_to_geojson(original_tiff_path, destination_geojson_path, band): \"\"\" Convert tiff file to geojson",
"path+name of the tiff file we want to convert destination_geojson_path (str): path+name of",
"rasterio from rasterio.features import shapes import geopandas as gpd def convert_tiff_to_geojson(original_tiff_path, destination_geojson_path, band):",
"targeted geojson band (int): tiff band you want to handle Returns: Upload the",
"we want to convert destination_geojson_path (str): path+name of the targeted geojson band (int):",
"os.listdir(\"asset/tiff\"): print(\"Conversion of \" + file + \" starting ...\") try: if file.replace(\"tiff\",",
"transform=data[\"transform\"]) ) ) geoms = list(results) gpd_polygonized_raster = gpd.GeoDataFrame.from_features(geoms, crs=c) gpd_polygonized_raster.to_file(destination_geojson_path, driver=\"GeoJSON\") if",
"mask = None with rasterio.open(original_tiff_path) as src: image = src.read(band) # first band",
"1) print(\"Conversion of \" + file + \" successful !\") else: print(\"File already",
"original_tiff_path (str): path+name of the tiff file we want to convert destination_geojson_path (str):",
"of the tiff file we want to convert destination_geojson_path (str): path+name of the",
"GeoDataFrame handling. Args: original_tiff_path (str): path+name of the tiff file we want to",
"to geojson for GeoDataFrame handling. Args: original_tiff_path (str): path+name of the tiff file",
"destination_geojson_path (str): path+name of the targeted geojson band (int): tiff band you want",
"results = ( {\"properties\": {\"property\": v}, \"geometry\": s} for i, (s, v) in",
"file in os.listdir(\"asset/tiff\"): print(\"Conversion of \" + file + \" starting ...\") try:",
"in enumerate( shapes(image, mask=mask, transform=data[\"transform\"]) ) ) geoms = list(results) gpd_polygonized_raster = gpd.GeoDataFrame.from_features(geoms,",
"gpd.GeoDataFrame.from_features(geoms, crs=c) gpd_polygonized_raster.to_file(destination_geojson_path, driver=\"GeoJSON\") if __name__ == \"__main__\": for file in os.listdir(\"asset/tiff\"): print(\"Conversion",
"band): \"\"\" Convert tiff file to geojson for GeoDataFrame handling. Args: original_tiff_path (str):",
"print(\"Conversion of \" + file + \" successful !\") else: print(\"File already converted",
"import rasterio from rasterio.features import shapes import geopandas as gpd def convert_tiff_to_geojson(original_tiff_path, destination_geojson_path,",
"= ( {\"properties\": {\"property\": v}, \"geometry\": s} for i, (s, v) in enumerate(",
"+ file + \" starting ...\") try: if file.replace(\"tiff\", \"geojson\") not in os.listdir(\"asset/geojson\"):",
"= str(data[\"crs\"]) mask = None with rasterio.open(original_tiff_path) as src: image = src.read(band) #",
"handle Returns: Upload the geojson file in the destination. \"\"\" data = rasterio.open(original_tiff_path).meta",
"in the destination. \"\"\" data = rasterio.open(original_tiff_path).meta c = str(data[\"crs\"]) mask = None",
"image = src.read(band) # first band results = ( {\"properties\": {\"property\": v}, \"geometry\":",
"( {\"properties\": {\"property\": v}, \"geometry\": s} for i, (s, v) in enumerate( shapes(image,",
"import shapes import geopandas as gpd def convert_tiff_to_geojson(original_tiff_path, destination_geojson_path, band): \"\"\" Convert tiff",
"(s, v) in enumerate( shapes(image, mask=mask, transform=data[\"transform\"]) ) ) geoms = list(results) gpd_polygonized_raster",
"+ \"asset/tiff/\" + file geojson_path = tiff_path.replace(\"tiff\", \"geojson\") convert_tiff_to_geojson(tiff_path, geojson_path, 1) print(\"Conversion of",
"print(\"Conversion of \" + file + \" starting ...\") try: if file.replace(\"tiff\", \"geojson\")",
"from rasterio.features import shapes import geopandas as gpd def convert_tiff_to_geojson(original_tiff_path, destination_geojson_path, band): \"\"\"",
"in os.listdir(\"asset/tiff\"): print(\"Conversion of \" + file + \" starting ...\") try: if",
"= list(results) gpd_polygonized_raster = gpd.GeoDataFrame.from_features(geoms, crs=c) gpd_polygonized_raster.to_file(destination_geojson_path, driver=\"GeoJSON\") if __name__ == \"__main__\": for",
"the tiff file we want to convert destination_geojson_path (str): path+name of the targeted",
") ) geoms = list(results) gpd_polygonized_raster = gpd.GeoDataFrame.from_features(geoms, crs=c) gpd_polygonized_raster.to_file(destination_geojson_path, driver=\"GeoJSON\") if __name__",
"+ file geojson_path = tiff_path.replace(\"tiff\", \"geojson\") convert_tiff_to_geojson(tiff_path, geojson_path, 1) print(\"Conversion of \" +",
"of the targeted geojson band (int): tiff band you want to handle Returns:",
"!\") else: print(\"File already converted in geojson !\") except Exception as e: print(\"Couldn't",
"band (int): tiff band you want to handle Returns: Upload the geojson file",
"geojson_path, 1) print(\"Conversion of \" + file + \" successful !\") else: print(\"File",
"already converted in geojson !\") except Exception as e: print(\"Couldn't convert file \"",
"\" + file + \" successful !\") else: print(\"File already converted in geojson",
"str(data[\"crs\"]) mask = None with rasterio.open(original_tiff_path) as src: image = src.read(band) # first",
"s} for i, (s, v) in enumerate( shapes(image, mask=mask, transform=data[\"transform\"]) ) ) geoms",
"if __name__ == \"__main__\": for file in os.listdir(\"asset/tiff\"): print(\"Conversion of \" + file",
"tiff_path = os.getcwd() + \"asset/tiff/\" + file geojson_path = tiff_path.replace(\"tiff\", \"geojson\") convert_tiff_to_geojson(tiff_path, geojson_path,",
"list(results) gpd_polygonized_raster = gpd.GeoDataFrame.from_features(geoms, crs=c) gpd_polygonized_raster.to_file(destination_geojson_path, driver=\"GeoJSON\") if __name__ == \"__main__\": for file",
"os.getcwd() + \"asset/tiff/\" + file geojson_path = tiff_path.replace(\"tiff\", \"geojson\") convert_tiff_to_geojson(tiff_path, geojson_path, 1) print(\"Conversion",
"if file.replace(\"tiff\", \"geojson\") not in os.listdir(\"asset/geojson\"): tiff_path = os.getcwd() + \"asset/tiff/\" + file",
"= gpd.GeoDataFrame.from_features(geoms, crs=c) gpd_polygonized_raster.to_file(destination_geojson_path, driver=\"GeoJSON\") if __name__ == \"__main__\": for file in os.listdir(\"asset/tiff\"):",
"with rasterio.open(original_tiff_path) as src: image = src.read(band) # first band results = (",
"else: print(\"File already converted in geojson !\") except Exception as e: print(\"Couldn't convert",
"\" starting ...\") try: if file.replace(\"tiff\", \"geojson\") not in os.listdir(\"asset/geojson\"): tiff_path = os.getcwd()",
"first band results = ( {\"properties\": {\"property\": v}, \"geometry\": s} for i, (s,",
"gpd_polygonized_raster.to_file(destination_geojson_path, driver=\"GeoJSON\") if __name__ == \"__main__\": for file in os.listdir(\"asset/tiff\"): print(\"Conversion of \"",
"as gpd def convert_tiff_to_geojson(original_tiff_path, destination_geojson_path, band): \"\"\" Convert tiff file to geojson for",
"you want to handle Returns: Upload the geojson file in the destination. \"\"\"",
"(int): tiff band you want to handle Returns: Upload the geojson file in",
"import os import rasterio from rasterio.features import shapes import geopandas as gpd def",
"Convert tiff file to geojson for GeoDataFrame handling. Args: original_tiff_path (str): path+name of",
"handling. Args: original_tiff_path (str): path+name of the tiff file we want to convert",
"destination. \"\"\" data = rasterio.open(original_tiff_path).meta c = str(data[\"crs\"]) mask = None with rasterio.open(original_tiff_path)",
"for file in os.listdir(\"asset/tiff\"): print(\"Conversion of \" + file + \" starting ...\")",
"want to convert destination_geojson_path (str): path+name of the targeted geojson band (int): tiff",
"+ \" starting ...\") try: if file.replace(\"tiff\", \"geojson\") not in os.listdir(\"asset/geojson\"): tiff_path =",
"as e: print(\"Couldn't convert file \" + file + \", exception :\" +",
"tiff file to geojson for GeoDataFrame handling. Args: original_tiff_path (str): path+name of the",
"Exception as e: print(\"Couldn't convert file \" + file + \", exception :\"",
"starting ...\") try: if file.replace(\"tiff\", \"geojson\") not in os.listdir(\"asset/geojson\"): tiff_path = os.getcwd() +",
"shapes(image, mask=mask, transform=data[\"transform\"]) ) ) geoms = list(results) gpd_polygonized_raster = gpd.GeoDataFrame.from_features(geoms, crs=c) gpd_polygonized_raster.to_file(destination_geojson_path,",
"v) in enumerate( shapes(image, mask=mask, transform=data[\"transform\"]) ) ) geoms = list(results) gpd_polygonized_raster =",
"Upload the geojson file in the destination. \"\"\" data = rasterio.open(original_tiff_path).meta c =",
"shapes import geopandas as gpd def convert_tiff_to_geojson(original_tiff_path, destination_geojson_path, band): \"\"\" Convert tiff file",
"file geojson_path = tiff_path.replace(\"tiff\", \"geojson\") convert_tiff_to_geojson(tiff_path, geojson_path, 1) print(\"Conversion of \" + file",
"file + \" successful !\") else: print(\"File already converted in geojson !\") except",
"= src.read(band) # first band results = ( {\"properties\": {\"property\": v}, \"geometry\": s}",
"mask=mask, transform=data[\"transform\"]) ) ) geoms = list(results) gpd_polygonized_raster = gpd.GeoDataFrame.from_features(geoms, crs=c) gpd_polygonized_raster.to_file(destination_geojson_path, driver=\"GeoJSON\")",
"crs=c) gpd_polygonized_raster.to_file(destination_geojson_path, driver=\"GeoJSON\") if __name__ == \"__main__\": for file in os.listdir(\"asset/tiff\"): print(\"Conversion of",
"Returns: Upload the geojson file in the destination. \"\"\" data = rasterio.open(original_tiff_path).meta c",
"file.replace(\"tiff\", \"geojson\") not in os.listdir(\"asset/geojson\"): tiff_path = os.getcwd() + \"asset/tiff/\" + file geojson_path",
"os import rasterio from rasterio.features import shapes import geopandas as gpd def convert_tiff_to_geojson(original_tiff_path,",
"enumerate( shapes(image, mask=mask, transform=data[\"transform\"]) ) ) geoms = list(results) gpd_polygonized_raster = gpd.GeoDataFrame.from_features(geoms, crs=c)",
"driver=\"GeoJSON\") if __name__ == \"__main__\": for file in os.listdir(\"asset/tiff\"): print(\"Conversion of \" +",
"of \" + file + \" successful !\") else: print(\"File already converted in",
"for GeoDataFrame handling. Args: original_tiff_path (str): path+name of the tiff file we want",
"file + \" starting ...\") try: if file.replace(\"tiff\", \"geojson\") not in os.listdir(\"asset/geojson\"): tiff_path",
"<filename>src/utils/tiff_to_geojson.py import os import rasterio from rasterio.features import shapes import geopandas as gpd",
"path+name of the targeted geojson band (int): tiff band you want to handle",
"geojson band (int): tiff band you want to handle Returns: Upload the geojson",
"v}, \"geometry\": s} for i, (s, v) in enumerate( shapes(image, mask=mask, transform=data[\"transform\"]) )",
"rasterio.features import shapes import geopandas as gpd def convert_tiff_to_geojson(original_tiff_path, destination_geojson_path, band): \"\"\" Convert",
"to handle Returns: Upload the geojson file in the destination. \"\"\" data =",
"data = rasterio.open(original_tiff_path).meta c = str(data[\"crs\"]) mask = None with rasterio.open(original_tiff_path) as src:",
"gpd_polygonized_raster = gpd.GeoDataFrame.from_features(geoms, crs=c) gpd_polygonized_raster.to_file(destination_geojson_path, driver=\"GeoJSON\") if __name__ == \"__main__\": for file in",
"...\") try: if file.replace(\"tiff\", \"geojson\") not in os.listdir(\"asset/geojson\"): tiff_path = os.getcwd() + \"asset/tiff/\"",
"src: image = src.read(band) # first band results = ( {\"properties\": {\"property\": v},",
"tiff_path.replace(\"tiff\", \"geojson\") convert_tiff_to_geojson(tiff_path, geojson_path, 1) print(\"Conversion of \" + file + \" successful",
"def convert_tiff_to_geojson(original_tiff_path, destination_geojson_path, band): \"\"\" Convert tiff file to geojson for GeoDataFrame handling.",
"successful !\") else: print(\"File already converted in geojson !\") except Exception as e:",
"converted in geojson !\") except Exception as e: print(\"Couldn't convert file \" +",
"in geojson !\") except Exception as e: print(\"Couldn't convert file \" + file",
"try: if file.replace(\"tiff\", \"geojson\") not in os.listdir(\"asset/geojson\"): tiff_path = os.getcwd() + \"asset/tiff/\" +",
"== \"__main__\": for file in os.listdir(\"asset/tiff\"): print(\"Conversion of \" + file + \"",
"= os.getcwd() + \"asset/tiff/\" + file geojson_path = tiff_path.replace(\"tiff\", \"geojson\") convert_tiff_to_geojson(tiff_path, geojson_path, 1)",
"import geopandas as gpd def convert_tiff_to_geojson(original_tiff_path, destination_geojson_path, band): \"\"\" Convert tiff file to",
"\"geometry\": s} for i, (s, v) in enumerate( shapes(image, mask=mask, transform=data[\"transform\"]) ) )",
"file in the destination. \"\"\" data = rasterio.open(original_tiff_path).meta c = str(data[\"crs\"]) mask =",
"the targeted geojson band (int): tiff band you want to handle Returns: Upload",
"+ file + \" successful !\") else: print(\"File already converted in geojson !\")",
"e: print(\"Couldn't convert file \" + file + \", exception :\" + e.__str__())",
"= tiff_path.replace(\"tiff\", \"geojson\") convert_tiff_to_geojson(tiff_path, geojson_path, 1) print(\"Conversion of \" + file + \"",
"\" successful !\") else: print(\"File already converted in geojson !\") except Exception as",
"= None with rasterio.open(original_tiff_path) as src: image = src.read(band) # first band results",
"for i, (s, v) in enumerate( shapes(image, mask=mask, transform=data[\"transform\"]) ) ) geoms =",
"as src: image = src.read(band) # first band results = ( {\"properties\": {\"property\":",
"\"\"\" data = rasterio.open(original_tiff_path).meta c = str(data[\"crs\"]) mask = None with rasterio.open(original_tiff_path) as",
"geojson for GeoDataFrame handling. Args: original_tiff_path (str): path+name of the tiff file we",
"rasterio.open(original_tiff_path) as src: image = src.read(band) # first band results = ( {\"properties\":",
"os.listdir(\"asset/geojson\"): tiff_path = os.getcwd() + \"asset/tiff/\" + file geojson_path = tiff_path.replace(\"tiff\", \"geojson\") convert_tiff_to_geojson(tiff_path,",
"destination_geojson_path, band): \"\"\" Convert tiff file to geojson for GeoDataFrame handling. Args: original_tiff_path",
"\" + file + \" starting ...\") try: if file.replace(\"tiff\", \"geojson\") not in",
"__name__ == \"__main__\": for file in os.listdir(\"asset/tiff\"): print(\"Conversion of \" + file +",
"\"geojson\") convert_tiff_to_geojson(tiff_path, geojson_path, 1) print(\"Conversion of \" + file + \" successful !\")",
"geojson !\") except Exception as e: print(\"Couldn't convert file \" + file +",
"except Exception as e: print(\"Couldn't convert file \" + file + \", exception",
"not in os.listdir(\"asset/geojson\"): tiff_path = os.getcwd() + \"asset/tiff/\" + file geojson_path = tiff_path.replace(\"tiff\",",
"band results = ( {\"properties\": {\"property\": v}, \"geometry\": s} for i, (s, v)",
"!\") except Exception as e: print(\"Couldn't convert file \" + file + \",",
"to convert destination_geojson_path (str): path+name of the targeted geojson band (int): tiff band",
"Args: original_tiff_path (str): path+name of the tiff file we want to convert destination_geojson_path",
"src.read(band) # first band results = ( {\"properties\": {\"property\": v}, \"geometry\": s} for",
"convert destination_geojson_path (str): path+name of the targeted geojson band (int): tiff band you",
"print(\"File already converted in geojson !\") except Exception as e: print(\"Couldn't convert file",
"+ \" successful !\") else: print(\"File already converted in geojson !\") except Exception",
"file we want to convert destination_geojson_path (str): path+name of the targeted geojson band",
"gpd def convert_tiff_to_geojson(original_tiff_path, destination_geojson_path, band): \"\"\" Convert tiff file to geojson for GeoDataFrame",
"convert_tiff_to_geojson(original_tiff_path, destination_geojson_path, band): \"\"\" Convert tiff file to geojson for GeoDataFrame handling. Args:",
"tiff band you want to handle Returns: Upload the geojson file in the",
"geoms = list(results) gpd_polygonized_raster = gpd.GeoDataFrame.from_features(geoms, crs=c) gpd_polygonized_raster.to_file(destination_geojson_path, driver=\"GeoJSON\") if __name__ == \"__main__\":",
"\"geojson\") not in os.listdir(\"asset/geojson\"): tiff_path = os.getcwd() + \"asset/tiff/\" + file geojson_path =",
"want to handle Returns: Upload the geojson file in the destination. \"\"\" data",
"geojson_path = tiff_path.replace(\"tiff\", \"geojson\") convert_tiff_to_geojson(tiff_path, geojson_path, 1) print(\"Conversion of \" + file +",
"{\"properties\": {\"property\": v}, \"geometry\": s} for i, (s, v) in enumerate( shapes(image, mask=mask,",
"i, (s, v) in enumerate( shapes(image, mask=mask, transform=data[\"transform\"]) ) ) geoms = list(results)",
"convert_tiff_to_geojson(tiff_path, geojson_path, 1) print(\"Conversion of \" + file + \" successful !\") else:",
"band you want to handle Returns: Upload the geojson file in the destination.",
") geoms = list(results) gpd_polygonized_raster = gpd.GeoDataFrame.from_features(geoms, crs=c) gpd_polygonized_raster.to_file(destination_geojson_path, driver=\"GeoJSON\") if __name__ ==",
"\"\"\" Convert tiff file to geojson for GeoDataFrame handling. Args: original_tiff_path (str): path+name",
"{\"property\": v}, \"geometry\": s} for i, (s, v) in enumerate( shapes(image, mask=mask, transform=data[\"transform\"])",
"# first band results = ( {\"properties\": {\"property\": v}, \"geometry\": s} for i,",
"in os.listdir(\"asset/geojson\"): tiff_path = os.getcwd() + \"asset/tiff/\" + file geojson_path = tiff_path.replace(\"tiff\", \"geojson\")",
"the destination. \"\"\" data = rasterio.open(original_tiff_path).meta c = str(data[\"crs\"]) mask = None with",
"of \" + file + \" starting ...\") try: if file.replace(\"tiff\", \"geojson\") not",
"= rasterio.open(original_tiff_path).meta c = str(data[\"crs\"]) mask = None with rasterio.open(original_tiff_path) as src: image",
"geojson file in the destination. \"\"\" data = rasterio.open(original_tiff_path).meta c = str(data[\"crs\"]) mask",
"None with rasterio.open(original_tiff_path) as src: image = src.read(band) # first band results =",
"rasterio.open(original_tiff_path).meta c = str(data[\"crs\"]) mask = None with rasterio.open(original_tiff_path) as src: image =",
"\"asset/tiff/\" + file geojson_path = tiff_path.replace(\"tiff\", \"geojson\") convert_tiff_to_geojson(tiff_path, geojson_path, 1) print(\"Conversion of \"",
"tiff file we want to convert destination_geojson_path (str): path+name of the targeted geojson",
"the geojson file in the destination. \"\"\" data = rasterio.open(original_tiff_path).meta c = str(data[\"crs\"])",
"c = str(data[\"crs\"]) mask = None with rasterio.open(original_tiff_path) as src: image = src.read(band)",
"file to geojson for GeoDataFrame handling. Args: original_tiff_path (str): path+name of the tiff"
] |
[
"while respecting the deadlines. Please refer to documentation for appropriate setup of solving",
"range(NB_WORKERS): if t.skills[w] > 0: wt = mdl.interval_var(optional=True, name=\"H{}-{}({})\".format(loc, t.name, WORKER_NAMES[w])) worker_tasks[w].append(wt) allocs.append(wt)",
"# Maximize total of skills mdl.add(mdl.maximize(total_skill)) #----------------------------------------------------------------------------- # Solve the model and display",
"task requires one worker that will have to be selected among the ones",
"INTERVAL_MIN import docplex.cp.utils_visu as visu #----------------------------------------------------------------------------- # Initialize the problem data #----------------------------------------------------------------------------- NB_HOUSES",
"deadlines. Please refer to documentation for appropriate setup of solving configuration. \"\"\" from",
"2016 # -------------------------------------------------------------------------- \"\"\" This is a problem of building five houses. The",
"(CARPENTRY, ROOFING), (CEILING, PAINTING), (ROOFING, WINDOWS), (ROOFING, FACADE), (PLUMBING, FACADE), (ROOFING, GARDEN), (PLUMBING,",
"'lightgreen' else: # Red-like color when task does not use the most skilled",
"Build the model #----------------------------------------------------------------------------- # Create model mdl = CpoModel() # Initialize model",
"t in worker_tasks[w]: wt = msol.get_var_solution(t) if wt.is_present(): if desc[t].skills[w] == max(desc[t].skills): #",
"# -------------------------------------------------------------------------- # Source file provided under Apache License, Version 2.0, January 2004,",
"to tasks ALL_TASKS = (MASONRY, CARPENTRY, PLUMBING, CEILING, ROOFING, PAINTING, WINDOWS, FACADE, GARDEN,",
"Create model mdl = CpoModel() # Initialize model variable sets total_skill = 0",
"function def make_house(loc, deadline): ''' Create model elements corresponding to the building of",
"10, [0, 9, 6]) WINDOWS = BuildingTask('windows', 5, [8, 0, 5]) FACADE =",
"of solving configuration. \"\"\" from docplex.cp.model import CpoModel, INTERVAL_MIN import docplex.cp.utils_visu as visu",
"modeling #----------------------------------------------------------------------------- # Assign an index to tasks ALL_TASKS = (MASONRY, CARPENTRY, PLUMBING,",
"(CEILING, PAINTING), (ROOFING, WINDOWS), (ROOFING, FACADE), (PLUMBING, FACADE), (ROOFING, GARDEN), (PLUMBING, GARDEN), (WINDOWS,",
"2015, 2016 # -------------------------------------------------------------------------- \"\"\" This is a problem of building five houses.",
"2.0, January 2004, # http://www.apache.org/licenses/ # (c) Copyright IBM Corp. 2015, 2016 #",
"among the ones who have a non null skill level for that task.",
"\"\"\" from docplex.cp.model import CpoModel, INTERVAL_MIN import docplex.cp.utils_visu as visu #----------------------------------------------------------------------------- # Initialize",
"visu.sequence(name=WORKER_NAMES[w]) for t in worker_tasks[w]: wt = msol.get_var_solution(t) if wt.is_present(): if desc[t].skills[w] ==",
"configuration. \"\"\" from docplex.cp.model import CpoModel, INTERVAL_MIN import docplex.cp.utils_visu as visu #----------------------------------------------------------------------------- #",
"(PLUMBING, GARDEN), (WINDOWS, MOVING), (FACADE, MOVING), (GARDEN, MOVING), (PAINTING, MOVING), ) #----------------------------------------------------------------------------- #",
"name[1:].split('-', 1) return task[0].upper() + loc # Solve model print(\"Solving model....\") msol =",
"building of a house loc Identification of house location deadline Deadline for finishing",
"#----------------------------------------------------------------------------- # Solve the model and display the result #----------------------------------------------------------------------------- def compact(name): #",
"p, s in PRECEDENCES: mdl.add(mdl.end_before_start(tasks[p.id], tasks[s.id])) # Allocate tasks to workers global total_skill",
"assigned to the tasks while respecting the deadlines. Please refer to documentation for",
"building task descriptor class BuildingTask(object): def __init__(self, name, duration, skills): self.name = name",
"# Build the model #----------------------------------------------------------------------------- # Create model mdl = CpoModel() # Initialize",
"precedence constraints for p, s in PRECEDENCES: mdl.add(mdl.end_before_start(tasks[p.id], tasks[s.id])) # Allocate tasks to",
"wt = mdl.interval_var(optional=True, name=\"H{}-{}({})\".format(loc, t.name, WORKER_NAMES[w])) worker_tasks[w].append(wt) allocs.append(wt) total_skill += (t.skills[w] * mdl.presence_of(wt))",
"7, 0]) PAINTING = BuildingTask('painting', 10, [0, 9, 6]) WINDOWS = BuildingTask('windows', 5,",
"for w in range(NB_WORKERS)] # Tasks (interval variables) assigned to a each worker",
"(MASONRY, CEILING), (CARPENTRY, ROOFING), (CEILING, PAINTING), (ROOFING, WINDOWS), (ROOFING, FACADE), (PLUMBING, FACADE), (ROOFING,",
"respecting the deadlines. Please refer to documentation for appropriate setup of solving configuration.",
"'-' + t.name) for t in ALL_TASKS] # Add precedence constraints for p,",
"before start of Y) PRECEDENCES = ( (MASONRY, CARPENTRY), (MASONRY, PLUMBING), (MASONRY, CEILING),",
"# Solve model print(\"Solving model....\") msol = mdl.solve(FailLimit=10000, TimeLimit=10) print(\"Solution: \") msol.print_solution() #",
"= BuildingTask('painting', 10, [0, 9, 6]) WINDOWS = BuildingTask('windows', 5, [8, 0, 5])",
"= 0 # Expression computing total of skills worker_tasks = [[] for w",
"(interval variables) assigned to a each worker desc = dict() # Map retrieving",
"ends before start of Y) PRECEDENCES = ( (MASONRY, CARPENTRY), (MASONRY, PLUMBING), (MASONRY,",
"str(loc) + '-' + t.name) for t in ALL_TASKS] # Add precedence constraints",
"result #----------------------------------------------------------------------------- def compact(name): # Example: H3-garden -> G3 # ^ ^ loc,",
"Create model elements corresponding to the building of a house loc Identification of",
"worker_tasks[w].append(wt) allocs.append(wt) total_skill += (t.skills[w] * mdl.presence_of(wt)) desc[wt] = t mdl.add(mdl.alternative(tasks[t.id], allocs)) #",
"NB_HOUSES = 5 DEADLINE = 318 WORKER_NAMES = ['Joe', 'Jack', 'Jim'] NB_WORKERS =",
"end=(INTERVAL_MIN, deadline), name='H' + str(loc) + '-' + t.name) for t in ALL_TASKS]",
"overlapping between tasks of each worker for w in range(NB_WORKERS): mdl.add(mdl.no_overlap(worker_tasks[w])) # Maximize",
"= [mdl.interval_var(size=t.duration, end=(INTERVAL_MIN, deadline), name='H' + str(loc) + '-' + t.name) for t",
"#----------------------------------------------------------------------------- NB_HOUSES = 5 DEADLINE = 318 WORKER_NAMES = ['Joe', 'Jack', 'Jim'] NB_WORKERS",
"in ALL_TASKS: allocs = [] for w in range(NB_WORKERS): if t.skills[w] > 0:",
"make_house(h, DEADLINE) # Avoid overlapping between tasks of each worker for w in",
"the model #----------------------------------------------------------------------------- # Create model mdl = CpoModel() # Initialize model variable",
"and each worker has a given non-negative skill level for each task. Each",
"for each task for this house tasks = [mdl.interval_var(size=t.duration, end=(INTERVAL_MIN, deadline), name='H' +",
"ALL_TASKS] # Add precedence constraints for p, s in PRECEDENCES: mdl.add(mdl.end_before_start(tasks[p.id], tasks[s.id])) #",
"# Initialize the problem data #----------------------------------------------------------------------------- NB_HOUSES = 5 DEADLINE = 318 WORKER_NAMES",
"corresponding to the building of a house loc Identification of house location deadline",
"[[] for w in range(NB_WORKERS)] # Tasks (interval variables) assigned to a each",
"skilled worker color = 'lightgreen' else: # Red-like color when task does not",
"task is using the most skilled worker color = 'lightgreen' else: # Red-like",
"mdl.add(mdl.alternative(tasks[t.id], allocs)) # Make houses for h in range(NB_HOUSES): make_house(h, DEADLINE) # Avoid",
"len(WORKER_NAMES) # House building task descriptor class BuildingTask(object): def __init__(self, name, duration, skills):",
"= BuildingTask('windows', 5, [8, 0, 5]) FACADE = BuildingTask('facade', 10, [5, 5, 0])",
"model print(\"Solving model....\") msol = mdl.solve(FailLimit=10000, TimeLimit=10) print(\"Solution: \") msol.print_solution() # Draw solution",
"SchedOptional', 0, DEADLINE) for w in range(NB_WORKERS): visu.sequence(name=WORKER_NAMES[w]) for t in worker_tasks[w]: wt",
"= name[1:].split('-', 1) return task[0].upper() + loc # Solve model print(\"Solving model....\") msol",
"# Utility function def make_house(loc, deadline): ''' Create model elements corresponding to the",
"docplex.cp.model import CpoModel, INTERVAL_MIN import docplex.cp.utils_visu as visu #----------------------------------------------------------------------------- # Initialize the problem",
"= ['Joe', 'Jack', 'Jim'] NB_WORKERS = len(WORKER_NAMES) # House building task descriptor class",
"visu #----------------------------------------------------------------------------- # Initialize the problem data #----------------------------------------------------------------------------- NB_HOUSES = 5 DEADLINE =",
"35, [9, 5, 0]) CARPENTRY = BuildingTask('carpentry', 15, [7, 0, 5]) PLUMBING =",
"is using the most skilled worker color = 'lightgreen' else: # Red-like color",
"318 WORKER_NAMES = ['Joe', 'Jack', 'Jim'] NB_WORKERS = len(WORKER_NAMES) # House building task",
"workers assigned to the tasks while respecting the deadlines. Please refer to documentation",
"data #----------------------------------------------------------------------------- NB_HOUSES = 5 DEADLINE = 318 WORKER_NAMES = ['Joe', 'Jack', 'Jim']",
"problem data #----------------------------------------------------------------------------- NB_HOUSES = 5 DEADLINE = 318 WORKER_NAMES = ['Joe', 'Jack',",
"WINDOWS), (ROOFING, FACADE), (PLUMBING, FACADE), (ROOFING, GARDEN), (PLUMBING, GARDEN), (WINDOWS, MOVING), (FACADE, MOVING),",
"in range(NB_WORKERS)] # Tasks (interval variables) assigned to a each worker desc =",
"# House building task descriptor class BuildingTask(object): def __init__(self, name, duration, skills): self.name",
"file provided under Apache License, Version 2.0, January 2004, # http://www.apache.org/licenses/ # (c)",
"Deadline for finishing the house ''' # Create interval variable for each task",
"desc[t].skills[w] == max(desc[t].skills): # Green-like color when task is using the most skilled",
"have to be selected among the ones who have a non null skill",
"visu.is_visu_enabled(): visu.timeline('Solution SchedOptional', 0, DEADLINE) for w in range(NB_WORKERS): visu.sequence(name=WORKER_NAMES[w]) for t in",
"of each worker for this task # List of tasks to be executed",
"allocs)) # Make houses for h in range(NB_HOUSES): make_house(h, DEADLINE) # Avoid overlapping",
"and visu.is_visu_enabled(): visu.timeline('Solution SchedOptional', 0, DEADLINE) for w in range(NB_WORKERS): visu.sequence(name=WORKER_NAMES[w]) for t",
"to workers global total_skill for t in ALL_TASKS: allocs = [] for w",
"5, 0]) CARPENTRY = BuildingTask('carpentry', 15, [7, 0, 5]) PLUMBING = BuildingTask('plumbing', 40,",
"tasks ALL_TASKS = (MASONRY, CARPENTRY, PLUMBING, CEILING, ROOFING, PAINTING, WINDOWS, FACADE, GARDEN, MOVING)",
"a house loc Identification of house location deadline Deadline for finishing the house",
"(MASONRY, CARPENTRY), (MASONRY, PLUMBING), (MASONRY, CEILING), (CARPENTRY, ROOFING), (CEILING, PAINTING), (ROOFING, WINDOWS), (ROOFING,",
"WINDOWS, FACADE, GARDEN, MOVING) for i in range(len(ALL_TASKS)): ALL_TASKS[i].id = i #----------------------------------------------------------------------------- #",
"ALL_TASKS[i].id = i #----------------------------------------------------------------------------- # Build the model #----------------------------------------------------------------------------- # Create model mdl",
"if wt.is_present(): if desc[t].skills[w] == max(desc[t].skills): # Green-like color when task is using",
"9]) MOVING = BuildingTask('moving', 5, [6, 0, 8]) # Tasks precedence constraints (each",
"Red-like color when task does not use the most skilled worker color =",
"print(\"Solving model....\") msol = mdl.solve(FailLimit=10000, TimeLimit=10) print(\"Solution: \") msol.print_solution() # Draw solution if",
"= t mdl.add(mdl.alternative(tasks[t.id], allocs)) # Make houses for h in range(NB_HOUSES): make_house(h, DEADLINE)",
"for this task # List of tasks to be executed for each house",
"i #----------------------------------------------------------------------------- # Build the model #----------------------------------------------------------------------------- # Create model mdl = CpoModel()",
"# Prepare the data for modeling #----------------------------------------------------------------------------- # Assign an index to tasks",
"= skills # Skills of each worker for this task # List of",
"40, [0, 7, 0]) CEILING = BuildingTask('ceiling', 15, [5, 8, 0]) ROOFING =",
"necessarily take place before others and these requirements are expressed through precedence constraints.",
"if desc[t].skills[w] == max(desc[t].skills): # Green-like color when task is using the most",
"before others and these requirements are expressed through precedence constraints. There are three",
"for that task. A worker can be assigned to only one task at",
"mdl.add(mdl.no_overlap(worker_tasks[w])) # Maximize total of skills mdl.add(mdl.maximize(total_skill)) #----------------------------------------------------------------------------- # Solve the model and",
"task from interval variable # Utility function def make_house(loc, deadline): ''' Create model",
"[6, 0, 8]) # Tasks precedence constraints (each tuple (X, Y) means X",
"= 'lightgreen' else: # Red-like color when task does not use the most",
"# Draw solution if msol and visu.is_visu_enabled(): visu.timeline('Solution SchedOptional', 0, DEADLINE) for w",
"tasks[s.id])) # Allocate tasks to workers global total_skill for t in ALL_TASKS: allocs",
"constraints (each tuple (X, Y) means X ends before start of Y) PRECEDENCES",
"each worker for this task # List of tasks to be executed for",
"dict() # Map retrieving task from interval variable # Utility function def make_house(loc,",
"GARDEN), (PLUMBING, GARDEN), (WINDOWS, MOVING), (FACADE, MOVING), (GARDEN, MOVING), (PAINTING, MOVING), ) #-----------------------------------------------------------------------------",
"constraints. There are three workers, and each worker has a given non-negative skill",
"= (MASONRY, CARPENTRY, PLUMBING, CEILING, ROOFING, PAINTING, WINDOWS, FACADE, GARDEN, MOVING) for i",
"if t.skills[w] > 0: wt = mdl.interval_var(optional=True, name=\"H{}-{}({})\".format(loc, t.name, WORKER_NAMES[w])) worker_tasks[w].append(wt) allocs.append(wt) total_skill",
"Add precedence constraints for p, s in PRECEDENCES: mdl.add(mdl.end_before_start(tasks[p.id], tasks[s.id])) # Allocate tasks",
"model mdl = CpoModel() # Initialize model variable sets total_skill = 0 #",
"import docplex.cp.utils_visu as visu #----------------------------------------------------------------------------- # Initialize the problem data #----------------------------------------------------------------------------- NB_HOUSES =",
"between tasks of each worker for w in range(NB_WORKERS): mdl.add(mdl.no_overlap(worker_tasks[w])) # Maximize total",
"def compact(name): # Example: H3-garden -> G3 # ^ ^ loc, task =",
"that will have to be selected among the ones who have a non",
"variable sets total_skill = 0 # Expression computing total of skills worker_tasks =",
"each worker desc = dict() # Map retrieving task from interval variable #",
"= [] for w in range(NB_WORKERS): if t.skills[w] > 0: wt = mdl.interval_var(optional=True,",
"i in range(len(ALL_TASKS)): ALL_TASKS[i].id = i #----------------------------------------------------------------------------- # Build the model #----------------------------------------------------------------------------- #",
"= msol.get_var_solution(t) if wt.is_present(): if desc[t].skills[w] == max(desc[t].skills): # Green-like color when task",
"0]) PAINTING = BuildingTask('painting', 10, [0, 9, 6]) WINDOWS = BuildingTask('windows', 5, [8,",
"solving configuration. \"\"\" from docplex.cp.model import CpoModel, INTERVAL_MIN import docplex.cp.utils_visu as visu #-----------------------------------------------------------------------------",
"5, [8, 0, 5]) FACADE = BuildingTask('facade', 10, [5, 5, 0]) GARDEN =",
"= i #----------------------------------------------------------------------------- # Build the model #----------------------------------------------------------------------------- # Create model mdl =",
"= duration # Task duration self.skills = skills # Skills of each worker",
"print(\"Solution: \") msol.print_solution() # Draw solution if msol and visu.is_visu_enabled(): visu.timeline('Solution SchedOptional', 0,",
"* mdl.presence_of(wt)) desc[wt] = t mdl.add(mdl.alternative(tasks[t.id], allocs)) # Make houses for h in",
"worker can be assigned to only one task at a time. Each house",
"Assign an index to tasks ALL_TASKS = (MASONRY, CARPENTRY, PLUMBING, CEILING, ROOFING, PAINTING,",
"Maximize total of skills mdl.add(mdl.maximize(total_skill)) #----------------------------------------------------------------------------- # Solve the model and display the",
"worker desc = dict() # Map retrieving task from interval variable # Utility",
"5]) FACADE = BuildingTask('facade', 10, [5, 5, 0]) GARDEN = BuildingTask('garden', 5, [5,",
"allocs.append(wt) total_skill += (t.skills[w] * mdl.presence_of(wt)) desc[wt] = t mdl.add(mdl.alternative(tasks[t.id], allocs)) # Make",
"range(len(ALL_TASKS)): ALL_TASKS[i].id = i #----------------------------------------------------------------------------- # Build the model #----------------------------------------------------------------------------- # Create model",
"DEADLINE) # Avoid overlapping between tasks of each worker for w in range(NB_WORKERS):",
"skill levels of the workers assigned to the tasks while respecting the deadlines.",
"name='H' + str(loc) + '-' + t.name) for t in ALL_TASKS] # Add",
"s in PRECEDENCES: mdl.add(mdl.end_before_start(tasks[p.id], tasks[s.id])) # Allocate tasks to workers global total_skill for",
"deadline): ''' Create model elements corresponding to the building of a house loc",
"CpoModel() # Initialize model variable sets total_skill = 0 # Expression computing total",
"8, 0]) ROOFING = BuildingTask('roofing', 5, [6, 7, 0]) PAINTING = BuildingTask('painting', 10,",
"Skills of each worker for this task # List of tasks to be",
"for each house MASONRY = BuildingTask('masonry', 35, [9, 5, 0]) CARPENTRY = BuildingTask('carpentry',",
"CpoModel, INTERVAL_MIN import docplex.cp.utils_visu as visu #----------------------------------------------------------------------------- # Initialize the problem data #-----------------------------------------------------------------------------",
"task. A worker can be assigned to only one task at a time.",
"worker has a given non-negative skill level for each task. Each task requires",
"+ loc # Solve model print(\"Solving model....\") msol = mdl.solve(FailLimit=10000, TimeLimit=10) print(\"Solution: \")",
"requirements are expressed through precedence constraints. There are three workers, and each worker",
"10, [5, 5, 0]) GARDEN = BuildingTask('garden', 5, [5, 5, 9]) MOVING =",
"0, 8]) # Tasks precedence constraints (each tuple (X, Y) means X ends",
"tasks to workers global total_skill for t in ALL_TASKS: allocs = [] for",
"<gh_stars>1-10 # -------------------------------------------------------------------------- # Source file provided under Apache License, Version 2.0, January",
"t.skills[w] > 0: wt = mdl.interval_var(optional=True, name=\"H{}-{}({})\".format(loc, t.name, WORKER_NAMES[w])) worker_tasks[w].append(wt) allocs.append(wt) total_skill +=",
"[5, 5, 9]) MOVING = BuildingTask('moving', 5, [6, 0, 8]) # Tasks precedence",
"solution if msol and visu.is_visu_enabled(): visu.timeline('Solution SchedOptional', 0, DEADLINE) for w in range(NB_WORKERS):",
"Green-like color when task is using the most skilled worker color = 'lightgreen'",
"for p, s in PRECEDENCES: mdl.add(mdl.end_before_start(tasks[p.id], tasks[s.id])) # Allocate tasks to workers global",
"BuildingTask('windows', 5, [8, 0, 5]) FACADE = BuildingTask('facade', 10, [5, 5, 0]) GARDEN",
"and these requirements are expressed through precedence constraints. There are three workers, and",
"assigned to a each worker desc = dict() # Map retrieving task from",
"range(NB_WORKERS): visu.sequence(name=WORKER_NAMES[w]) for t in worker_tasks[w]: wt = msol.get_var_solution(t) if wt.is_present(): if desc[t].skills[w]",
"total_skill for t in ALL_TASKS: allocs = [] for w in range(NB_WORKERS): if",
"MOVING), (PAINTING, MOVING), ) #----------------------------------------------------------------------------- # Prepare the data for modeling #----------------------------------------------------------------------------- #",
"when task does not use the most skilled worker color = 'salmon' visu.interval(wt,",
"WORKER_NAMES = ['Joe', 'Jack', 'Jim'] NB_WORKERS = len(WORKER_NAMES) # House building task descriptor",
"MASONRY = BuildingTask('masonry', 35, [9, 5, 0]) CARPENTRY = BuildingTask('carpentry', 15, [7, 0,",
"model elements corresponding to the building of a house loc Identification of house",
"these requirements are expressed through precedence constraints. There are three workers, and each",
"precedence constraints (each tuple (X, Y) means X ends before start of Y)",
"docplex.cp.utils_visu as visu #----------------------------------------------------------------------------- # Initialize the problem data #----------------------------------------------------------------------------- NB_HOUSES = 5",
"January 2004, # http://www.apache.org/licenses/ # (c) Copyright IBM Corp. 2015, 2016 # --------------------------------------------------------------------------",
"ALL_TASKS = (MASONRY, CARPENTRY, PLUMBING, CEILING, ROOFING, PAINTING, WINDOWS, FACADE, GARDEN, MOVING) for",
"# Source file provided under Apache License, Version 2.0, January 2004, # http://www.apache.org/licenses/",
"(ROOFING, FACADE), (PLUMBING, FACADE), (ROOFING, GARDEN), (PLUMBING, GARDEN), (WINDOWS, MOVING), (FACADE, MOVING), (GARDEN,",
"= 318 WORKER_NAMES = ['Joe', 'Jack', 'Jim'] NB_WORKERS = len(WORKER_NAMES) # House building",
"Task duration self.skills = skills # Skills of each worker for this task",
"tasks = [mdl.interval_var(size=t.duration, end=(INTERVAL_MIN, deadline), name='H' + str(loc) + '-' + t.name) for",
"PAINTING = BuildingTask('painting', 10, [0, 9, 6]) WINDOWS = BuildingTask('windows', 5, [8, 0,",
"for w in range(NB_WORKERS): mdl.add(mdl.no_overlap(worker_tasks[w])) # Maximize total of skills mdl.add(mdl.maximize(total_skill)) #----------------------------------------------------------------------------- #",
"= BuildingTask('facade', 10, [5, 5, 0]) GARDEN = BuildingTask('garden', 5, [5, 5, 9])",
"import CpoModel, INTERVAL_MIN import docplex.cp.utils_visu as visu #----------------------------------------------------------------------------- # Initialize the problem data",
"worker_tasks = [[] for w in range(NB_WORKERS)] # Tasks (interval variables) assigned to",
"0, DEADLINE) for w in range(NB_WORKERS): visu.sequence(name=WORKER_NAMES[w]) for t in worker_tasks[w]: wt =",
"# Green-like color when task is using the most skilled worker color =",
"one task at a time. Each house has a deadline. The objective is",
"Map retrieving task from interval variable # Utility function def make_house(loc, deadline): '''",
"constraints for p, s in PRECEDENCES: mdl.add(mdl.end_before_start(tasks[p.id], tasks[s.id])) # Allocate tasks to workers",
") #----------------------------------------------------------------------------- # Prepare the data for modeling #----------------------------------------------------------------------------- # Assign an index",
"maximize the skill levels of the workers assigned to the tasks while respecting",
"model #----------------------------------------------------------------------------- # Create model mdl = CpoModel() # Initialize model variable sets",
"the skill levels of the workers assigned to the tasks while respecting the",
"w in range(NB_WORKERS): mdl.add(mdl.no_overlap(worker_tasks[w])) # Maximize total of skills mdl.add(mdl.maximize(total_skill)) #----------------------------------------------------------------------------- # Solve",
"problem of building five houses. The masonry, roofing, painting, etc. must be scheduled.",
"a time. Each house has a deadline. The objective is to maximize the",
"This is a problem of building five houses. The masonry, roofing, painting, etc.",
"total_skill = 0 # Expression computing total of skills worker_tasks = [[] for",
"does not use the most skilled worker color = 'salmon' visu.interval(wt, color, compact(wt.get_name()))",
"House building task descriptor class BuildingTask(object): def __init__(self, name, duration, skills): self.name =",
"deadline), name='H' + str(loc) + '-' + t.name) for t in ALL_TASKS] #",
"in range(len(ALL_TASKS)): ALL_TASKS[i].id = i #----------------------------------------------------------------------------- # Build the model #----------------------------------------------------------------------------- # Create",
"sets total_skill = 0 # Expression computing total of skills worker_tasks = [[]",
"w in range(NB_WORKERS)] # Tasks (interval variables) assigned to a each worker desc",
"selected among the ones who have a non null skill level for that",
"scheduled. Some tasks must necessarily take place before others and these requirements are",
"CARPENTRY), (MASONRY, PLUMBING), (MASONRY, CEILING), (CARPENTRY, ROOFING), (CEILING, PAINTING), (ROOFING, WINDOWS), (ROOFING, FACADE),",
"# Create interval variable for each task for this house tasks = [mdl.interval_var(size=t.duration,",
"house tasks = [mdl.interval_var(size=t.duration, end=(INTERVAL_MIN, deadline), name='H' + str(loc) + '-' + t.name)",
"total_skill += (t.skills[w] * mdl.presence_of(wt)) desc[wt] = t mdl.add(mdl.alternative(tasks[t.id], allocs)) # Make houses",
"of house location deadline Deadline for finishing the house ''' # Create interval",
"worker_tasks[w]: wt = msol.get_var_solution(t) if wt.is_present(): if desc[t].skills[w] == max(desc[t].skills): # Green-like color",
"= len(WORKER_NAMES) # House building task descriptor class BuildingTask(object): def __init__(self, name, duration,",
"[5, 8, 0]) ROOFING = BuildingTask('roofing', 5, [6, 7, 0]) PAINTING = BuildingTask('painting',",
"class BuildingTask(object): def __init__(self, name, duration, skills): self.name = name self.duration = duration",
"roofing, painting, etc. must be scheduled. Some tasks must necessarily take place before",
"levels of the workers assigned to the tasks while respecting the deadlines. Please",
"PAINTING, WINDOWS, FACADE, GARDEN, MOVING) for i in range(len(ALL_TASKS)): ALL_TASKS[i].id = i #-----------------------------------------------------------------------------",
"color when task does not use the most skilled worker color = 'salmon'",
"each worker for w in range(NB_WORKERS): mdl.add(mdl.no_overlap(worker_tasks[w])) # Maximize total of skills mdl.add(mdl.maximize(total_skill))",
"each house MASONRY = BuildingTask('masonry', 35, [9, 5, 0]) CARPENTRY = BuildingTask('carpentry', 15,",
"PRECEDENCES = ( (MASONRY, CARPENTRY), (MASONRY, PLUMBING), (MASONRY, CEILING), (CARPENTRY, ROOFING), (CEILING, PAINTING),",
"# Assign an index to tasks ALL_TASKS = (MASONRY, CARPENTRY, PLUMBING, CEILING, ROOFING,",
"self.name = name self.duration = duration # Task duration self.skills = skills #",
"BuildingTask('facade', 10, [5, 5, 0]) GARDEN = BuildingTask('garden', 5, [5, 5, 9]) MOVING",
"= BuildingTask('carpentry', 15, [7, 0, 5]) PLUMBING = BuildingTask('plumbing', 40, [0, 7, 0])",
"task at a time. Each house has a deadline. The objective is to",
"List of tasks to be executed for each house MASONRY = BuildingTask('masonry', 35,",
"loc Identification of house location deadline Deadline for finishing the house ''' #",
"to only one task at a time. Each house has a deadline. The",
"task # List of tasks to be executed for each house MASONRY =",
"Make houses for h in range(NB_HOUSES): make_house(h, DEADLINE) # Avoid overlapping between tasks",
"DEADLINE = 318 WORKER_NAMES = ['Joe', 'Jack', 'Jim'] NB_WORKERS = len(WORKER_NAMES) # House",
"15, [7, 0, 5]) PLUMBING = BuildingTask('plumbing', 40, [0, 7, 0]) CEILING =",
"The masonry, roofing, painting, etc. must be scheduled. Some tasks must necessarily take",
"worker color = 'lightgreen' else: # Red-like color when task does not use",
"mdl.presence_of(wt)) desc[wt] = t mdl.add(mdl.alternative(tasks[t.id], allocs)) # Make houses for h in range(NB_HOUSES):",
"start of Y) PRECEDENCES = ( (MASONRY, CARPENTRY), (MASONRY, PLUMBING), (MASONRY, CEILING), (CARPENTRY,",
"0]) CARPENTRY = BuildingTask('carpentry', 15, [7, 0, 5]) PLUMBING = BuildingTask('plumbing', 40, [0,",
"workers global total_skill for t in ALL_TASKS: allocs = [] for w in",
"given non-negative skill level for each task. Each task requires one worker that",
"of building five houses. The masonry, roofing, painting, etc. must be scheduled. Some",
"15, [5, 8, 0]) ROOFING = BuildingTask('roofing', 5, [6, 7, 0]) PAINTING =",
"[0, 9, 6]) WINDOWS = BuildingTask('windows', 5, [8, 0, 5]) FACADE = BuildingTask('facade',",
"= BuildingTask('plumbing', 40, [0, 7, 0]) CEILING = BuildingTask('ceiling', 15, [5, 8, 0])",
"not use the most skilled worker color = 'salmon' visu.interval(wt, color, compact(wt.get_name())) visu.show()",
"to maximize the skill levels of the workers assigned to the tasks while",
"[9, 5, 0]) CARPENTRY = BuildingTask('carpentry', 15, [7, 0, 5]) PLUMBING = BuildingTask('plumbing',",
"the data for modeling #----------------------------------------------------------------------------- # Assign an index to tasks ALL_TASKS =",
"display the result #----------------------------------------------------------------------------- def compact(name): # Example: H3-garden -> G3 # ^",
"= mdl.interval_var(optional=True, name=\"H{}-{}({})\".format(loc, t.name, WORKER_NAMES[w])) worker_tasks[w].append(wt) allocs.append(wt) total_skill += (t.skills[w] * mdl.presence_of(wt)) desc[wt]",
"PLUMBING), (MASONRY, CEILING), (CARPENTRY, ROOFING), (CEILING, PAINTING), (ROOFING, WINDOWS), (ROOFING, FACADE), (PLUMBING, FACADE),",
"loc # Solve model print(\"Solving model....\") msol = mdl.solve(FailLimit=10000, TimeLimit=10) print(\"Solution: \") msol.print_solution()",
"# Skills of each worker for this task # List of tasks to",
"worker for w in range(NB_WORKERS): mdl.add(mdl.no_overlap(worker_tasks[w])) # Maximize total of skills mdl.add(mdl.maximize(total_skill)) #-----------------------------------------------------------------------------",
"(t.skills[w] * mdl.presence_of(wt)) desc[wt] = t mdl.add(mdl.alternative(tasks[t.id], allocs)) # Make houses for h",
"# Map retrieving task from interval variable # Utility function def make_house(loc, deadline):",
"Y) PRECEDENCES = ( (MASONRY, CARPENTRY), (MASONRY, PLUMBING), (MASONRY, CEILING), (CARPENTRY, ROOFING), (CEILING,",
"CARPENTRY, PLUMBING, CEILING, ROOFING, PAINTING, WINDOWS, FACADE, GARDEN, MOVING) for i in range(len(ALL_TASKS)):",
"most skilled worker color = 'lightgreen' else: # Red-like color when task does",
"\"\"\" This is a problem of building five houses. The masonry, roofing, painting,",
"the workers assigned to the tasks while respecting the deadlines. Please refer to",
"MOVING), ) #----------------------------------------------------------------------------- # Prepare the data for modeling #----------------------------------------------------------------------------- # Assign an",
"variables) assigned to a each worker desc = dict() # Map retrieving task",
"The objective is to maximize the skill levels of the workers assigned to",
"house loc Identification of house location deadline Deadline for finishing the house '''",
"= BuildingTask('ceiling', 15, [5, 8, 0]) ROOFING = BuildingTask('roofing', 5, [6, 7, 0])",
"model....\") msol = mdl.solve(FailLimit=10000, TimeLimit=10) print(\"Solution: \") msol.print_solution() # Draw solution if msol",
"# (c) Copyright IBM Corp. 2015, 2016 # -------------------------------------------------------------------------- \"\"\" This is a",
"# Create model mdl = CpoModel() # Initialize model variable sets total_skill =",
"(FACADE, MOVING), (GARDEN, MOVING), (PAINTING, MOVING), ) #----------------------------------------------------------------------------- # Prepare the data for",
"return task[0].upper() + loc # Solve model print(\"Solving model....\") msol = mdl.solve(FailLimit=10000, TimeLimit=10)",
"loc, task = name[1:].split('-', 1) return task[0].upper() + loc # Solve model print(\"Solving",
"#----------------------------------------------------------------------------- def compact(name): # Example: H3-garden -> G3 # ^ ^ loc, task",
"desc = dict() # Map retrieving task from interval variable # Utility function",
"others and these requirements are expressed through precedence constraints. There are three workers,",
"5, [5, 5, 9]) MOVING = BuildingTask('moving', 5, [6, 0, 8]) # Tasks",
"max(desc[t].skills): # Green-like color when task is using the most skilled worker color",
"null skill level for that task. A worker can be assigned to only",
"to the tasks while respecting the deadlines. Please refer to documentation for appropriate",
"Corp. 2015, 2016 # -------------------------------------------------------------------------- \"\"\" This is a problem of building five",
"using the most skilled worker color = 'lightgreen' else: # Red-like color when",
"+= (t.skills[w] * mdl.presence_of(wt)) desc[wt] = t mdl.add(mdl.alternative(tasks[t.id], allocs)) # Make houses for",
"5]) PLUMBING = BuildingTask('plumbing', 40, [0, 7, 0]) CEILING = BuildingTask('ceiling', 15, [5,",
"def make_house(loc, deadline): ''' Create model elements corresponding to the building of a",
"in PRECEDENCES: mdl.add(mdl.end_before_start(tasks[p.id], tasks[s.id])) # Allocate tasks to workers global total_skill for t",
"descriptor class BuildingTask(object): def __init__(self, name, duration, skills): self.name = name self.duration =",
"# List of tasks to be executed for each house MASONRY = BuildingTask('masonry',",
"as visu #----------------------------------------------------------------------------- # Initialize the problem data #----------------------------------------------------------------------------- NB_HOUSES = 5 DEADLINE",
"t.name) for t in ALL_TASKS] # Add precedence constraints for p, s in",
"# Solve the model and display the result #----------------------------------------------------------------------------- def compact(name): # Example:",
"worker for this task # List of tasks to be executed for each",
"Copyright IBM Corp. 2015, 2016 # -------------------------------------------------------------------------- \"\"\" This is a problem of",
"Example: H3-garden -> G3 # ^ ^ loc, task = name[1:].split('-', 1) return",
"t.name, WORKER_NAMES[w])) worker_tasks[w].append(wt) allocs.append(wt) total_skill += (t.skills[w] * mdl.presence_of(wt)) desc[wt] = t mdl.add(mdl.alternative(tasks[t.id],",
"NB_WORKERS = len(WORKER_NAMES) # House building task descriptor class BuildingTask(object): def __init__(self, name,",
"index to tasks ALL_TASKS = (MASONRY, CARPENTRY, PLUMBING, CEILING, ROOFING, PAINTING, WINDOWS, FACADE,",
"Create interval variable for each task for this house tasks = [mdl.interval_var(size=t.duration, end=(INTERVAL_MIN,",
"Identification of house location deadline Deadline for finishing the house ''' # Create",
"Expression computing total of skills worker_tasks = [[] for w in range(NB_WORKERS)] #",
"0, 5]) FACADE = BuildingTask('facade', 10, [5, 5, 0]) GARDEN = BuildingTask('garden', 5,",
"MOVING), (FACADE, MOVING), (GARDEN, MOVING), (PAINTING, MOVING), ) #----------------------------------------------------------------------------- # Prepare the data",
"this task # List of tasks to be executed for each house MASONRY",
"for appropriate setup of solving configuration. \"\"\" from docplex.cp.model import CpoModel, INTERVAL_MIN import",
"houses for h in range(NB_HOUSES): make_house(h, DEADLINE) # Avoid overlapping between tasks of",
"skill level for that task. A worker can be assigned to only one",
"= 5 DEADLINE = 318 WORKER_NAMES = ['Joe', 'Jack', 'Jim'] NB_WORKERS = len(WORKER_NAMES)",
"tasks must necessarily take place before others and these requirements are expressed through",
"1) return task[0].upper() + loc # Solve model print(\"Solving model....\") msol = mdl.solve(FailLimit=10000,",
"-------------------------------------------------------------------------- # Source file provided under Apache License, Version 2.0, January 2004, #",
"0: wt = mdl.interval_var(optional=True, name=\"H{}-{}({})\".format(loc, t.name, WORKER_NAMES[w])) worker_tasks[w].append(wt) allocs.append(wt) total_skill += (t.skills[w] *",
"6]) WINDOWS = BuildingTask('windows', 5, [8, 0, 5]) FACADE = BuildingTask('facade', 10, [5,",
"for t in worker_tasks[w]: wt = msol.get_var_solution(t) if wt.is_present(): if desc[t].skills[w] == max(desc[t].skills):",
"IBM Corp. 2015, 2016 # -------------------------------------------------------------------------- \"\"\" This is a problem of building",
"[7, 0, 5]) PLUMBING = BuildingTask('plumbing', 40, [0, 7, 0]) CEILING = BuildingTask('ceiling',",
"# -------------------------------------------------------------------------- \"\"\" This is a problem of building five houses. The masonry,",
"# Task duration self.skills = skills # Skills of each worker for this",
"task[0].upper() + loc # Solve model print(\"Solving model....\") msol = mdl.solve(FailLimit=10000, TimeLimit=10) print(\"Solution:",
"Solve the model and display the result #----------------------------------------------------------------------------- def compact(name): # Example: H3-garden",
"t mdl.add(mdl.alternative(tasks[t.id], allocs)) # Make houses for h in range(NB_HOUSES): make_house(h, DEADLINE) #",
"if msol and visu.is_visu_enabled(): visu.timeline('Solution SchedOptional', 0, DEADLINE) for w in range(NB_WORKERS): visu.sequence(name=WORKER_NAMES[w])",
"(ROOFING, WINDOWS), (ROOFING, FACADE), (PLUMBING, FACADE), (ROOFING, GARDEN), (PLUMBING, GARDEN), (WINDOWS, MOVING), (FACADE,",
"DEADLINE) for w in range(NB_WORKERS): visu.sequence(name=WORKER_NAMES[w]) for t in worker_tasks[w]: wt = msol.get_var_solution(t)",
"mdl.interval_var(optional=True, name=\"H{}-{}({})\".format(loc, t.name, WORKER_NAMES[w])) worker_tasks[w].append(wt) allocs.append(wt) total_skill += (t.skills[w] * mdl.presence_of(wt)) desc[wt] =",
"visu.timeline('Solution SchedOptional', 0, DEADLINE) for w in range(NB_WORKERS): visu.sequence(name=WORKER_NAMES[w]) for t in worker_tasks[w]:",
"(WINDOWS, MOVING), (FACADE, MOVING), (GARDEN, MOVING), (PAINTING, MOVING), ) #----------------------------------------------------------------------------- # Prepare the",
"house ''' # Create interval variable for each task for this house tasks",
"houses. The masonry, roofing, painting, etc. must be scheduled. Some tasks must necessarily",
"5 DEADLINE = 318 WORKER_NAMES = ['Joe', 'Jack', 'Jim'] NB_WORKERS = len(WORKER_NAMES) #",
"through precedence constraints. There are three workers, and each worker has a given",
"CEILING = BuildingTask('ceiling', 15, [5, 8, 0]) ROOFING = BuildingTask('roofing', 5, [6, 7,",
"make_house(loc, deadline): ''' Create model elements corresponding to the building of a house",
"in range(NB_WORKERS): visu.sequence(name=WORKER_NAMES[w]) for t in worker_tasks[w]: wt = msol.get_var_solution(t) if wt.is_present(): if",
"desc[wt] = t mdl.add(mdl.alternative(tasks[t.id], allocs)) # Make houses for h in range(NB_HOUSES): make_house(h,",
"house has a deadline. The objective is to maximize the skill levels of",
"# Tasks precedence constraints (each tuple (X, Y) means X ends before start",
"at a time. Each house has a deadline. The objective is to maximize",
"__init__(self, name, duration, skills): self.name = name self.duration = duration # Task duration",
"is a problem of building five houses. The masonry, roofing, painting, etc. must",
"assigned to only one task at a time. Each house has a deadline.",
"(MASONRY, PLUMBING), (MASONRY, CEILING), (CARPENTRY, ROOFING), (CEILING, PAINTING), (ROOFING, WINDOWS), (ROOFING, FACADE), (PLUMBING,",
"Version 2.0, January 2004, # http://www.apache.org/licenses/ # (c) Copyright IBM Corp. 2015, 2016",
"range(NB_HOUSES): make_house(h, DEADLINE) # Avoid overlapping between tasks of each worker for w",
"of skills worker_tasks = [[] for w in range(NB_WORKERS)] # Tasks (interval variables)",
"[mdl.interval_var(size=t.duration, end=(INTERVAL_MIN, deadline), name='H' + str(loc) + '-' + t.name) for t in",
"= BuildingTask('moving', 5, [6, 0, 8]) # Tasks precedence constraints (each tuple (X,",
"house MASONRY = BuildingTask('masonry', 35, [9, 5, 0]) CARPENTRY = BuildingTask('carpentry', 15, [7,",
"three workers, and each worker has a given non-negative skill level for each",
"of a house loc Identification of house location deadline Deadline for finishing the",
"PAINTING), (ROOFING, WINDOWS), (ROOFING, FACADE), (PLUMBING, FACADE), (ROOFING, GARDEN), (PLUMBING, GARDEN), (WINDOWS, MOVING),",
"objective is to maximize the skill levels of the workers assigned to the",
"FACADE, GARDEN, MOVING) for i in range(len(ALL_TASKS)): ALL_TASKS[i].id = i #----------------------------------------------------------------------------- # Build",
"from docplex.cp.model import CpoModel, INTERVAL_MIN import docplex.cp.utils_visu as visu #----------------------------------------------------------------------------- # Initialize the",
"5, [6, 7, 0]) PAINTING = BuildingTask('painting', 10, [0, 9, 6]) WINDOWS =",
"Tasks precedence constraints (each tuple (X, Y) means X ends before start of",
"CEILING), (CARPENTRY, ROOFING), (CEILING, PAINTING), (ROOFING, WINDOWS), (ROOFING, FACADE), (PLUMBING, FACADE), (ROOFING, GARDEN),",
"# Allocate tasks to workers global total_skill for t in ALL_TASKS: allocs =",
"TimeLimit=10) print(\"Solution: \") msol.print_solution() # Draw solution if msol and visu.is_visu_enabled(): visu.timeline('Solution SchedOptional',",
"five houses. The masonry, roofing, painting, etc. must be scheduled. Some tasks must",
"house location deadline Deadline for finishing the house ''' # Create interval variable",
"when task is using the most skilled worker color = 'lightgreen' else: #",
"can be assigned to only one task at a time. Each house has",
"''' Create model elements corresponding to the building of a house loc Identification",
"skills worker_tasks = [[] for w in range(NB_WORKERS)] # Tasks (interval variables) assigned",
"FACADE = BuildingTask('facade', 10, [5, 5, 0]) GARDEN = BuildingTask('garden', 5, [5, 5,",
"of tasks to be executed for each house MASONRY = BuildingTask('masonry', 35, [9,",
"a each worker desc = dict() # Map retrieving task from interval variable",
"elements corresponding to the building of a house loc Identification of house location",
"w in range(NB_WORKERS): if t.skills[w] > 0: wt = mdl.interval_var(optional=True, name=\"H{}-{}({})\".format(loc, t.name, WORKER_NAMES[w]))",
"Each task requires one worker that will have to be selected among the",
"self.skills = skills # Skills of each worker for this task # List",
"variable for each task for this house tasks = [mdl.interval_var(size=t.duration, end=(INTERVAL_MIN, deadline), name='H'",
"mdl.solve(FailLimit=10000, TimeLimit=10) print(\"Solution: \") msol.print_solution() # Draw solution if msol and visu.is_visu_enabled(): visu.timeline('Solution",
"0]) GARDEN = BuildingTask('garden', 5, [5, 5, 9]) MOVING = BuildingTask('moving', 5, [6,",
"#----------------------------------------------------------------------------- # Build the model #----------------------------------------------------------------------------- # Create model mdl = CpoModel() #",
"w in range(NB_WORKERS): visu.sequence(name=WORKER_NAMES[w]) for t in worker_tasks[w]: wt = msol.get_var_solution(t) if wt.is_present():",
"0]) CEILING = BuildingTask('ceiling', 15, [5, 8, 0]) ROOFING = BuildingTask('roofing', 5, [6,",
"(c) Copyright IBM Corp. 2015, 2016 # -------------------------------------------------------------------------- \"\"\" This is a problem",
"= dict() # Map retrieving task from interval variable # Utility function def",
"task = name[1:].split('-', 1) return task[0].upper() + loc # Solve model print(\"Solving model....\")",
"deadline Deadline for finishing the house ''' # Create interval variable for each",
"# Tasks (interval variables) assigned to a each worker desc = dict() #",
"# Avoid overlapping between tasks of each worker for w in range(NB_WORKERS): mdl.add(mdl.no_overlap(worker_tasks[w]))",
"tuple (X, Y) means X ends before start of Y) PRECEDENCES = (",
"WINDOWS = BuildingTask('windows', 5, [8, 0, 5]) FACADE = BuildingTask('facade', 10, [5, 5,",
"model variable sets total_skill = 0 # Expression computing total of skills worker_tasks",
"of the workers assigned to the tasks while respecting the deadlines. Please refer",
"to the building of a house loc Identification of house location deadline Deadline",
"to documentation for appropriate setup of solving configuration. \"\"\" from docplex.cp.model import CpoModel,",
"8]) # Tasks precedence constraints (each tuple (X, Y) means X ends before",
"BuildingTask('roofing', 5, [6, 7, 0]) PAINTING = BuildingTask('painting', 10, [0, 9, 6]) WINDOWS",
"+ str(loc) + '-' + t.name) for t in ALL_TASKS] # Add precedence",
"MOVING) for i in range(len(ALL_TASKS)): ALL_TASKS[i].id = i #----------------------------------------------------------------------------- # Build the model",
"be assigned to only one task at a time. Each house has a",
"skills # Skills of each worker for this task # List of tasks",
"allocs = [] for w in range(NB_WORKERS): if t.skills[w] > 0: wt =",
"GARDEN), (WINDOWS, MOVING), (FACADE, MOVING), (GARDEN, MOVING), (PAINTING, MOVING), ) #----------------------------------------------------------------------------- # Prepare",
"each task. Each task requires one worker that will have to be selected",
"= name self.duration = duration # Task duration self.skills = skills # Skills",
"# Initialize model variable sets total_skill = 0 # Expression computing total of",
"mdl.add(mdl.end_before_start(tasks[p.id], tasks[s.id])) # Allocate tasks to workers global total_skill for t in ALL_TASKS:",
"9, 6]) WINDOWS = BuildingTask('windows', 5, [8, 0, 5]) FACADE = BuildingTask('facade', 10,",
"task does not use the most skilled worker color = 'salmon' visu.interval(wt, color,",
"'Jim'] NB_WORKERS = len(WORKER_NAMES) # House building task descriptor class BuildingTask(object): def __init__(self,",
"workers, and each worker has a given non-negative skill level for each task.",
"MOVING = BuildingTask('moving', 5, [6, 0, 8]) # Tasks precedence constraints (each tuple",
"interval variable for each task for this house tasks = [mdl.interval_var(size=t.duration, end=(INTERVAL_MIN, deadline),",
"in ALL_TASKS] # Add precedence constraints for p, s in PRECEDENCES: mdl.add(mdl.end_before_start(tasks[p.id], tasks[s.id]))",
"FACADE), (ROOFING, GARDEN), (PLUMBING, GARDEN), (WINDOWS, MOVING), (FACADE, MOVING), (GARDEN, MOVING), (PAINTING, MOVING),",
"a given non-negative skill level for each task. Each task requires one worker",
"the building of a house loc Identification of house location deadline Deadline for",
"range(NB_WORKERS): mdl.add(mdl.no_overlap(worker_tasks[w])) # Maximize total of skills mdl.add(mdl.maximize(total_skill)) #----------------------------------------------------------------------------- # Solve the model",
"GARDEN = BuildingTask('garden', 5, [5, 5, 9]) MOVING = BuildingTask('moving', 5, [6, 0,",
"BuildingTask('plumbing', 40, [0, 7, 0]) CEILING = BuildingTask('ceiling', 15, [5, 8, 0]) ROOFING",
"refer to documentation for appropriate setup of solving configuration. \"\"\" from docplex.cp.model import",
"H3-garden -> G3 # ^ ^ loc, task = name[1:].split('-', 1) return task[0].upper()",
"GARDEN, MOVING) for i in range(len(ALL_TASKS)): ALL_TASKS[i].id = i #----------------------------------------------------------------------------- # Build the",
"+ '-' + t.name) for t in ALL_TASKS] # Add precedence constraints for",
"== max(desc[t].skills): # Green-like color when task is using the most skilled worker",
"only one task at a time. Each house has a deadline. The objective",
"total of skills mdl.add(mdl.maximize(total_skill)) #----------------------------------------------------------------------------- # Solve the model and display the result",
"must necessarily take place before others and these requirements are expressed through precedence",
"PLUMBING = BuildingTask('plumbing', 40, [0, 7, 0]) CEILING = BuildingTask('ceiling', 15, [5, 8,",
"for t in ALL_TASKS: allocs = [] for w in range(NB_WORKERS): if t.skills[w]",
"CEILING, ROOFING, PAINTING, WINDOWS, FACADE, GARDEN, MOVING) for i in range(len(ALL_TASKS)): ALL_TASKS[i].id =",
"BuildingTask('ceiling', 15, [5, 8, 0]) ROOFING = BuildingTask('roofing', 5, [6, 7, 0]) PAINTING",
"are three workers, and each worker has a given non-negative skill level for",
"precedence constraints. There are three workers, and each worker has a given non-negative",
"for i in range(len(ALL_TASKS)): ALL_TASKS[i].id = i #----------------------------------------------------------------------------- # Build the model #-----------------------------------------------------------------------------",
"#----------------------------------------------------------------------------- # Assign an index to tasks ALL_TASKS = (MASONRY, CARPENTRY, PLUMBING, CEILING,",
"= BuildingTask('masonry', 35, [9, 5, 0]) CARPENTRY = BuildingTask('carpentry', 15, [7, 0, 5])",
"to be executed for each house MASONRY = BuildingTask('masonry', 35, [9, 5, 0])",
"tasks while respecting the deadlines. Please refer to documentation for appropriate setup of",
"Please refer to documentation for appropriate setup of solving configuration. \"\"\" from docplex.cp.model",
"= [[] for w in range(NB_WORKERS)] # Tasks (interval variables) assigned to a",
"BuildingTask('masonry', 35, [9, 5, 0]) CARPENTRY = BuildingTask('carpentry', 15, [7, 0, 5]) PLUMBING",
"of skills mdl.add(mdl.maximize(total_skill)) #----------------------------------------------------------------------------- # Solve the model and display the result #-----------------------------------------------------------------------------",
"X ends before start of Y) PRECEDENCES = ( (MASONRY, CARPENTRY), (MASONRY, PLUMBING),",
"7, 0]) CEILING = BuildingTask('ceiling', 15, [5, 8, 0]) ROOFING = BuildingTask('roofing', 5,",
"Y) means X ends before start of Y) PRECEDENCES = ( (MASONRY, CARPENTRY),",
"^ ^ loc, task = name[1:].split('-', 1) return task[0].upper() + loc # Solve",
"will have to be selected among the ones who have a non null",
"time. Each house has a deadline. The objective is to maximize the skill",
"#----------------------------------------------------------------------------- # Initialize the problem data #----------------------------------------------------------------------------- NB_HOUSES = 5 DEADLINE = 318",
"non-negative skill level for each task. Each task requires one worker that will",
"5, 9]) MOVING = BuildingTask('moving', 5, [6, 0, 8]) # Tasks precedence constraints",
"executed for each house MASONRY = BuildingTask('masonry', 35, [9, 5, 0]) CARPENTRY =",
"for t in ALL_TASKS] # Add precedence constraints for p, s in PRECEDENCES:",
"['Joe', 'Jack', 'Jim'] NB_WORKERS = len(WORKER_NAMES) # House building task descriptor class BuildingTask(object):",
"( (MASONRY, CARPENTRY), (MASONRY, PLUMBING), (MASONRY, CEILING), (CARPENTRY, ROOFING), (CEILING, PAINTING), (ROOFING, WINDOWS),",
"mdl = CpoModel() # Initialize model variable sets total_skill = 0 # Expression",
"level for that task. A worker can be assigned to only one task",
"mdl.add(mdl.maximize(total_skill)) #----------------------------------------------------------------------------- # Solve the model and display the result #----------------------------------------------------------------------------- def compact(name):",
"to a each worker desc = dict() # Map retrieving task from interval",
"worker that will have to be selected among the ones who have a",
"a deadline. The objective is to maximize the skill levels of the workers",
"under Apache License, Version 2.0, January 2004, # http://www.apache.org/licenses/ # (c) Copyright IBM",
"skills): self.name = name self.duration = duration # Task duration self.skills = skills",
"(PAINTING, MOVING), ) #----------------------------------------------------------------------------- # Prepare the data for modeling #----------------------------------------------------------------------------- # Assign",
"duration # Task duration self.skills = skills # Skills of each worker for",
"PRECEDENCES: mdl.add(mdl.end_before_start(tasks[p.id], tasks[s.id])) # Allocate tasks to workers global total_skill for t in",
"'Jack', 'Jim'] NB_WORKERS = len(WORKER_NAMES) # House building task descriptor class BuildingTask(object): def",
"Some tasks must necessarily take place before others and these requirements are expressed",
"each worker has a given non-negative skill level for each task. Each task",
"h in range(NB_HOUSES): make_house(h, DEADLINE) # Avoid overlapping between tasks of each worker",
"# Make houses for h in range(NB_HOUSES): make_house(h, DEADLINE) # Avoid overlapping between",
"the result #----------------------------------------------------------------------------- def compact(name): # Example: H3-garden -> G3 # ^ ^",
"of Y) PRECEDENCES = ( (MASONRY, CARPENTRY), (MASONRY, PLUMBING), (MASONRY, CEILING), (CARPENTRY, ROOFING),",
"Draw solution if msol and visu.is_visu_enabled(): visu.timeline('Solution SchedOptional', 0, DEADLINE) for w in",
"[5, 5, 0]) GARDEN = BuildingTask('garden', 5, [5, 5, 9]) MOVING = BuildingTask('moving',",
"has a given non-negative skill level for each task. Each task requires one",
"G3 # ^ ^ loc, task = name[1:].split('-', 1) return task[0].upper() + loc",
"Prepare the data for modeling #----------------------------------------------------------------------------- # Assign an index to tasks ALL_TASKS",
"requires one worker that will have to be selected among the ones who",
"0, 5]) PLUMBING = BuildingTask('plumbing', 40, [0, 7, 0]) CEILING = BuildingTask('ceiling', 15,",
"are expressed through precedence constraints. There are three workers, and each worker has",
"for modeling #----------------------------------------------------------------------------- # Assign an index to tasks ALL_TASKS = (MASONRY, CARPENTRY,",
"tasks to be executed for each house MASONRY = BuildingTask('masonry', 35, [9, 5,",
"one worker that will have to be selected among the ones who have",
"provided under Apache License, Version 2.0, January 2004, # http://www.apache.org/licenses/ # (c) Copyright",
"(ROOFING, GARDEN), (PLUMBING, GARDEN), (WINDOWS, MOVING), (FACADE, MOVING), (GARDEN, MOVING), (PAINTING, MOVING), )",
"Solve model print(\"Solving model....\") msol = mdl.solve(FailLimit=10000, TimeLimit=10) print(\"Solution: \") msol.print_solution() # Draw",
"a non null skill level for that task. A worker can be assigned",
"task. Each task requires one worker that will have to be selected among",
"Tasks (interval variables) assigned to a each worker desc = dict() # Map",
"name=\"H{}-{}({})\".format(loc, t.name, WORKER_NAMES[w])) worker_tasks[w].append(wt) allocs.append(wt) total_skill += (t.skills[w] * mdl.presence_of(wt)) desc[wt] = t",
"painting, etc. must be scheduled. Some tasks must necessarily take place before others",
"ROOFING, PAINTING, WINDOWS, FACADE, GARDEN, MOVING) for i in range(len(ALL_TASKS)): ALL_TASKS[i].id = i",
"in range(NB_HOUSES): make_house(h, DEADLINE) # Avoid overlapping between tasks of each worker for",
"[6, 7, 0]) PAINTING = BuildingTask('painting', 10, [0, 9, 6]) WINDOWS = BuildingTask('windows',",
"an index to tasks ALL_TASKS = (MASONRY, CARPENTRY, PLUMBING, CEILING, ROOFING, PAINTING, WINDOWS,",
"msol = mdl.solve(FailLimit=10000, TimeLimit=10) print(\"Solution: \") msol.print_solution() # Draw solution if msol and",
"to be selected among the ones who have a non null skill level",
"# http://www.apache.org/licenses/ # (c) Copyright IBM Corp. 2015, 2016 # -------------------------------------------------------------------------- \"\"\" This",
"^ loc, task = name[1:].split('-', 1) return task[0].upper() + loc # Solve model",
"5, 0]) GARDEN = BuildingTask('garden', 5, [5, 5, 9]) MOVING = BuildingTask('moving', 5,",
"must be scheduled. Some tasks must necessarily take place before others and these",
"WORKER_NAMES[w])) worker_tasks[w].append(wt) allocs.append(wt) total_skill += (t.skills[w] * mdl.presence_of(wt)) desc[wt] = t mdl.add(mdl.alternative(tasks[t.id], allocs))",
"# Example: H3-garden -> G3 # ^ ^ loc, task = name[1:].split('-', 1)",
"task for this house tasks = [mdl.interval_var(size=t.duration, end=(INTERVAL_MIN, deadline), name='H' + str(loc) +",
"for this house tasks = [mdl.interval_var(size=t.duration, end=(INTERVAL_MIN, deadline), name='H' + str(loc) + '-'",
"0]) ROOFING = BuildingTask('roofing', 5, [6, 7, 0]) PAINTING = BuildingTask('painting', 10, [0,",
"name self.duration = duration # Task duration self.skills = skills # Skills of",
"tasks of each worker for w in range(NB_WORKERS): mdl.add(mdl.no_overlap(worker_tasks[w])) # Maximize total of",
"be scheduled. Some tasks must necessarily take place before others and these requirements",
"Initialize the problem data #----------------------------------------------------------------------------- NB_HOUSES = 5 DEADLINE = 318 WORKER_NAMES =",
"this house tasks = [mdl.interval_var(size=t.duration, end=(INTERVAL_MIN, deadline), name='H' + str(loc) + '-' +",
"finishing the house ''' # Create interval variable for each task for this",
"a problem of building five houses. The masonry, roofing, painting, etc. must be",
"etc. must be scheduled. Some tasks must necessarily take place before others and",
"retrieving task from interval variable # Utility function def make_house(loc, deadline): ''' Create",
"for finishing the house ''' # Create interval variable for each task for",
"# Expression computing total of skills worker_tasks = [[] for w in range(NB_WORKERS)]",
"def __init__(self, name, duration, skills): self.name = name self.duration = duration # Task",
"t in ALL_TASKS] # Add precedence constraints for p, s in PRECEDENCES: mdl.add(mdl.end_before_start(tasks[p.id],",
"ROOFING), (CEILING, PAINTING), (ROOFING, WINDOWS), (ROOFING, FACADE), (PLUMBING, FACADE), (ROOFING, GARDEN), (PLUMBING, GARDEN),",
"skills mdl.add(mdl.maximize(total_skill)) #----------------------------------------------------------------------------- # Solve the model and display the result #----------------------------------------------------------------------------- def",
"level for each task. Each task requires one worker that will have to",
"the model and display the result #----------------------------------------------------------------------------- def compact(name): # Example: H3-garden ->",
"the tasks while respecting the deadlines. Please refer to documentation for appropriate setup",
"deadline. The objective is to maximize the skill levels of the workers assigned",
"global total_skill for t in ALL_TASKS: allocs = [] for w in range(NB_WORKERS):",
"BuildingTask('garden', 5, [5, 5, 9]) MOVING = BuildingTask('moving', 5, [6, 0, 8]) #",
"documentation for appropriate setup of solving configuration. \"\"\" from docplex.cp.model import CpoModel, INTERVAL_MIN",
"A worker can be assigned to only one task at a time. Each",
"masonry, roofing, painting, etc. must be scheduled. Some tasks must necessarily take place",
"duration self.skills = skills # Skills of each worker for this task #",
"for each task. Each task requires one worker that will have to be",
"# Red-like color when task does not use the most skilled worker color",
"BuildingTask('moving', 5, [6, 0, 8]) # Tasks precedence constraints (each tuple (X, Y)",
"Avoid overlapping between tasks of each worker for w in range(NB_WORKERS): mdl.add(mdl.no_overlap(worker_tasks[w])) #",
"(each tuple (X, Y) means X ends before start of Y) PRECEDENCES =",
"msol.print_solution() # Draw solution if msol and visu.is_visu_enabled(): visu.timeline('Solution SchedOptional', 0, DEADLINE) for",
"Each house has a deadline. The objective is to maximize the skill levels",
"[0, 7, 0]) CEILING = BuildingTask('ceiling', 15, [5, 8, 0]) ROOFING = BuildingTask('roofing',",
"Initialize model variable sets total_skill = 0 # Expression computing total of skills",
"ROOFING = BuildingTask('roofing', 5, [6, 7, 0]) PAINTING = BuildingTask('painting', 10, [0, 9,",
"[8, 0, 5]) FACADE = BuildingTask('facade', 10, [5, 5, 0]) GARDEN = BuildingTask('garden',",
"PLUMBING, CEILING, ROOFING, PAINTING, WINDOWS, FACADE, GARDEN, MOVING) for i in range(len(ALL_TASKS)): ALL_TASKS[i].id",
"# ^ ^ loc, task = name[1:].split('-', 1) return task[0].upper() + loc #",
"for w in range(NB_WORKERS): visu.sequence(name=WORKER_NAMES[w]) for t in worker_tasks[w]: wt = msol.get_var_solution(t) if",
"else: # Red-like color when task does not use the most skilled worker",
"in worker_tasks[w]: wt = msol.get_var_solution(t) if wt.is_present(): if desc[t].skills[w] == max(desc[t].skills): # Green-like",
"(PLUMBING, FACADE), (ROOFING, GARDEN), (PLUMBING, GARDEN), (WINDOWS, MOVING), (FACADE, MOVING), (GARDEN, MOVING), (PAINTING,",
"is to maximize the skill levels of the workers assigned to the tasks",
"appropriate setup of solving configuration. \"\"\" from docplex.cp.model import CpoModel, INTERVAL_MIN import docplex.cp.utils_visu",
"(MASONRY, CARPENTRY, PLUMBING, CEILING, ROOFING, PAINTING, WINDOWS, FACADE, GARDEN, MOVING) for i in",
"model and display the result #----------------------------------------------------------------------------- def compact(name): # Example: H3-garden -> G3",
"# Add precedence constraints for p, s in PRECEDENCES: mdl.add(mdl.end_before_start(tasks[p.id], tasks[s.id])) # Allocate",
"msol and visu.is_visu_enabled(): visu.timeline('Solution SchedOptional', 0, DEADLINE) for w in range(NB_WORKERS): visu.sequence(name=WORKER_NAMES[w]) for",
"msol.get_var_solution(t) if wt.is_present(): if desc[t].skills[w] == max(desc[t].skills): # Green-like color when task is",
"wt.is_present(): if desc[t].skills[w] == max(desc[t].skills): # Green-like color when task is using the",
"color = 'lightgreen' else: # Red-like color when task does not use the",
"be selected among the ones who have a non null skill level for",
"range(NB_WORKERS)] # Tasks (interval variables) assigned to a each worker desc = dict()",
"Source file provided under Apache License, Version 2.0, January 2004, # http://www.apache.org/licenses/ #",
"each task for this house tasks = [mdl.interval_var(size=t.duration, end=(INTERVAL_MIN, deadline), name='H' + str(loc)",
"ALL_TASKS: allocs = [] for w in range(NB_WORKERS): if t.skills[w] > 0: wt",
"non null skill level for that task. A worker can be assigned to",
"setup of solving configuration. \"\"\" from docplex.cp.model import CpoModel, INTERVAL_MIN import docplex.cp.utils_visu as",
"License, Version 2.0, January 2004, # http://www.apache.org/licenses/ # (c) Copyright IBM Corp. 2015,",
"duration, skills): self.name = name self.duration = duration # Task duration self.skills =",
"from interval variable # Utility function def make_house(loc, deadline): ''' Create model elements",
"task descriptor class BuildingTask(object): def __init__(self, name, duration, skills): self.name = name self.duration",
"#----------------------------------------------------------------------------- # Create model mdl = CpoModel() # Initialize model variable sets total_skill",
"data for modeling #----------------------------------------------------------------------------- # Assign an index to tasks ALL_TASKS = (MASONRY,",
"Allocate tasks to workers global total_skill for t in ALL_TASKS: allocs = []",
"building five houses. The masonry, roofing, painting, etc. must be scheduled. Some tasks",
"(GARDEN, MOVING), (PAINTING, MOVING), ) #----------------------------------------------------------------------------- # Prepare the data for modeling #-----------------------------------------------------------------------------",
"compact(name): # Example: H3-garden -> G3 # ^ ^ loc, task = name[1:].split('-',",
"means X ends before start of Y) PRECEDENCES = ( (MASONRY, CARPENTRY), (MASONRY,",
"Utility function def make_house(loc, deadline): ''' Create model elements corresponding to the building",
"interval variable # Utility function def make_house(loc, deadline): ''' Create model elements corresponding",
"ones who have a non null skill level for that task. A worker",
"5, [6, 0, 8]) # Tasks precedence constraints (each tuple (X, Y) means",
"has a deadline. The objective is to maximize the skill levels of the",
"''' # Create interval variable for each task for this house tasks =",
"who have a non null skill level for that task. A worker can",
"of each worker for w in range(NB_WORKERS): mdl.add(mdl.no_overlap(worker_tasks[w])) # Maximize total of skills",
"self.duration = duration # Task duration self.skills = skills # Skills of each",
"\") msol.print_solution() # Draw solution if msol and visu.is_visu_enabled(): visu.timeline('Solution SchedOptional', 0, DEADLINE)",
"wt = msol.get_var_solution(t) if wt.is_present(): if desc[t].skills[w] == max(desc[t].skills): # Green-like color when",
"that task. A worker can be assigned to only one task at a",
"name, duration, skills): self.name = name self.duration = duration # Task duration self.skills",
"the ones who have a non null skill level for that task. A",
"-------------------------------------------------------------------------- \"\"\" This is a problem of building five houses. The masonry, roofing,",
"have a non null skill level for that task. A worker can be",
"+ t.name) for t in ALL_TASKS] # Add precedence constraints for p, s",
"take place before others and these requirements are expressed through precedence constraints. There",
"be executed for each house MASONRY = BuildingTask('masonry', 35, [9, 5, 0]) CARPENTRY",
"for h in range(NB_HOUSES): make_house(h, DEADLINE) # Avoid overlapping between tasks of each",
"0 # Expression computing total of skills worker_tasks = [[] for w in",
"in range(NB_WORKERS): if t.skills[w] > 0: wt = mdl.interval_var(optional=True, name=\"H{}-{}({})\".format(loc, t.name, WORKER_NAMES[w])) worker_tasks[w].append(wt)",
"MOVING), (GARDEN, MOVING), (PAINTING, MOVING), ) #----------------------------------------------------------------------------- # Prepare the data for modeling",
"= BuildingTask('roofing', 5, [6, 7, 0]) PAINTING = BuildingTask('painting', 10, [0, 9, 6])",
"expressed through precedence constraints. There are three workers, and each worker has a",
"place before others and these requirements are expressed through precedence constraints. There are",
"t in ALL_TASKS: allocs = [] for w in range(NB_WORKERS): if t.skills[w] >",
"= BuildingTask('garden', 5, [5, 5, 9]) MOVING = BuildingTask('moving', 5, [6, 0, 8])",
"= CpoModel() # Initialize model variable sets total_skill = 0 # Expression computing",
"2004, # http://www.apache.org/licenses/ # (c) Copyright IBM Corp. 2015, 2016 # -------------------------------------------------------------------------- \"\"\"",
"the house ''' # Create interval variable for each task for this house",
"FACADE), (PLUMBING, FACADE), (ROOFING, GARDEN), (PLUMBING, GARDEN), (WINDOWS, MOVING), (FACADE, MOVING), (GARDEN, MOVING),",
"BuildingTask('painting', 10, [0, 9, 6]) WINDOWS = BuildingTask('windows', 5, [8, 0, 5]) FACADE",
"> 0: wt = mdl.interval_var(optional=True, name=\"H{}-{}({})\".format(loc, t.name, WORKER_NAMES[w])) worker_tasks[w].append(wt) allocs.append(wt) total_skill += (t.skills[w]",
"http://www.apache.org/licenses/ # (c) Copyright IBM Corp. 2015, 2016 # -------------------------------------------------------------------------- \"\"\" This is",
"CARPENTRY = BuildingTask('carpentry', 15, [7, 0, 5]) PLUMBING = BuildingTask('plumbing', 40, [0, 7,",
"variable # Utility function def make_house(loc, deadline): ''' Create model elements corresponding to",
"the problem data #----------------------------------------------------------------------------- NB_HOUSES = 5 DEADLINE = 318 WORKER_NAMES = ['Joe',",
"and display the result #----------------------------------------------------------------------------- def compact(name): # Example: H3-garden -> G3 #",
"#----------------------------------------------------------------------------- # Prepare the data for modeling #----------------------------------------------------------------------------- # Assign an index to",
"for w in range(NB_WORKERS): if t.skills[w] > 0: wt = mdl.interval_var(optional=True, name=\"H{}-{}({})\".format(loc, t.name,",
"[] for w in range(NB_WORKERS): if t.skills[w] > 0: wt = mdl.interval_var(optional=True, name=\"H{}-{}({})\".format(loc,",
"location deadline Deadline for finishing the house ''' # Create interval variable for",
"There are three workers, and each worker has a given non-negative skill level",
"BuildingTask(object): def __init__(self, name, duration, skills): self.name = name self.duration = duration #",
"Apache License, Version 2.0, January 2004, # http://www.apache.org/licenses/ # (c) Copyright IBM Corp.",
"color when task is using the most skilled worker color = 'lightgreen' else:",
"BuildingTask('carpentry', 15, [7, 0, 5]) PLUMBING = BuildingTask('plumbing', 40, [0, 7, 0]) CEILING",
"= ( (MASONRY, CARPENTRY), (MASONRY, PLUMBING), (MASONRY, CEILING), (CARPENTRY, ROOFING), (CEILING, PAINTING), (ROOFING,",
"-> G3 # ^ ^ loc, task = name[1:].split('-', 1) return task[0].upper() +",
"total of skills worker_tasks = [[] for w in range(NB_WORKERS)] # Tasks (interval",
"computing total of skills worker_tasks = [[] for w in range(NB_WORKERS)] # Tasks",
"= mdl.solve(FailLimit=10000, TimeLimit=10) print(\"Solution: \") msol.print_solution() # Draw solution if msol and visu.is_visu_enabled():",
"in range(NB_WORKERS): mdl.add(mdl.no_overlap(worker_tasks[w])) # Maximize total of skills mdl.add(mdl.maximize(total_skill)) #----------------------------------------------------------------------------- # Solve the",
"the most skilled worker color = 'lightgreen' else: # Red-like color when task",
"the deadlines. Please refer to documentation for appropriate setup of solving configuration. \"\"\"",
"(X, Y) means X ends before start of Y) PRECEDENCES = ( (MASONRY,",
"skill level for each task. Each task requires one worker that will have"
] |
[
"Script que identifica si un numero ingresado por el usuario es PAR. '''",
"un numero Entero: \") num = int(input()) if num % 2 == 0",
": print (\"El Numero es Par: \") else: print (\"El Numero es Impar:",
"ingresado por el usuario es PAR. ''' N = 0 print (\"Ingrese un",
"0 print (\"Ingrese un numero Entero: \") num = int(input()) if num %",
"<reponame>caibacord6/Programming-2020B ''' Script que identifica si un numero ingresado por el usuario es",
"si un numero ingresado por el usuario es PAR. ''' N = 0",
"identifica si un numero ingresado por el usuario es PAR. ''' N =",
"el usuario es PAR. ''' N = 0 print (\"Ingrese un numero Entero:",
"que identifica si un numero ingresado por el usuario es PAR. ''' N",
"PAR. ''' N = 0 print (\"Ingrese un numero Entero: \") num =",
"0 : print (\"El Numero es Par: \") else: print (\"El Numero es",
"== 0 : print (\"El Numero es Par: \") else: print (\"El Numero",
"% 2 == 0 : print (\"El Numero es Par: \") else: print",
"print (\"El Numero es Par: \") else: print (\"El Numero es Impar: \")",
"N = 0 print (\"Ingrese un numero Entero: \") num = int(input()) if",
"= 0 print (\"Ingrese un numero Entero: \") num = int(input()) if num",
"(\"Ingrese un numero Entero: \") num = int(input()) if num % 2 ==",
"usuario es PAR. ''' N = 0 print (\"Ingrese un numero Entero: \")",
"''' Script que identifica si un numero ingresado por el usuario es PAR.",
"num % 2 == 0 : print (\"El Numero es Par: \") else:",
"''' N = 0 print (\"Ingrese un numero Entero: \") num = int(input())",
"Entero: \") num = int(input()) if num % 2 == 0 : print",
"por el usuario es PAR. ''' N = 0 print (\"Ingrese un numero",
"2 == 0 : print (\"El Numero es Par: \") else: print (\"El",
"print (\"Ingrese un numero Entero: \") num = int(input()) if num % 2",
"un numero ingresado por el usuario es PAR. ''' N = 0 print",
"numero ingresado por el usuario es PAR. ''' N = 0 print (\"Ingrese",
"es PAR. ''' N = 0 print (\"Ingrese un numero Entero: \") num",
"= int(input()) if num % 2 == 0 : print (\"El Numero es",
"numero Entero: \") num = int(input()) if num % 2 == 0 :",
"if num % 2 == 0 : print (\"El Numero es Par: \")",
"\") num = int(input()) if num % 2 == 0 : print (\"El",
"num = int(input()) if num % 2 == 0 : print (\"El Numero",
"int(input()) if num % 2 == 0 : print (\"El Numero es Par:"
] |
[
"for idx, ch in enumerate(S): if ch == '(': stack.append(idx) elif ch ==",
"idx, ch in enumerate(S): if ch == '(': stack.append(idx) elif ch == ')':",
"S: str) -> int: stack = [] violations = 0 if S ==",
"0 if S == '': return 0 for idx, ch in enumerate(S): if",
"elif ch == ')': if len(stack) == 0: violations += 1 else: stack.pop()",
"-> int: stack = [] violations = 0 if S == '': return",
"len(stack) == 0: violations += 1 else: stack.pop() if len(stack) > 0: violations",
"== ')': if len(stack) == 0: violations += 1 else: stack.pop() if len(stack)",
"stack = [] violations = 0 if S == '': return 0 for",
"class Solution: def minAddToMakeValid(self, S: str) -> int: stack = [] violations =",
"str) -> int: stack = [] violations = 0 if S == '':",
"= 0 if S == '': return 0 for idx, ch in enumerate(S):",
"0: violations += 1 else: stack.pop() if len(stack) > 0: violations += len(stack)",
"<reponame>MartinMa28/Algorithms_review class Solution: def minAddToMakeValid(self, S: str) -> int: stack = [] violations",
"return 0 for idx, ch in enumerate(S): if ch == '(': stack.append(idx) elif",
"0 for idx, ch in enumerate(S): if ch == '(': stack.append(idx) elif ch",
"+= 1 else: stack.pop() if len(stack) > 0: violations += len(stack) return violations",
"ch == '(': stack.append(idx) elif ch == ')': if len(stack) == 0: violations",
"== '': return 0 for idx, ch in enumerate(S): if ch == '(':",
"ch == ')': if len(stack) == 0: violations += 1 else: stack.pop() if",
"def minAddToMakeValid(self, S: str) -> int: stack = [] violations = 0 if",
"in enumerate(S): if ch == '(': stack.append(idx) elif ch == ')': if len(stack)",
"if S == '': return 0 for idx, ch in enumerate(S): if ch",
"'(': stack.append(idx) elif ch == ')': if len(stack) == 0: violations += 1",
"[] violations = 0 if S == '': return 0 for idx, ch",
"== 0: violations += 1 else: stack.pop() if len(stack) > 0: violations +=",
"violations += 1 else: stack.pop() if len(stack) > 0: violations += len(stack) return",
"S == '': return 0 for idx, ch in enumerate(S): if ch ==",
"int: stack = [] violations = 0 if S == '': return 0",
"')': if len(stack) == 0: violations += 1 else: stack.pop() if len(stack) >",
"Solution: def minAddToMakeValid(self, S: str) -> int: stack = [] violations = 0",
"if len(stack) == 0: violations += 1 else: stack.pop() if len(stack) > 0:",
"minAddToMakeValid(self, S: str) -> int: stack = [] violations = 0 if S",
"= [] violations = 0 if S == '': return 0 for idx,",
"'': return 0 for idx, ch in enumerate(S): if ch == '(': stack.append(idx)",
"stack.append(idx) elif ch == ')': if len(stack) == 0: violations += 1 else:",
"== '(': stack.append(idx) elif ch == ')': if len(stack) == 0: violations +=",
"violations = 0 if S == '': return 0 for idx, ch in",
"enumerate(S): if ch == '(': stack.append(idx) elif ch == ')': if len(stack) ==",
"ch in enumerate(S): if ch == '(': stack.append(idx) elif ch == ')': if",
"if ch == '(': stack.append(idx) elif ch == ')': if len(stack) == 0:"
] |
[] |
[
"\"\"\" This module tests the creation of pipeline nodes from various different types",
"( \"function_single_nodes\", 4, \"\"\"\\ from kedro.pipeline import Pipeline, node node_a_b = node(lambda x:",
"4, \"\"\"\\ from kedro.pipeline import node nodes_pipeline = [ node(lambda x: x, \"a\",",
"x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") ]) \"\"\", ),",
"] ] \"\"\", ), ( \"nested_tuple_nodes\", 4, \"\"\"\\ from kedro.pipeline import node nodes_pipeline",
"x: x, \"b\", \"c\", name=\"b_c\"), ]) node_a2 = node(lambda x: x, \"a2\", \"b2\",",
"x, \"a2\", \"b2\", name=\"a_b2\"), node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\"), ) } \"\"\",",
"kedro.pipeline import node, Pipeline nodes_pipeline = Pipeline([ node(lambda x: x, \"a\", \"b\", name=\"a_b\"),",
"node(lambda x: x, \"b\", \"c\", name=\"b_c\") def create_pipeline(): return Pipeline([ node(lambda x: x,",
"x: x, \"b2\", \"c2\", name=\"b_c2\") \"\"\", ), ( \"list_nodes_nodes\", 4, \"\"\"\\ from kedro.pipeline",
"import find_kedro contents = [ ( \"single_nodes\", 2, \"\"\"\\ from kedro.pipeline import node",
"\"b\", \"c\", name=\"b_c\"), ] node_a2 = node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\") node_b2",
"x, \"b\", \"c\", name=\"b_c\") ) \"\"\", ), ( \"pipeline_nodes\", 2, \"\"\"\\ from kedro.pipeline",
"node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ] ) \"\"\", ), ( \"function_single_nodes\", 4,",
"[ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\")",
"\"\"\"\\ from kedro.pipeline import node, Pipeline nodes = Pipeline([ node(lambda x: x, \"a\",",
"from kedro.pipeline import node nodes = ( node(lambda x: x, \"a\", \"b\", name=\"a_b\"),",
"node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") )",
"x, \"b\", \"c\", name=\"b_c\") def create_pipeline(): return Pipeline([ node(lambda x: x, \"fa\", \"fb\",",
"kedro.pipeline import Pipeline, node def create_pipeline(): return Pipeline([ node(lambda x: x, \"a\", \"b\",",
"node, Pipeline nodes = Pipeline([ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x:",
"] ) \"\"\", ), ( \"function_single_nodes\", 4, \"\"\"\\ from kedro.pipeline import Pipeline, node",
"\"a2\", \"b2\", name=\"a_b2\") node_b2 = node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\") \"\"\", ),",
"x: x, \"a2\", \"b2\", name=\"a_b2\") node_b2 = node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\")",
"\"nested_list_nodes\", 4, \"\"\"\\ from kedro.pipeline import node nodes_pipeline = [ node(lambda x: x,",
"x, \"fa\", \"fb\", name=\"fa_fb\"), node(lambda x: x, \"fb\", \"fc\", name=\"fb_fc\"), ] ) \"\"\",",
"x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") ] \"\"\",",
"node creaste_pipeline = [ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x,",
"x: x, \"fb\", \"fc\", name=\"fb_fc\"), ] ) \"\"\", ), ( \"list_create_pipeline\", 2, \"\"\"\\",
"[ node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\"), node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\"),",
"\"fc\", name=\"fb_fc\"), ] ) \"\"\", ), ( \"function_list_nodes\", 4, \"\"\"\\ from kedro.pipeline import",
"), ] @pytest.mark.parametrize(\"name, num_nodes, content\", contents) def test_create_file(tmpdir, name, num_nodes, content): p =",
"]) nodes_list = [ node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\"), node(lambda x: x,",
"x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ]) nodes_list",
"\"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") ]) \"\"\", ), (",
"x: x, \"b\", \"c\", name=\"b_c\"), ] ) \"\"\", ), ( \"function_single_nodes\", 4, \"\"\"\\",
"2, \"\"\"\\ from kedro.pipeline import node nodes = [ node(lambda x: x, \"a\",",
"import node nodes = ( node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x:",
"= node(lambda x: x, \"a\", \"b\", name=\"a_b\") node_b_c = node(lambda x: x, \"b\",",
"contents) def test_create_file(tmpdir, name, num_nodes, content): p = tmpdir.mkdir(\"nodes\").join(f\"{ name }.py\") p.write(textwrap.dedent(content)) pipelines",
"} \"\"\", ), ( \"tuple_nodes\", 2, \"\"\"\\ from kedro.pipeline import node nodes =",
"( len(pipelines[\"__default__\"].nodes) == num_nodes ), f\"did not collect all nodes from { name",
"\"b2\", \"c2\", name=\"b_c2\"), ) } \"\"\", ), ( \"function_nodes\", 2, \"\"\"\\ from kedro.pipeline",
"list(pipelines.keys()) == [f\"nodes.{ name }\", \"__default__\"] assert ( len(pipelines[\"__default__\"].nodes) == num_nodes ), f\"did",
"x: x, f\"a{n}\", f\"a{n+1}\", name=f\"a{n}_a{n+1}\") for n in range(100)] \"\"\", ), ( \"dynamic_pipeline_nodes\",",
"\"b\", name=\"a_b\") node_b_c = node(lambda x: x, \"b\", \"c\", name=\"b_c\") def create_pipeline(): return",
"name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") ] \"\"\", ), ( \"set_nodes\", 2,",
"find_kedro(directory=tmpdir, verbose=True) assert list(pipelines.keys()) == [f\"nodes.{ name }\", \"__default__\"] assert ( len(pipelines[\"__default__\"].nodes) ==",
"node_a2 = node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\") node_b2 = node(lambda x: x,",
"\"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ]) node_a2 = node(lambda x:",
"node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") }",
"name=\"fa_fb\"), node(lambda x: x, \"fb\", \"fc\", name=\"fb_fc\"), ] ) \"\"\", ), ( \"function_list_nodes\",",
"x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ] )",
"\"b\", \"c\", name=\"b_c\"), ]) nodes_list = [ node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\"),",
"\"\"\", ), ( \"list_nodes_nodes\", 4, \"\"\"\\ from kedro.pipeline import node nodes_pipeline = [",
"node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), [",
"x: x, \"b\", \"c\", name=\"b_c\") ] \"\"\", ), ] @pytest.mark.parametrize(\"name, num_nodes, content\", contents)",
"\"b2\", \"c2\", name=\"b_c2\"), ] \"\"\", ), ( \"pipeline_nodes_nodes\", 4, \"\"\"\\ from kedro.pipeline import",
"def create_pipeline(): return Pipeline([ node(lambda x: x, \"fa\", \"fb\", name=\"fa_fb\"), node(lambda x: x,",
"\"\"\"\\ from kedro.pipeline import node node_a_b = node(lambda x: x, \"a\", \"b\", name=\"a_b\")",
"kedro.pipeline import Pipeline, node creaste_pipeline = [ node(lambda x: x, \"a\", \"b\", name=\"a_b\"),",
"nodes_pipeline = [ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\",",
"textwrap import pytest from find_kedro import find_kedro contents = [ ( \"single_nodes\", 2,",
"\"b2\", \"c2\", name=\"b_c2\"), ] ] \"\"\", ), ( \"nested_tuple_nodes\", 4, \"\"\"\\ from kedro.pipeline",
"of types. \"\"\" import textwrap import pytest from find_kedro import find_kedro contents =",
"( \"list_create_pipeline\", 2, \"\"\"\\ from kedro.pipeline import Pipeline, node creaste_pipeline = [ node(lambda",
"from kedro.pipeline import node node_a_b = node(lambda x: x, \"a\", \"b\", name=\"a_b\") node_b_c",
"x: x, \"b\", \"c\", name=\"b_c\") ]) \"\"\", ), ( \"pipeline_list_nodes\", 4, \"\"\"\\ from",
"types. \"\"\" import textwrap import pytest from find_kedro import find_kedro contents = [",
"node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ]) nodes_list = [ node(lambda x: x,",
"in range(100)] \"\"\", ), ( \"dynamic_pipeline_nodes\", 100, \"\"\"\\ from kedro.pipeline import node, Pipeline",
"x, \"b\", \"c\", name=\"b_c\") } \"\"\", ), ( \"tuple_nodes\", 2, \"\"\"\\ from kedro.pipeline",
"\"\"\", ), ( \"nested_list_nodes\", 4, \"\"\"\\ from kedro.pipeline import node nodes_pipeline = [",
"name=\"a_b2\") node_b2 = node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\") \"\"\", ), ( \"list_nodes_nodes\",",
"node nodes = [ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x,",
"module tests the creation of pipeline nodes from various different types and combinations",
"node(lambda x: x, \"b\", \"c\", name=\"b_c\"), [ node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\"),",
"\"c\", name=\"b_c\") ] \"\"\", ), ( \"set_nodes\", 2, \"\"\"\\ from kedro.pipeline import node",
"= find_kedro(directory=tmpdir, verbose=True) assert list(pipelines.keys()) == [f\"nodes.{ name }\", \"__default__\"] assert ( len(pipelines[\"__default__\"].nodes)",
"), ( \"dynamic_list_nodes\", 100, \"\"\"\\ from kedro.pipeline import node nodes_pipeline = [ node(lambda",
"nodes = Pipeline([ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\",",
"\"\"\", ), ( \"dynamic_list_nodes\", 100, \"\"\"\\ from kedro.pipeline import node nodes_pipeline = [",
"name=\"a_b\") node_b_c = node(lambda x: x, \"b\", \"c\", name=\"b_c\") def create_pipeline(): return Pipeline([",
"), ( \"nested_tuple_nodes\", 4, \"\"\"\\ from kedro.pipeline import node nodes_pipeline = ( node(lambda",
"( \"dynamic_pipeline_nodes\", 100, \"\"\"\\ from kedro.pipeline import node, Pipeline nodes_pipeline = Pipeline([ node(lambda",
"\"pipeline_nodes\", 2, \"\"\"\\ from kedro.pipeline import node, Pipeline nodes = Pipeline([ node(lambda x:",
"]) \"\"\", ), ( \"pipeline_list_nodes\", 4, \"\"\"\\ from kedro.pipeline import node, Pipeline nodes_pipeline",
"import node, Pipeline nodes_pipeline = Pipeline([ node(lambda x: x, f\"a{n}\", f\"a{n+1}\", name=f\"a{n}_a{n+1}\") for",
"node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") ])",
"\"b\", \"c\", name=\"b_c\") ) \"\"\", ), ( \"pipeline_nodes\", 2, \"\"\"\\ from kedro.pipeline import",
"name=\"b_c2\") \"\"\", ), ( \"list_nodes_nodes\", 4, \"\"\"\\ from kedro.pipeline import node nodes_pipeline =",
"x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), [ node(lambda x:",
"kedro.pipeline import node nodes_pipeline = [ node(lambda x: x, f\"a{n}\", f\"a{n+1}\", name=f\"a{n}_a{n+1}\") for",
"x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), [ node(lambda",
"f\"a{n}\", f\"a{n+1}\", name=f\"a{n}_a{n+1}\") for n in range(100)] \"\"\", ), ( \"dynamic_pipeline_nodes\", 100, \"\"\"\\",
"name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") ) \"\"\", ), ( \"pipeline_nodes\", 2,",
"), ( \"nested_list_nodes\", 4, \"\"\"\\ from kedro.pipeline import node nodes_pipeline = [ node(lambda",
") \"\"\", ), ( \"function_list_nodes\", 4, \"\"\"\\ from kedro.pipeline import Pipeline, node nodes",
"x, \"b\", \"c\", name=\"b_c\"), ]) nodes_list = [ node(lambda x: x, \"a2\", \"b2\",",
"= node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\") node_b2 = node(lambda x: x, \"b2\",",
"nodes_pipeline = ( node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\",",
"kedro.pipeline import node node_a_b = node(lambda x: x, \"a\", \"b\", name=\"a_b\") node_b_c =",
"return Pipeline([ node(lambda x: x, \"fa\", \"fb\", name=\"fa_fb\"), node(lambda x: x, \"fb\", \"fc\",",
"node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ]",
"Pipeline nodes = Pipeline([ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x,",
"from kedro.pipeline import node nodes = [ node(lambda x: x, \"a\", \"b\", name=\"a_b\"),",
"from kedro.pipeline import node, Pipeline nodes_pipeline = Pipeline([ node(lambda x: x, f\"a{n}\", f\"a{n+1}\",",
"\"\"\", ), ( \"nested_tuple_nodes\", 4, \"\"\"\\ from kedro.pipeline import node nodes_pipeline = (",
"\"\"\", ), ( \"list_nodes\", 2, \"\"\"\\ from kedro.pipeline import node nodes = [",
"\"b\", \"c\", name=\"b_c\") \"\"\", ), ( \"list_nodes\", 2, \"\"\"\\ from kedro.pipeline import node",
"create_pipeline(): return Pipeline([ node(lambda x: x, \"fa\", \"fb\", name=\"fa_fb\"), node(lambda x: x, \"fb\",",
"node(lambda x: x, \"b\", \"c\", name=\"b_c\") ) \"\"\", ), ( \"pipeline_nodes\", 2, \"\"\"\\",
"kedro.pipeline import node nodes = [ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda",
"nodes_pipeline = { node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\",",
"\"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") ] \"\"\", ), ( \"set_nodes\",",
"), ( \"function_list_nodes\", 4, \"\"\"\\ from kedro.pipeline import Pipeline, node nodes = [",
"4, \"\"\"\\ from kedro.pipeline import Pipeline, node node_a_b = node(lambda x: x, \"a\",",
"[ node(lambda x: x, f\"a{n}\", f\"a{n+1}\", name=f\"a{n}_a{n+1}\") for n in range(100)] \"\"\", ),",
"name=\"a_b2\"), node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\"), ] ] \"\"\", ), ( \"nested_tuple_nodes\",",
"x: x, \"b\", \"c\", name=\"b_c\"), ] node_a2 = node(lambda x: x, \"a2\", \"b2\",",
"from kedro.pipeline import node nodes_pipeline = { node(lambda x: x, \"a\", \"b\", name=\"a_b\"),",
"different types and combinations of types. \"\"\" import textwrap import pytest from find_kedro",
"\"c2\", name=\"b_c2\") \"\"\", ), ( \"dynamic_list_nodes\", 100, \"\"\"\\ from kedro.pipeline import node nodes_pipeline",
"x: x, \"b2\", \"c2\", name=\"b_c2\"), ] ] \"\"\", ), ( \"nested_tuple_nodes\", 4, \"\"\"\\",
"\"single_nodes\", 2, \"\"\"\\ from kedro.pipeline import node node_a_b = node(lambda x: x, \"a\",",
"\"\"\" import textwrap import pytest from find_kedro import find_kedro contents = [ (",
"import node node_a_b = node(lambda x: x, \"a\", \"b\", name=\"a_b\") node_b_c = node(lambda",
"name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") ]) \"\"\", ), ( \"pipeline_list_nodes\", 4,",
"x, \"b\", \"c\", name=\"b_c\"), ] ) \"\"\", ), ( \"function_single_nodes\", 4, \"\"\"\\ from",
"\"\"\", ), ( \"pipeline_list_nodes\", 4, \"\"\"\\ from kedro.pipeline import node, Pipeline nodes_pipeline =",
"x: x, \"b\", \"c\", name=\"b_c\") ] def create_pipeline(): return Pipeline([ node(lambda x: x,",
"\"b2\", \"c2\", name=\"b_c2\") \"\"\", ), ( \"dynamic_list_nodes\", 100, \"\"\"\\ from kedro.pipeline import node",
"\"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") } \"\"\", ), (",
"kedro.pipeline import node, Pipeline nodes_pipeline = Pipeline([ node(lambda x: x, f\"a{n}\", f\"a{n+1}\", name=f\"a{n}_a{n+1}\")",
"This module tests the creation of pipeline nodes from various different types and",
"( \"function_nodes\", 2, \"\"\"\\ from kedro.pipeline import Pipeline, node def create_pipeline(): return Pipeline([",
") \"\"\", ), ( \"nested_set_nodes\", 4, \"\"\"\\ from kedro.pipeline import node nodes_pipeline =",
"name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ]) node_a2 = node(lambda x: x,",
"\"\"\"\\ from kedro.pipeline import Pipeline, node nodes = [ node(lambda x: x, \"a\",",
"node(lambda x: x, \"fb\", \"fc\", name=\"fb_fc\"), ] ) \"\"\", ), ( \"list_create_pipeline\", 2,",
"x: x, \"fb\", \"fc\", name=\"fb_fc\"), ] ) \"\"\", ), ( \"function_list_nodes\", 4, \"\"\"\\",
"( \"nested_set_nodes\", 4, \"\"\"\\ from kedro.pipeline import node nodes_pipeline = { node(lambda x:",
"\"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") ]) \"\"\", ), ( \"pipeline_list_nodes\",",
"import Pipeline, node def create_pipeline(): return Pipeline([ node(lambda x: x, \"a\", \"b\", name=\"a_b\"),",
"x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") } \"\"\",",
"x: x, \"b2\", \"c2\", name=\"b_c2\"), ) ) \"\"\", ), ( \"nested_set_nodes\", 4, \"\"\"\\",
"Pipeline, node node_a_b = node(lambda x: x, \"a\", \"b\", name=\"a_b\") node_b_c = node(lambda",
"for n in range(100)] \"\"\", ), ( \"dynamic_pipeline_nodes\", 100, \"\"\"\\ from kedro.pipeline import",
"] \"\"\", ), ( \"nested_tuple_nodes\", 4, \"\"\"\\ from kedro.pipeline import node nodes_pipeline =",
"name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ] ) \"\"\", ), ( \"function_single_nodes\",",
"x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") } \"\"\", ),",
"] def create_pipeline(): return Pipeline([ node(lambda x: x, \"fa\", \"fb\", name=\"fa_fb\"), node(lambda x:",
"name=\"b_c\") ) \"\"\", ), ( \"pipeline_nodes\", 2, \"\"\"\\ from kedro.pipeline import node, Pipeline",
"name }\", \"__default__\"] assert ( len(pipelines[\"__default__\"].nodes) == num_nodes ), f\"did not collect all",
"x, \"fb\", \"fc\", name=\"fb_fc\"), ] ) \"\"\", ), ( \"list_create_pipeline\", 2, \"\"\"\\ from",
"\"b2\", name=\"a_b2\"), node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\"), ] ] \"\"\", ), (",
"\"a2\", \"b2\", name=\"a_b2\"), node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\"), ) ) \"\"\", ),",
"x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ]) nodes_list =",
"nodes_pipeline = [ node(lambda x: x, f\"a{n}\", f\"a{n+1}\", name=f\"a{n}_a{n+1}\") for n in range(100)]",
"types and combinations of types. \"\"\" import textwrap import pytest from find_kedro import",
"}\", \"__default__\"] assert ( len(pipelines[\"__default__\"].nodes) == num_nodes ), f\"did not collect all nodes",
"\"\"\", ), ( \"nested_set_nodes\", 4, \"\"\"\\ from kedro.pipeline import node nodes_pipeline = {",
"\"a2\", \"b2\", name=\"a_b2\"), node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\"), ] ] \"\"\", ),",
"node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\"), ) ) \"\"\", ), ( \"nested_set_nodes\", 4,",
"\"b\", \"c\", name=\"b_c\"), [ node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\"), node(lambda x: x,",
"\"\"\"\\ from kedro.pipeline import node nodes_pipeline = { node(lambda x: x, \"a\", \"b\",",
"x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ] ) \"\"\",",
"name=\"b_c\") ] def create_pipeline(): return Pipeline([ node(lambda x: x, \"fa\", \"fb\", name=\"fa_fb\"), node(lambda",
"\"c\", name=\"b_c\"), ]) nodes_list = [ node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\"), node(lambda",
"\"c\", name=\"b_c\"), ] node_a2 = node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\") node_b2 =",
"), ( \"nested_set_nodes\", 4, \"\"\"\\ from kedro.pipeline import node nodes_pipeline = { node(lambda",
"x: x, \"a\", \"b\", name=\"a_b\") node_b_c = node(lambda x: x, \"b\", \"c\", name=\"b_c\")",
"\"b2\", name=\"a_b2\"), node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\"), ) ) \"\"\", ), (",
"node def create_pipeline(): return Pipeline([ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x:",
"kedro.pipeline import node nodes_pipeline = { node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda",
"name=\"a_b2\"), node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\"), ] \"\"\", ), ( \"pipeline_nodes_nodes\", 4,",
"), ( \"pipeline_list_nodes\", 4, \"\"\"\\ from kedro.pipeline import node, Pipeline nodes_pipeline = Pipeline([",
"name=\"b_c2\"), ] ] \"\"\", ), ( \"nested_tuple_nodes\", 4, \"\"\"\\ from kedro.pipeline import node",
"node, Pipeline nodes_pipeline = Pipeline([ node(lambda x: x, f\"a{n}\", f\"a{n+1}\", name=f\"a{n}_a{n+1}\") for n",
"tests the creation of pipeline nodes from various different types and combinations of",
"x: x, \"b\", \"c\", name=\"b_c\") \"\"\", ), ( \"list_nodes\", 2, \"\"\"\\ from kedro.pipeline",
"name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") ] \"\"\", ), ] @pytest.mark.parametrize(\"name, num_nodes,",
"x, \"b\", \"c\", name=\"b_c\") ] \"\"\", ), ] @pytest.mark.parametrize(\"name, num_nodes, content\", contents) def",
"node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\"), ) } \"\"\", ), ( \"function_nodes\", 2,",
"( \"function_list_nodes\", 4, \"\"\"\\ from kedro.pipeline import Pipeline, node nodes = [ node(lambda",
"\"\"\"\\ from kedro.pipeline import Pipeline, node creaste_pipeline = [ node(lambda x: x, \"a\",",
"\"list_nodes\", 2, \"\"\"\\ from kedro.pipeline import node nodes = [ node(lambda x: x,",
"x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ]) node_a2 =",
"\"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ( node(lambda x: x, \"a2\",",
"2, \"\"\"\\ from kedro.pipeline import node nodes = { node(lambda x: x, \"a\",",
"node_b2 = node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\") \"\"\", ), ( \"list_nodes_nodes\", 4,",
"\"fb\", \"fc\", name=\"fb_fc\"), ] ) \"\"\", ), ( \"function_list_nodes\", 4, \"\"\"\\ from kedro.pipeline",
"x: x, \"a2\", \"b2\", name=\"a_b2\"), node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\"), ) )",
"x: x, \"b\", \"c\", name=\"b_c\"), ( node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\"), node(lambda",
"def test_create_file(tmpdir, name, num_nodes, content): p = tmpdir.mkdir(\"nodes\").join(f\"{ name }.py\") p.write(textwrap.dedent(content)) pipelines =",
"\"c\", name=\"b_c\") } \"\"\", ), ( \"tuple_nodes\", 2, \"\"\"\\ from kedro.pipeline import node",
"= [ ( \"single_nodes\", 2, \"\"\"\\ from kedro.pipeline import node node_a_b = node(lambda",
") \"\"\", ), ( \"pipeline_nodes\", 2, \"\"\"\\ from kedro.pipeline import node, Pipeline nodes",
"name=\"a_b\") node_b_c = node(lambda x: x, \"b\", \"c\", name=\"b_c\") \"\"\", ), ( \"list_nodes\",",
"= node(lambda x: x, \"b\", \"c\", name=\"b_c\") \"\"\", ), ( \"list_nodes\", 2, \"\"\"\\",
"pipelines = find_kedro(directory=tmpdir, verbose=True) assert list(pipelines.keys()) == [f\"nodes.{ name }\", \"__default__\"] assert (",
"\"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), [ node(lambda x: x, \"a2\",",
"} \"\"\", ), ( \"function_nodes\", 2, \"\"\"\\ from kedro.pipeline import Pipeline, node def",
"name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ]) nodes_list = [ node(lambda x:",
"node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ]) node_a2 = node(lambda x: x, \"a2\",",
"\"\"\", ), ( \"pipeline_nodes_nodes\", 4, \"\"\"\\ from kedro.pipeline import node, Pipeline nodes_pipeline =",
"node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ] node_a2 = node(lambda x: x, \"a2\",",
"name=\"b_c\"), ]) node_a2 = node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\") node_b2 = node(lambda",
"creation of pipeline nodes from various different types and combinations of types. \"\"\"",
"4, \"\"\"\\ from kedro.pipeline import node nodes_pipeline = ( node(lambda x: x, \"a\",",
"node(lambda x: x, \"b\", \"c\", name=\"b_c\") ] def create_pipeline(): return Pipeline([ node(lambda x:",
"\"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") ] def create_pipeline(): return",
"= node(lambda x: x, \"b\", \"c\", name=\"b_c\") def create_pipeline(): return Pipeline([ node(lambda x:",
"\"\"\", ), ( \"set_nodes\", 2, \"\"\"\\ from kedro.pipeline import node nodes = {",
"( \"pipeline_nodes\", 2, \"\"\"\\ from kedro.pipeline import node, Pipeline nodes = Pipeline([ node(lambda",
"), ( \"function_nodes\", 2, \"\"\"\\ from kedro.pipeline import Pipeline, node def create_pipeline(): return",
"\"c\", name=\"b_c\") ] \"\"\", ), ] @pytest.mark.parametrize(\"name, num_nodes, content\", contents) def test_create_file(tmpdir, name,",
"f\"did not collect all nodes from { name }.py\" assert len(tmpdir.listdir()) == 1",
"x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ] node_a2 =",
"range(100)]) \"\"\", ), ( \"nested_list_nodes\", 4, \"\"\"\\ from kedro.pipeline import node nodes_pipeline =",
"import node nodes_pipeline = [ node(lambda x: x, f\"a{n}\", f\"a{n+1}\", name=f\"a{n}_a{n+1}\") for n",
"from find_kedro import find_kedro contents = [ ( \"single_nodes\", 2, \"\"\"\\ from kedro.pipeline",
"node nodes = { node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x,",
"create_pipeline(): return Pipeline([ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\",",
"[ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"),",
"\"\"\"\\ from kedro.pipeline import Pipeline, node def create_pipeline(): return Pipeline([ node(lambda x: x,",
"x, \"fb\", \"fc\", name=\"fb_fc\"), ] ) \"\"\", ), ( \"function_list_nodes\", 4, \"\"\"\\ from",
"from kedro.pipeline import Pipeline, node def create_pipeline(): return Pipeline([ node(lambda x: x, \"a\",",
"\"list_nodes_nodes\", 4, \"\"\"\\ from kedro.pipeline import node nodes_pipeline = [ node(lambda x: x,",
"in range(100)]) \"\"\", ), ( \"nested_list_nodes\", 4, \"\"\"\\ from kedro.pipeline import node nodes_pipeline",
"nodes = ( node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\",",
"name=\"fb_fc\"), ] ) \"\"\", ), ( \"list_create_pipeline\", 2, \"\"\"\\ from kedro.pipeline import Pipeline,",
"\"fb\", name=\"fa_fb\"), node(lambda x: x, \"fb\", \"fc\", name=\"fb_fc\"), ] ) \"\"\", ), (",
"name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), [ node(lambda x: x, \"a2\", \"b2\",",
"import node nodes_pipeline = { node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x:",
"= [ node(lambda x: x, f\"a{n}\", f\"a{n+1}\", name=f\"a{n}_a{n+1}\") for n in range(100)] \"\"\",",
"node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") ]",
"\"\"\"\\ from kedro.pipeline import node nodes = [ node(lambda x: x, \"a\", \"b\",",
"2, \"\"\"\\ from kedro.pipeline import Pipeline, node creaste_pipeline = [ node(lambda x: x,",
"import textwrap import pytest from find_kedro import find_kedro contents = [ ( \"single_nodes\",",
"\"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") } \"\"\", ), ( \"tuple_nodes\",",
"\"\"\"\\ from kedro.pipeline import node nodes_pipeline = ( node(lambda x: x, \"a\", \"b\",",
"node_b_c = node(lambda x: x, \"b\", \"c\", name=\"b_c\") \"\"\", ), ( \"list_nodes\", 2,",
"node nodes_pipeline = { node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x,",
"import node nodes = { node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x:",
"\"c\", name=\"b_c\"), ]) node_a2 = node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\") node_b2 =",
"name=\"b_c2\"), ) } \"\"\", ), ( \"function_nodes\", 2, \"\"\"\\ from kedro.pipeline import Pipeline,",
"nodes = { node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\",",
"nodes from various different types and combinations of types. \"\"\" import textwrap import",
"x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ( node(lambda",
"\"a\", \"b\", name=\"a_b\") node_b_c = node(lambda x: x, \"b\", \"c\", name=\"b_c\") def create_pipeline():",
"p.write(textwrap.dedent(content)) pipelines = find_kedro(directory=tmpdir, verbose=True) assert list(pipelines.keys()) == [f\"nodes.{ name }\", \"__default__\"] assert",
"\"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), [ node(lambda x: x,",
"= tmpdir.mkdir(\"nodes\").join(f\"{ name }.py\") p.write(textwrap.dedent(content)) pipelines = find_kedro(directory=tmpdir, verbose=True) assert list(pipelines.keys()) == [f\"nodes.{",
"x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ] node_a2",
"), ( \"list_nodes\", 2, \"\"\"\\ from kedro.pipeline import node nodes = [ node(lambda",
"\"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ] ) \"\"\", ), (",
"Pipeline([ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"),",
"}.py\") p.write(textwrap.dedent(content)) pipelines = find_kedro(directory=tmpdir, verbose=True) assert list(pipelines.keys()) == [f\"nodes.{ name }\", \"__default__\"]",
"\"c2\", name=\"b_c2\"), ] ] \"\"\", ), ( \"nested_tuple_nodes\", 4, \"\"\"\\ from kedro.pipeline import",
"range(100)] \"\"\", ), ( \"dynamic_pipeline_nodes\", 100, \"\"\"\\ from kedro.pipeline import node, Pipeline nodes_pipeline",
"x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") ] \"\"\", ),",
"for n in range(100)]) \"\"\", ), ( \"nested_list_nodes\", 4, \"\"\"\\ from kedro.pipeline import",
"\"\"\", ), ( \"tuple_nodes\", 2, \"\"\"\\ from kedro.pipeline import node nodes = (",
"\"b\", \"c\", name=\"b_c\") def create_pipeline(): return Pipeline([ node(lambda x: x, \"fa\", \"fb\", name=\"fa_fb\"),",
"node_b2 = node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\") \"\"\", ), ( \"dynamic_list_nodes\", 100,",
"num_nodes, content): p = tmpdir.mkdir(\"nodes\").join(f\"{ name }.py\") p.write(textwrap.dedent(content)) pipelines = find_kedro(directory=tmpdir, verbose=True) assert",
"find_kedro contents = [ ( \"single_nodes\", 2, \"\"\"\\ from kedro.pipeline import node node_a_b",
"x: x, \"b\", \"c\", name=\"b_c\") ) \"\"\", ), ( \"pipeline_nodes\", 2, \"\"\"\\ from",
"assert list(pipelines.keys()) == [f\"nodes.{ name }\", \"__default__\"] assert ( len(pipelines[\"__default__\"].nodes) == num_nodes ),",
"node(lambda x: x, \"fb\", \"fc\", name=\"fb_fc\"), ] ) \"\"\", ), ( \"function_list_nodes\", 4,",
"node(lambda x: x, \"fa\", \"fb\", name=\"fa_fb\"), node(lambda x: x, \"fb\", \"fc\", name=\"fb_fc\"), ]",
"x: x, \"b\", \"c\", name=\"b_c\"), ]) nodes_list = [ node(lambda x: x, \"a2\",",
"\"pipeline_list_nodes\", 4, \"\"\"\\ from kedro.pipeline import node, Pipeline nodes_pipeline = Pipeline([ node(lambda x:",
"from kedro.pipeline import Pipeline, node creaste_pipeline = [ node(lambda x: x, \"a\", \"b\",",
"x, \"b2\", \"c2\", name=\"b_c2\") \"\"\", ), ( \"list_nodes_nodes\", 4, \"\"\"\\ from kedro.pipeline import",
"4, \"\"\"\\ from kedro.pipeline import node, Pipeline nodes_pipeline = Pipeline([ node(lambda x: x,",
"2, \"\"\"\\ from kedro.pipeline import Pipeline, node def create_pipeline(): return Pipeline([ node(lambda x:",
"name=\"b_c\"), ] node_a2 = node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\") node_b2 = node(lambda",
"\"\"\", ), ( \"function_list_nodes\", 4, \"\"\"\\ from kedro.pipeline import Pipeline, node nodes =",
"from various different types and combinations of types. \"\"\" import textwrap import pytest",
"node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\"), ] \"\"\", ), ( \"pipeline_nodes_nodes\", 4, \"\"\"\\",
"( node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\"), node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\"),",
"x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ]) node_a2",
"various different types and combinations of types. \"\"\" import textwrap import pytest from",
"x, \"a\", \"b\", name=\"a_b\") node_b_c = node(lambda x: x, \"b\", \"c\", name=\"b_c\") \"\"\",",
"( \"list_nodes\", 2, \"\"\"\\ from kedro.pipeline import node nodes = [ node(lambda x:",
"Pipeline([ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\")",
"pytest from find_kedro import find_kedro contents = [ ( \"single_nodes\", 2, \"\"\"\\ from",
"node_a_b = node(lambda x: x, \"a\", \"b\", name=\"a_b\") node_b_c = node(lambda x: x,",
"\"nested_tuple_nodes\", 4, \"\"\"\\ from kedro.pipeline import node nodes_pipeline = ( node(lambda x: x,",
"Pipeline, node creaste_pipeline = [ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x:",
"node nodes_pipeline = [ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x,",
"f\"a{n+1}\", name=f\"a{n}_a{n+1}\") for n in range(100)] \"\"\", ), ( \"dynamic_pipeline_nodes\", 100, \"\"\"\\ from",
"\"b\", \"c\", name=\"b_c\"), ] ) \"\"\", ), ( \"function_single_nodes\", 4, \"\"\"\\ from kedro.pipeline",
"] \"\"\", ), ( \"set_nodes\", 2, \"\"\"\\ from kedro.pipeline import node nodes =",
"( \"tuple_nodes\", 2, \"\"\"\\ from kedro.pipeline import node nodes = ( node(lambda x:",
"from kedro.pipeline import node, Pipeline nodes = Pipeline([ node(lambda x: x, \"a\", \"b\",",
"node(lambda x: x, \"b\", \"c\", name=\"b_c\") } \"\"\", ), ( \"tuple_nodes\", 2, \"\"\"\\",
"from kedro.pipeline import node, Pipeline nodes_pipeline = Pipeline([ node(lambda x: x, \"a\", \"b\",",
"name=\"b_c\") def create_pipeline(): return Pipeline([ node(lambda x: x, \"fa\", \"fb\", name=\"fa_fb\"), node(lambda x:",
"\"\"\", ), ] @pytest.mark.parametrize(\"name, num_nodes, content\", contents) def test_create_file(tmpdir, name, num_nodes, content): p",
"name=\"fb_fc\"), ] ) \"\"\", ), ( \"function_list_nodes\", 4, \"\"\"\\ from kedro.pipeline import Pipeline,",
"x, \"b2\", \"c2\", name=\"b_c2\"), ] \"\"\", ), ( \"pipeline_nodes_nodes\", 4, \"\"\"\\ from kedro.pipeline",
"\"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ] node_a2 = node(lambda",
"kedro.pipeline import Pipeline, node nodes = [ node(lambda x: x, \"a\", \"b\", name=\"a_b\"),",
"{ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\")",
"\"c\", name=\"b_c\") ] def create_pipeline(): return Pipeline([ node(lambda x: x, \"fa\", \"fb\", name=\"fa_fb\"),",
"x: x, \"b\", \"c\", name=\"b_c\") def create_pipeline(): return Pipeline([ node(lambda x: x, \"fa\",",
"\"\"\"\\ from kedro.pipeline import node nodes = { node(lambda x: x, \"a\", \"b\",",
"name=\"b_c\"), ( node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\"), node(lambda x: x, \"b2\", \"c2\",",
"\"\"\"\\ from kedro.pipeline import node nodes = ( node(lambda x: x, \"a\", \"b\",",
"num_nodes ), f\"did not collect all nodes from { name }.py\" assert len(tmpdir.listdir())",
"def create_pipeline(): return Pipeline([ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x,",
"\"\"\"\\ from kedro.pipeline import node, Pipeline nodes_pipeline = Pipeline([ node(lambda x: x, f\"a{n}\",",
"Pipeline([ node(lambda x: x, f\"a{n}\", f\"a{n+1}\", name=f\"a{n}_a{n+1}\") for n in range(100)]) \"\"\", ),",
"x, \"b2\", \"c2\", name=\"b_c2\") \"\"\", ), ( \"dynamic_list_nodes\", 100, \"\"\"\\ from kedro.pipeline import",
"x, f\"a{n}\", f\"a{n+1}\", name=f\"a{n}_a{n+1}\") for n in range(100)]) \"\"\", ), ( \"nested_list_nodes\", 4,",
"name=\"b_c\") ] \"\"\", ), ( \"set_nodes\", 2, \"\"\"\\ from kedro.pipeline import node nodes",
"\"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") ) \"\"\", ), ( \"pipeline_nodes\",",
"kedro.pipeline import node nodes_pipeline = [ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda",
"creaste_pipeline = [ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\",",
"x, \"b\", \"c\", name=\"b_c\") ] def create_pipeline(): return Pipeline([ node(lambda x: x, \"fa\",",
"nodes = [ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\",",
"x: x, \"a2\", \"b2\", name=\"a_b2\"), node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\"), ) }",
"), ( \"set_nodes\", 2, \"\"\"\\ from kedro.pipeline import node nodes = { node(lambda",
"node(lambda x: x, \"b\", \"c\", name=\"b_c\") ] \"\"\", ), ] @pytest.mark.parametrize(\"name, num_nodes, content\",",
"name=\"a_b2\"), node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\"), ) ) \"\"\", ), ( \"nested_set_nodes\",",
"import node, Pipeline nodes_pipeline = Pipeline([ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda",
"num_nodes, content\", contents) def test_create_file(tmpdir, name, num_nodes, content): p = tmpdir.mkdir(\"nodes\").join(f\"{ name }.py\")",
"x, \"a2\", \"b2\", name=\"a_b2\"), node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\"), ) ) \"\"\",",
"\"\"\"\\ from kedro.pipeline import node nodes_pipeline = [ node(lambda x: x, f\"a{n}\", f\"a{n+1}\",",
"x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") ] def",
"{ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"),",
"( \"nested_tuple_nodes\", 4, \"\"\"\\ from kedro.pipeline import node nodes_pipeline = ( node(lambda x:",
"x: x, \"b2\", \"c2\", name=\"b_c2\"), ] \"\"\", ), ( \"pipeline_nodes_nodes\", 4, \"\"\"\\ from",
"name=\"b_c\"), [ node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\"), node(lambda x: x, \"b2\", \"c2\",",
"x, \"b\", \"c\", name=\"b_c\"), ] node_a2 = node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\")",
"kedro.pipeline import node, Pipeline nodes = Pipeline([ node(lambda x: x, \"a\", \"b\", name=\"a_b\"),",
"\"pipeline_nodes_nodes\", 4, \"\"\"\\ from kedro.pipeline import node, Pipeline nodes_pipeline = Pipeline([ node(lambda x:",
"( \"pipeline_nodes_nodes\", 4, \"\"\"\\ from kedro.pipeline import node, Pipeline nodes_pipeline = Pipeline([ node(lambda",
"]) node_a2 = node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\") node_b2 = node(lambda x:",
"x, \"b2\", \"c2\", name=\"b_c2\"), ) ) \"\"\", ), ( \"nested_set_nodes\", 4, \"\"\"\\ from",
"x, \"b\", \"c\", name=\"b_c\"), [ node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\"), node(lambda x:",
"the creation of pipeline nodes from various different types and combinations of types.",
"from kedro.pipeline import Pipeline, node node_a_b = node(lambda x: x, \"a\", \"b\", name=\"a_b\")",
"@pytest.mark.parametrize(\"name, num_nodes, content\", contents) def test_create_file(tmpdir, name, num_nodes, content): p = tmpdir.mkdir(\"nodes\").join(f\"{ name",
"content\", contents) def test_create_file(tmpdir, name, num_nodes, content): p = tmpdir.mkdir(\"nodes\").join(f\"{ name }.py\") p.write(textwrap.dedent(content))",
"node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\") \"\"\", ), ( \"dynamic_list_nodes\", 100, \"\"\"\\ from",
"x: x, f\"a{n}\", f\"a{n+1}\", name=f\"a{n}_a{n+1}\") for n in range(100)]) \"\"\", ), ( \"nested_list_nodes\",",
"\"nested_set_nodes\", 4, \"\"\"\\ from kedro.pipeline import node nodes_pipeline = { node(lambda x: x,",
"node, Pipeline nodes_pipeline = Pipeline([ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x:",
"\"b2\", \"c2\", name=\"b_c2\") \"\"\", ), ( \"list_nodes_nodes\", 4, \"\"\"\\ from kedro.pipeline import node",
"test_create_file(tmpdir, name, num_nodes, content): p = tmpdir.mkdir(\"nodes\").join(f\"{ name }.py\") p.write(textwrap.dedent(content)) pipelines = find_kedro(directory=tmpdir,",
"\"a2\", \"b2\", name=\"a_b2\"), node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\"), ] \"\"\", ), (",
"verbose=True) assert list(pipelines.keys()) == [f\"nodes.{ name }\", \"__default__\"] assert ( len(pipelines[\"__default__\"].nodes) == num_nodes",
"name=\"a_b2\"), node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\"), ) } \"\"\", ), ( \"function_nodes\",",
"f\"a{n+1}\", name=f\"a{n}_a{n+1}\") for n in range(100)]) \"\"\", ), ( \"nested_list_nodes\", 4, \"\"\"\\ from",
"name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") ] def create_pipeline(): return Pipeline([ node(lambda",
"\"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") ) \"\"\", ), (",
"name=f\"a{n}_a{n+1}\") for n in range(100)]) \"\"\", ), ( \"nested_list_nodes\", 4, \"\"\"\\ from kedro.pipeline",
"\"c2\", name=\"b_c2\"), ) ) \"\"\", ), ( \"nested_set_nodes\", 4, \"\"\"\\ from kedro.pipeline import",
"node nodes_pipeline = [ node(lambda x: x, f\"a{n}\", f\"a{n+1}\", name=f\"a{n}_a{n+1}\") for n in",
"\"b\", \"c\", name=\"b_c\"), ]) node_a2 = node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\") node_b2",
"node nodes = ( node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x,",
"x, f\"a{n}\", f\"a{n+1}\", name=f\"a{n}_a{n+1}\") for n in range(100)] \"\"\", ), ( \"dynamic_pipeline_nodes\", 100,",
"\"c2\", name=\"b_c2\"), ) } \"\"\", ), ( \"function_nodes\", 2, \"\"\"\\ from kedro.pipeline import",
"import Pipeline, node creaste_pipeline = [ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda",
"\"c\", name=\"b_c\"), [ node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\"), node(lambda x: x, \"b2\",",
"\"\"\"\\ from kedro.pipeline import node, Pipeline nodes_pipeline = Pipeline([ node(lambda x: x, \"a\",",
"), ( \"pipeline_nodes_nodes\", 4, \"\"\"\\ from kedro.pipeline import node, Pipeline nodes_pipeline = Pipeline([",
"x, \"b2\", \"c2\", name=\"b_c2\"), ) } \"\"\", ), ( \"function_nodes\", 2, \"\"\"\\ from",
"name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") } \"\"\", ), ( \"tuple_nodes\", 2,",
"\"b\", \"c\", name=\"b_c\") ] \"\"\", ), ] @pytest.mark.parametrize(\"name, num_nodes, content\", contents) def test_create_file(tmpdir,",
"from kedro.pipeline import node nodes_pipeline = ( node(lambda x: x, \"a\", \"b\", name=\"a_b\"),",
"x: x, \"b2\", \"c2\", name=\"b_c2\"), ) } \"\"\", ), ( \"function_nodes\", 2, \"\"\"\\",
"name=\"b_c\") } \"\"\", ), ( \"tuple_nodes\", 2, \"\"\"\\ from kedro.pipeline import node nodes",
"[f\"nodes.{ name }\", \"__default__\"] assert ( len(pipelines[\"__default__\"].nodes) == num_nodes ), f\"did not collect",
"\"fa\", \"fb\", name=\"fa_fb\"), node(lambda x: x, \"fb\", \"fc\", name=\"fb_fc\"), ] ) \"\"\", ),",
"), ( \"pipeline_nodes\", 2, \"\"\"\\ from kedro.pipeline import node, Pipeline nodes = Pipeline([",
"x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") ) \"\"\",",
"\"c\", name=\"b_c\"), ] ) \"\"\", ), ( \"function_single_nodes\", 4, \"\"\"\\ from kedro.pipeline import",
"100, \"\"\"\\ from kedro.pipeline import node, Pipeline nodes_pipeline = Pipeline([ node(lambda x: x,",
") \"\"\", ), ( \"function_single_nodes\", 4, \"\"\"\\ from kedro.pipeline import Pipeline, node node_a_b",
"x: x, \"a2\", \"b2\", name=\"a_b2\"), node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\"), ] \"\"\",",
"), ( \"dynamic_pipeline_nodes\", 100, \"\"\"\\ from kedro.pipeline import node, Pipeline nodes_pipeline = Pipeline([",
"] \"\"\", ), ] @pytest.mark.parametrize(\"name, num_nodes, content\", contents) def test_create_file(tmpdir, name, num_nodes, content):",
"] \"\"\", ), ( \"pipeline_nodes_nodes\", 4, \"\"\"\\ from kedro.pipeline import node, Pipeline nodes_pipeline",
"\"b2\", name=\"a_b2\") node_b2 = node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\") \"\"\", ), (",
"name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ] node_a2 = node(lambda x: x,",
"4, \"\"\"\\ from kedro.pipeline import Pipeline, node nodes = [ node(lambda x: x,",
"\"b2\", \"c2\", name=\"b_c2\"), ) ) \"\"\", ), ( \"nested_set_nodes\", 4, \"\"\"\\ from kedro.pipeline",
"\"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") ] def create_pipeline(): return Pipeline([",
"name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ( node(lambda x: x, \"a2\", \"b2\",",
"[ ( \"single_nodes\", 2, \"\"\"\\ from kedro.pipeline import node node_a_b = node(lambda x:",
"n in range(100)] \"\"\", ), ( \"dynamic_pipeline_nodes\", 100, \"\"\"\\ from kedro.pipeline import node,",
"), ( \"tuple_nodes\", 2, \"\"\"\\ from kedro.pipeline import node nodes = ( node(lambda",
"import Pipeline, node node_a_b = node(lambda x: x, \"a\", \"b\", name=\"a_b\") node_b_c =",
"x, \"b2\", \"c2\", name=\"b_c2\"), ] ] \"\"\", ), ( \"nested_tuple_nodes\", 4, \"\"\"\\ from",
"name, num_nodes, content): p = tmpdir.mkdir(\"nodes\").join(f\"{ name }.py\") p.write(textwrap.dedent(content)) pipelines = find_kedro(directory=tmpdir, verbose=True)",
"), ( \"list_nodes_nodes\", 4, \"\"\"\\ from kedro.pipeline import node nodes_pipeline = [ node(lambda",
"name=\"b_c\"), ] ) \"\"\", ), ( \"function_single_nodes\", 4, \"\"\"\\ from kedro.pipeline import Pipeline,",
"name=f\"a{n}_a{n+1}\") for n in range(100)] \"\"\", ), ( \"dynamic_pipeline_nodes\", 100, \"\"\"\\ from kedro.pipeline",
"\"b\", \"c\", name=\"b_c\") ]) \"\"\", ), ( \"pipeline_list_nodes\", 4, \"\"\"\\ from kedro.pipeline import",
"\"b\", name=\"a_b\") node_b_c = node(lambda x: x, \"b\", \"c\", name=\"b_c\") \"\"\", ), (",
"x: x, \"fa\", \"fb\", name=\"fa_fb\"), node(lambda x: x, \"fb\", \"fc\", name=\"fb_fc\"), ] )",
"kedro.pipeline import node nodes = { node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda",
"] node_a2 = node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\") node_b2 = node(lambda x:",
"( node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\")",
"\"c\", name=\"b_c\"), ( node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\"), node(lambda x: x, \"b2\",",
"x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") ) \"\"\", ),",
"\"set_nodes\", 2, \"\"\"\\ from kedro.pipeline import node nodes = { node(lambda x: x,",
"x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ( node(lambda x:",
"( \"set_nodes\", 2, \"\"\"\\ from kedro.pipeline import node nodes = { node(lambda x:",
"return Pipeline([ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\",",
"\"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ( node(lambda x: x,",
"4, \"\"\"\\ from kedro.pipeline import node nodes_pipeline = { node(lambda x: x, \"a\",",
"\"function_single_nodes\", 4, \"\"\"\\ from kedro.pipeline import Pipeline, node node_a_b = node(lambda x: x,",
"= [ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\",",
"] @pytest.mark.parametrize(\"name, num_nodes, content\", contents) def test_create_file(tmpdir, name, num_nodes, content): p = tmpdir.mkdir(\"nodes\").join(f\"{",
"contents = [ ( \"single_nodes\", 2, \"\"\"\\ from kedro.pipeline import node node_a_b =",
"node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\"), node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\"), ]",
"\"function_nodes\", 2, \"\"\"\\ from kedro.pipeline import Pipeline, node def create_pipeline(): return Pipeline([ node(lambda",
"x, \"b\", \"c\", name=\"b_c\") \"\"\", ), ( \"list_nodes\", 2, \"\"\"\\ from kedro.pipeline import",
"Pipeline, node def create_pipeline(): return Pipeline([ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda",
"node(lambda x: x, f\"a{n}\", f\"a{n+1}\", name=f\"a{n}_a{n+1}\") for n in range(100)]) \"\"\", ), (",
"node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\"), node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\"), )",
"\"\"\"\\ from kedro.pipeline import Pipeline, node node_a_b = node(lambda x: x, \"a\", \"b\",",
"node node_a_b = node(lambda x: x, \"a\", \"b\", name=\"a_b\") node_b_c = node(lambda x:",
"= [ node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\"), node(lambda x: x, \"b2\", \"c2\",",
"\"c2\", name=\"b_c2\"), ] \"\"\", ), ( \"pipeline_nodes_nodes\", 4, \"\"\"\\ from kedro.pipeline import node,",
"\"b\", \"c\", name=\"b_c\") } \"\"\", ), ( \"tuple_nodes\", 2, \"\"\"\\ from kedro.pipeline import",
"kedro.pipeline import node nodes = ( node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda",
"x: x, \"a2\", \"b2\", name=\"a_b2\"), node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\"), ] ]",
"), f\"did not collect all nodes from { name }.py\" assert len(tmpdir.listdir()) ==",
"\"c\", name=\"b_c\") ]) \"\"\", ), ( \"pipeline_list_nodes\", 4, \"\"\"\\ from kedro.pipeline import node,",
"node(lambda x: x, \"b\", \"c\", name=\"b_c\") ]) \"\"\", ), ( \"pipeline_list_nodes\", 4, \"\"\"\\",
"name=\"b_c\"), ]) nodes_list = [ node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\"), node(lambda x:",
"import node nodes_pipeline = ( node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x:",
"= { node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\",",
"x, \"b\", \"c\", name=\"b_c\"), ( node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\"), node(lambda x:",
"node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), (",
"\"fc\", name=\"fb_fc\"), ] ) \"\"\", ), ( \"list_create_pipeline\", 2, \"\"\"\\ from kedro.pipeline import",
"x, \"b\", \"c\", name=\"b_c\"), ]) node_a2 = node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\")",
"x, \"b\", \"c\", name=\"b_c\") ] \"\"\", ), ( \"set_nodes\", 2, \"\"\"\\ from kedro.pipeline",
"nodes_pipeline = Pipeline([ node(lambda x: x, f\"a{n}\", f\"a{n+1}\", name=f\"a{n}_a{n+1}\") for n in range(100)])",
"node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\") \"\"\", ), ( \"list_nodes_nodes\", 4, \"\"\"\\ from",
"x, \"a2\", \"b2\", name=\"a_b2\"), node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\"), ] \"\"\", ),",
"] ) \"\"\", ), ( \"list_create_pipeline\", 2, \"\"\"\\ from kedro.pipeline import Pipeline, node",
"\"tuple_nodes\", 2, \"\"\"\\ from kedro.pipeline import node nodes = ( node(lambda x: x,",
"name=\"b_c2\"), ] \"\"\", ), ( \"pipeline_nodes_nodes\", 4, \"\"\"\\ from kedro.pipeline import node, Pipeline",
"\"\"\", ), ( \"list_create_pipeline\", 2, \"\"\"\\ from kedro.pipeline import Pipeline, node creaste_pipeline =",
"\"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") ] \"\"\", ), ]",
"\"b\", \"c\", name=\"b_c\") ] def create_pipeline(): return Pipeline([ node(lambda x: x, \"fa\", \"fb\",",
"name=\"b_c2\") \"\"\", ), ( \"dynamic_list_nodes\", 100, \"\"\"\\ from kedro.pipeline import node nodes_pipeline =",
"\"\"\", ), ( \"dynamic_pipeline_nodes\", 100, \"\"\"\\ from kedro.pipeline import node, Pipeline nodes_pipeline =",
"== num_nodes ), f\"did not collect all nodes from { name }.py\" assert",
"name=\"b_c2\"), ) ) \"\"\", ), ( \"nested_set_nodes\", 4, \"\"\"\\ from kedro.pipeline import node",
"\"dynamic_list_nodes\", 100, \"\"\"\\ from kedro.pipeline import node nodes_pipeline = [ node(lambda x: x,",
"\"\"\", ), ( \"function_single_nodes\", 4, \"\"\"\\ from kedro.pipeline import Pipeline, node node_a_b =",
"\"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") ] \"\"\", ), (",
"name=\"fa_fb\"), node(lambda x: x, \"fb\", \"fc\", name=\"fb_fc\"), ] ) \"\"\", ), ( \"list_create_pipeline\",",
"\"c\", name=\"b_c\") ) \"\"\", ), ( \"pipeline_nodes\", 2, \"\"\"\\ from kedro.pipeline import node,",
"Pipeline, node nodes = [ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x:",
"\"fb\", \"fc\", name=\"fb_fc\"), ] ) \"\"\", ), ( \"list_create_pipeline\", 2, \"\"\"\\ from kedro.pipeline",
"tmpdir.mkdir(\"nodes\").join(f\"{ name }.py\") p.write(textwrap.dedent(content)) pipelines = find_kedro(directory=tmpdir, verbose=True) assert list(pipelines.keys()) == [f\"nodes.{ name",
"\"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ] ) \"\"\", ),",
"x: x, \"b2\", \"c2\", name=\"b_c2\") \"\"\", ), ( \"dynamic_list_nodes\", 100, \"\"\"\\ from kedro.pipeline",
"( \"dynamic_list_nodes\", 100, \"\"\"\\ from kedro.pipeline import node nodes_pipeline = [ node(lambda x:",
"f\"a{n}\", f\"a{n+1}\", name=f\"a{n}_a{n+1}\") for n in range(100)]) \"\"\", ), ( \"nested_list_nodes\", 4, \"\"\"\\",
"\"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") ] \"\"\", ), ] @pytest.mark.parametrize(\"name,",
"\"b\", \"c\", name=\"b_c\"), ( node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\"), node(lambda x: x,",
"x: x, \"b\", \"c\", name=\"b_c\") } \"\"\", ), ( \"tuple_nodes\", 2, \"\"\"\\ from",
"\"\"\", ), ( \"pipeline_nodes\", 2, \"\"\"\\ from kedro.pipeline import node, Pipeline nodes =",
") } \"\"\", ), ( \"function_nodes\", 2, \"\"\"\\ from kedro.pipeline import Pipeline, node",
"\"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ]) nodes_list = [",
"node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\"), ] ] \"\"\", ), ( \"nested_tuple_nodes\", 4,",
"import node, Pipeline nodes = Pipeline([ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda",
"assert ( len(pipelines[\"__default__\"].nodes) == num_nodes ), f\"did not collect all nodes from {",
"import node nodes_pipeline = [ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x:",
"\"\"\"\\ from kedro.pipeline import node nodes_pipeline = [ node(lambda x: x, \"a\", \"b\",",
"( \"nested_list_nodes\", 4, \"\"\"\\ from kedro.pipeline import node nodes_pipeline = [ node(lambda x:",
"\"c\", name=\"b_c\") \"\"\", ), ( \"list_nodes\", 2, \"\"\"\\ from kedro.pipeline import node nodes",
"\"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ]) nodes_list = [ node(lambda",
"n in range(100)]) \"\"\", ), ( \"nested_list_nodes\", 4, \"\"\"\\ from kedro.pipeline import node",
"node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ])",
"p = tmpdir.mkdir(\"nodes\").join(f\"{ name }.py\") p.write(textwrap.dedent(content)) pipelines = find_kedro(directory=tmpdir, verbose=True) assert list(pipelines.keys()) ==",
"100, \"\"\"\\ from kedro.pipeline import node nodes_pipeline = [ node(lambda x: x, f\"a{n}\",",
"), ( \"list_create_pipeline\", 2, \"\"\"\\ from kedro.pipeline import Pipeline, node creaste_pipeline = [",
"2, \"\"\"\\ from kedro.pipeline import node node_a_b = node(lambda x: x, \"a\", \"b\",",
"node(lambda x: x, \"a\", \"b\", name=\"a_b\") node_b_c = node(lambda x: x, \"b\", \"c\",",
"= node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\") \"\"\", ), ( \"dynamic_list_nodes\", 100, \"\"\"\\",
"name=\"b_c\") ]) \"\"\", ), ( \"pipeline_list_nodes\", 4, \"\"\"\\ from kedro.pipeline import node, Pipeline",
"node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\") node_b2 = node(lambda x: x, \"b2\", \"c2\",",
"name=\"b_c\") ] \"\"\", ), ] @pytest.mark.parametrize(\"name, num_nodes, content\", contents) def test_create_file(tmpdir, name, num_nodes,",
"and combinations of types. \"\"\" import textwrap import pytest from find_kedro import find_kedro",
"node(lambda x: x, \"b\", \"c\", name=\"b_c\") ] \"\"\", ), ( \"set_nodes\", 2, \"\"\"\\",
"node nodes_pipeline = ( node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x,",
"( node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"),",
"\"b\", \"c\", name=\"b_c\") ] \"\"\", ), ( \"set_nodes\", 2, \"\"\"\\ from kedro.pipeline import",
"== [f\"nodes.{ name }\", \"__default__\"] assert ( len(pipelines[\"__default__\"].nodes) == num_nodes ), f\"did not",
"\"c\", name=\"b_c\") def create_pipeline(): return Pipeline([ node(lambda x: x, \"fa\", \"fb\", name=\"fa_fb\"), node(lambda",
"content): p = tmpdir.mkdir(\"nodes\").join(f\"{ name }.py\") p.write(textwrap.dedent(content)) pipelines = find_kedro(directory=tmpdir, verbose=True) assert list(pipelines.keys())",
"] ) \"\"\", ), ( \"function_list_nodes\", 4, \"\"\"\\ from kedro.pipeline import Pipeline, node",
"node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ( node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\"),",
"\"\"\", ), ( \"function_nodes\", 2, \"\"\"\\ from kedro.pipeline import Pipeline, node def create_pipeline():",
"from kedro.pipeline import node nodes = { node(lambda x: x, \"a\", \"b\", name=\"a_b\"),",
"Pipeline([ node(lambda x: x, \"fa\", \"fb\", name=\"fa_fb\"), node(lambda x: x, \"fb\", \"fc\", name=\"fb_fc\"),",
"kedro.pipeline import node nodes_pipeline = ( node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda",
"x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") ]) \"\"\",",
"2, \"\"\"\\ from kedro.pipeline import node nodes = ( node(lambda x: x, \"a\",",
"find_kedro import find_kedro contents = [ ( \"single_nodes\", 2, \"\"\"\\ from kedro.pipeline import",
"\"__default__\"] assert ( len(pipelines[\"__default__\"].nodes) == num_nodes ), f\"did not collect all nodes from",
"pipeline nodes from various different types and combinations of types. \"\"\" import textwrap",
"\"c2\", name=\"b_c2\") \"\"\", ), ( \"list_nodes_nodes\", 4, \"\"\"\\ from kedro.pipeline import node nodes_pipeline",
"= Pipeline([ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\",",
"x, \"a\", \"b\", name=\"a_b\") node_b_c = node(lambda x: x, \"b\", \"c\", name=\"b_c\") def",
"\"b2\", name=\"a_b2\"), node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\"), ] \"\"\", ), ( \"pipeline_nodes_nodes\",",
"( \"list_nodes_nodes\", 4, \"\"\"\\ from kedro.pipeline import node nodes_pipeline = [ node(lambda x:",
"x, \"b\", \"c\", name=\"b_c\") ]) \"\"\", ), ( \"pipeline_list_nodes\", 4, \"\"\"\\ from kedro.pipeline",
"x, \"a2\", \"b2\", name=\"a_b2\") node_b2 = node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\") \"\"\",",
"name=\"a_b2\") node_b2 = node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\") \"\"\", ), ( \"dynamic_list_nodes\",",
"= ( node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\",",
"), ( \"function_single_nodes\", 4, \"\"\"\\ from kedro.pipeline import Pipeline, node node_a_b = node(lambda",
"\"dynamic_pipeline_nodes\", 100, \"\"\"\\ from kedro.pipeline import node, Pipeline nodes_pipeline = Pipeline([ node(lambda x:",
"2, \"\"\"\\ from kedro.pipeline import node, Pipeline nodes = Pipeline([ node(lambda x: x,",
"Pipeline nodes_pipeline = Pipeline([ node(lambda x: x, f\"a{n}\", f\"a{n+1}\", name=f\"a{n}_a{n+1}\") for n in",
") ) \"\"\", ), ( \"nested_set_nodes\", 4, \"\"\"\\ from kedro.pipeline import node nodes_pipeline",
"x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\") ] def create_pipeline():",
"import node nodes = [ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x:",
"Pipeline nodes_pipeline = Pipeline([ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x,",
") \"\"\", ), ( \"list_create_pipeline\", 2, \"\"\"\\ from kedro.pipeline import Pipeline, node creaste_pipeline",
"\"b2\", name=\"a_b2\"), node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\"), ) } \"\"\", ), (",
"= node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\") \"\"\", ), ( \"list_nodes_nodes\", 4, \"\"\"\\",
"( \"single_nodes\", 2, \"\"\"\\ from kedro.pipeline import node node_a_b = node(lambda x: x,",
"from kedro.pipeline import node nodes_pipeline = [ node(lambda x: x, f\"a{n}\", f\"a{n+1}\", name=f\"a{n}_a{n+1}\")",
"node(lambda x: x, f\"a{n}\", f\"a{n+1}\", name=f\"a{n}_a{n+1}\") for n in range(100)] \"\"\", ), (",
"kedro.pipeline import Pipeline, node node_a_b = node(lambda x: x, \"a\", \"b\", name=\"a_b\") node_b_c",
"\"function_list_nodes\", 4, \"\"\"\\ from kedro.pipeline import Pipeline, node nodes = [ node(lambda x:",
"of pipeline nodes from various different types and combinations of types. \"\"\" import",
"\"list_create_pipeline\", 2, \"\"\"\\ from kedro.pipeline import Pipeline, node creaste_pipeline = [ node(lambda x:",
"\"a\", \"b\", name=\"a_b\") node_b_c = node(lambda x: x, \"b\", \"c\", name=\"b_c\") \"\"\", ),",
"name }.py\") p.write(textwrap.dedent(content)) pipelines = find_kedro(directory=tmpdir, verbose=True) assert list(pipelines.keys()) == [f\"nodes.{ name }\",",
"= Pipeline([ node(lambda x: x, f\"a{n}\", f\"a{n+1}\", name=f\"a{n}_a{n+1}\") for n in range(100)]) \"\"\",",
"nodes_list = [ node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\"), node(lambda x: x, \"b2\",",
"x: x, \"b\", \"c\", name=\"b_c\"), [ node(lambda x: x, \"a2\", \"b2\", name=\"a_b2\"), node(lambda",
"node_b_c = node(lambda x: x, \"b\", \"c\", name=\"b_c\") def create_pipeline(): return Pipeline([ node(lambda",
"import pytest from find_kedro import find_kedro contents = [ ( \"single_nodes\", 2, \"\"\"\\",
"from kedro.pipeline import node nodes_pipeline = [ node(lambda x: x, \"a\", \"b\", name=\"a_b\"),",
"nodes_pipeline = Pipeline([ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\",",
"( \"pipeline_list_nodes\", 4, \"\"\"\\ from kedro.pipeline import node, Pipeline nodes_pipeline = Pipeline([ node(lambda",
"combinations of types. \"\"\" import textwrap import pytest from find_kedro import find_kedro contents",
"node(lambda x: x, \"b\", \"c\", name=\"b_c\") \"\"\", ), ( \"list_nodes\", 2, \"\"\"\\ from",
"name=\"b_c\") \"\"\", ), ( \"list_nodes\", 2, \"\"\"\\ from kedro.pipeline import node nodes =",
"\"a2\", \"b2\", name=\"a_b2\"), node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\"), ) } \"\"\", ),",
"from kedro.pipeline import Pipeline, node nodes = [ node(lambda x: x, \"a\", \"b\",",
"len(pipelines[\"__default__\"].nodes) == num_nodes ), f\"did not collect all nodes from { name }.py\"",
"x: x, \"b\", \"c\", name=\"b_c\") ] \"\"\", ), ( \"set_nodes\", 2, \"\"\"\\ from",
"\"a\", \"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ]) node_a2 = node(lambda",
"import Pipeline, node nodes = [ node(lambda x: x, \"a\", \"b\", name=\"a_b\"), node(lambda",
"\"b\", name=\"a_b\"), node(lambda x: x, \"b\", \"c\", name=\"b_c\"), ] node_a2 = node(lambda x:",
"x, \"a2\", \"b2\", name=\"a_b2\"), node(lambda x: x, \"b2\", \"c2\", name=\"b_c2\"), ] ] \"\"\","
] |
[
"'value': 'RUN: ls -lash', 'op': 'replace'}], expect_errors=True, context=self.context) self.assertEqual(404, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message'])",
"self.dbapi.create_configfile(cdict) data = self.get_json('/configfiles/%s' % uuid) self.assertIn('links', data.keys()) self.assertEqual(2, len(data['links'])) self.assertIn(uuid, data['links'][0]['href']) self.assertTrue(self.validate_link(data['links'][0]['href']))",
"brickconfig_uuid) self.assertEqual(len(data['configfiles']), len(cf_list)) uuids = [n['uuid'] for n in data['configfiles']] self.assertEqual(uuids.sort(), cf_list.sort()) def",
"= [n['uuid'] for n in data['configfiles']] self.assertEqual(uuids.sort(), cf_list.sort()) def test_links(self): uuid = utils.generate_uuid()",
"'api') configs = [] for id in range(5): ndict = dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid())",
"self.assertEqual(200, response.status_code) result = self.get_json('/configfiles/%s' % cdict['uuid']) self.assertEqual(desc, result['description']) return_updated_at = timeutils.parse_isotime( result['updated_at']).replace(tzinfo=None)",
"self.assertEqual(cdict['uuid'], result['uuid']) self.assertFalse(result['updated_at']) return_created_at = timeutils.parse_isotime(result['created_at']).replace(tzinfo=None) self.assertEqual(test_time, return_created_at) def test_create_configfile_generate_uuid(self): cdict = dbutils.get_test_configfile()",
"cf = self.dbapi.create_configfile(ndict) configs.append(cf['uuid']) data = self.get_json('/configfiles?limit=3&brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(3, len(data['configfiles'])) next_marker = data['configfiles'][-1]['uuid'] self.assertIn(next_marker,",
"config = self.dbapi.create_configfile(ndict) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(config['uuid'], data['configfiles'][0][\"uuid\"]) self.assertNotIn('environ', data['configfiles'][0]) def test_detail(self): cdict",
"self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(3, len(data['configfiles'])) next_marker = data['configfiles'][-1]['uuid'] self.assertIn(next_marker, data['next']) class TestPatch(base.FunctionalTest): def setUp(self): super(TestPatch,",
"self.assertEqual(3, len(data['configfiles'])) next_marker = data['configfiles'][-1]['uuid'] self.assertIn(next_marker, data['next']) def test_collection_links_default_limit(self): cfg.CONF.set_override('max_limit', 3, 'api') configs",
"[{'path': '/uuid', 'op': 'remove'}], expect_errors=True) self.assertEqual(400, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) class TestPost(base.FunctionalTest): @mock.patch.object(timeutils,",
"= [] for id in range(5): ndict = dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid()) cf =",
"return_updated_at = timeutils.parse_isotime( result['updated_at']).replace(tzinfo=None) self.assertEqual(test_time, return_updated_at) def test_remove_uuid(self): cdict = dbutils.get_test_configfile() response =",
"= dbutils.get_test_configfile() response = self.patch_json('/configfiles/%s' % cdict['uuid'], [{'path': '/uuid', 'op': 'remove'}], expect_errors=True) self.assertEqual(400,",
"config['uuid'], expect_errors=True) self.assertEqual(404, response.status_int) def test_many(self): cf_list = [] for id in range(5):",
"= data['configfiles'][-1]['uuid'] self.assertIn(next_marker, data['next']) class TestPatch(base.FunctionalTest): def setUp(self): super(TestPatch, self).setUp() cdict = dbutils.get_test_configfile()",
"dbutils.get_test_configfile() del cdict['uuid'] self.post_json('/configfiles', cdict, context=self.context) result = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(cdict['name'], result['configfiles'][0]['name']) self.assertTrue(utils.is_uuid_like(result['configfiles'][0]['uuid'])) def",
"self.assertEqual(3, len(data['configfiles'])) next_marker = data['configfiles'][-1]['uuid'] self.assertIn(next_marker, data['next']) class TestPatch(base.FunctionalTest): def setUp(self): super(TestPatch, self).setUp()",
"len(cf_list)) uuids = [n['uuid'] for n in data['configfiles']] self.assertEqual(uuids.sort(), cf_list.sort()) def test_links(self): uuid",
"= dbutils.get_test_configfile() self.dbapi.create_configfile(cdict) self.delete('/configfiles/%s' % cdict['uuid'], context=self.context) response = self.get_json('/configfiles/%s' % cdict['uuid'], expect_errors=True,",
"uuid) self.assertIn('links', data.keys()) self.assertEqual(2, len(data['links'])) self.assertIn(uuid, data['links'][0]['href']) self.assertTrue(self.validate_link(data['links'][0]['href'])) self.assertTrue(self.validate_link(data['links'][1]['href'])) def test_collection_links(self): configs =",
"result['description']) return_updated_at = timeutils.parse_isotime( result['updated_at']).replace(tzinfo=None) self.assertEqual(test_time, return_updated_at) def test_remove_uuid(self): cdict = dbutils.get_test_configfile() response",
"mock from oslo.config import cfg from bricks.common import utils from bricks.openstack.common import timeutils",
"import datetime import mock from oslo.config import cfg from bricks.common import utils from",
"for the API /configfiles/ methods. \"\"\" import datetime import mock from oslo.config import",
"datetime.datetime(2000, 1, 1, 0, 0) mock_utcnow.return_value = test_time response = self.post_json( '/configfiles', cdict,",
"ndict = dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid()) cf = self.dbapi.create_configfile(ndict) cf_list.append(cf['uuid']) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(len(data['configfiles']),",
"self.assertIn(next_marker, data['next']) class TestPatch(base.FunctionalTest): def setUp(self): super(TestPatch, self).setUp() cdict = dbutils.get_test_configfile() self.dbapi.create_configfile(cdict) def",
"'foo' mock_utcnow.return_value = test_time response = self.patch_json('/configfiles/%s' % cdict['uuid'], [{'path': '/description', 'value': desc,",
"def setUp(self): super(TestPatch, self).setUp() cdict = dbutils.get_test_configfile() self.dbapi.create_configfile(cdict) def test_update_not_found(self): uuid = utils.generate_uuid()",
"import utils from bricks.openstack.common import timeutils from bricks.tests.api import base from bricks.tests.api import",
"self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual([], data['configfiles']) def test_one(self): ndict = dbutils.get_test_configfile() config = self.dbapi.create_configfile(ndict) data =",
"self.assertTrue(utils.is_uuid_like(result['configfiles'][0]['uuid'])) def test_create_configfile_invalid_name(self): cdict = dbutils.get_test_configfile() del cdict['name'] response = self.post_json('/configfiles', cdict, expect_errors=True,",
"self.assertTrue(response.json['error_message']) class TestPost(base.FunctionalTest): @mock.patch.object(timeutils, 'utcnow') def test_create_configfile(self, mock_utcnow): cdict = dbutils.get_test_configfile() test_time =",
"def test_detail_against_single(self): cdict = dbutils.get_test_configfile() config = self.dbapi.create_configfile(cdict) response = self.get_json('/configfiles/%s/detail' % config['uuid'],",
"cfg.CONF.set_override('max_limit', 3, 'api') configs = [] for id in range(5): ndict = dbutils.get_test_configfile(",
"next_marker = data['configfiles'][-1]['uuid'] self.assertIn(next_marker, data['next']) class TestPatch(base.FunctionalTest): def setUp(self): super(TestPatch, self).setUp() cdict =",
"test_many(self): cf_list = [] for id in range(5): ndict = dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid())",
"def test_brickconfig_filter(self): cf_list = [] brickconfig_uuid = utils.generate_uuid() for id in range(5): ndict",
"id=id, uuid=utils.generate_uuid()) cf = self.dbapi.create_configfile(ndict) configs.append(cf['uuid']) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(3, len(data['configfiles'])) next_marker =",
"apiutils from bricks.tests.db import utils as dbutils class TestListConfigFiles(base.FunctionalTest): def test_empty(self): data =",
"% config['uuid'], expect_errors=True) self.assertEqual(404, response.status_int) def test_many(self): cf_list = [] for id in",
"[n['uuid'] for n in data['configfiles']] self.assertEqual(uuids.sort(), cf_list.sort()) def test_links(self): uuid = utils.generate_uuid() cdict",
"len(data['links'])) self.assertIn(uuid, data['links'][0]['href']) self.assertTrue(self.validate_link(data['links'][0]['href'])) self.assertTrue(self.validate_link(data['links'][1]['href'])) def test_collection_links(self): configs = [] for id in",
"uuid = utils.generate_uuid() response = self.delete('/configfiles/%s' % uuid, expect_errors=True, context=self.context) self.assertEqual(404, response.status_int) self.assertEqual('application/json',",
"expect_errors=True) self.assertEqual(400, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) class TestPost(base.FunctionalTest): @mock.patch.object(timeutils, 'utcnow') def test_create_configfile(self, mock_utcnow):",
"utils.generate_uuid() cdict = dbutils.get_test_configfile(id=1, uuid=uuid) self.dbapi.create_configfile(cdict) data = self.get_json('/configfiles/%s' % uuid) self.assertIn('links', data.keys())",
"next_marker = data['configfiles'][-1]['uuid'] self.assertIn(next_marker, data['next']) def test_collection_links_default_limit(self): cfg.CONF.set_override('max_limit', 3, 'api') configs = []",
"def test_links(self): uuid = utils.generate_uuid() cdict = dbutils.get_test_configfile(id=1, uuid=uuid) self.dbapi.create_configfile(cdict) data = self.get_json('/configfiles/%s'",
"expect_errors=True) self.assertEqual(404, response.status_int) def test_many(self): cf_list = [] for id in range(5): ndict",
"= utils.generate_uuid() response = self.delete('/configfiles/%s' % uuid, expect_errors=True, context=self.context) self.assertEqual(404, response.status_int) self.assertEqual('application/json', response.content_type)",
"id in range(5): ndict = dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid(), brickconfig_uuid=brickconfig_uuid) cf = self.dbapi.create_configfile(ndict) cf_list.append(cf['uuid'])",
"= dbutils.get_test_configfile() test_time = datetime.datetime(2000, 1, 1, 0, 0) mock_utcnow.return_value = test_time response",
"self.post_json('/configfiles', cdict, expect_errors=True, context=self.context) self.assertEqual(400, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) class TestDelete(base.FunctionalTest): def test_delete_configfile(self):",
"as apiutils from bricks.tests.db import utils as dbutils class TestListConfigFiles(base.FunctionalTest): def test_empty(self): data",
"range(5): ndict = dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid(), brickconfig_uuid=brickconfig_uuid) cf = self.dbapi.create_configfile(ndict) cf_list.append(cf['uuid']) data =",
"cf_list = [] for id in range(5): ndict = dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid()) cf",
"% uuid) self.assertIn('links', data.keys()) self.assertEqual(2, len(data['links'])) self.assertIn(uuid, data['links'][0]['href']) self.assertTrue(self.validate_link(data['links'][0]['href'])) self.assertTrue(self.validate_link(data['links'][1]['href'])) def test_collection_links(self): configs",
"self.dbapi.create_configfile(ndict) cf_list.append(cf['uuid']) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(len(data['configfiles']), len(cf_list)) uuids = [n['uuid'] for n in",
"= [] brickconfig_uuid = utils.generate_uuid() for id in range(5): ndict = dbutils.get_test_configfile( id=id,",
"self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) @mock.patch.object(timeutils, 'utcnow') def test_replace_singular(self, mock_utcnow): cdict = dbutils.get_test_configfile() test_time =",
"= self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(config['uuid'], data['configfiles'][0][\"uuid\"]) self.assertNotIn('environ', data['configfiles'][0]) def test_detail(self): cdict = dbutils.get_test_configfile() config =",
"len(data['configfiles'])) next_marker = data['configfiles'][-1]['uuid'] self.assertIn(next_marker, data['next']) class TestPatch(base.FunctionalTest): def setUp(self): super(TestPatch, self).setUp() cdict",
"dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid()) cf = self.dbapi.create_configfile(ndict) configs.append(cf['uuid']) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(3, len(data['configfiles'])) next_marker",
"setUp(self): super(TestPatch, self).setUp() cdict = dbutils.get_test_configfile() self.dbapi.create_configfile(cdict) def test_update_not_found(self): uuid = utils.generate_uuid() response",
"'/configfiles?brickconfig_uuid=%s' % brickconfig_uuid) self.assertEqual(len(data['configfiles']), len(cf_list)) uuids = [n['uuid'] for n in data['configfiles']] self.assertEqual(uuids.sort(),",
"cdict['uuid'], expect_errors=True, context=self.context) self.assertEqual(404, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) def test_delete_brick_not_found(self): uuid = utils.generate_uuid()",
"= data['configfiles'][-1]['uuid'] self.assertIn(next_marker, data['next']) def test_collection_links_default_limit(self): cfg.CONF.set_override('max_limit', 3, 'api') configs = [] for",
"def test_update_not_found(self): uuid = utils.generate_uuid() response = self.patch_json('/configfiles/%s' % uuid, [{'path': '/contents', 'value':",
"Tests for the API /configfiles/ methods. \"\"\" import datetime import mock from oslo.config",
"cdict = dbutils.get_test_configfile() config = self.dbapi.create_configfile(cdict) response = self.get_json('/configfiles/%s/detail' % config['uuid'], expect_errors=True) self.assertEqual(404,",
"/configfiles/ methods. \"\"\" import datetime import mock from oslo.config import cfg from bricks.common",
"self.get_json('/configfiles/%s' % uuid) self.assertIn('links', data.keys()) self.assertEqual(2, len(data['links'])) self.assertIn(uuid, data['links'][0]['href']) self.assertTrue(self.validate_link(data['links'][0]['href'])) self.assertTrue(self.validate_link(data['links'][1]['href'])) def test_collection_links(self):",
"self.dbapi.create_configfile(ndict) cf_list.append(cf['uuid']) data = self.get_json( '/configfiles?brickconfig_uuid=%s' % brickconfig_uuid) self.assertEqual(len(data['configfiles']), len(cf_list)) uuids = [n['uuid']",
"def test_remove_uuid(self): cdict = dbutils.get_test_configfile() response = self.patch_json('/configfiles/%s' % cdict['uuid'], [{'path': '/uuid', 'op':",
"methods. \"\"\" import datetime import mock from oslo.config import cfg from bricks.common import",
"'/configfiles', cdict, context=self.context) self.assertEqual(201, response.status_int) result = self.get_json('/configfiles/%s' % cdict['uuid']) self.assertEqual(cdict['uuid'], result['uuid']) self.assertFalse(result['updated_at'])",
"uuid=utils.generate_uuid()) cf = self.dbapi.create_configfile(ndict) configs.append(cf['uuid']) data = self.get_json('/configfiles?limit=3&brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(3, len(data['configfiles'])) next_marker = data['configfiles'][-1]['uuid']",
"self.assertFalse(result['updated_at']) return_created_at = timeutils.parse_isotime(result['created_at']).replace(tzinfo=None) self.assertEqual(test_time, return_created_at) def test_create_configfile_generate_uuid(self): cdict = dbutils.get_test_configfile() del cdict['uuid']",
"return_updated_at) def test_remove_uuid(self): cdict = dbutils.get_test_configfile() response = self.patch_json('/configfiles/%s' % cdict['uuid'], [{'path': '/uuid',",
"self.dbapi.create_configfile(cdict) self.delete('/configfiles/%s' % cdict['uuid'], context=self.context) response = self.get_json('/configfiles/%s' % cdict['uuid'], expect_errors=True, context=self.context) self.assertEqual(404,",
"cdict['uuid']) self.assertEqual(cdict['uuid'], result['uuid']) self.assertFalse(result['updated_at']) return_created_at = timeutils.parse_isotime(result['created_at']).replace(tzinfo=None) self.assertEqual(test_time, return_created_at) def test_create_configfile_generate_uuid(self): cdict =",
"cdict = dbutils.get_test_configfile() test_time = datetime.datetime(2000, 1, 1, 0, 0) desc = 'foo'",
"bricks.common import utils from bricks.openstack.common import timeutils from bricks.tests.api import base from bricks.tests.api",
"= self.get_json('/configfiles/%s' % cdict['uuid']) self.assertEqual(cdict['uuid'], result['uuid']) self.assertFalse(result['updated_at']) return_created_at = timeutils.parse_isotime(result['created_at']).replace(tzinfo=None) self.assertEqual(test_time, return_created_at) def",
"config = self.dbapi.create_configfile(cdict) response = self.get_json('/configfiles/%s/detail' % config['uuid'], expect_errors=True) self.assertEqual(404, response.status_int) def test_many(self):",
"del cdict['uuid'] self.post_json('/configfiles', cdict, context=self.context) result = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(cdict['name'], result['configfiles'][0]['name']) self.assertTrue(utils.is_uuid_like(result['configfiles'][0]['uuid'])) def test_create_configfile_invalid_name(self):",
"self.assertIn('description', data['configfiles'][0]) def test_detail_against_single(self): cdict = dbutils.get_test_configfile() config = self.dbapi.create_configfile(cdict) response = self.get_json('/configfiles/%s/detail'",
"data['next']) class TestPatch(base.FunctionalTest): def setUp(self): super(TestPatch, self).setUp() cdict = dbutils.get_test_configfile() self.dbapi.create_configfile(cdict) def test_update_not_found(self):",
"class TestDelete(base.FunctionalTest): def test_delete_configfile(self): cdict = dbutils.get_test_configfile() self.dbapi.create_configfile(cdict) self.delete('/configfiles/%s' % cdict['uuid'], context=self.context) response",
"response = self.get_json('/configfiles/%s' % cdict['uuid'], expect_errors=True, context=self.context) self.assertEqual(404, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) def",
"def test_detail(self): cdict = dbutils.get_test_configfile() config = self.dbapi.create_configfile(cdict) data = self.get_json('/configfiles/detail?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(config['uuid'], data['configfiles'][0][\"uuid\"])",
"self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(config['uuid'], data['configfiles'][0][\"uuid\"]) self.assertNotIn('environ', data['configfiles'][0]) def test_detail(self): cdict = dbutils.get_test_configfile() config = self.dbapi.create_configfile(cdict)",
"dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid()) cf = self.dbapi.create_configfile(ndict) configs.append(cf['uuid']) data = self.get_json('/configfiles?limit=3&brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(3, len(data['configfiles'])) next_marker",
"cdict, context=self.context) self.assertEqual(201, response.status_int) result = self.get_json('/configfiles/%s' % cdict['uuid']) self.assertEqual(cdict['uuid'], result['uuid']) self.assertFalse(result['updated_at']) return_created_at",
"'op': 'remove'}], expect_errors=True) self.assertEqual(400, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) class TestPost(base.FunctionalTest): @mock.patch.object(timeutils, 'utcnow') def",
"bricks.tests.db import utils as dbutils class TestListConfigFiles(base.FunctionalTest): def test_empty(self): data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual([],",
"self.assertNotIn('environ', data['configfiles'][0]) def test_detail(self): cdict = dbutils.get_test_configfile() config = self.dbapi.create_configfile(cdict) data = self.get_json('/configfiles/detail?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123')",
"self.dbapi.create_configfile(cdict) data = self.get_json('/configfiles/detail?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(config['uuid'], data['configfiles'][0][\"uuid\"]) self.assertIn('description', data['configfiles'][0]) def test_detail_against_single(self): cdict = dbutils.get_test_configfile()",
"[] for id in range(5): ndict = dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid()) cf = self.dbapi.create_configfile(ndict)",
"self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) def test_delete_brick_not_found(self): uuid = utils.generate_uuid() response = self.delete('/configfiles/%s' % uuid,",
"dbutils class TestListConfigFiles(base.FunctionalTest): def test_empty(self): data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual([], data['configfiles']) def test_one(self): ndict",
"self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(cdict['name'], result['configfiles'][0]['name']) self.assertTrue(utils.is_uuid_like(result['configfiles'][0]['uuid'])) def test_create_configfile_invalid_name(self): cdict = dbutils.get_test_configfile() del cdict['name'] response =",
"dbutils.get_test_configfile() response = self.patch_json('/configfiles/%s' % cdict['uuid'], [{'path': '/uuid', 'op': 'remove'}], expect_errors=True) self.assertEqual(400, response.status_int)",
"test_create_configfile_invalid_name(self): cdict = dbutils.get_test_configfile() del cdict['name'] response = self.post_json('/configfiles', cdict, expect_errors=True, context=self.context) self.assertEqual(400,",
"dbutils.get_test_configfile() del cdict['name'] response = self.post_json('/configfiles', cdict, expect_errors=True, context=self.context) self.assertEqual(400, response.status_int) self.assertEqual('application/json', response.content_type)",
"API /configfiles/ methods. \"\"\" import datetime import mock from oslo.config import cfg from",
"import utils as dbutils class TestListConfigFiles(base.FunctionalTest): def test_empty(self): data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual([], data['configfiles'])",
"dbutils.get_test_configfile() test_time = datetime.datetime(2000, 1, 1, 0, 0) mock_utcnow.return_value = test_time response =",
"self.assertTrue(response.json['error_message']) class TestDelete(base.FunctionalTest): def test_delete_configfile(self): cdict = dbutils.get_test_configfile() self.dbapi.create_configfile(cdict) self.delete('/configfiles/%s' % cdict['uuid'], context=self.context)",
"cf = self.dbapi.create_configfile(ndict) cf_list.append(cf['uuid']) data = self.get_json( '/configfiles?brickconfig_uuid=%s' % brickconfig_uuid) self.assertEqual(len(data['configfiles']), len(cf_list)) uuids",
"1, 0, 0) mock_utcnow.return_value = test_time response = self.post_json( '/configfiles', cdict, context=self.context) self.assertEqual(201,",
"uuid=utils.generate_uuid()) cf = self.dbapi.create_configfile(ndict) configs.append(cf['uuid']) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(3, len(data['configfiles'])) next_marker = data['configfiles'][-1]['uuid']",
"import utils as apiutils from bricks.tests.db import utils as dbutils class TestListConfigFiles(base.FunctionalTest): def",
"self.assertIn('links', data.keys()) self.assertEqual(2, len(data['links'])) self.assertIn(uuid, data['links'][0]['href']) self.assertTrue(self.validate_link(data['links'][0]['href'])) self.assertTrue(self.validate_link(data['links'][1]['href'])) def test_collection_links(self): configs = []",
"range(5): ndict = dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid()) cf = self.dbapi.create_configfile(ndict) cf_list.append(cf['uuid']) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123')",
"utils as apiutils from bricks.tests.db import utils as dbutils class TestListConfigFiles(base.FunctionalTest): def test_empty(self):",
"cdict = dbutils.get_test_configfile() del cdict['name'] response = self.post_json('/configfiles', cdict, expect_errors=True, context=self.context) self.assertEqual(400, response.status_int)",
"= self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual([], data['configfiles']) def test_one(self): ndict = dbutils.get_test_configfile() config = self.dbapi.create_configfile(ndict) data",
"1, 0, 0) desc = 'foo' mock_utcnow.return_value = test_time response = self.patch_json('/configfiles/%s' %",
"0, 0) desc = 'foo' mock_utcnow.return_value = test_time response = self.patch_json('/configfiles/%s' % cdict['uuid'],",
"dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid(), brickconfig_uuid=brickconfig_uuid) cf = self.dbapi.create_configfile(ndict) cf_list.append(cf['uuid']) data = self.get_json( '/configfiles?brickconfig_uuid=%s' %",
"% cdict['uuid'], context=self.context) response = self.get_json('/configfiles/%s' % cdict['uuid'], expect_errors=True, context=self.context) self.assertEqual(404, response.status_int) self.assertEqual('application/json',",
"data = self.get_json('/configfiles?limit=3&brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(3, len(data['configfiles'])) next_marker = data['configfiles'][-1]['uuid'] self.assertIn(next_marker, data['next']) def test_collection_links_default_limit(self): cfg.CONF.set_override('max_limit',",
"self.patch_json('/configfiles/%s' % cdict['uuid'], [{'path': '/uuid', 'op': 'remove'}], expect_errors=True) self.assertEqual(400, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message'])",
"cf_list = [] brickconfig_uuid = utils.generate_uuid() for id in range(5): ndict = dbutils.get_test_configfile(",
"utils.generate_uuid() response = self.patch_json('/configfiles/%s' % uuid, [{'path': '/contents', 'value': 'RUN: ls -lash', 'op':",
"= self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(len(data['configfiles']), len(cf_list)) uuids = [n['uuid'] for n in data['configfiles']] self.assertEqual(uuids.sort(), cf_list.sort())",
"= self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(cdict['name'], result['configfiles'][0]['name']) self.assertTrue(utils.is_uuid_like(result['configfiles'][0]['uuid'])) def test_create_configfile_invalid_name(self): cdict = dbutils.get_test_configfile() del cdict['name'] response",
"bricks.tests.api import utils as apiutils from bricks.tests.db import utils as dbutils class TestListConfigFiles(base.FunctionalTest):",
"context=self.context) self.assertEqual(201, response.status_int) result = self.get_json('/configfiles/%s' % cdict['uuid']) self.assertEqual(cdict['uuid'], result['uuid']) self.assertFalse(result['updated_at']) return_created_at =",
"self.assertEqual(len(data['configfiles']), len(cf_list)) uuids = [n['uuid'] for n in data['configfiles']] self.assertEqual(uuids.sort(), cf_list.sort()) def test_links(self):",
"= dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid()) cf = self.dbapi.create_configfile(ndict) cf_list.append(cf['uuid']) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(len(data['configfiles']), len(cf_list))",
"self.patch_json('/configfiles/%s' % uuid, [{'path': '/contents', 'value': 'RUN: ls -lash', 'op': 'replace'}], expect_errors=True, context=self.context)",
"1, 1, 0, 0) desc = 'foo' mock_utcnow.return_value = test_time response = self.patch_json('/configfiles/%s'",
"1, 1, 0, 0) mock_utcnow.return_value = test_time response = self.post_json( '/configfiles', cdict, context=self.context)",
"test_delete_brick_not_found(self): uuid = utils.generate_uuid() response = self.delete('/configfiles/%s' % uuid, expect_errors=True, context=self.context) self.assertEqual(404, response.status_int)",
"[n['uuid'] for n in data['configfiles']] self.assertEqual(uuids.sort(), cf_list.sort()) def test_brickconfig_filter(self): cf_list = [] brickconfig_uuid",
"\"\"\" import datetime import mock from oslo.config import cfg from bricks.common import utils",
"test_collection_links(self): configs = [] for id in range(5): ndict = dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid())",
"context=self.context) response = self.get_json('/configfiles/%s' % cdict['uuid'], expect_errors=True, context=self.context) self.assertEqual(404, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message'])",
"test_remove_uuid(self): cdict = dbutils.get_test_configfile() response = self.patch_json('/configfiles/%s' % cdict['uuid'], [{'path': '/uuid', 'op': 'remove'}],",
"-lash', 'op': 'replace'}], expect_errors=True, context=self.context) self.assertEqual(404, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) @mock.patch.object(timeutils, 'utcnow') def",
"oslo.config import cfg from bricks.common import utils from bricks.openstack.common import timeutils from bricks.tests.api",
"from bricks.tests.api import utils as apiutils from bricks.tests.db import utils as dbutils class",
"self.assertEqual(404, response.status_int) def test_many(self): cf_list = [] for id in range(5): ndict =",
"cf = self.dbapi.create_configfile(ndict) cf_list.append(cf['uuid']) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(len(data['configfiles']), len(cf_list)) uuids = [n['uuid'] for",
"range(5): ndict = dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid()) cf = self.dbapi.create_configfile(ndict) configs.append(cf['uuid']) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123')",
"self.dbapi.create_configfile(ndict) configs.append(cf['uuid']) data = self.get_json('/configfiles?limit=3&brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(3, len(data['configfiles'])) next_marker = data['configfiles'][-1]['uuid'] self.assertIn(next_marker, data['next']) def",
"cdict['uuid'], [{'path': '/description', 'value': desc, 'op': 'replace'}], context=self.context) self.assertEqual('application/json', response.content_type) self.assertEqual(200, response.status_code) result",
"result = self.get_json('/configfiles/%s' % cdict['uuid']) self.assertEqual(desc, result['description']) return_updated_at = timeutils.parse_isotime( result['updated_at']).replace(tzinfo=None) self.assertEqual(test_time, return_updated_at)",
"response = self.post_json( '/configfiles', cdict, context=self.context) self.assertEqual(201, response.status_int) result = self.get_json('/configfiles/%s' % cdict['uuid'])",
"cf_list.sort()) def test_brickconfig_filter(self): cf_list = [] brickconfig_uuid = utils.generate_uuid() for id in range(5):",
"= dbutils.get_test_configfile() self.dbapi.create_configfile(cdict) def test_update_not_found(self): uuid = utils.generate_uuid() response = self.patch_json('/configfiles/%s' % uuid,",
"cdict, expect_errors=True, context=self.context) self.assertEqual(400, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) class TestDelete(base.FunctionalTest): def test_delete_configfile(self): cdict",
"uuid=uuid) self.dbapi.create_configfile(cdict) data = self.get_json('/configfiles/%s' % uuid) self.assertIn('links', data.keys()) self.assertEqual(2, len(data['links'])) self.assertIn(uuid, data['links'][0]['href'])",
"'op': 'replace'}], expect_errors=True, context=self.context) self.assertEqual(404, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) @mock.patch.object(timeutils, 'utcnow') def test_replace_singular(self,",
"cf = self.dbapi.create_configfile(ndict) configs.append(cf['uuid']) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(3, len(data['configfiles'])) next_marker = data['configfiles'][-1]['uuid'] self.assertIn(next_marker,",
"context=self.context) result = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(cdict['name'], result['configfiles'][0]['name']) self.assertTrue(utils.is_uuid_like(result['configfiles'][0]['uuid'])) def test_create_configfile_invalid_name(self): cdict = dbutils.get_test_configfile() del",
"id=id, uuid=utils.generate_uuid()) cf = self.dbapi.create_configfile(ndict) configs.append(cf['uuid']) data = self.get_json('/configfiles?limit=3&brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(3, len(data['configfiles'])) next_marker =",
"result['updated_at']).replace(tzinfo=None) self.assertEqual(test_time, return_updated_at) def test_remove_uuid(self): cdict = dbutils.get_test_configfile() response = self.patch_json('/configfiles/%s' % cdict['uuid'],",
"uuid = utils.generate_uuid() response = self.patch_json('/configfiles/%s' % uuid, [{'path': '/contents', 'value': 'RUN: ls",
"= dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid()) cf = self.dbapi.create_configfile(ndict) configs.append(cf['uuid']) data = self.get_json('/configfiles?limit=3&brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(3, len(data['configfiles']))",
"= self.patch_json('/configfiles/%s' % cdict['uuid'], [{'path': '/uuid', 'op': 'remove'}], expect_errors=True) self.assertEqual(400, response.status_int) self.assertEqual('application/json', response.content_type)",
"in data['configfiles']] self.assertEqual(uuids.sort(), cf_list.sort()) def test_brickconfig_filter(self): cf_list = [] brickconfig_uuid = utils.generate_uuid() for",
"mock_utcnow.return_value = test_time response = self.post_json( '/configfiles', cdict, context=self.context) self.assertEqual(201, response.status_int) result =",
"cdict['uuid'] self.post_json('/configfiles', cdict, context=self.context) result = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(cdict['name'], result['configfiles'][0]['name']) self.assertTrue(utils.is_uuid_like(result['configfiles'][0]['uuid'])) def test_create_configfile_invalid_name(self): cdict",
"cdict = dbutils.get_test_configfile() config = self.dbapi.create_configfile(cdict) data = self.get_json('/configfiles/detail?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(config['uuid'], data['configfiles'][0][\"uuid\"]) self.assertIn('description', data['configfiles'][0])",
"len(cf_list)) uuids = [n['uuid'] for n in data['configfiles']] self.assertEqual(uuids.sort(), cf_list.sort()) def test_brickconfig_filter(self): cf_list",
"self.get_json( '/configfiles?brickconfig_uuid=%s' % brickconfig_uuid) self.assertEqual(len(data['configfiles']), len(cf_list)) uuids = [n['uuid'] for n in data['configfiles']]",
"expect_errors=True, context=self.context) self.assertEqual(400, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) class TestDelete(base.FunctionalTest): def test_delete_configfile(self): cdict =",
"for id in range(5): ndict = dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid(), brickconfig_uuid=brickconfig_uuid) cf = self.dbapi.create_configfile(ndict)",
"= timeutils.parse_isotime( result['updated_at']).replace(tzinfo=None) self.assertEqual(test_time, return_updated_at) def test_remove_uuid(self): cdict = dbutils.get_test_configfile() response = self.patch_json('/configfiles/%s'",
"timeutils.parse_isotime( result['updated_at']).replace(tzinfo=None) self.assertEqual(test_time, return_updated_at) def test_remove_uuid(self): cdict = dbutils.get_test_configfile() response = self.patch_json('/configfiles/%s' %",
"self.delete('/configfiles/%s' % cdict['uuid'], context=self.context) response = self.get_json('/configfiles/%s' % cdict['uuid'], expect_errors=True, context=self.context) self.assertEqual(404, response.status_int)",
"cf_list.append(cf['uuid']) data = self.get_json( '/configfiles?brickconfig_uuid=%s' % brickconfig_uuid) self.assertEqual(len(data['configfiles']), len(cf_list)) uuids = [n['uuid'] for",
"= 'foo' mock_utcnow.return_value = test_time response = self.patch_json('/configfiles/%s' % cdict['uuid'], [{'path': '/description', 'value':",
"= self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(3, len(data['configfiles'])) next_marker = data['configfiles'][-1]['uuid'] self.assertIn(next_marker, data['next']) class TestPatch(base.FunctionalTest): def setUp(self):",
"test_collection_links_default_limit(self): cfg.CONF.set_override('max_limit', 3, 'api') configs = [] for id in range(5): ndict =",
"from bricks.tests.api import base from bricks.tests.api import utils as apiutils from bricks.tests.db import",
"test_update_not_found(self): uuid = utils.generate_uuid() response = self.patch_json('/configfiles/%s' % uuid, [{'path': '/contents', 'value': 'RUN:",
"cdict = dbutils.get_test_configfile() del cdict['uuid'] self.post_json('/configfiles', cdict, context=self.context) result = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(cdict['name'], result['configfiles'][0]['name'])",
"dbutils.get_test_configfile() config = self.dbapi.create_configfile(ndict) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(config['uuid'], data['configfiles'][0][\"uuid\"]) self.assertNotIn('environ', data['configfiles'][0]) def test_detail(self):",
"del cdict['name'] response = self.post_json('/configfiles', cdict, expect_errors=True, context=self.context) self.assertEqual(400, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message'])",
"'RUN: ls -lash', 'op': 'replace'}], expect_errors=True, context=self.context) self.assertEqual(404, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) @mock.patch.object(timeutils,",
"test_delete_configfile(self): cdict = dbutils.get_test_configfile() self.dbapi.create_configfile(cdict) self.delete('/configfiles/%s' % cdict['uuid'], context=self.context) response = self.get_json('/configfiles/%s' %",
"data = self.get_json('/configfiles/detail?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(config['uuid'], data['configfiles'][0][\"uuid\"]) self.assertIn('description', data['configfiles'][0]) def test_detail_against_single(self): cdict = dbutils.get_test_configfile() config",
"mock_utcnow.return_value = test_time response = self.patch_json('/configfiles/%s' % cdict['uuid'], [{'path': '/description', 'value': desc, 'op':",
"len(data['configfiles'])) next_marker = data['configfiles'][-1]['uuid'] self.assertIn(next_marker, data['next']) def test_collection_links_default_limit(self): cfg.CONF.set_override('max_limit', 3, 'api') configs =",
"% cdict['uuid'], [{'path': '/uuid', 'op': 'remove'}], expect_errors=True) self.assertEqual(400, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) class",
"'replace'}], context=self.context) self.assertEqual('application/json', response.content_type) self.assertEqual(200, response.status_code) result = self.get_json('/configfiles/%s' % cdict['uuid']) self.assertEqual(desc, result['description'])",
"utils from bricks.openstack.common import timeutils from bricks.tests.api import base from bricks.tests.api import utils",
"brickconfig_uuid=brickconfig_uuid) cf = self.dbapi.create_configfile(ndict) cf_list.append(cf['uuid']) data = self.get_json( '/configfiles?brickconfig_uuid=%s' % brickconfig_uuid) self.assertEqual(len(data['configfiles']), len(cf_list))",
"self.assertEqual(uuids.sort(), cf_list.sort()) def test_links(self): uuid = utils.generate_uuid() cdict = dbutils.get_test_configfile(id=1, uuid=uuid) self.dbapi.create_configfile(cdict) data",
"test_one(self): ndict = dbutils.get_test_configfile() config = self.dbapi.create_configfile(ndict) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(config['uuid'], data['configfiles'][0][\"uuid\"]) self.assertNotIn('environ',",
"import mock from oslo.config import cfg from bricks.common import utils from bricks.openstack.common import",
"self.assertEqual(2, len(data['links'])) self.assertIn(uuid, data['links'][0]['href']) self.assertTrue(self.validate_link(data['links'][0]['href'])) self.assertTrue(self.validate_link(data['links'][1]['href'])) def test_collection_links(self): configs = [] for id",
"data['configfiles'][-1]['uuid'] self.assertIn(next_marker, data['next']) class TestPatch(base.FunctionalTest): def setUp(self): super(TestPatch, self).setUp() cdict = dbutils.get_test_configfile() self.dbapi.create_configfile(cdict)",
"result = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(cdict['name'], result['configfiles'][0]['name']) self.assertTrue(utils.is_uuid_like(result['configfiles'][0]['uuid'])) def test_create_configfile_invalid_name(self): cdict = dbutils.get_test_configfile() del cdict['name']",
"self.assertEqual(test_time, return_created_at) def test_create_configfile_generate_uuid(self): cdict = dbutils.get_test_configfile() del cdict['uuid'] self.post_json('/configfiles', cdict, context=self.context) result",
"desc = 'foo' mock_utcnow.return_value = test_time response = self.patch_json('/configfiles/%s' % cdict['uuid'], [{'path': '/description',",
"import timeutils from bricks.tests.api import base from bricks.tests.api import utils as apiutils from",
"self.assertEqual(404, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) @mock.patch.object(timeutils, 'utcnow') def test_replace_singular(self, mock_utcnow): cdict = dbutils.get_test_configfile()",
"dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid()) cf = self.dbapi.create_configfile(ndict) cf_list.append(cf['uuid']) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(len(data['configfiles']), len(cf_list)) uuids",
"= self.post_json('/configfiles', cdict, expect_errors=True, context=self.context) self.assertEqual(400, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) class TestDelete(base.FunctionalTest): def",
"0) mock_utcnow.return_value = test_time response = self.post_json( '/configfiles', cdict, context=self.context) self.assertEqual(201, response.status_int) result",
"ndict = dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid(), brickconfig_uuid=brickconfig_uuid) cf = self.dbapi.create_configfile(ndict) cf_list.append(cf['uuid']) data = self.get_json(",
"result['uuid']) self.assertFalse(result['updated_at']) return_created_at = timeutils.parse_isotime(result['created_at']).replace(tzinfo=None) self.assertEqual(test_time, return_created_at) def test_create_configfile_generate_uuid(self): cdict = dbutils.get_test_configfile() del",
"id in range(5): ndict = dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid()) cf = self.dbapi.create_configfile(ndict) cf_list.append(cf['uuid']) data",
"'/uuid', 'op': 'remove'}], expect_errors=True) self.assertEqual(400, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) class TestPost(base.FunctionalTest): @mock.patch.object(timeutils, 'utcnow')",
"base from bricks.tests.api import utils as apiutils from bricks.tests.db import utils as dbutils",
"test_replace_singular(self, mock_utcnow): cdict = dbutils.get_test_configfile() test_time = datetime.datetime(2000, 1, 1, 0, 0) desc",
"super(TestPatch, self).setUp() cdict = dbutils.get_test_configfile() self.dbapi.create_configfile(cdict) def test_update_not_found(self): uuid = utils.generate_uuid() response =",
"data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(3, len(data['configfiles'])) next_marker = data['configfiles'][-1]['uuid'] self.assertIn(next_marker, data['next']) class TestPatch(base.FunctionalTest): def",
"self.dbapi.create_configfile(ndict) configs.append(cf['uuid']) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(3, len(data['configfiles'])) next_marker = data['configfiles'][-1]['uuid'] self.assertIn(next_marker, data['next']) class",
"= self.get_json('/configfiles/%s' % cdict['uuid']) self.assertEqual(desc, result['description']) return_updated_at = timeutils.parse_isotime( result['updated_at']).replace(tzinfo=None) self.assertEqual(test_time, return_updated_at) def",
"test_time = datetime.datetime(2000, 1, 1, 0, 0) mock_utcnow.return_value = test_time response = self.post_json(",
"data['links'][0]['href']) self.assertTrue(self.validate_link(data['links'][0]['href'])) self.assertTrue(self.validate_link(data['links'][1]['href'])) def test_collection_links(self): configs = [] for id in range(5): ndict",
"self.get_json('/configfiles/%s/detail' % config['uuid'], expect_errors=True) self.assertEqual(404, response.status_int) def test_many(self): cf_list = [] for id",
"uuids = [n['uuid'] for n in data['configfiles']] self.assertEqual(uuids.sort(), cf_list.sort()) def test_brickconfig_filter(self): cf_list =",
"def test_collection_links_default_limit(self): cfg.CONF.set_override('max_limit', 3, 'api') configs = [] for id in range(5): ndict",
"result = self.get_json('/configfiles/%s' % cdict['uuid']) self.assertEqual(cdict['uuid'], result['uuid']) self.assertFalse(result['updated_at']) return_created_at = timeutils.parse_isotime(result['created_at']).replace(tzinfo=None) self.assertEqual(test_time, return_created_at)",
"context=self.context) self.assertEqual(404, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) def test_delete_brick_not_found(self): uuid = utils.generate_uuid() response =",
"response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) def test_delete_brick_not_found(self): uuid = utils.generate_uuid() response = self.delete('/configfiles/%s' %",
"self.get_json('/configfiles/detail?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(config['uuid'], data['configfiles'][0][\"uuid\"]) self.assertIn('description', data['configfiles'][0]) def test_detail_against_single(self): cdict = dbutils.get_test_configfile() config = self.dbapi.create_configfile(cdict)",
"for id in range(5): ndict = dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid()) cf = self.dbapi.create_configfile(ndict) configs.append(cf['uuid'])",
"cdict['uuid'], context=self.context) response = self.get_json('/configfiles/%s' % cdict['uuid'], expect_errors=True, context=self.context) self.assertEqual(404, response.status_int) self.assertEqual('application/json', response.content_type)",
"dbutils.get_test_configfile(id=1, uuid=uuid) self.dbapi.create_configfile(cdict) data = self.get_json('/configfiles/%s' % uuid) self.assertIn('links', data.keys()) self.assertEqual(2, len(data['links'])) self.assertIn(uuid,",
"= dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid()) cf = self.dbapi.create_configfile(ndict) configs.append(cf['uuid']) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(3, len(data['configfiles']))",
"self.assertIn(next_marker, data['next']) def test_collection_links_default_limit(self): cfg.CONF.set_override('max_limit', 3, 'api') configs = [] for id in",
"'op': 'replace'}], context=self.context) self.assertEqual('application/json', response.content_type) self.assertEqual(200, response.status_code) result = self.get_json('/configfiles/%s' % cdict['uuid']) self.assertEqual(desc,",
"bricks.tests.api import base from bricks.tests.api import utils as apiutils from bricks.tests.db import utils",
"= self.dbapi.create_configfile(ndict) configs.append(cf['uuid']) data = self.get_json('/configfiles?limit=3&brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(3, len(data['configfiles'])) next_marker = data['configfiles'][-1]['uuid'] self.assertIn(next_marker, data['next'])",
"= self.get_json( '/configfiles?brickconfig_uuid=%s' % brickconfig_uuid) self.assertEqual(len(data['configfiles']), len(cf_list)) uuids = [n['uuid'] for n in",
"configs = [] for id in range(5): ndict = dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid()) cf",
"context=self.context) self.assertEqual(400, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) class TestDelete(base.FunctionalTest): def test_delete_configfile(self): cdict = dbutils.get_test_configfile()",
"as dbutils class TestListConfigFiles(base.FunctionalTest): def test_empty(self): data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual([], data['configfiles']) def test_one(self):",
"from bricks.openstack.common import timeutils from bricks.tests.api import base from bricks.tests.api import utils as",
"self.assertEqual([], data['configfiles']) def test_one(self): ndict = dbutils.get_test_configfile() config = self.dbapi.create_configfile(ndict) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123')",
"data['configfiles'][0][\"uuid\"]) self.assertNotIn('environ', data['configfiles'][0]) def test_detail(self): cdict = dbutils.get_test_configfile() config = self.dbapi.create_configfile(cdict) data =",
"self.assertEqual(test_time, return_updated_at) def test_remove_uuid(self): cdict = dbutils.get_test_configfile() response = self.patch_json('/configfiles/%s' % cdict['uuid'], [{'path':",
"self.assertTrue(self.validate_link(data['links'][1]['href'])) def test_collection_links(self): configs = [] for id in range(5): ndict = dbutils.get_test_configfile(",
"def test_create_configfile_invalid_name(self): cdict = dbutils.get_test_configfile() del cdict['name'] response = self.post_json('/configfiles', cdict, expect_errors=True, context=self.context)",
"result['configfiles'][0]['name']) self.assertTrue(utils.is_uuid_like(result['configfiles'][0]['uuid'])) def test_create_configfile_invalid_name(self): cdict = dbutils.get_test_configfile() del cdict['name'] response = self.post_json('/configfiles', cdict,",
"data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual([], data['configfiles']) def test_one(self): ndict = dbutils.get_test_configfile() config = self.dbapi.create_configfile(ndict)",
"context=self.context) self.assertEqual(404, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) @mock.patch.object(timeutils, 'utcnow') def test_replace_singular(self, mock_utcnow): cdict =",
"% cdict['uuid']) self.assertEqual(cdict['uuid'], result['uuid']) self.assertFalse(result['updated_at']) return_created_at = timeutils.parse_isotime(result['created_at']).replace(tzinfo=None) self.assertEqual(test_time, return_created_at) def test_create_configfile_generate_uuid(self): cdict",
"response.content_type) self.assertTrue(response.json['error_message']) def test_delete_brick_not_found(self): uuid = utils.generate_uuid() response = self.delete('/configfiles/%s' % uuid, expect_errors=True,",
"cf_list.sort()) def test_links(self): uuid = utils.generate_uuid() cdict = dbutils.get_test_configfile(id=1, uuid=uuid) self.dbapi.create_configfile(cdict) data =",
"dbutils.get_test_configfile() test_time = datetime.datetime(2000, 1, 1, 0, 0) desc = 'foo' mock_utcnow.return_value =",
"data = self.get_json( '/configfiles?brickconfig_uuid=%s' % brickconfig_uuid) self.assertEqual(len(data['configfiles']), len(cf_list)) uuids = [n['uuid'] for n",
"from bricks.common import utils from bricks.openstack.common import timeutils from bricks.tests.api import base from",
"= utils.generate_uuid() for id in range(5): ndict = dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid(), brickconfig_uuid=brickconfig_uuid) cf",
"'remove'}], expect_errors=True) self.assertEqual(400, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) class TestPost(base.FunctionalTest): @mock.patch.object(timeutils, 'utcnow') def test_create_configfile(self,",
"= self.patch_json('/configfiles/%s' % uuid, [{'path': '/contents', 'value': 'RUN: ls -lash', 'op': 'replace'}], expect_errors=True,",
"test_create_configfile(self, mock_utcnow): cdict = dbutils.get_test_configfile() test_time = datetime.datetime(2000, 1, 1, 0, 0) mock_utcnow.return_value",
"def test_delete_brick_not_found(self): uuid = utils.generate_uuid() response = self.delete('/configfiles/%s' % uuid, expect_errors=True, context=self.context) self.assertEqual(404,",
"bricks.openstack.common import timeutils from bricks.tests.api import base from bricks.tests.api import utils as apiutils",
"import cfg from bricks.common import utils from bricks.openstack.common import timeutils from bricks.tests.api import",
"for id in range(5): ndict = dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid()) cf = self.dbapi.create_configfile(ndict) cf_list.append(cf['uuid'])",
"\"\"\" Tests for the API /configfiles/ methods. \"\"\" import datetime import mock from",
"TestPatch(base.FunctionalTest): def setUp(self): super(TestPatch, self).setUp() cdict = dbutils.get_test_configfile() self.dbapi.create_configfile(cdict) def test_update_not_found(self): uuid =",
"'utcnow') def test_replace_singular(self, mock_utcnow): cdict = dbutils.get_test_configfile() test_time = datetime.datetime(2000, 1, 1, 0,",
"= dbutils.get_test_configfile() config = self.dbapi.create_configfile(ndict) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(config['uuid'], data['configfiles'][0][\"uuid\"]) self.assertNotIn('environ', data['configfiles'][0]) def",
"self.assertEqual(config['uuid'], data['configfiles'][0][\"uuid\"]) self.assertNotIn('environ', data['configfiles'][0]) def test_detail(self): cdict = dbutils.get_test_configfile() config = self.dbapi.create_configfile(cdict) data",
"self.assertTrue(self.validate_link(data['links'][0]['href'])) self.assertTrue(self.validate_link(data['links'][1]['href'])) def test_collection_links(self): configs = [] for id in range(5): ndict =",
"data['configfiles'][0]) def test_detail_against_single(self): cdict = dbutils.get_test_configfile() config = self.dbapi.create_configfile(cdict) response = self.get_json('/configfiles/%s/detail' %",
"desc, 'op': 'replace'}], context=self.context) self.assertEqual('application/json', response.content_type) self.assertEqual(200, response.status_code) result = self.get_json('/configfiles/%s' % cdict['uuid'])",
"0) desc = 'foo' mock_utcnow.return_value = test_time response = self.patch_json('/configfiles/%s' % cdict['uuid'], [{'path':",
"'/contents', 'value': 'RUN: ls -lash', 'op': 'replace'}], expect_errors=True, context=self.context) self.assertEqual(404, response.status_int) self.assertEqual('application/json', response.content_type)",
"% cdict['uuid'], [{'path': '/description', 'value': desc, 'op': 'replace'}], context=self.context) self.assertEqual('application/json', response.content_type) self.assertEqual(200, response.status_code)",
"data['next']) def test_collection_links_default_limit(self): cfg.CONF.set_override('max_limit', 3, 'api') configs = [] for id in range(5):",
"= self.get_json('/configfiles?limit=3&brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(3, len(data['configfiles'])) next_marker = data['configfiles'][-1]['uuid'] self.assertIn(next_marker, data['next']) def test_collection_links_default_limit(self): cfg.CONF.set_override('max_limit', 3,",
"timeutils from bricks.tests.api import base from bricks.tests.api import utils as apiutils from bricks.tests.db",
"test_time response = self.post_json( '/configfiles', cdict, context=self.context) self.assertEqual(201, response.status_int) result = self.get_json('/configfiles/%s' %",
"test_links(self): uuid = utils.generate_uuid() cdict = dbutils.get_test_configfile(id=1, uuid=uuid) self.dbapi.create_configfile(cdict) data = self.get_json('/configfiles/%s' %",
"test_empty(self): data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual([], data['configfiles']) def test_one(self): ndict = dbutils.get_test_configfile() config =",
"'value': desc, 'op': 'replace'}], context=self.context) self.assertEqual('application/json', response.content_type) self.assertEqual(200, response.status_code) result = self.get_json('/configfiles/%s' %",
"response = self.get_json('/configfiles/%s/detail' % config['uuid'], expect_errors=True) self.assertEqual(404, response.status_int) def test_many(self): cf_list = []",
"= self.dbapi.create_configfile(ndict) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(config['uuid'], data['configfiles'][0][\"uuid\"]) self.assertNotIn('environ', data['configfiles'][0]) def test_detail(self): cdict =",
"= datetime.datetime(2000, 1, 1, 0, 0) mock_utcnow.return_value = test_time response = self.post_json( '/configfiles',",
"response.status_code) result = self.get_json('/configfiles/%s' % cdict['uuid']) self.assertEqual(desc, result['description']) return_updated_at = timeutils.parse_isotime( result['updated_at']).replace(tzinfo=None) self.assertEqual(test_time,",
"data['configfiles'][0][\"uuid\"]) self.assertIn('description', data['configfiles'][0]) def test_detail_against_single(self): cdict = dbutils.get_test_configfile() config = self.dbapi.create_configfile(cdict) response =",
"data['configfiles']] self.assertEqual(uuids.sort(), cf_list.sort()) def test_links(self): uuid = utils.generate_uuid() cdict = dbutils.get_test_configfile(id=1, uuid=uuid) self.dbapi.create_configfile(cdict)",
"data['configfiles'][-1]['uuid'] self.assertIn(next_marker, data['next']) def test_collection_links_default_limit(self): cfg.CONF.set_override('max_limit', 3, 'api') configs = [] for id",
"uuids = [n['uuid'] for n in data['configfiles']] self.assertEqual(uuids.sort(), cf_list.sort()) def test_links(self): uuid =",
"'replace'}], expect_errors=True, context=self.context) self.assertEqual(404, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) @mock.patch.object(timeutils, 'utcnow') def test_replace_singular(self, mock_utcnow):",
"dbutils.get_test_configfile() self.dbapi.create_configfile(cdict) self.delete('/configfiles/%s' % cdict['uuid'], context=self.context) response = self.get_json('/configfiles/%s' % cdict['uuid'], expect_errors=True, context=self.context)",
"test_detail(self): cdict = dbutils.get_test_configfile() config = self.dbapi.create_configfile(cdict) data = self.get_json('/configfiles/detail?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(config['uuid'], data['configfiles'][0][\"uuid\"]) self.assertIn('description',",
"response.content_type) self.assertTrue(response.json['error_message']) @mock.patch.object(timeutils, 'utcnow') def test_replace_singular(self, mock_utcnow): cdict = dbutils.get_test_configfile() test_time = datetime.datetime(2000,",
"def test_replace_singular(self, mock_utcnow): cdict = dbutils.get_test_configfile() test_time = datetime.datetime(2000, 1, 1, 0, 0)",
"self.assertEqual(400, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) class TestDelete(base.FunctionalTest): def test_delete_configfile(self): cdict = dbutils.get_test_configfile() self.dbapi.create_configfile(cdict)",
"= dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid(), brickconfig_uuid=brickconfig_uuid) cf = self.dbapi.create_configfile(ndict) cf_list.append(cf['uuid']) data = self.get_json( '/configfiles?brickconfig_uuid=%s'",
"dbutils.get_test_configfile() config = self.dbapi.create_configfile(cdict) response = self.get_json('/configfiles/%s/detail' % config['uuid'], expect_errors=True) self.assertEqual(404, response.status_int) def",
"= dbutils.get_test_configfile() del cdict['uuid'] self.post_json('/configfiles', cdict, context=self.context) result = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(cdict['name'], result['configfiles'][0]['name']) self.assertTrue(utils.is_uuid_like(result['configfiles'][0]['uuid']))",
"= self.dbapi.create_configfile(ndict) cf_list.append(cf['uuid']) data = self.get_json( '/configfiles?brickconfig_uuid=%s' % brickconfig_uuid) self.assertEqual(len(data['configfiles']), len(cf_list)) uuids =",
"self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) class TestDelete(base.FunctionalTest): def test_delete_configfile(self): cdict = dbutils.get_test_configfile() self.dbapi.create_configfile(cdict) self.delete('/configfiles/%s' %",
"uuid=utils.generate_uuid()) cf = self.dbapi.create_configfile(ndict) cf_list.append(cf['uuid']) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(len(data['configfiles']), len(cf_list)) uuids = [n['uuid']",
"self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) class TestPost(base.FunctionalTest): @mock.patch.object(timeutils, 'utcnow') def test_create_configfile(self, mock_utcnow): cdict = dbutils.get_test_configfile()",
"self.dbapi.create_configfile(ndict) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(config['uuid'], data['configfiles'][0][\"uuid\"]) self.assertNotIn('environ', data['configfiles'][0]) def test_detail(self): cdict = dbutils.get_test_configfile()",
"self.assertEqual('application/json', response.content_type) self.assertEqual(200, response.status_code) result = self.get_json('/configfiles/%s' % cdict['uuid']) self.assertEqual(desc, result['description']) return_updated_at =",
"response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) class TestPost(base.FunctionalTest): @mock.patch.object(timeutils, 'utcnow') def test_create_configfile(self, mock_utcnow): cdict =",
"uuid, [{'path': '/contents', 'value': 'RUN: ls -lash', 'op': 'replace'}], expect_errors=True, context=self.context) self.assertEqual(404, response.status_int)",
"test_time response = self.patch_json('/configfiles/%s' % cdict['uuid'], [{'path': '/description', 'value': desc, 'op': 'replace'}], context=self.context)",
"data.keys()) self.assertEqual(2, len(data['links'])) self.assertIn(uuid, data['links'][0]['href']) self.assertTrue(self.validate_link(data['links'][0]['href'])) self.assertTrue(self.validate_link(data['links'][1]['href'])) def test_collection_links(self): configs = [] for",
"= test_time response = self.patch_json('/configfiles/%s' % cdict['uuid'], [{'path': '/description', 'value': desc, 'op': 'replace'}],",
"class TestPost(base.FunctionalTest): @mock.patch.object(timeutils, 'utcnow') def test_create_configfile(self, mock_utcnow): cdict = dbutils.get_test_configfile() test_time = datetime.datetime(2000,",
"@mock.patch.object(timeutils, 'utcnow') def test_replace_singular(self, mock_utcnow): cdict = dbutils.get_test_configfile() test_time = datetime.datetime(2000, 1, 1,",
"dbutils.get_test_configfile() self.dbapi.create_configfile(cdict) def test_update_not_found(self): uuid = utils.generate_uuid() response = self.patch_json('/configfiles/%s' % uuid, [{'path':",
"3, 'api') configs = [] for id in range(5): ndict = dbutils.get_test_configfile( id=id,",
"response = self.post_json('/configfiles', cdict, expect_errors=True, context=self.context) self.assertEqual(400, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) class TestDelete(base.FunctionalTest):",
"self).setUp() cdict = dbutils.get_test_configfile() self.dbapi.create_configfile(cdict) def test_update_not_found(self): uuid = utils.generate_uuid() response = self.patch_json('/configfiles/%s'",
"id in range(5): ndict = dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid()) cf = self.dbapi.create_configfile(ndict) configs.append(cf['uuid']) data",
"self.post_json('/configfiles', cdict, context=self.context) result = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(cdict['name'], result['configfiles'][0]['name']) self.assertTrue(utils.is_uuid_like(result['configfiles'][0]['uuid'])) def test_create_configfile_invalid_name(self): cdict =",
"n in data['configfiles']] self.assertEqual(uuids.sort(), cf_list.sort()) def test_brickconfig_filter(self): cf_list = [] brickconfig_uuid = utils.generate_uuid()",
"self.get_json('/configfiles?limit=3&brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(3, len(data['configfiles'])) next_marker = data['configfiles'][-1]['uuid'] self.assertIn(next_marker, data['next']) def test_collection_links_default_limit(self): cfg.CONF.set_override('max_limit', 3, 'api')",
"def test_one(self): ndict = dbutils.get_test_configfile() config = self.dbapi.create_configfile(ndict) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(config['uuid'], data['configfiles'][0][\"uuid\"])",
"test_detail_against_single(self): cdict = dbutils.get_test_configfile() config = self.dbapi.create_configfile(cdict) response = self.get_json('/configfiles/%s/detail' % config['uuid'], expect_errors=True)",
"ls -lash', 'op': 'replace'}], expect_errors=True, context=self.context) self.assertEqual(404, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) @mock.patch.object(timeutils, 'utcnow')",
"dbutils.get_test_configfile() config = self.dbapi.create_configfile(cdict) data = self.get_json('/configfiles/detail?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(config['uuid'], data['configfiles'][0][\"uuid\"]) self.assertIn('description', data['configfiles'][0]) def test_detail_against_single(self):",
"cdict = dbutils.get_test_configfile() test_time = datetime.datetime(2000, 1, 1, 0, 0) mock_utcnow.return_value = test_time",
"cdict = dbutils.get_test_configfile() response = self.patch_json('/configfiles/%s' % cdict['uuid'], [{'path': '/uuid', 'op': 'remove'}], expect_errors=True)",
"= [n['uuid'] for n in data['configfiles']] self.assertEqual(uuids.sort(), cf_list.sort()) def test_brickconfig_filter(self): cf_list = []",
"self.assertEqual(len(data['configfiles']), len(cf_list)) uuids = [n['uuid'] for n in data['configfiles']] self.assertEqual(uuids.sort(), cf_list.sort()) def test_brickconfig_filter(self):",
"import base from bricks.tests.api import utils as apiutils from bricks.tests.db import utils as",
"def test_create_configfile_generate_uuid(self): cdict = dbutils.get_test_configfile() del cdict['uuid'] self.post_json('/configfiles', cdict, context=self.context) result = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123')",
"utils.generate_uuid() for id in range(5): ndict = dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid(), brickconfig_uuid=brickconfig_uuid) cf =",
"def test_collection_links(self): configs = [] for id in range(5): ndict = dbutils.get_test_configfile( id=id,",
"% cdict['uuid']) self.assertEqual(desc, result['description']) return_updated_at = timeutils.parse_isotime( result['updated_at']).replace(tzinfo=None) self.assertEqual(test_time, return_updated_at) def test_remove_uuid(self): cdict",
"cdict['name'] response = self.post_json('/configfiles', cdict, expect_errors=True, context=self.context) self.assertEqual(400, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) class",
"response = self.patch_json('/configfiles/%s' % uuid, [{'path': '/contents', 'value': 'RUN: ls -lash', 'op': 'replace'}],",
"self.dbapi.create_configfile(cdict) def test_update_not_found(self): uuid = utils.generate_uuid() response = self.patch_json('/configfiles/%s' % uuid, [{'path': '/contents',",
"class TestListConfigFiles(base.FunctionalTest): def test_empty(self): data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual([], data['configfiles']) def test_one(self): ndict =",
"[{'path': '/contents', 'value': 'RUN: ls -lash', 'op': 'replace'}], expect_errors=True, context=self.context) self.assertEqual(404, response.status_int) self.assertEqual('application/json',",
"cdict['uuid'], [{'path': '/uuid', 'op': 'remove'}], expect_errors=True) self.assertEqual(400, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) class TestPost(base.FunctionalTest):",
"mock_utcnow): cdict = dbutils.get_test_configfile() test_time = datetime.datetime(2000, 1, 1, 0, 0) mock_utcnow.return_value =",
"ndict = dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid()) cf = self.dbapi.create_configfile(ndict) configs.append(cf['uuid']) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(3,",
"data = self.get_json('/configfiles/%s' % uuid) self.assertIn('links', data.keys()) self.assertEqual(2, len(data['links'])) self.assertIn(uuid, data['links'][0]['href']) self.assertTrue(self.validate_link(data['links'][0]['href'])) self.assertTrue(self.validate_link(data['links'][1]['href']))",
"TestDelete(base.FunctionalTest): def test_delete_configfile(self): cdict = dbutils.get_test_configfile() self.dbapi.create_configfile(cdict) self.delete('/configfiles/%s' % cdict['uuid'], context=self.context) response =",
"ndict = dbutils.get_test_configfile() config = self.dbapi.create_configfile(ndict) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(config['uuid'], data['configfiles'][0][\"uuid\"]) self.assertNotIn('environ', data['configfiles'][0])",
"expect_errors=True, context=self.context) self.assertEqual(404, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) @mock.patch.object(timeutils, 'utcnow') def test_replace_singular(self, mock_utcnow): cdict",
"data['configfiles']) def test_one(self): ndict = dbutils.get_test_configfile() config = self.dbapi.create_configfile(ndict) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(config['uuid'],",
"= self.get_json('/configfiles/%s' % uuid) self.assertIn('links', data.keys()) self.assertEqual(2, len(data['links'])) self.assertIn(uuid, data['links'][0]['href']) self.assertTrue(self.validate_link(data['links'][0]['href'])) self.assertTrue(self.validate_link(data['links'][1]['href'])) def",
"test_time = datetime.datetime(2000, 1, 1, 0, 0) desc = 'foo' mock_utcnow.return_value = test_time",
"cfg from bricks.common import utils from bricks.openstack.common import timeutils from bricks.tests.api import base",
"mock_utcnow): cdict = dbutils.get_test_configfile() test_time = datetime.datetime(2000, 1, 1, 0, 0) desc =",
"range(5): ndict = dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid()) cf = self.dbapi.create_configfile(ndict) configs.append(cf['uuid']) data = self.get_json('/configfiles?limit=3&brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123')",
"cdict = dbutils.get_test_configfile() self.dbapi.create_configfile(cdict) self.delete('/configfiles/%s' % cdict['uuid'], context=self.context) response = self.get_json('/configfiles/%s' % cdict['uuid'],",
"= self.get_json('/configfiles/%s' % cdict['uuid'], expect_errors=True, context=self.context) self.assertEqual(404, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) def test_delete_brick_not_found(self):",
"def test_create_configfile(self, mock_utcnow): cdict = dbutils.get_test_configfile() test_time = datetime.datetime(2000, 1, 1, 0, 0)",
"= test_time response = self.post_json( '/configfiles', cdict, context=self.context) self.assertEqual(201, response.status_int) result = self.get_json('/configfiles/%s'",
"in range(5): ndict = dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid()) cf = self.dbapi.create_configfile(ndict) cf_list.append(cf['uuid']) data =",
"response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) class TestDelete(base.FunctionalTest): def test_delete_configfile(self): cdict = dbutils.get_test_configfile() self.dbapi.create_configfile(cdict) self.delete('/configfiles/%s'",
"% cdict['uuid'], expect_errors=True, context=self.context) self.assertEqual(404, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) def test_delete_brick_not_found(self): uuid =",
"datetime import mock from oslo.config import cfg from bricks.common import utils from bricks.openstack.common",
"% brickconfig_uuid) self.assertEqual(len(data['configfiles']), len(cf_list)) uuids = [n['uuid'] for n in data['configfiles']] self.assertEqual(uuids.sort(), cf_list.sort())",
"self.assertEqual(404, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) def test_delete_brick_not_found(self): uuid = utils.generate_uuid() response = self.delete('/configfiles/%s'",
"brickconfig_uuid = utils.generate_uuid() for id in range(5): ndict = dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid(), brickconfig_uuid=brickconfig_uuid)",
"response = self.patch_json('/configfiles/%s' % cdict['uuid'], [{'path': '/description', 'value': desc, 'op': 'replace'}], context=self.context) self.assertEqual('application/json',",
"test_create_configfile_generate_uuid(self): cdict = dbutils.get_test_configfile() del cdict['uuid'] self.post_json('/configfiles', cdict, context=self.context) result = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(cdict['name'],",
"response.content_type) self.assertTrue(response.json['error_message']) class TestDelete(base.FunctionalTest): def test_delete_configfile(self): cdict = dbutils.get_test_configfile() self.dbapi.create_configfile(cdict) self.delete('/configfiles/%s' % cdict['uuid'],",
"return_created_at) def test_create_configfile_generate_uuid(self): cdict = dbutils.get_test_configfile() del cdict['uuid'] self.post_json('/configfiles', cdict, context=self.context) result =",
"self.assertEqual(uuids.sort(), cf_list.sort()) def test_brickconfig_filter(self): cf_list = [] brickconfig_uuid = utils.generate_uuid() for id in",
"def test_empty(self): data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual([], data['configfiles']) def test_one(self): ndict = dbutils.get_test_configfile() config",
"self.dbapi.create_configfile(cdict) response = self.get_json('/configfiles/%s/detail' % config['uuid'], expect_errors=True) self.assertEqual(404, response.status_int) def test_many(self): cf_list =",
"timeutils.parse_isotime(result['created_at']).replace(tzinfo=None) self.assertEqual(test_time, return_created_at) def test_create_configfile_generate_uuid(self): cdict = dbutils.get_test_configfile() del cdict['uuid'] self.post_json('/configfiles', cdict, context=self.context)",
"from oslo.config import cfg from bricks.common import utils from bricks.openstack.common import timeutils from",
"= datetime.datetime(2000, 1, 1, 0, 0) desc = 'foo' mock_utcnow.return_value = test_time response",
"utils.generate_uuid() response = self.delete('/configfiles/%s' % uuid, expect_errors=True, context=self.context) self.assertEqual(404, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message'])",
"n in data['configfiles']] self.assertEqual(uuids.sort(), cf_list.sort()) def test_links(self): uuid = utils.generate_uuid() cdict = dbutils.get_test_configfile(id=1,",
"[{'path': '/description', 'value': desc, 'op': 'replace'}], context=self.context) self.assertEqual('application/json', response.content_type) self.assertEqual(200, response.status_code) result =",
"@mock.patch.object(timeutils, 'utcnow') def test_create_configfile(self, mock_utcnow): cdict = dbutils.get_test_configfile() test_time = datetime.datetime(2000, 1, 1,",
"'/description', 'value': desc, 'op': 'replace'}], context=self.context) self.assertEqual('application/json', response.content_type) self.assertEqual(200, response.status_code) result = self.get_json('/configfiles/%s'",
"= self.dbapi.create_configfile(cdict) data = self.get_json('/configfiles/detail?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(config['uuid'], data['configfiles'][0][\"uuid\"]) self.assertIn('description', data['configfiles'][0]) def test_detail_against_single(self): cdict =",
"self.assertEqual(desc, result['description']) return_updated_at = timeutils.parse_isotime( result['updated_at']).replace(tzinfo=None) self.assertEqual(test_time, return_updated_at) def test_remove_uuid(self): cdict = dbutils.get_test_configfile()",
"def test_delete_configfile(self): cdict = dbutils.get_test_configfile() self.dbapi.create_configfile(cdict) self.delete('/configfiles/%s' % cdict['uuid'], context=self.context) response = self.get_json('/configfiles/%s'",
"= self.get_json('/configfiles/detail?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(config['uuid'], data['configfiles'][0][\"uuid\"]) self.assertIn('description', data['configfiles'][0]) def test_detail_against_single(self): cdict = dbutils.get_test_configfile() config =",
"= self.dbapi.create_configfile(cdict) response = self.get_json('/configfiles/%s/detail' % config['uuid'], expect_errors=True) self.assertEqual(404, response.status_int) def test_many(self): cf_list",
"cf_list.append(cf['uuid']) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(len(data['configfiles']), len(cf_list)) uuids = [n['uuid'] for n in data['configfiles']]",
"= self.post_json( '/configfiles', cdict, context=self.context) self.assertEqual(201, response.status_int) result = self.get_json('/configfiles/%s' % cdict['uuid']) self.assertEqual(cdict['uuid'],",
"expect_errors=True, context=self.context) self.assertEqual(404, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) def test_delete_brick_not_found(self): uuid = utils.generate_uuid() response",
"self.patch_json('/configfiles/%s' % cdict['uuid'], [{'path': '/description', 'value': desc, 'op': 'replace'}], context=self.context) self.assertEqual('application/json', response.content_type) self.assertEqual(200,",
"response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) @mock.patch.object(timeutils, 'utcnow') def test_replace_singular(self, mock_utcnow): cdict = dbutils.get_test_configfile() test_time",
"self.assertEqual(400, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) class TestPost(base.FunctionalTest): @mock.patch.object(timeutils, 'utcnow') def test_create_configfile(self, mock_utcnow): cdict",
"response = self.patch_json('/configfiles/%s' % cdict['uuid'], [{'path': '/uuid', 'op': 'remove'}], expect_errors=True) self.assertEqual(400, response.status_int) self.assertEqual('application/json',",
"cdict = dbutils.get_test_configfile(id=1, uuid=uuid) self.dbapi.create_configfile(cdict) data = self.get_json('/configfiles/%s' % uuid) self.assertIn('links', data.keys()) self.assertEqual(2,",
"self.get_json('/configfiles/%s' % cdict['uuid']) self.assertEqual(cdict['uuid'], result['uuid']) self.assertFalse(result['updated_at']) return_created_at = timeutils.parse_isotime(result['created_at']).replace(tzinfo=None) self.assertEqual(test_time, return_created_at) def test_create_configfile_generate_uuid(self):",
"id=id, uuid=utils.generate_uuid(), brickconfig_uuid=brickconfig_uuid) cf = self.dbapi.create_configfile(ndict) cf_list.append(cf['uuid']) data = self.get_json( '/configfiles?brickconfig_uuid=%s' % brickconfig_uuid)",
"datetime.datetime(2000, 1, 1, 0, 0) desc = 'foo' mock_utcnow.return_value = test_time response =",
"configs.append(cf['uuid']) data = self.get_json('/configfiles?limit=3&brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(3, len(data['configfiles'])) next_marker = data['configfiles'][-1]['uuid'] self.assertIn(next_marker, data['next']) def test_collection_links_default_limit(self):",
"class TestPatch(base.FunctionalTest): def setUp(self): super(TestPatch, self).setUp() cdict = dbutils.get_test_configfile() self.dbapi.create_configfile(cdict) def test_update_not_found(self): uuid",
"data['configfiles']] self.assertEqual(uuids.sort(), cf_list.sort()) def test_brickconfig_filter(self): cf_list = [] brickconfig_uuid = utils.generate_uuid() for id",
"[] brickconfig_uuid = utils.generate_uuid() for id in range(5): ndict = dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid(),",
"self.get_json('/configfiles/%s' % cdict['uuid']) self.assertEqual(desc, result['description']) return_updated_at = timeutils.parse_isotime( result['updated_at']).replace(tzinfo=None) self.assertEqual(test_time, return_updated_at) def test_remove_uuid(self):",
"configs.append(cf['uuid']) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(3, len(data['configfiles'])) next_marker = data['configfiles'][-1]['uuid'] self.assertIn(next_marker, data['next']) class TestPatch(base.FunctionalTest):",
"uuid = utils.generate_uuid() cdict = dbutils.get_test_configfile(id=1, uuid=uuid) self.dbapi.create_configfile(cdict) data = self.get_json('/configfiles/%s' % uuid)",
"= self.dbapi.create_configfile(ndict) configs.append(cf['uuid']) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(3, len(data['configfiles'])) next_marker = data['configfiles'][-1]['uuid'] self.assertIn(next_marker, data['next'])",
"for n in data['configfiles']] self.assertEqual(uuids.sort(), cf_list.sort()) def test_links(self): uuid = utils.generate_uuid() cdict =",
"= dbutils.get_test_configfile() test_time = datetime.datetime(2000, 1, 1, 0, 0) desc = 'foo' mock_utcnow.return_value",
"ndict = dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid()) cf = self.dbapi.create_configfile(ndict) configs.append(cf['uuid']) data = self.get_json('/configfiles?limit=3&brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(3,",
"self.assertTrue(response.json['error_message']) def test_delete_brick_not_found(self): uuid = utils.generate_uuid() response = self.delete('/configfiles/%s' % uuid, expect_errors=True, context=self.context)",
"def test_many(self): cf_list = [] for id in range(5): ndict = dbutils.get_test_configfile( id=id,",
"self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(len(data['configfiles']), len(cf_list)) uuids = [n['uuid'] for n in data['configfiles']] self.assertEqual(uuids.sort(), cf_list.sort()) def",
"= dbutils.get_test_configfile(id=1, uuid=uuid) self.dbapi.create_configfile(cdict) data = self.get_json('/configfiles/%s' % uuid) self.assertIn('links', data.keys()) self.assertEqual(2, len(data['links']))",
"id=id, uuid=utils.generate_uuid()) cf = self.dbapi.create_configfile(ndict) cf_list.append(cf['uuid']) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(len(data['configfiles']), len(cf_list)) uuids =",
"in data['configfiles']] self.assertEqual(uuids.sort(), cf_list.sort()) def test_links(self): uuid = utils.generate_uuid() cdict = dbutils.get_test_configfile(id=1, uuid=uuid)",
"self.get_json('/configfiles/%s' % cdict['uuid'], expect_errors=True, context=self.context) self.assertEqual(404, response.status_int) self.assertEqual('application/json', response.content_type) self.assertTrue(response.json['error_message']) def test_delete_brick_not_found(self): uuid",
"config = self.dbapi.create_configfile(cdict) data = self.get_json('/configfiles/detail?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(config['uuid'], data['configfiles'][0][\"uuid\"]) self.assertIn('description', data['configfiles'][0]) def test_detail_against_single(self): cdict",
"from bricks.tests.db import utils as dbutils class TestListConfigFiles(base.FunctionalTest): def test_empty(self): data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123')",
"return_created_at = timeutils.parse_isotime(result['created_at']).replace(tzinfo=None) self.assertEqual(test_time, return_created_at) def test_create_configfile_generate_uuid(self): cdict = dbutils.get_test_configfile() del cdict['uuid'] self.post_json('/configfiles',",
"cdict, context=self.context) result = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(cdict['name'], result['configfiles'][0]['name']) self.assertTrue(utils.is_uuid_like(result['configfiles'][0]['uuid'])) def test_create_configfile_invalid_name(self): cdict = dbutils.get_test_configfile()",
"= dbutils.get_test_configfile() config = self.dbapi.create_configfile(cdict) response = self.get_json('/configfiles/%s/detail' % config['uuid'], expect_errors=True) self.assertEqual(404, response.status_int)",
"TestPost(base.FunctionalTest): @mock.patch.object(timeutils, 'utcnow') def test_create_configfile(self, mock_utcnow): cdict = dbutils.get_test_configfile() test_time = datetime.datetime(2000, 1,",
"cdict['uuid']) self.assertEqual(desc, result['description']) return_updated_at = timeutils.parse_isotime( result['updated_at']).replace(tzinfo=None) self.assertEqual(test_time, return_updated_at) def test_remove_uuid(self): cdict =",
"= timeutils.parse_isotime(result['created_at']).replace(tzinfo=None) self.assertEqual(test_time, return_created_at) def test_create_configfile_generate_uuid(self): cdict = dbutils.get_test_configfile() del cdict['uuid'] self.post_json('/configfiles', cdict,",
"response.status_int) def test_many(self): cf_list = [] for id in range(5): ndict = dbutils.get_test_configfile(",
"% uuid, [{'path': '/contents', 'value': 'RUN: ls -lash', 'op': 'replace'}], expect_errors=True, context=self.context) self.assertEqual(404,",
"self.assertEqual(config['uuid'], data['configfiles'][0][\"uuid\"]) self.assertIn('description', data['configfiles'][0]) def test_detail_against_single(self): cdict = dbutils.get_test_configfile() config = self.dbapi.create_configfile(cdict) response",
"in range(5): ndict = dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid()) cf = self.dbapi.create_configfile(ndict) configs.append(cf['uuid']) data =",
"response.content_type) self.assertEqual(200, response.status_code) result = self.get_json('/configfiles/%s' % cdict['uuid']) self.assertEqual(desc, result['description']) return_updated_at = timeutils.parse_isotime(",
"cdict = dbutils.get_test_configfile() self.dbapi.create_configfile(cdict) def test_update_not_found(self): uuid = utils.generate_uuid() response = self.patch_json('/configfiles/%s' %",
"self.assertEqual(201, response.status_int) result = self.get_json('/configfiles/%s' % cdict['uuid']) self.assertEqual(cdict['uuid'], result['uuid']) self.assertFalse(result['updated_at']) return_created_at = timeutils.parse_isotime(result['created_at']).replace(tzinfo=None)",
"= dbutils.get_test_configfile() del cdict['name'] response = self.post_json('/configfiles', cdict, expect_errors=True, context=self.context) self.assertEqual(400, response.status_int) self.assertEqual('application/json',",
"for n in data['configfiles']] self.assertEqual(uuids.sort(), cf_list.sort()) def test_brickconfig_filter(self): cf_list = [] brickconfig_uuid =",
"data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(len(data['configfiles']), len(cf_list)) uuids = [n['uuid'] for n in data['configfiles']] self.assertEqual(uuids.sort(),",
"self.assertTrue(response.json['error_message']) @mock.patch.object(timeutils, 'utcnow') def test_replace_singular(self, mock_utcnow): cdict = dbutils.get_test_configfile() test_time = datetime.datetime(2000, 1,",
"= self.patch_json('/configfiles/%s' % cdict['uuid'], [{'path': '/description', 'value': desc, 'op': 'replace'}], context=self.context) self.assertEqual('application/json', response.content_type)",
"test_brickconfig_filter(self): cf_list = [] brickconfig_uuid = utils.generate_uuid() for id in range(5): ndict =",
"response.status_int) result = self.get_json('/configfiles/%s' % cdict['uuid']) self.assertEqual(cdict['uuid'], result['uuid']) self.assertFalse(result['updated_at']) return_created_at = timeutils.parse_isotime(result['created_at']).replace(tzinfo=None) self.assertEqual(test_time,",
"TestListConfigFiles(base.FunctionalTest): def test_empty(self): data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual([], data['configfiles']) def test_one(self): ndict = dbutils.get_test_configfile()",
"'utcnow') def test_create_configfile(self, mock_utcnow): cdict = dbutils.get_test_configfile() test_time = datetime.datetime(2000, 1, 1, 0,",
"the API /configfiles/ methods. \"\"\" import datetime import mock from oslo.config import cfg",
"= utils.generate_uuid() cdict = dbutils.get_test_configfile(id=1, uuid=uuid) self.dbapi.create_configfile(cdict) data = self.get_json('/configfiles/%s' % uuid) self.assertIn('links',",
"self.assertEqual(cdict['name'], result['configfiles'][0]['name']) self.assertTrue(utils.is_uuid_like(result['configfiles'][0]['uuid'])) def test_create_configfile_invalid_name(self): cdict = dbutils.get_test_configfile() del cdict['name'] response = self.post_json('/configfiles',",
"response.content_type) self.assertTrue(response.json['error_message']) class TestPost(base.FunctionalTest): @mock.patch.object(timeutils, 'utcnow') def test_create_configfile(self, mock_utcnow): cdict = dbutils.get_test_configfile() test_time",
"= dbutils.get_test_configfile() config = self.dbapi.create_configfile(cdict) data = self.get_json('/configfiles/detail?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(config['uuid'], data['configfiles'][0][\"uuid\"]) self.assertIn('description', data['configfiles'][0]) def",
"data['configfiles'][0]) def test_detail(self): cdict = dbutils.get_test_configfile() config = self.dbapi.create_configfile(cdict) data = self.get_json('/configfiles/detail?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(config['uuid'],",
"context=self.context) self.assertEqual('application/json', response.content_type) self.assertEqual(200, response.status_code) result = self.get_json('/configfiles/%s' % cdict['uuid']) self.assertEqual(desc, result['description']) return_updated_at",
"uuid=utils.generate_uuid(), brickconfig_uuid=brickconfig_uuid) cf = self.dbapi.create_configfile(ndict) cf_list.append(cf['uuid']) data = self.get_json( '/configfiles?brickconfig_uuid=%s' % brickconfig_uuid) self.assertEqual(len(data['configfiles']),",
"self.assertIn(uuid, data['links'][0]['href']) self.assertTrue(self.validate_link(data['links'][0]['href'])) self.assertTrue(self.validate_link(data['links'][1]['href'])) def test_collection_links(self): configs = [] for id in range(5):",
"0, 0) mock_utcnow.return_value = test_time response = self.post_json( '/configfiles', cdict, context=self.context) self.assertEqual(201, response.status_int)",
"= self.get_json('/configfiles/%s/detail' % config['uuid'], expect_errors=True) self.assertEqual(404, response.status_int) def test_many(self): cf_list = [] for",
"utils as dbutils class TestListConfigFiles(base.FunctionalTest): def test_empty(self): data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual([], data['configfiles']) def",
"self.post_json( '/configfiles', cdict, context=self.context) self.assertEqual(201, response.status_int) result = self.get_json('/configfiles/%s' % cdict['uuid']) self.assertEqual(cdict['uuid'], result['uuid'])",
"= self.dbapi.create_configfile(ndict) cf_list.append(cf['uuid']) data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(len(data['configfiles']), len(cf_list)) uuids = [n['uuid'] for n",
"in range(5): ndict = dbutils.get_test_configfile( id=id, uuid=utils.generate_uuid(), brickconfig_uuid=brickconfig_uuid) cf = self.dbapi.create_configfile(ndict) cf_list.append(cf['uuid']) data",
"= utils.generate_uuid() response = self.patch_json('/configfiles/%s' % uuid, [{'path': '/contents', 'value': 'RUN: ls -lash',",
"data = self.get_json('/configfiles?brickconfig_uuid=1be26c0b-03f2-4d2e-ae87-c02d7f33c123') self.assertEqual(config['uuid'], data['configfiles'][0][\"uuid\"]) self.assertNotIn('environ', data['configfiles'][0]) def test_detail(self): cdict = dbutils.get_test_configfile() config"
] |
[
"'.join('{:02x}'.format(c) for c in r) l2 = ''.join(chr(c) if 32 <= c <",
"hexDump(data): size, over = divmod(len(data), 16) if over: size += 1 offsets =",
"for c in r) return l1, l2 def hexDump(data): size, over = divmod(len(data),",
"return l1, l2 def hexDump(data): size, over = divmod(len(data), 16) if over: size",
"= divmod(len(data), 16) if over: size += 1 offsets = range(0, size *",
"r = list(r) l1 = ' '.join('{:02x}'.format(c) for c in r) l2 =",
"size * 16, 16) for o in offsets: row = itertools.islice(data, o, o",
"l1 = ' '.join('{:02x}'.format(c) for c in r) l2 = ''.join(chr(c) if 32",
"over = divmod(len(data), 16) if over: size += 1 offsets = range(0, size",
"def hexDump(data): size, over = divmod(len(data), 16) if over: size += 1 offsets",
"list(r) l1 = ' '.join('{:02x}'.format(c) for c in r) l2 = ''.join(chr(c) if",
"r) return l1, l2 def hexDump(data): size, over = divmod(len(data), 16) if over:",
"16) for o in offsets: row = itertools.islice(data, o, o + 16) yield",
"= ' '.join('{:02x}'.format(c) for c in r) l2 = ''.join(chr(c) if 32 <=",
"= list(r) l1 = ' '.join('{:02x}'.format(c) for c in r) l2 = ''.join(chr(c)",
"in r) l2 = ''.join(chr(c) if 32 <= c < 127 else '.'",
"< 127 else '.' for c in r) return l1, l2 def hexDump(data):",
"import itertools def formatLine(r): r = list(r) l1 = ' '.join('{:02x}'.format(c) for c",
"itertools def formatLine(r): r = list(r) l1 = ' '.join('{:02x}'.format(c) for c in",
"size, over = divmod(len(data), 16) if over: size += 1 offsets = range(0,",
"utf8 -*- import itertools def formatLine(r): r = list(r) l1 = ' '.join('{:02x}'.format(c)",
"if 32 <= c < 127 else '.' for c in r) return",
"offsets = range(0, size * 16, 16) for o in offsets: row =",
"for o in offsets: row = itertools.islice(data, o, o + 16) yield '{:010X}:",
"16, 16) for o in offsets: row = itertools.islice(data, o, o + 16)",
"o in offsets: row = itertools.islice(data, o, o + 16) yield '{:010X}: {:48}",
"* 16, 16) for o in offsets: row = itertools.islice(data, o, o +",
"c in r) return l1, l2 def hexDump(data): size, over = divmod(len(data), 16)",
"over: size += 1 offsets = range(0, size * 16, 16) for o",
"# -*- coding: utf8 -*- import itertools def formatLine(r): r = list(r) l1",
"offsets: row = itertools.islice(data, o, o + 16) yield '{:010X}: {:48} {:16}'.format(o, *formatLine(row))",
"= range(0, size * 16, 16) for o in offsets: row = itertools.islice(data,",
"+= 1 offsets = range(0, size * 16, 16) for o in offsets:",
"l2 = ''.join(chr(c) if 32 <= c < 127 else '.' for c",
"l2 def hexDump(data): size, over = divmod(len(data), 16) if over: size += 1",
"def formatLine(r): r = list(r) l1 = ' '.join('{:02x}'.format(c) for c in r)",
"''.join(chr(c) if 32 <= c < 127 else '.' for c in r)",
"32 <= c < 127 else '.' for c in r) return l1,",
"<= c < 127 else '.' for c in r) return l1, l2",
"c < 127 else '.' for c in r) return l1, l2 def",
"r) l2 = ''.join(chr(c) if 32 <= c < 127 else '.' for",
"in r) return l1, l2 def hexDump(data): size, over = divmod(len(data), 16) if",
"16) if over: size += 1 offsets = range(0, size * 16, 16)",
"size += 1 offsets = range(0, size * 16, 16) for o in",
"1 offsets = range(0, size * 16, 16) for o in offsets: row",
"c in r) l2 = ''.join(chr(c) if 32 <= c < 127 else",
"in offsets: row = itertools.islice(data, o, o + 16) yield '{:010X}: {:48} {:16}'.format(o,",
"else '.' for c in r) return l1, l2 def hexDump(data): size, over",
"= ''.join(chr(c) if 32 <= c < 127 else '.' for c in",
"'.' for c in r) return l1, l2 def hexDump(data): size, over =",
"formatLine(r): r = list(r) l1 = ' '.join('{:02x}'.format(c) for c in r) l2",
"coding: utf8 -*- import itertools def formatLine(r): r = list(r) l1 = '",
"l1, l2 def hexDump(data): size, over = divmod(len(data), 16) if over: size +=",
"127 else '.' for c in r) return l1, l2 def hexDump(data): size,",
"-*- coding: utf8 -*- import itertools def formatLine(r): r = list(r) l1 =",
"divmod(len(data), 16) if over: size += 1 offsets = range(0, size * 16,",
"-*- import itertools def formatLine(r): r = list(r) l1 = ' '.join('{:02x}'.format(c) for",
"range(0, size * 16, 16) for o in offsets: row = itertools.islice(data, o,",
"if over: size += 1 offsets = range(0, size * 16, 16) for",
"' '.join('{:02x}'.format(c) for c in r) l2 = ''.join(chr(c) if 32 <= c",
"for c in r) l2 = ''.join(chr(c) if 32 <= c < 127"
] |
[
"amet, consectetur adipiscing elit. # Morbi non lorem porttitor neque feugiat blandit. Ut",
"ipsum eget quam lacinia accumsan. # Etiam sed turpis ac ipsum condimentum fringilla.",
"adipiscing elit. # Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum",
"rhoncus gravida arcu. from PyQt5.QtWidgets import QWidget from Ui_Content import Ui_Content class ContentWidget(QWidget,",
"dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. #",
"# Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam",
"import QWidget from Ui_Content import Ui_Content class ContentWidget(QWidget, Ui_Content): def __init__(self, *args, **kwargs):",
"import Ui_Content class ContentWidget(QWidget, Ui_Content): def __init__(self, *args, **kwargs): super(ContentWidget, self).__init__(*args, **kwargs) self.setupUi(self)",
"accumsan. # Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. # Proin",
"erat volutpat. Pellentesque sagittis ligula eget metus. # Vestibulum commodo. Ut rhoncus gravida",
"gravida arcu. from PyQt5.QtWidgets import QWidget from Ui_Content import Ui_Content class ContentWidget(QWidget, Ui_Content):",
"Vestibulum commodo. Ut rhoncus gravida arcu. from PyQt5.QtWidgets import QWidget from Ui_Content import",
"class ContentWidget(QWidget, Ui_Content): def __init__(self, *args, **kwargs): super(ContentWidget, self).__init__(*args, **kwargs) self.setupUi(self) self.par=self.parent() #",
"vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. # Vestibulum commodo.",
"ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. # Vestibulum commodo. Ut",
"Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. # Proin dapibus sapien",
"sed turpis ac ipsum condimentum fringilla. Maecenas magna. # Proin dapibus sapien vel",
"ac ipsum condimentum fringilla. Maecenas magna. # Proin dapibus sapien vel ante. Aliquam",
"porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. # Etiam",
"sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. # Vestibulum",
"eget metus. # Vestibulum commodo. Ut rhoncus gravida arcu. from PyQt5.QtWidgets import QWidget",
"Ui_Content import Ui_Content class ContentWidget(QWidget, Ui_Content): def __init__(self, *args, **kwargs): super(ContentWidget, self).__init__(*args, **kwargs)",
"# Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. # Proin dapibus",
"condimentum fringilla. Maecenas magna. # Proin dapibus sapien vel ante. Aliquam erat volutpat.",
"from PyQt5.QtWidgets import QWidget from Ui_Content import Ui_Content class ContentWidget(QWidget, Ui_Content): def __init__(self,",
"ContentWidget(QWidget, Ui_Content): def __init__(self, *args, **kwargs): super(ContentWidget, self).__init__(*args, **kwargs) self.setupUi(self) self.par=self.parent() # connect",
"# Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget",
"def __init__(self, *args, **kwargs): super(ContentWidget, self).__init__(*args, **kwargs) self.setupUi(self) self.par=self.parent() # connect self.pushButton_3.clicked.connect(self.par.loginShow) self.pushButton_24.clicked.connect(self.par.checkResults)",
"elit. # Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget",
"# Vestibulum commodo. Ut rhoncus gravida arcu. from PyQt5.QtWidgets import QWidget from Ui_Content",
"from Ui_Content import Ui_Content class ContentWidget(QWidget, Ui_Content): def __init__(self, *args, **kwargs): super(ContentWidget, self).__init__(*args,",
"<reponame>yujiecong/PyQt-Zhku-Client<filename>contentWidget.py # Copyright (c) 2020. Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. # Morbi non lorem porttitor",
"quam lacinia accumsan. # Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.",
"non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.",
"ipsum dolor sit amet, consectetur adipiscing elit. # Morbi non lorem porttitor neque",
"volutpat. Pellentesque sagittis ligula eget metus. # Vestibulum commodo. Ut rhoncus gravida arcu.",
"Pellentesque sagittis ligula eget metus. # Vestibulum commodo. Ut rhoncus gravida arcu. from",
"ligula eget metus. # Vestibulum commodo. Ut rhoncus gravida arcu. from PyQt5.QtWidgets import",
"vitae ipsum eget quam lacinia accumsan. # Etiam sed turpis ac ipsum condimentum",
"arcu. from PyQt5.QtWidgets import QWidget from Ui_Content import Ui_Content class ContentWidget(QWidget, Ui_Content): def",
"# Copyright (c) 2020. Lorem ipsum dolor sit amet, consectetur adipiscing elit. #",
"Ut rhoncus gravida arcu. from PyQt5.QtWidgets import QWidget from Ui_Content import Ui_Content class",
"Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. # Vestibulum commodo. Ut rhoncus",
"sagittis ligula eget metus. # Vestibulum commodo. Ut rhoncus gravida arcu. from PyQt5.QtWidgets",
"commodo. Ut rhoncus gravida arcu. from PyQt5.QtWidgets import QWidget from Ui_Content import Ui_Content",
"magna. # Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula",
"ipsum condimentum fringilla. Maecenas magna. # Proin dapibus sapien vel ante. Aliquam erat",
"Copyright (c) 2020. Lorem ipsum dolor sit amet, consectetur adipiscing elit. # Morbi",
"blandit. Ut vitae ipsum eget quam lacinia accumsan. # Etiam sed turpis ac",
"sit amet, consectetur adipiscing elit. # Morbi non lorem porttitor neque feugiat blandit.",
"dolor sit amet, consectetur adipiscing elit. # Morbi non lorem porttitor neque feugiat",
"Maecenas magna. # Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis",
"PyQt5.QtWidgets import QWidget from Ui_Content import Ui_Content class ContentWidget(QWidget, Ui_Content): def __init__(self, *args,",
"QWidget from Ui_Content import Ui_Content class ContentWidget(QWidget, Ui_Content): def __init__(self, *args, **kwargs): super(ContentWidget,",
"Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia",
"lacinia accumsan. # Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. #",
"eget quam lacinia accumsan. # Etiam sed turpis ac ipsum condimentum fringilla. Maecenas",
"fringilla. Maecenas magna. # Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque",
"metus. # Vestibulum commodo. Ut rhoncus gravida arcu. from PyQt5.QtWidgets import QWidget from",
"neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. # Etiam sed",
"Ut vitae ipsum eget quam lacinia accumsan. # Etiam sed turpis ac ipsum",
"2020. Lorem ipsum dolor sit amet, consectetur adipiscing elit. # Morbi non lorem",
"consectetur adipiscing elit. # Morbi non lorem porttitor neque feugiat blandit. Ut vitae",
"Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.",
"Ui_Content class ContentWidget(QWidget, Ui_Content): def __init__(self, *args, **kwargs): super(ContentWidget, self).__init__(*args, **kwargs) self.setupUi(self) self.par=self.parent()",
"Ui_Content): def __init__(self, *args, **kwargs): super(ContentWidget, self).__init__(*args, **kwargs) self.setupUi(self) self.par=self.parent() # connect self.pushButton_3.clicked.connect(self.par.loginShow)",
"feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. # Etiam sed turpis",
"(c) 2020. Lorem ipsum dolor sit amet, consectetur adipiscing elit. # Morbi non",
"turpis ac ipsum condimentum fringilla. Maecenas magna. # Proin dapibus sapien vel ante.",
"lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. #"
] |
[
"= session['email'] author_nickname = User.find_by_email(author_email).nick_name note_for_save = Note(title=title, content=content, author_email=author_email, shared=share, author_nickname=author_nickname ,share_only_with_users=share_only_with_users)",
"note.author_email == session['email']: author_email_is_session = True else: author_email_is_session = False except: author_email_is_session =",
"return render_template('error_page.html', error_msgr='Crashed during reading your note...') @note_blueprint.route('/add_note', methods=['GET', 'POST']) @user_decorators.require_login def create_note():",
"note...') @note_blueprint.route('/add_note', methods=['GET', 'POST']) @user_decorators.require_login def create_note(): try: if request.method == 'POST': share",
"during reading your notes...') @note_blueprint.route('/note/<string:note_id>') def note(note_id): try: note = Note.find_by_id(note_id) user =",
"@user_decorators.require_login def share_note(note_id): try: Note.find_by_id(note_id).share_or_unshare() finally: return redirect(url_for('.note', note_id=note_id, msg='Your note is shared!!',",
"= Blueprint('notes', __name__) @note_blueprint.route('/my_notes/') @user_decorators.require_login def user_notes(): try: user = User.find_by_email(session['email']) user_notes =",
"error_msgr='Crashed during saving your note...') @note_blueprint.route('/delete_note/<string:note_id>') @user_decorators.require_login def delete_note(note_id): try: Note.find_by_id(note_id).delete() finally: return",
"note(note_id): try: note = Note.find_by_id(note_id) user = User.find_by_email(note.author_email) try: if note.author_email == session['email']:",
"= True share_only_with_users = False else: share = False share_only_with_users = True title",
"request, session, url_for, render_template from werkzeug.utils import redirect from src.models.notes.note import Note import",
"'POST': share = request.form['inputGroupSelect01'] if share == '0': return render_template('/notes/create_note.html', error_msg=\"You did not",
"= content note.save_to_mongo() return redirect(url_for('.note', note_id=note_id)) else: return render_template('/notes/edit_note.html', note=note) except: error_msg =",
"notes...') @note_blueprint.route('/edit_note/<string:note_id>', methods=['GET', 'POST']) @user_decorators.require_login def edit_note(note_id): try: note = Note.find_by_id(note_id) if request.method",
"True title = request.form['title'] content = request.form['content'] note.shared = share note.share_only_with_users = share_only_with_users",
"= traceback.format_exc().split('\\n') try: Error_obj = Error_(error_msg=''.join(error_msg), error_location='note reading NOTE:' + note._id) except: Error_obj",
"= User.find_by_email(author_email).nick_name note_for_save = Note(title=title, content=content, author_email=author_email, shared=share, author_nickname=author_nickname ,share_only_with_users=share_only_with_users) note_for_save.save_to_mongo() return redirect(url_for('.user_notes'))",
"reading your notes...') @note_blueprint.route('/note/<string:note_id>') def note(note_id): try: note = Note.find_by_id(note_id) user = User.find_by_email(note.author_email)",
"True share_only_with_users = False else: share = False share_only_with_users = True title =",
"@note_blueprint.route('/my_notes/') @user_decorators.require_login def user_notes(): try: user = User.find_by_email(session['email']) user_notes = User.get_notes(user) user_name =",
"except: error_msg = traceback.format_exc().split('\\n') try: Error_obj = Error_(error_msg=''.join(error_msg), error_location='note reading NOTE:' + note._id)",
"= traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='create_note creating note') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during",
"= traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='edit_note saveing and getting input from html file')",
"= Note(title=title, content=content, author_email=author_email, shared=share, author_nickname=author_nickname ,share_only_with_users=share_only_with_users) note_for_save.save_to_mongo() return redirect(url_for('.user_notes')) return render_template('/notes/create_note.html') except:",
"share == '1': share = True share_only_with_users = False else: share = False",
"import Error_ import traceback note_blueprint = Blueprint('notes', __name__) @note_blueprint.route('/my_notes/') @user_decorators.require_login def user_notes(): try:",
"= title note.content = content note.save_to_mongo() return redirect(url_for('.note', note_id=note_id)) else: return render_template('/notes/edit_note.html', note=note)",
"return render_template('/notes/pub_notes.html', notes=Note.find_shared_notes()) else: return render_template('/notes/pub_notes.html', notes=Note.get_only_with_users() + Note.find_shared_notes()) except: return render_template('/notes/pub_notes.html', notes=Note.find_shared_notes())",
"saving your note...') @note_blueprint.route('/delete_note/<string:note_id>') @user_decorators.require_login def delete_note(note_id): try: Note.find_by_id(note_id).delete() finally: return redirect(url_for('.user_notes')) @note_blueprint.route('/share_note/<string:note_id>')",
"as user_decorators from src.models.users.user import User from src.models.error_logs.error_log import Error_ import traceback note_blueprint",
"msg_=True)) @note_blueprint.route('/pub_notes/') def notes(): try: try: if session['email'] is None: return render_template('/notes/pub_notes.html', notes=Note.find_shared_notes())",
"redirect(url_for('.note', note_id=note_id)) else: return render_template('/notes/edit_note.html', note=note) except: error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg),",
"import redirect from src.models.notes.note import Note import src.models.users.decorators as user_decorators from src.models.users.user import",
"during saving your note...') @note_blueprint.route('/delete_note/<string:note_id>') @user_decorators.require_login def delete_note(note_id): try: Note.find_by_id(note_id).delete() finally: return redirect(url_for('.user_notes'))",
"'POST': if request.method == 'POST': share = request.form['inputGroupSelect01'] if share == '0': return",
"render_template from werkzeug.utils import redirect from src.models.notes.note import Note import src.models.users.decorators as user_decorators",
"creating note') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during saving your note...') @note_blueprint.route('/delete_note/<string:note_id>') @user_decorators.require_login def",
"def delete_note(note_id): try: Note.find_by_id(note_id).delete() finally: return redirect(url_for('.user_notes')) @note_blueprint.route('/share_note/<string:note_id>') @user_decorators.require_login def share_note(note_id): try: Note.find_by_id(note_id).share_or_unshare()",
"notes...') @note_blueprint.route('/note/<string:note_id>') def note(note_id): try: note = Note.find_by_id(note_id) user = User.find_by_email(note.author_email) try: if",
",share_only_with_users=share_only_with_users) note_for_save.save_to_mongo() return redirect(url_for('.user_notes')) return render_template('/notes/create_note.html') except: error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg),",
"request.method == 'POST': if request.method == 'POST': share = request.form['inputGroupSelect01'] if share ==",
"= True title = request.form['title'] content = request.form['content'] author_email = session['email'] author_nickname =",
"@user_decorators.require_login def edit_note(note_id): try: note = Note.find_by_id(note_id) if request.method == 'POST': if request.method",
"Error_obj = Error_(error_msg=''.join(error_msg), error_location='user note reading USER:' + session['email']) Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed",
"return render_template('/notes/edit_note.html', note=note) except: error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='edit_note saveing and",
"users notes...') @note_blueprint.route('/edit_note/<string:note_id>', methods=['GET', 'POST']) @user_decorators.require_login def edit_note(note_id): try: note = Note.find_by_id(note_id) if",
"Blueprint('notes', __name__) @note_blueprint.route('/my_notes/') @user_decorators.require_login def user_notes(): try: user = User.find_by_email(session['email']) user_notes = User.get_notes(user)",
"Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during reading your note...') @note_blueprint.route('/add_note', methods=['GET', 'POST']) @user_decorators.require_login def",
"session['email'] is None: return render_template('/notes/pub_notes.html', notes=Note.find_shared_notes()) else: return render_template('/notes/pub_notes.html', notes=Note.get_only_with_users() + Note.find_shared_notes()) except:",
"try: if request.method == 'POST': share = request.form['inputGroupSelect01'] if share == '0': return",
"= request.form['title'] content = request.form['content'] author_email = session['email'] author_nickname = User.find_by_email(author_email).nick_name note_for_save =",
"False share_only_with_users = True title = request.form['title'] content = request.form['content'] note.shared = share",
"note=note) except: error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='edit_note saveing and getting input",
"reading NOTE:NONE') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during reading your note...') @note_blueprint.route('/add_note', methods=['GET', 'POST'])",
"user_name = user.email return render_template('/notes/my_notes.html', user_name=user_name, user_notes=user_notes) except: error_msg = traceback.format_exc().split('\\n') Error_obj =",
"error_msgr='Crashed during reading users notes...') @note_blueprint.route('/edit_note/<string:note_id>', methods=['GET', 'POST']) @user_decorators.require_login def edit_note(note_id): try: note",
"methods=['GET', 'POST']) @user_decorators.require_login def create_note(): try: if request.method == 'POST': share = request.form['inputGroupSelect01']",
"getting input from html file') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during saving your note...')",
"render_template('error_page.html', error_msgr='Crashed during reading your note...') @note_blueprint.route('/add_note', methods=['GET', 'POST']) @user_decorators.require_login def create_note(): try:",
"except: return render_template('/notes/pub_notes.html', notes=Note.find_shared_notes()) except: error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='notes publick",
"an Share label.\") if share == '1': share = True share_only_with_users = False",
"return render_template('/notes/pub_notes.html', notes=Note.find_shared_notes()) except: error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='notes publick note",
"= True else: author_email_is_session = False except: author_email_is_session = False finally: return render_template('/notes/note.html',",
"= User.find_by_email(note.author_email) try: if note.author_email == session['email']: author_email_is_session = True else: author_email_is_session =",
"= Note.find_by_id(note_id) if request.method == 'POST': if request.method == 'POST': share = request.form['inputGroupSelect01']",
"render_template('/notes/pub_notes.html', notes=Note.find_shared_notes()) except: error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='notes publick note reading')",
"'POST']) @user_decorators.require_login def create_note(): try: if request.method == 'POST': share = request.form['inputGroupSelect01'] if",
"reading users notes...') @note_blueprint.route('/edit_note/<string:note_id>', methods=['GET', 'POST']) @user_decorators.require_login def edit_note(note_id): try: note = Note.find_by_id(note_id)",
"if note.author_email == session['email']: author_email_is_session = True else: author_email_is_session = False except: author_email_is_session",
"notes=Note.get_only_with_users() + Note.find_shared_notes()) except: return render_template('/notes/pub_notes.html', notes=Note.find_shared_notes()) except: error_msg = traceback.format_exc().split('\\n') Error_obj =",
"share = False share_only_with_users = True title = request.form['title'] content = request.form['content'] note.shared",
"from src.models.notes.note import Note import src.models.users.decorators as user_decorators from src.models.users.user import User from",
"= False share_only_with_users = True title = request.form['title'] content = request.form['content'] note.shared =",
"@user_decorators.require_login def user_notes(): try: user = User.find_by_email(session['email']) user_notes = User.get_notes(user) user_name = user.email",
"render_template('/notes/pub_notes.html', notes=Note.get_only_with_users() + Note.find_shared_notes()) except: return render_template('/notes/pub_notes.html', notes=Note.find_shared_notes()) except: error_msg = traceback.format_exc().split('\\n') Error_obj",
"error_msgr='Crashed during reading your notes...') @note_blueprint.route('/note/<string:note_id>') def note(note_id): try: note = Note.find_by_id(note_id) user",
"try: user = User.find_by_email(session['email']) user_notes = User.get_notes(user) user_name = user.email return render_template('/notes/my_notes.html', user_name=user_name,",
"@note_blueprint.route('/note/<string:note_id>') def note(note_id): try: note = Note.find_by_id(note_id) user = User.find_by_email(note.author_email) try: if note.author_email",
"note.content = content note.save_to_mongo() return redirect(url_for('.note', note_id=note_id)) else: return render_template('/notes/edit_note.html', note=note) except: error_msg",
"user_notes = User.get_notes(user) user_name = user.email return render_template('/notes/my_notes.html', user_name=user_name, user_notes=user_notes) except: error_msg =",
"return render_template('/notes/my_notes.html', user_name=user_name, user_notes=user_notes) except: error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='user note",
"else: return render_template('/notes/pub_notes.html', notes=Note.get_only_with_users() + Note.find_shared_notes()) except: return render_template('/notes/pub_notes.html', notes=Note.find_shared_notes()) except: error_msg =",
"url_for, render_template from werkzeug.utils import redirect from src.models.notes.note import Note import src.models.users.decorators as",
"title = request.form['title'] content = request.form['content'] author_email = session['email'] author_nickname = User.find_by_email(author_email).nick_name note_for_save",
"import Note import src.models.users.decorators as user_decorators from src.models.users.user import User from src.models.error_logs.error_log import",
"Note.find_shared_notes()) except: return render_template('/notes/pub_notes.html', notes=Note.find_shared_notes()) except: error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='notes",
"from werkzeug.utils import redirect from src.models.notes.note import Note import src.models.users.decorators as user_decorators from",
"False share_only_with_users = True title = request.form['title'] content = request.form['content'] author_email = session['email']",
"render_template('/notes/create_note.html', error_msg=\"You did not selected an Share label. Please select an Share label.\")",
"render_template('/notes/pub_notes.html', notes=Note.find_shared_notes()) else: return render_template('/notes/pub_notes.html', notes=Note.get_only_with_users() + Note.find_shared_notes()) except: return render_template('/notes/pub_notes.html', notes=Note.find_shared_notes()) except:",
"Note.find_by_id(note_id) if request.method == 'POST': if request.method == 'POST': share = request.form['inputGroupSelect01'] if",
"note reading USER:' + session['email']) Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during reading your notes...')",
"error_location='notes publick note reading') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during reading users notes...') @note_blueprint.route('/edit_note/<string:note_id>',",
"= False share_only_with_users = True title = request.form['title'] content = request.form['content'] author_email =",
"@note_blueprint.route('/pub_notes/') def notes(): try: try: if session['email'] is None: return render_template('/notes/pub_notes.html', notes=Note.find_shared_notes()) else:",
"try: if session['email'] is None: return render_template('/notes/pub_notes.html', notes=Note.find_shared_notes()) else: return render_template('/notes/pub_notes.html', notes=Note.get_only_with_users() +",
"== 'POST': if request.method == 'POST': share = request.form['inputGroupSelect01'] if share == '0':",
"== '1': share = True share_only_with_users = False else: share = False share_only_with_users",
"True title = request.form['title'] content = request.form['content'] author_email = session['email'] author_nickname = User.find_by_email(author_email).nick_name",
"finally: return redirect(url_for('.note', note_id=note_id, msg='Your note is shared!!', msg_=True)) @note_blueprint.route('/pub_notes/') def notes(): try:",
"try: Error_obj = Error_(error_msg=''.join(error_msg), error_location='note reading NOTE:' + note._id) except: Error_obj = Error_(error_msg=''.join(error_msg),",
"render_template('/notes/create_note.html') except: error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='create_note creating note') Error_obj.save_to_mongo() return",
"= User.get_notes(user) user_name = user.email return render_template('/notes/my_notes.html', user_name=user_name, user_notes=user_notes) except: error_msg = traceback.format_exc().split('\\n')",
"False finally: return render_template('/notes/note.html', note=note, author_email_is_session=author_email_is_session, msg_=False, user=user) except: error_msg = traceback.format_exc().split('\\n') try:",
"note.title = title note.content = content note.save_to_mongo() return redirect(url_for('.note', note_id=note_id)) else: return render_template('/notes/edit_note.html',",
"'0': return render_template('/notes/create_note.html', error_msg=\"You did not selected an Share label. Please select an",
"from src.models.users.user import User from src.models.error_logs.error_log import Error_ import traceback note_blueprint = Blueprint('notes',",
"title note.content = content note.save_to_mongo() return redirect(url_for('.note', note_id=note_id)) else: return render_template('/notes/edit_note.html', note=note) except:",
"reading') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during reading users notes...') @note_blueprint.route('/edit_note/<string:note_id>', methods=['GET', 'POST']) @user_decorators.require_login",
"redirect from src.models.notes.note import Note import src.models.users.decorators as user_decorators from src.models.users.user import User",
"= user.email return render_template('/notes/my_notes.html', user_name=user_name, user_notes=user_notes) except: error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg),",
"+ note._id) except: Error_obj = Error_(error_msg=''.join(error_msg), error_location='note reading NOTE:NONE') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed",
"finally: return redirect(url_for('.user_notes')) @note_blueprint.route('/share_note/<string:note_id>') @user_decorators.require_login def share_note(note_id): try: Note.find_by_id(note_id).share_or_unshare() finally: return redirect(url_for('.note', note_id=note_id,",
"error_location='user note reading USER:' + session['email']) Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during reading your",
"= request.form['content'] author_email = session['email'] author_nickname = User.find_by_email(author_email).nick_name note_for_save = Note(title=title, content=content, author_email=author_email,",
"content = request.form['content'] note.shared = share note.share_only_with_users = share_only_with_users note.title = title note.content",
"render_template('error_page.html', error_msgr='Crashed during saving your note...') @note_blueprint.route('/delete_note/<string:note_id>') @user_decorators.require_login def delete_note(note_id): try: Note.find_by_id(note_id).delete() finally:",
"error_msg=\"You did not selected an Share label. Please select an Share label.\") if",
"edit_note(note_id): try: note = Note.find_by_id(note_id) if request.method == 'POST': if request.method == 'POST':",
"User.get_notes(user) user_name = user.email return render_template('/notes/my_notes.html', user_name=user_name, user_notes=user_notes) except: error_msg = traceback.format_exc().split('\\n') Error_obj",
"create_note(): try: if request.method == 'POST': share = request.form['inputGroupSelect01'] if share == '0':",
"Error_(error_msg=''.join(error_msg), error_location='edit_note saveing and getting input from html file') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed",
"werkzeug.utils import redirect from src.models.notes.note import Note import src.models.users.decorators as user_decorators from src.models.users.user",
"author_email_is_session = True else: author_email_is_session = False except: author_email_is_session = False finally: return",
"<filename>models/notes/views.py<gh_stars>0 from flask import Blueprint, request, session, url_for, render_template from werkzeug.utils import redirect",
"import Blueprint, request, session, url_for, render_template from werkzeug.utils import redirect from src.models.notes.note import",
"error_msg = traceback.format_exc().split('\\n') try: Error_obj = Error_(error_msg=''.join(error_msg), error_location='note reading NOTE:' + note._id) except:",
"return render_template('error_page.html', error_msgr='Crashed during reading your notes...') @note_blueprint.route('/note/<string:note_id>') def note(note_id): try: note =",
"= Error_(error_msg=''.join(error_msg), error_location='user note reading USER:' + session['email']) Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during",
"share = False share_only_with_users = True title = request.form['title'] content = request.form['content'] author_email",
"def share_note(note_id): try: Note.find_by_id(note_id).share_or_unshare() finally: return redirect(url_for('.note', note_id=note_id, msg='Your note is shared!!', msg_=True))",
"flask import Blueprint, request, session, url_for, render_template from werkzeug.utils import redirect from src.models.notes.note",
"Share label.\") if share == '1': share = True share_only_with_users = False else:",
"Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during saving your note...') @note_blueprint.route('/delete_note/<string:note_id>') @user_decorators.require_login def delete_note(note_id): try:",
"Error_obj = Error_(error_msg=''.join(error_msg), error_location='note reading NOTE:' + note._id) except: Error_obj = Error_(error_msg=''.join(error_msg), error_location='note",
"share == '0': return render_template('/notes/create_note.html', error_msg=\"You did not selected an Share label. Please",
"return render_template('error_page.html', error_msgr='Crashed during saving your note...') @note_blueprint.route('/delete_note/<string:note_id>') @user_decorators.require_login def delete_note(note_id): try: Note.find_by_id(note_id).delete()",
"note = Note.find_by_id(note_id) if request.method == 'POST': if request.method == 'POST': share =",
"redirect(url_for('.user_notes')) @note_blueprint.route('/share_note/<string:note_id>') @user_decorators.require_login def share_note(note_id): try: Note.find_by_id(note_id).share_or_unshare() finally: return redirect(url_for('.note', note_id=note_id, msg='Your note",
"Share label. Please select an Share label.\") if share == '1': share =",
"error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='notes publick note reading') Error_obj.save_to_mongo() return render_template('error_page.html',",
"during reading your note...') @note_blueprint.route('/add_note', methods=['GET', 'POST']) @user_decorators.require_login def create_note(): try: if request.method",
"def user_notes(): try: user = User.find_by_email(session['email']) user_notes = User.get_notes(user) user_name = user.email return",
"if share == '1': share = True share_only_with_users = False else: share =",
"src.models.users.user import User from src.models.error_logs.error_log import Error_ import traceback note_blueprint = Blueprint('notes', __name__)",
"User.find_by_email(author_email).nick_name note_for_save = Note(title=title, content=content, author_email=author_email, shared=share, author_nickname=author_nickname ,share_only_with_users=share_only_with_users) note_for_save.save_to_mongo() return redirect(url_for('.user_notes')) return",
"except: error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='user note reading USER:' + session['email'])",
"notes=Note.find_shared_notes()) except: error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='notes publick note reading') Error_obj.save_to_mongo()",
"reading NOTE:' + note._id) except: Error_obj = Error_(error_msg=''.join(error_msg), error_location='note reading NOTE:NONE') Error_obj.save_to_mongo() return",
"share = request.form['inputGroupSelect01'] if share == '0': return render_template('/notes/create_note.html', error_msg=\"You did not selected",
"user_notes(): try: user = User.find_by_email(session['email']) user_notes = User.get_notes(user) user_name = user.email return render_template('/notes/my_notes.html',",
"error_msgr='Crashed during reading your note...') @note_blueprint.route('/add_note', methods=['GET', 'POST']) @user_decorators.require_login def create_note(): try: if",
"return render_template('error_page.html', error_msgr='Crashed during reading users notes...') @note_blueprint.route('/edit_note/<string:note_id>', methods=['GET', 'POST']) @user_decorators.require_login def edit_note(note_id):",
"author_email_is_session = False except: author_email_is_session = False finally: return render_template('/notes/note.html', note=note, author_email_is_session=author_email_is_session, msg_=False,",
"request.form['inputGroupSelect01'] if share == '0': return render_template('/notes/create_note.html', error_msg=\"You did not selected an Share",
"== 'POST': share = request.form['inputGroupSelect01'] if share == '0': return render_template('/notes/create_note.html', error_msg=\"You did",
"note is shared!!', msg_=True)) @note_blueprint.route('/pub_notes/') def notes(): try: try: if session['email'] is None:",
"content=content, author_email=author_email, shared=share, author_nickname=author_nickname ,share_only_with_users=share_only_with_users) note_for_save.save_to_mongo() return redirect(url_for('.user_notes')) return render_template('/notes/create_note.html') except: error_msg =",
"traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='notes publick note reading') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during",
"methods=['GET', 'POST']) @user_decorators.require_login def edit_note(note_id): try: note = Note.find_by_id(note_id) if request.method == 'POST':",
"user_name=user_name, user_notes=user_notes) except: error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='user note reading USER:'",
"user = User.find_by_email(note.author_email) try: if note.author_email == session['email']: author_email_is_session = True else: author_email_is_session",
"session, url_for, render_template from werkzeug.utils import redirect from src.models.notes.note import Note import src.models.users.decorators",
"def note(note_id): try: note = Note.find_by_id(note_id) user = User.find_by_email(note.author_email) try: if note.author_email ==",
"during reading users notes...') @note_blueprint.route('/edit_note/<string:note_id>', methods=['GET', 'POST']) @user_decorators.require_login def edit_note(note_id): try: note =",
"import User from src.models.error_logs.error_log import Error_ import traceback note_blueprint = Blueprint('notes', __name__) @note_blueprint.route('/my_notes/')",
"== '0': return render_template('/notes/create_note.html', error_msg=\"You did not selected an Share label. Please select",
"note reading') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during reading users notes...') @note_blueprint.route('/edit_note/<string:note_id>', methods=['GET', 'POST'])",
"note = Note.find_by_id(note_id) user = User.find_by_email(note.author_email) try: if note.author_email == session['email']: author_email_is_session =",
"note_for_save = Note(title=title, content=content, author_email=author_email, shared=share, author_nickname=author_nickname ,share_only_with_users=share_only_with_users) note_for_save.save_to_mongo() return redirect(url_for('.user_notes')) return render_template('/notes/create_note.html')",
"except: author_email_is_session = False finally: return render_template('/notes/note.html', note=note, author_email_is_session=author_email_is_session, msg_=False, user=user) except: error_msg",
"return render_template('/notes/pub_notes.html', notes=Note.get_only_with_users() + Note.find_shared_notes()) except: return render_template('/notes/pub_notes.html', notes=Note.find_shared_notes()) except: error_msg = traceback.format_exc().split('\\n')",
"user_decorators from src.models.users.user import User from src.models.error_logs.error_log import Error_ import traceback note_blueprint =",
"session['email']) Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during reading your notes...') @note_blueprint.route('/note/<string:note_id>') def note(note_id): try:",
"content note.save_to_mongo() return redirect(url_for('.note', note_id=note_id)) else: return render_template('/notes/edit_note.html', note=note) except: error_msg = traceback.format_exc().split('\\n')",
"request.form['content'] author_email = session['email'] author_nickname = User.find_by_email(author_email).nick_name note_for_save = Note(title=title, content=content, author_email=author_email, shared=share,",
"note.share_only_with_users = share_only_with_users note.title = title note.content = content note.save_to_mongo() return redirect(url_for('.note', note_id=note_id))",
"if share == '0': return render_template('/notes/create_note.html', error_msg=\"You did not selected an Share label.",
"render_template('/notes/note.html', note=note, author_email_is_session=author_email_is_session, msg_=False, user=user) except: error_msg = traceback.format_exc().split('\\n') try: Error_obj = Error_(error_msg=''.join(error_msg),",
"author_nickname=author_nickname ,share_only_with_users=share_only_with_users) note_for_save.save_to_mongo() return redirect(url_for('.user_notes')) return render_template('/notes/create_note.html') except: error_msg = traceback.format_exc().split('\\n') Error_obj =",
"import traceback note_blueprint = Blueprint('notes', __name__) @note_blueprint.route('/my_notes/') @user_decorators.require_login def user_notes(): try: user =",
"@user_decorators.require_login def create_note(): try: if request.method == 'POST': share = request.form['inputGroupSelect01'] if share",
"Note(title=title, content=content, author_email=author_email, shared=share, author_nickname=author_nickname ,share_only_with_users=share_only_with_users) note_for_save.save_to_mongo() return redirect(url_for('.user_notes')) return render_template('/notes/create_note.html') except: error_msg",
"traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='create_note creating note') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during saving",
"@note_blueprint.route('/share_note/<string:note_id>') @user_decorators.require_login def share_note(note_id): try: Note.find_by_id(note_id).share_or_unshare() finally: return redirect(url_for('.note', note_id=note_id, msg='Your note is",
"label.\") if share == '1': share = True share_only_with_users = False else: share",
"user = User.find_by_email(session['email']) user_notes = User.get_notes(user) user_name = user.email return render_template('/notes/my_notes.html', user_name=user_name, user_notes=user_notes)",
"= request.form['content'] note.shared = share note.share_only_with_users = share_only_with_users note.title = title note.content =",
"render_template('error_page.html', error_msgr='Crashed during reading your notes...') @note_blueprint.route('/note/<string:note_id>') def note(note_id): try: note = Note.find_by_id(note_id)",
"is None: return render_template('/notes/pub_notes.html', notes=Note.find_shared_notes()) else: return render_template('/notes/pub_notes.html', notes=Note.get_only_with_users() + Note.find_shared_notes()) except: return",
"author_email = session['email'] author_nickname = User.find_by_email(author_email).nick_name note_for_save = Note(title=title, content=content, author_email=author_email, shared=share, author_nickname=author_nickname",
"None: return render_template('/notes/pub_notes.html', notes=Note.find_shared_notes()) else: return render_template('/notes/pub_notes.html', notes=Note.get_only_with_users() + Note.find_shared_notes()) except: return render_template('/notes/pub_notes.html',",
"User from src.models.error_logs.error_log import Error_ import traceback note_blueprint = Blueprint('notes', __name__) @note_blueprint.route('/my_notes/') @user_decorators.require_login",
"@note_blueprint.route('/delete_note/<string:note_id>') @user_decorators.require_login def delete_note(note_id): try: Note.find_by_id(note_id).delete() finally: return redirect(url_for('.user_notes')) @note_blueprint.route('/share_note/<string:note_id>') @user_decorators.require_login def share_note(note_id):",
"title = request.form['title'] content = request.form['content'] note.shared = share note.share_only_with_users = share_only_with_users note.title",
"Error_ import traceback note_blueprint = Blueprint('notes', __name__) @note_blueprint.route('/my_notes/') @user_decorators.require_login def user_notes(): try: user",
"and getting input from html file') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during saving your",
"Error_obj = Error_(error_msg=''.join(error_msg), error_location='edit_note saveing and getting input from html file') Error_obj.save_to_mongo() return",
"Error_obj = Error_(error_msg=''.join(error_msg), error_location='note reading NOTE:NONE') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during reading your",
"= Error_(error_msg=''.join(error_msg), error_location='notes publick note reading') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during reading users",
"share note.share_only_with_users = share_only_with_users note.title = title note.content = content note.save_to_mongo() return redirect(url_for('.note',",
"note._id) except: Error_obj = Error_(error_msg=''.join(error_msg), error_location='note reading NOTE:NONE') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during",
"share_only_with_users = False else: share = False share_only_with_users = True title = request.form['title']",
"Error_(error_msg=''.join(error_msg), error_location='note reading NOTE:NONE') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during reading your note...') @note_blueprint.route('/add_note',",
"NOTE:' + note._id) except: Error_obj = Error_(error_msg=''.join(error_msg), error_location='note reading NOTE:NONE') Error_obj.save_to_mongo() return render_template('error_page.html',",
"notes=Note.find_shared_notes()) else: return render_template('/notes/pub_notes.html', notes=Note.get_only_with_users() + Note.find_shared_notes()) except: return render_template('/notes/pub_notes.html', notes=Note.find_shared_notes()) except: error_msg",
"note.shared = share note.share_only_with_users = share_only_with_users note.title = title note.content = content note.save_to_mongo()",
"if request.method == 'POST': share = request.form['inputGroupSelect01'] if share == '0': return render_template('/notes/create_note.html',",
"selected an Share label. Please select an Share label.\") if share == '1':",
"note') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during saving your note...') @note_blueprint.route('/delete_note/<string:note_id>') @user_decorators.require_login def delete_note(note_id):",
"Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during reading users notes...') @note_blueprint.route('/edit_note/<string:note_id>', methods=['GET', 'POST']) @user_decorators.require_login def",
"error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='create_note creating note') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed",
"did not selected an Share label. Please select an Share label.\") if share",
"msg_=False, user=user) except: error_msg = traceback.format_exc().split('\\n') try: Error_obj = Error_(error_msg=''.join(error_msg), error_location='note reading NOTE:'",
"not selected an Share label. Please select an Share label.\") if share ==",
"traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='user note reading USER:' + session['email']) Error_obj.save_to_mongo() return render_template('error_page.html',",
"finally: return render_template('/notes/note.html', note=note, author_email_is_session=author_email_is_session, msg_=False, user=user) except: error_msg = traceback.format_exc().split('\\n') try: Error_obj",
"= User.find_by_email(session['email']) user_notes = User.get_notes(user) user_name = user.email return render_template('/notes/my_notes.html', user_name=user_name, user_notes=user_notes) except:",
"request.form['title'] content = request.form['content'] author_email = session['email'] author_nickname = User.find_by_email(author_email).nick_name note_for_save = Note(title=title,",
"False except: author_email_is_session = False finally: return render_template('/notes/note.html', note=note, author_email_is_session=author_email_is_session, msg_=False, user=user) except:",
"shared!!', msg_=True)) @note_blueprint.route('/pub_notes/') def notes(): try: try: if session['email'] is None: return render_template('/notes/pub_notes.html',",
"= request.form['title'] content = request.form['content'] note.shared = share note.share_only_with_users = share_only_with_users note.title =",
"from flask import Blueprint, request, session, url_for, render_template from werkzeug.utils import redirect from",
"Please select an Share label.\") if share == '1': share = True share_only_with_users",
"'POST']) @user_decorators.require_login def edit_note(note_id): try: note = Note.find_by_id(note_id) if request.method == 'POST': if",
"note_id=note_id)) else: return render_template('/notes/edit_note.html', note=note) except: error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='edit_note",
"except: error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='edit_note saveing and getting input from",
"= share note.share_only_with_users = share_only_with_users note.title = title note.content = content note.save_to_mongo() return",
"share = True share_only_with_users = False else: share = False share_only_with_users = True",
"@note_blueprint.route('/add_note', methods=['GET', 'POST']) @user_decorators.require_login def create_note(): try: if request.method == 'POST': share =",
"return render_template('/notes/create_note.html') except: error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='create_note creating note') Error_obj.save_to_mongo()",
"else: author_email_is_session = False except: author_email_is_session = False finally: return render_template('/notes/note.html', note=note, author_email_is_session=author_email_is_session,",
"def create_note(): try: if request.method == 'POST': share = request.form['inputGroupSelect01'] if share ==",
"return redirect(url_for('.user_notes')) return render_template('/notes/create_note.html') except: error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='create_note creating",
"request.method == 'POST': share = request.form['inputGroupSelect01'] if share == '0': return render_template('/notes/create_note.html', error_msg=\"You",
"= False else: share = False share_only_with_users = True title = request.form['title'] content",
"select an Share label.\") if share == '1': share = True share_only_with_users =",
"traceback.format_exc().split('\\n') try: Error_obj = Error_(error_msg=''.join(error_msg), error_location='note reading NOTE:' + note._id) except: Error_obj =",
"try: if note.author_email == session['email']: author_email_is_session = True else: author_email_is_session = False except:",
"src.models.error_logs.error_log import Error_ import traceback note_blueprint = Blueprint('notes', __name__) @note_blueprint.route('/my_notes/') @user_decorators.require_login def user_notes():",
"delete_note(note_id): try: Note.find_by_id(note_id).delete() finally: return redirect(url_for('.user_notes')) @note_blueprint.route('/share_note/<string:note_id>') @user_decorators.require_login def share_note(note_id): try: Note.find_by_id(note_id).share_or_unshare() finally:",
"share_only_with_users note.title = title note.content = content note.save_to_mongo() return redirect(url_for('.note', note_id=note_id)) else: return",
"error_location='create_note creating note') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during saving your note...') @note_blueprint.route('/delete_note/<string:note_id>') @user_decorators.require_login",
"error_location='note reading NOTE:' + note._id) except: Error_obj = Error_(error_msg=''.join(error_msg), error_location='note reading NOTE:NONE') Error_obj.save_to_mongo()",
"share_note(note_id): try: Note.find_by_id(note_id).share_or_unshare() finally: return redirect(url_for('.note', note_id=note_id, msg='Your note is shared!!', msg_=True)) @note_blueprint.route('/pub_notes/')",
"error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='user note reading USER:' + session['email']) Error_obj.save_to_mongo()",
"import src.models.users.decorators as user_decorators from src.models.users.user import User from src.models.error_logs.error_log import Error_ import",
"author_email_is_session = False finally: return render_template('/notes/note.html', note=note, author_email_is_session=author_email_is_session, msg_=False, user=user) except: error_msg =",
"note_blueprint = Blueprint('notes', __name__) @note_blueprint.route('/my_notes/') @user_decorators.require_login def user_notes(): try: user = User.find_by_email(session['email']) user_notes",
"== session['email']: author_email_is_session = True else: author_email_is_session = False except: author_email_is_session = False",
"+ session['email']) Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during reading your notes...') @note_blueprint.route('/note/<string:note_id>') def note(note_id):",
"NOTE:NONE') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during reading your note...') @note_blueprint.route('/add_note', methods=['GET', 'POST']) @user_decorators.require_login",
"= False finally: return render_template('/notes/note.html', note=note, author_email_is_session=author_email_is_session, msg_=False, user=user) except: error_msg = traceback.format_exc().split('\\n')",
"session['email']: author_email_is_session = True else: author_email_is_session = False except: author_email_is_session = False finally:",
"try: note = Note.find_by_id(note_id) user = User.find_by_email(note.author_email) try: if note.author_email == session['email']: author_email_is_session",
"Error_(error_msg=''.join(error_msg), error_location='note reading NOTE:' + note._id) except: Error_obj = Error_(error_msg=''.join(error_msg), error_location='note reading NOTE:NONE')",
"return render_template('/notes/create_note.html', error_msg=\"You did not selected an Share label. Please select an Share",
"try: Note.find_by_id(note_id).share_or_unshare() finally: return redirect(url_for('.note', note_id=note_id, msg='Your note is shared!!', msg_=True)) @note_blueprint.route('/pub_notes/') def",
"session['email'] author_nickname = User.find_by_email(author_email).nick_name note_for_save = Note(title=title, content=content, author_email=author_email, shared=share, author_nickname=author_nickname ,share_only_with_users=share_only_with_users) note_for_save.save_to_mongo()",
"= Error_(error_msg=''.join(error_msg), error_location='edit_note saveing and getting input from html file') Error_obj.save_to_mongo() return render_template('error_page.html',",
"user=user) except: error_msg = traceback.format_exc().split('\\n') try: Error_obj = Error_(error_msg=''.join(error_msg), error_location='note reading NOTE:' +",
"note...') @note_blueprint.route('/delete_note/<string:note_id>') @user_decorators.require_login def delete_note(note_id): try: Note.find_by_id(note_id).delete() finally: return redirect(url_for('.user_notes')) @note_blueprint.route('/share_note/<string:note_id>') @user_decorators.require_login def",
"share_only_with_users = True title = request.form['title'] content = request.form['content'] author_email = session['email'] author_nickname",
"return redirect(url_for('.note', note_id=note_id, msg='Your note is shared!!', msg_=True)) @note_blueprint.route('/pub_notes/') def notes(): try: try:",
"redirect(url_for('.user_notes')) return render_template('/notes/create_note.html') except: error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='create_note creating note')",
"user.email return render_template('/notes/my_notes.html', user_name=user_name, user_notes=user_notes) except: error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='user",
"user_notes=user_notes) except: error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='user note reading USER:' +",
"note_for_save.save_to_mongo() return redirect(url_for('.user_notes')) return render_template('/notes/create_note.html') except: error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='create_note",
"Note.find_by_id(note_id) user = User.find_by_email(note.author_email) try: if note.author_email == session['email']: author_email_is_session = True else:",
"except: error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='create_note creating note') Error_obj.save_to_mongo() return render_template('error_page.html',",
"= traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='user note reading USER:' + session['email']) Error_obj.save_to_mongo() return",
"Error_(error_msg=''.join(error_msg), error_location='create_note creating note') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during saving your note...') @note_blueprint.route('/delete_note/<string:note_id>')",
"Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during reading your notes...') @note_blueprint.route('/note/<string:note_id>') def note(note_id): try: note",
"= request.form['inputGroupSelect01'] if share == '0': return render_template('/notes/create_note.html', error_msg=\"You did not selected an",
"except: error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='notes publick note reading') Error_obj.save_to_mongo() return",
"redirect(url_for('.note', note_id=note_id, msg='Your note is shared!!', msg_=True)) @note_blueprint.route('/pub_notes/') def notes(): try: try: if",
"is shared!!', msg_=True)) @note_blueprint.route('/pub_notes/') def notes(): try: try: if session['email'] is None: return",
"@note_blueprint.route('/edit_note/<string:note_id>', methods=['GET', 'POST']) @user_decorators.require_login def edit_note(note_id): try: note = Note.find_by_id(note_id) if request.method ==",
"= Error_(error_msg=''.join(error_msg), error_location='create_note creating note') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during saving your note...')",
"content = request.form['content'] author_email = session['email'] author_nickname = User.find_by_email(author_email).nick_name note_for_save = Note(title=title, content=content,",
"traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='edit_note saveing and getting input from html file') Error_obj.save_to_mongo()",
"your notes...') @note_blueprint.route('/note/<string:note_id>') def note(note_id): try: note = Note.find_by_id(note_id) user = User.find_by_email(note.author_email) try:",
"= share_only_with_users note.title = title note.content = content note.save_to_mongo() return redirect(url_for('.note', note_id=note_id)) else:",
"publick note reading') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during reading users notes...') @note_blueprint.route('/edit_note/<string:note_id>', methods=['GET',",
"note_id=note_id, msg='Your note is shared!!', msg_=True)) @note_blueprint.route('/pub_notes/') def notes(): try: try: if session['email']",
"= True title = request.form['title'] content = request.form['content'] note.shared = share note.share_only_with_users =",
"share_only_with_users = True title = request.form['title'] content = request.form['content'] note.shared = share note.share_only_with_users",
"notes(): try: try: if session['email'] is None: return render_template('/notes/pub_notes.html', notes=Note.find_shared_notes()) else: return render_template('/notes/pub_notes.html',",
"User.find_by_email(session['email']) user_notes = User.get_notes(user) user_name = user.email return render_template('/notes/my_notes.html', user_name=user_name, user_notes=user_notes) except: error_msg",
"= Error_(error_msg=''.join(error_msg), error_location='note reading NOTE:' + note._id) except: Error_obj = Error_(error_msg=''.join(error_msg), error_location='note reading",
"= Error_(error_msg=''.join(error_msg), error_location='note reading NOTE:NONE') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during reading your note...')",
"author_email=author_email, shared=share, author_nickname=author_nickname ,share_only_with_users=share_only_with_users) note_for_save.save_to_mongo() return redirect(url_for('.user_notes')) return render_template('/notes/create_note.html') except: error_msg = traceback.format_exc().split('\\n')",
"saveing and getting input from html file') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during saving",
"Note.find_by_id(note_id).share_or_unshare() finally: return redirect(url_for('.note', note_id=note_id, msg='Your note is shared!!', msg_=True)) @note_blueprint.route('/pub_notes/') def notes():",
"if session['email'] is None: return render_template('/notes/pub_notes.html', notes=Note.find_shared_notes()) else: return render_template('/notes/pub_notes.html', notes=Note.get_only_with_users() + Note.find_shared_notes())",
"author_email_is_session=author_email_is_session, msg_=False, user=user) except: error_msg = traceback.format_exc().split('\\n') try: Error_obj = Error_(error_msg=''.join(error_msg), error_location='note reading",
"Note import src.models.users.decorators as user_decorators from src.models.users.user import User from src.models.error_logs.error_log import Error_",
"reading your note...') @note_blueprint.route('/add_note', methods=['GET', 'POST']) @user_decorators.require_login def create_note(): try: if request.method ==",
"Note.find_by_id(note_id).delete() finally: return redirect(url_for('.user_notes')) @note_blueprint.route('/share_note/<string:note_id>') @user_decorators.require_login def share_note(note_id): try: Note.find_by_id(note_id).share_or_unshare() finally: return redirect(url_for('.note',",
"Error_obj = Error_(error_msg=''.join(error_msg), error_location='create_note creating note') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during saving your",
"src.models.notes.note import Note import src.models.users.decorators as user_decorators from src.models.users.user import User from src.models.error_logs.error_log",
"= False except: author_email_is_session = False finally: return render_template('/notes/note.html', note=note, author_email_is_session=author_email_is_session, msg_=False, user=user)",
"render_template('error_page.html', error_msgr='Crashed during reading users notes...') @note_blueprint.route('/edit_note/<string:note_id>', methods=['GET', 'POST']) @user_decorators.require_login def edit_note(note_id): try:",
"= traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='notes publick note reading') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed",
"note=note, author_email_is_session=author_email_is_session, msg_=False, user=user) except: error_msg = traceback.format_exc().split('\\n') try: Error_obj = Error_(error_msg=''.join(error_msg), error_location='note",
"shared=share, author_nickname=author_nickname ,share_only_with_users=share_only_with_users) note_for_save.save_to_mongo() return redirect(url_for('.user_notes')) return render_template('/notes/create_note.html') except: error_msg = traceback.format_exc().split('\\n') Error_obj",
"try: Note.find_by_id(note_id).delete() finally: return redirect(url_for('.user_notes')) @note_blueprint.route('/share_note/<string:note_id>') @user_decorators.require_login def share_note(note_id): try: Note.find_by_id(note_id).share_or_unshare() finally: return",
"else: return render_template('/notes/edit_note.html', note=note) except: error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='edit_note saveing",
"__name__) @note_blueprint.route('/my_notes/') @user_decorators.require_login def user_notes(): try: user = User.find_by_email(session['email']) user_notes = User.get_notes(user) user_name",
"render_template('/notes/my_notes.html', user_name=user_name, user_notes=user_notes) except: error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='user note reading",
"Blueprint, request, session, url_for, render_template from werkzeug.utils import redirect from src.models.notes.note import Note",
"USER:' + session['email']) Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during reading your notes...') @note_blueprint.route('/note/<string:note_id>') def",
"def notes(): try: try: if session['email'] is None: return render_template('/notes/pub_notes.html', notes=Note.find_shared_notes()) else: return",
"= Note.find_by_id(note_id) user = User.find_by_email(note.author_email) try: if note.author_email == session['email']: author_email_is_session = True",
"render_template('/notes/edit_note.html', note=note) except: error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='edit_note saveing and getting",
"try: note = Note.find_by_id(note_id) if request.method == 'POST': if request.method == 'POST': share",
"your note...') @note_blueprint.route('/add_note', methods=['GET', 'POST']) @user_decorators.require_login def create_note(): try: if request.method == 'POST':",
"if request.method == 'POST': if request.method == 'POST': share = request.form['inputGroupSelect01'] if share",
"@user_decorators.require_login def delete_note(note_id): try: Note.find_by_id(note_id).delete() finally: return redirect(url_for('.user_notes')) @note_blueprint.route('/share_note/<string:note_id>') @user_decorators.require_login def share_note(note_id): try:",
"User.find_by_email(note.author_email) try: if note.author_email == session['email']: author_email_is_session = True else: author_email_is_session = False",
"request.form['content'] note.shared = share note.share_only_with_users = share_only_with_users note.title = title note.content = content",
"reading USER:' + session['email']) Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during reading your notes...') @note_blueprint.route('/note/<string:note_id>')",
"author_nickname = User.find_by_email(author_email).nick_name note_for_save = Note(title=title, content=content, author_email=author_email, shared=share, author_nickname=author_nickname ,share_only_with_users=share_only_with_users) note_for_save.save_to_mongo() return",
"False else: share = False share_only_with_users = True title = request.form['title'] content =",
"Error_(error_msg=''.join(error_msg), error_location='notes publick note reading') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during reading users notes...')",
"+ Note.find_shared_notes()) except: return render_template('/notes/pub_notes.html', notes=Note.find_shared_notes()) except: error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg),",
"return redirect(url_for('.note', note_id=note_id)) else: return render_template('/notes/edit_note.html', note=note) except: error_msg = traceback.format_exc().split('\\n') Error_obj =",
"def edit_note(note_id): try: note = Note.find_by_id(note_id) if request.method == 'POST': if request.method ==",
"request.form['title'] content = request.form['content'] note.shared = share note.share_only_with_users = share_only_with_users note.title = title",
"Error_obj = Error_(error_msg=''.join(error_msg), error_location='notes publick note reading') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during reading",
"error_msg = traceback.format_exc().split('\\n') Error_obj = Error_(error_msg=''.join(error_msg), error_location='edit_note saveing and getting input from html",
"try: try: if session['email'] is None: return render_template('/notes/pub_notes.html', notes=Note.find_shared_notes()) else: return render_template('/notes/pub_notes.html', notes=Note.get_only_with_users()",
"label. Please select an Share label.\") if share == '1': share = True",
"src.models.users.decorators as user_decorators from src.models.users.user import User from src.models.error_logs.error_log import Error_ import traceback",
"your note...') @note_blueprint.route('/delete_note/<string:note_id>') @user_decorators.require_login def delete_note(note_id): try: Note.find_by_id(note_id).delete() finally: return redirect(url_for('.user_notes')) @note_blueprint.route('/share_note/<string:note_id>') @user_decorators.require_login",
"'1': share = True share_only_with_users = False else: share = False share_only_with_users =",
"return render_template('/notes/note.html', note=note, author_email_is_session=author_email_is_session, msg_=False, user=user) except: error_msg = traceback.format_exc().split('\\n') try: Error_obj =",
"an Share label. Please select an Share label.\") if share == '1': share",
"msg='Your note is shared!!', msg_=True)) @note_blueprint.route('/pub_notes/') def notes(): try: try: if session['email'] is",
"traceback note_blueprint = Blueprint('notes', __name__) @note_blueprint.route('/my_notes/') @user_decorators.require_login def user_notes(): try: user = User.find_by_email(session['email'])",
"from src.models.error_logs.error_log import Error_ import traceback note_blueprint = Blueprint('notes', __name__) @note_blueprint.route('/my_notes/') @user_decorators.require_login def",
"note.save_to_mongo() return redirect(url_for('.note', note_id=note_id)) else: return render_template('/notes/edit_note.html', note=note) except: error_msg = traceback.format_exc().split('\\n') Error_obj",
"return redirect(url_for('.user_notes')) @note_blueprint.route('/share_note/<string:note_id>') @user_decorators.require_login def share_note(note_id): try: Note.find_by_id(note_id).share_or_unshare() finally: return redirect(url_for('.note', note_id=note_id, msg='Your",
"error_location='note reading NOTE:NONE') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during reading your note...') @note_blueprint.route('/add_note', methods=['GET',",
"True else: author_email_is_session = False except: author_email_is_session = False finally: return render_template('/notes/note.html', note=note,",
"except: Error_obj = Error_(error_msg=''.join(error_msg), error_location='note reading NOTE:NONE') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during reading",
"Error_(error_msg=''.join(error_msg), error_location='user note reading USER:' + session['email']) Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during reading",
"else: share = False share_only_with_users = True title = request.form['title'] content = request.form['content']",
"error_location='edit_note saveing and getting input from html file') Error_obj.save_to_mongo() return render_template('error_page.html', error_msgr='Crashed during"
] |
[
"version = version.replace(\"^\", \"~=\") return version # ~=X.X else: # Allow exact version",
"updates version = version.replace(\"^\", \"\") major, minor, patch = version.split(\".\") return \"~={}.{}\".format(major, minor)",
"= version.replace(\"^\", \"\") major, minor, patch = version.split(\".\") return \"~={}.{}\".format(major, minor) # ~=X.X",
"Raises: InvalidDependencyVersionFormat \"\"\" if ValidDependencyVersionRegex.MAJOR_MINOR_PATCH.value.match(version): return ValidDependencyVersionRegex.MAJOR_MINOR_PATCH if ValidDependencyVersionRegex.MAJOR_MINOR.value.match(version): return ValidDependencyVersionRegex.MAJOR_MINOR if ValidDependencyVersionRegex.MAJOR.value.match(version):",
"# ==X.X.X elif dependency_regex == ValidDependencyVersionRegex.MAJOR_MINOR: if version.startswith(\"~\"): # Allow patch updates version",
"version: str) -> PipReadyDependency: \"\"\" Raises: InvalidDependencyVersionFormat UnexpectedError \"\"\" dependency_regex: ValidDependencyVersionRegex = _get_dependency_version_format(",
"(^|~) X.X.X if version.startswith(\"~\"): # Allow patch updates return version.replace(\"~\", \"~=\") # ~=X.X.X",
"minor, patch = version.split(\".\") return \"~={}.{}\".format(major, minor) # ~=X.X else: # Allow exact",
"version = version.replace(\"~\", \"\") major, minor = version.split(\".\") return \"~={}.{}.0\".format(major, minor) # ~=X.X.0",
"version.replace(\"~\", \"\") return \"~={}.0.0\".format(version) # ~=X.0.0 elif version.startswith(\"^\"): # Allow minor updates version",
"raise InvalidDependencyVersionFormat( \"\\nThe version format for the wheel dependency '{dep}' is invalid. Use",
"dependency '{dep}' is not present in the wheel filename '{wheel}'\" .format(dep=dependency_name, wheel=version) )",
"else: # Allow exact version return \"=={}\".format(version) # ==X.X elif dependency_regex == ValidDependencyVersionRegex.MAJOR:",
"\"-\")\\ .lower() return wheel.endswith(dependency_name.replace(\"_\", \"-\").lower()) def _get_dependency_version_format(dependency_name: str, version: str) -> ValidDependencyVersionRegex: \"\"\"",
"ValidDependencyVersionRegex.TARGZ raise InvalidDependencyVersionFormat( \"\\nInvalid version format for the dependency '{dep}'. Only the following",
"-> ValidDependencyVersionRegex: \"\"\" Raises: InvalidDependencyVersionFormat \"\"\" if ValidDependencyVersionRegex.MAJOR_MINOR_PATCH.value.match(version): return ValidDependencyVersionRegex.MAJOR_MINOR_PATCH if ValidDependencyVersionRegex.MAJOR_MINOR.value.match(version): return",
"ValidDependencyVersionRegex.TARGZ: return version raise UnexpectedError(\"The dependency given should have thrown 'InvalidDependencyVersionFormat' but it",
"version.startswith(\"~\"): # Allow patch updates version = version.replace(\"~\", \"\") major, minor = version.split(\".\")",
"wheel = wheel[:-1*len(\"-{}\".format(version))]\\ .replace(\"_\", \"-\")\\ .lower() return wheel.endswith(dependency_name.replace(\"_\", \"-\").lower()) def _get_dependency_version_format(dependency_name: str, version:",
"not _is_dependency_name_in_wheel(dependency_name=dependency_name, wheel=wheel, version=wheel_version): raise InvalidDependencyVersionFormat( \"The dependency '{dep}' is not present in",
"= _get_dependency_version_format( dependency_name=dependency_name, version=version ) if dependency_regex == ValidDependencyVersionRegex.MAJOR_MINOR_PATCH: # (^|~) X.X.X if",
"Use a 'Final release' format \" \"(see https://www.python.org/dev/peps/pep-0440/#final-releases)\" .format(dep=dependency_name) ) return ValidDependencyVersionRegex.WHEEL if",
"bool: wheel = wheel[:-1*len(\"-{}\".format(version))]\\ .replace(\"_\", \"-\")\\ .lower() return wheel.endswith(dependency_name.replace(\"_\", \"-\").lower()) def _get_dependency_version_format(dependency_name: str,",
"# ~=X.0.0 elif version.startswith(\"^\"): # Allow minor updates version = version.replace(\"^\", \"\") return",
"return \"=={}\".format(version) # ==X elif dependency_regex == ValidDependencyVersionRegex.LATEST: return dependency_name.lower() elif dependency_regex ==",
".tar.gz Packages\" .format(dep=dependency_name) ) def generate_pip_ready_dependency(dependency_name: str, version: str) -> PipReadyDependency: \"\"\" Raises:",
"Allow minor updates version = version.replace(\"^\", \"~=\") return version # ~=X.X else: #",
"\"\") major, minor = version.split(\".\") return \"~={}.{}.0\".format(major, minor) # ~=X.X.0 elif version.startswith(\"^\"): #",
"import ValidDependencyVersionRegex from caos._internal.exceptions import InvalidDependencyVersionFormat, UnexpectedError from typing import NewType PipReadyDependency =",
"Allow patch updates return version.replace(\"~\", \"~=\") # ~=X.X.X elif version.startswith(\"^\"): # Allow minor",
"ValidDependencyVersionRegex.LATEST: return dependency_name.lower() elif dependency_regex == ValidDependencyVersionRegex.WHEEL: return version elif dependency_regex == ValidDependencyVersionRegex.TARGZ:",
"\"=={}\".format(version) # ==X elif dependency_regex == ValidDependencyVersionRegex.LATEST: return dependency_name.lower() elif dependency_regex == ValidDependencyVersionRegex.WHEEL:",
"\"\"\" Raises: InvalidDependencyVersionFormat \"\"\" if ValidDependencyVersionRegex.MAJOR_MINOR_PATCH.value.match(version): return ValidDependencyVersionRegex.MAJOR_MINOR_PATCH if ValidDependencyVersionRegex.MAJOR_MINOR.value.match(version): return ValidDependencyVersionRegex.MAJOR_MINOR if",
"dependency_regex: ValidDependencyVersionRegex = _get_dependency_version_format( dependency_name=dependency_name, version=version ) if dependency_regex == ValidDependencyVersionRegex.MAJOR_MINOR_PATCH: # (^|~)",
"patch updates return version.replace(\"~\", \"~=\") # ~=X.X.X elif version.startswith(\"^\"): # Allow minor updates",
"return \"~={}.{}\".format(major, minor) # ~=X.X else: # Allow exact version return \"=={}\".format(version) #",
"\"\\n - Final release format (see https://www.python.org/dev/peps/pep-0440/#final-releases)\" \"\\n - Wheel Binary Packages (see",
"elif version.startswith(\"^\"): # Allow minor updates version = version.replace(\"^\", \"\") return \"~={}.0\".format(version) #",
"if wheel_info: wheel = wheel_info.group(\"wheel\") wheel_version = wheel_info.group(\"version\") if not _is_dependency_name_in_wheel(dependency_name=dependency_name, wheel=wheel, version=wheel_version):",
"major, minor = version.split(\".\") return \"~={}.{}.0\".format(major, minor) # ~=X.X.0 elif version.startswith(\"^\"): # Allow",
"https://www.python.org/dev/peps/pep-0491/#file-format)\" \"\\n - .tar.gz Packages\" .format(dep=dependency_name) ) def generate_pip_ready_dependency(dependency_name: str, version: str) ->",
"from typing import NewType PipReadyDependency = NewType(name=\"PipReadyDependency\", tp=str) def _is_dependency_name_in_wheel(dependency_name: str, wheel: str,",
"updates return version.replace(\"~\", \"~=\") # ~=X.X.X elif version.startswith(\"^\"): # Allow minor updates version",
"dependency_regex == ValidDependencyVersionRegex.MAJOR_MINOR: if version.startswith(\"~\"): # Allow patch updates version = version.replace(\"~\", \"\")",
"Final release format (see https://www.python.org/dev/peps/pep-0440/#final-releases)\" \"\\n - Wheel Binary Packages (see https://www.python.org/dev/peps/pep-0491/#file-format)\" \"\\n",
"version.split(\".\") return \"~={}.{}.0\".format(major, minor) # ~=X.X.0 elif version.startswith(\"^\"): # Allow minor updates version",
"wheel_version = wheel_info.group(\"version\") if not _is_dependency_name_in_wheel(dependency_name=dependency_name, wheel=wheel, version=wheel_version): raise InvalidDependencyVersionFormat( \"The dependency '{dep}'",
"return ValidDependencyVersionRegex.WHEEL if ValidDependencyVersionRegex.TARGZ.value.match(version): return ValidDependencyVersionRegex.TARGZ raise InvalidDependencyVersionFormat( \"\\nInvalid version format for the",
"ValidDependencyVersionRegex.TARGZ.value.match(version): return ValidDependencyVersionRegex.TARGZ raise InvalidDependencyVersionFormat( \"\\nInvalid version format for the dependency '{dep}'. Only",
"dependency_regex == ValidDependencyVersionRegex.MAJOR_MINOR_PATCH: # (^|~) X.X.X if version.startswith(\"~\"): # Allow patch updates return",
"caos._internal.constants import ValidDependencyVersionRegex from caos._internal.exceptions import InvalidDependencyVersionFormat, UnexpectedError from typing import NewType PipReadyDependency",
"updates version = version.replace(\"^\", \"\") return \"~={}.0\".format(version) # ~=X.0 else: # Allow exact",
"elif version.startswith(\"^\"): # Allow minor updates version = version.replace(\"^\", \"~=\") return version #",
"== ValidDependencyVersionRegex.MAJOR_MINOR: if version.startswith(\"~\"): # Allow patch updates version = version.replace(\"~\", \"\") major,",
"\"\\n - .tar.gz Packages\" .format(dep=dependency_name) ) def generate_pip_ready_dependency(dependency_name: str, version: str) -> PipReadyDependency:",
"_is_dependency_name_in_wheel(dependency_name=dependency_name, wheel=wheel, version=wheel_version): raise InvalidDependencyVersionFormat( \"The dependency '{dep}' is not present in the",
"\"The dependency '{dep}' is not present in the wheel filename '{wheel}'\" .format(dep=dependency_name, wheel=version)",
"\"\") return \"~={}.0.0\".format(version) # ~=X.0.0 elif version.startswith(\"^\"): # Allow minor updates version =",
"return version # ~=X.X else: # Allow exact version return \"=={}\".format(version) # ==X.X",
"minor) # ~=X.X else: # Allow exact version return \"=={}\".format(version) # ==X.X.X elif",
"# Allow exact version return \"=={}\".format(version) # ==X.X elif dependency_regex == ValidDependencyVersionRegex.MAJOR: if",
"NewType(name=\"PipReadyDependency\", tp=str) def _is_dependency_name_in_wheel(dependency_name: str, wheel: str, version: str) -> bool: wheel =",
"Allow patch updates version = version.replace(\"~\", \"\") return \"~={}.0.0\".format(version) # ~=X.0.0 elif version.startswith(\"^\"):",
"str) -> PipReadyDependency: \"\"\" Raises: InvalidDependencyVersionFormat UnexpectedError \"\"\" dependency_regex: ValidDependencyVersionRegex = _get_dependency_version_format( dependency_name=dependency_name,",
"elif dependency_regex == ValidDependencyVersionRegex.TARGZ: return version raise UnexpectedError(\"The dependency given should have thrown",
"return wheel.endswith(dependency_name.replace(\"_\", \"-\").lower()) def _get_dependency_version_format(dependency_name: str, version: str) -> ValidDependencyVersionRegex: \"\"\" Raises: InvalidDependencyVersionFormat",
"tp=str) def _is_dependency_name_in_wheel(dependency_name: str, wheel: str, version: str) -> bool: wheel = wheel[:-1*len(\"-{}\".format(version))]\\",
"ValidDependencyVersionRegex.MAJOR_MINOR if ValidDependencyVersionRegex.MAJOR.value.match(version): return ValidDependencyVersionRegex.MAJOR if ValidDependencyVersionRegex.LATEST.value.match(version): return ValidDependencyVersionRegex.LATEST wheel_info = ValidDependencyVersionRegex.WHEEL.value.match(version) if",
"release format (see https://www.python.org/dev/peps/pep-0440/#final-releases)\" \"\\n - Wheel Binary Packages (see https://www.python.org/dev/peps/pep-0491/#file-format)\" \"\\n -",
"patch = version.split(\".\") return \"~={}.{}\".format(major, minor) # ~=X.X else: # Allow exact version",
"version: str) -> bool: wheel = wheel[:-1*len(\"-{}\".format(version))]\\ .replace(\"_\", \"-\")\\ .lower() return wheel.endswith(dependency_name.replace(\"_\", \"-\").lower())",
"not ValidDependencyVersionRegex.MAJOR_MINOR.value.match(wheel_version) and \\ not ValidDependencyVersionRegex.MAJOR.value.match(wheel_version): raise InvalidDependencyVersionFormat( \"\\nThe version format for the",
") if dependency_regex == ValidDependencyVersionRegex.MAJOR_MINOR_PATCH: # (^|~) X.X.X if version.startswith(\"~\"): # Allow patch",
"== ValidDependencyVersionRegex.MAJOR: if version.startswith(\"~\"): # Allow patch updates version = version.replace(\"~\", \"\") return",
"return ValidDependencyVersionRegex.TARGZ raise InvalidDependencyVersionFormat( \"\\nInvalid version format for the dependency '{dep}'. Only the",
"\" \"(see https://www.python.org/dev/peps/pep-0440/#final-releases)\" .format(dep=dependency_name) ) return ValidDependencyVersionRegex.WHEEL if ValidDependencyVersionRegex.TARGZ.value.match(version): return ValidDependencyVersionRegex.TARGZ raise InvalidDependencyVersionFormat(",
"version=version ) if dependency_regex == ValidDependencyVersionRegex.MAJOR_MINOR_PATCH: # (^|~) X.X.X if version.startswith(\"~\"): # Allow",
") return ValidDependencyVersionRegex.WHEEL if ValidDependencyVersionRegex.TARGZ.value.match(version): return ValidDependencyVersionRegex.TARGZ raise InvalidDependencyVersionFormat( \"\\nInvalid version format for",
"wheel=version) ) if not ValidDependencyVersionRegex.MAJOR_MINOR_PATCH.value.match(wheel_version) and \\ not ValidDependencyVersionRegex.MAJOR_MINOR.value.match(wheel_version) and \\ not ValidDependencyVersionRegex.MAJOR.value.match(wheel_version):",
"if dependency_regex == ValidDependencyVersionRegex.MAJOR_MINOR_PATCH: # (^|~) X.X.X if version.startswith(\"~\"): # Allow patch updates",
"patch updates version = version.replace(\"~\", \"\") return \"~={}.0.0\".format(version) # ~=X.0.0 elif version.startswith(\"^\"): #",
"\"~={}.{}\".format(major, minor) # ~=X.X else: # Allow exact version return \"=={}\".format(version) # ==X.X.X",
"== ValidDependencyVersionRegex.WHEEL: return version elif dependency_regex == ValidDependencyVersionRegex.TARGZ: return version raise UnexpectedError(\"The dependency",
"\"(see https://www.python.org/dev/peps/pep-0440/#final-releases)\" .format(dep=dependency_name) ) return ValidDependencyVersionRegex.WHEEL if ValidDependencyVersionRegex.TARGZ.value.match(version): return ValidDependencyVersionRegex.TARGZ raise InvalidDependencyVersionFormat( \"\\nInvalid",
"return \"~={}.0\".format(version) # ~=X.0 else: # Allow exact version return \"=={}\".format(version) # ==X",
"for the wheel dependency '{dep}' is invalid. Use a 'Final release' format \"",
"version return \"=={}\".format(version) # ==X elif dependency_regex == ValidDependencyVersionRegex.LATEST: return dependency_name.lower() elif dependency_regex",
"minor = version.split(\".\") return \"~={}.{}.0\".format(major, minor) # ~=X.X.0 elif version.startswith(\"^\"): # Allow minor",
"version # ~=X.X else: # Allow exact version return \"=={}\".format(version) # ==X.X elif",
"the wheel dependency '{dep}' is invalid. Use a 'Final release' format \" \"(see",
"~=X.X else: # Allow exact version return \"=={}\".format(version) # ==X.X.X elif dependency_regex ==",
"updates version = version.replace(\"~\", \"\") major, minor = version.split(\".\") return \"~={}.{}.0\".format(major, minor) #",
"for the dependency '{dep}'. Only the following formats are allowed:\" \"\\n - 'latest'",
"dependency '{dep}' is invalid. Use a 'Final release' format \" \"(see https://www.python.org/dev/peps/pep-0440/#final-releases)\" .format(dep=dependency_name)",
"_get_dependency_version_format( dependency_name=dependency_name, version=version ) if dependency_regex == ValidDependencyVersionRegex.MAJOR_MINOR_PATCH: # (^|~) X.X.X if version.startswith(\"~\"):",
"ValidDependencyVersionRegex.MAJOR.value.match(wheel_version): raise InvalidDependencyVersionFormat( \"\\nThe version format for the wheel dependency '{dep}' is invalid.",
"version return \"=={}\".format(version) # ==X.X.X elif dependency_regex == ValidDependencyVersionRegex.MAJOR_MINOR: if version.startswith(\"~\"): # Allow",
"ValidDependencyVersionRegex: \"\"\" Raises: InvalidDependencyVersionFormat \"\"\" if ValidDependencyVersionRegex.MAJOR_MINOR_PATCH.value.match(version): return ValidDependencyVersionRegex.MAJOR_MINOR_PATCH if ValidDependencyVersionRegex.MAJOR_MINOR.value.match(version): return ValidDependencyVersionRegex.MAJOR_MINOR",
"'{wheel}'\" .format(dep=dependency_name, wheel=version) ) if not ValidDependencyVersionRegex.MAJOR_MINOR_PATCH.value.match(wheel_version) and \\ not ValidDependencyVersionRegex.MAJOR_MINOR.value.match(wheel_version) and \\",
"dependency_name=dependency_name, version=version ) if dependency_regex == ValidDependencyVersionRegex.MAJOR_MINOR_PATCH: # (^|~) X.X.X if version.startswith(\"~\"): #",
"version.startswith(\"~\"): # Allow patch updates return version.replace(\"~\", \"~=\") # ~=X.X.X elif version.startswith(\"^\"): #",
"- Wheel Binary Packages (see https://www.python.org/dev/peps/pep-0491/#file-format)\" \"\\n - .tar.gz Packages\" .format(dep=dependency_name) ) def",
"\"~={}.0.0\".format(version) # ~=X.0.0 elif version.startswith(\"^\"): # Allow minor updates version = version.replace(\"^\", \"\")",
"version.replace(\"~\", \"\") major, minor = version.split(\".\") return \"~={}.{}.0\".format(major, minor) # ~=X.X.0 elif version.startswith(\"^\"):",
"dependency_name.lower() elif dependency_regex == ValidDependencyVersionRegex.WHEEL: return version elif dependency_regex == ValidDependencyVersionRegex.TARGZ: return version",
"Allow minor updates version = version.replace(\"^\", \"\") major, minor, patch = version.split(\".\") return",
"InvalidDependencyVersionFormat( \"The dependency '{dep}' is not present in the wheel filename '{wheel}'\" .format(dep=dependency_name,",
"ValidDependencyVersionRegex.MAJOR_MINOR.value.match(wheel_version) and \\ not ValidDependencyVersionRegex.MAJOR.value.match(wheel_version): raise InvalidDependencyVersionFormat( \"\\nThe version format for the wheel",
"if version.startswith(\"~\"): # Allow patch updates version = version.replace(\"~\", \"\") major, minor =",
"~=X.X.0 elif version.startswith(\"^\"): # Allow minor updates version = version.replace(\"^\", \"~=\") return version",
"version.split(\".\") return \"~={}.{}\".format(major, minor) # ~=X.X else: # Allow exact version return \"=={}\".format(version)",
"# Allow minor updates version = version.replace(\"^\", \"~=\") return version # ~=X.X else:",
"minor updates version = version.replace(\"^\", \"~=\") return version # ~=X.X else: # Allow",
"dependency_regex == ValidDependencyVersionRegex.TARGZ: return version raise UnexpectedError(\"The dependency given should have thrown 'InvalidDependencyVersionFormat'",
"return ValidDependencyVersionRegex.MAJOR_MINOR if ValidDependencyVersionRegex.MAJOR.value.match(version): return ValidDependencyVersionRegex.MAJOR if ValidDependencyVersionRegex.LATEST.value.match(version): return ValidDependencyVersionRegex.LATEST wheel_info = ValidDependencyVersionRegex.WHEEL.value.match(version)",
"\"=={}\".format(version) # ==X.X.X elif dependency_regex == ValidDependencyVersionRegex.MAJOR_MINOR: if version.startswith(\"~\"): # Allow patch updates",
"return \"~={}.0.0\".format(version) # ~=X.0.0 elif version.startswith(\"^\"): # Allow minor updates version = version.replace(\"^\",",
"format for the dependency '{dep}'. Only the following formats are allowed:\" \"\\n -",
"\"~=\") # ~=X.X.X elif version.startswith(\"^\"): # Allow minor updates version = version.replace(\"^\", \"\")",
"(see https://www.python.org/dev/peps/pep-0491/#file-format)\" \"\\n - .tar.gz Packages\" .format(dep=dependency_name) ) def generate_pip_ready_dependency(dependency_name: str, version: str)",
"InvalidDependencyVersionFormat UnexpectedError \"\"\" dependency_regex: ValidDependencyVersionRegex = _get_dependency_version_format( dependency_name=dependency_name, version=version ) if dependency_regex ==",
"from caos._internal.constants import ValidDependencyVersionRegex from caos._internal.exceptions import InvalidDependencyVersionFormat, UnexpectedError from typing import NewType",
"\"~=\") return version # ~=X.X else: # Allow exact version return \"=={}\".format(version) #",
"\"\"\" if ValidDependencyVersionRegex.MAJOR_MINOR_PATCH.value.match(version): return ValidDependencyVersionRegex.MAJOR_MINOR_PATCH if ValidDependencyVersionRegex.MAJOR_MINOR.value.match(version): return ValidDependencyVersionRegex.MAJOR_MINOR if ValidDependencyVersionRegex.MAJOR.value.match(version): return ValidDependencyVersionRegex.MAJOR",
"'{dep}'. Only the following formats are allowed:\" \"\\n - 'latest' or 'LATEST'\" \"\\n",
"'LATEST'\" \"\\n - Final release format (see https://www.python.org/dev/peps/pep-0440/#final-releases)\" \"\\n - Wheel Binary Packages",
"= version.split(\".\") return \"~={}.{}.0\".format(major, minor) # ~=X.X.0 elif version.startswith(\"^\"): # Allow minor updates",
"version.startswith(\"^\"): # Allow minor updates version = version.replace(\"^\", \"~=\") return version # ~=X.X",
"return version elif dependency_regex == ValidDependencyVersionRegex.TARGZ: return version raise UnexpectedError(\"The dependency given should",
"is not present in the wheel filename '{wheel}'\" .format(dep=dependency_name, wheel=version) ) if not",
"invalid. Use a 'Final release' format \" \"(see https://www.python.org/dev/peps/pep-0440/#final-releases)\" .format(dep=dependency_name) ) return ValidDependencyVersionRegex.WHEEL",
"\"\"\" Raises: InvalidDependencyVersionFormat UnexpectedError \"\"\" dependency_regex: ValidDependencyVersionRegex = _get_dependency_version_format( dependency_name=dependency_name, version=version ) if",
"the dependency '{dep}'. Only the following formats are allowed:\" \"\\n - 'latest' or",
"== ValidDependencyVersionRegex.TARGZ: return version raise UnexpectedError(\"The dependency given should have thrown 'InvalidDependencyVersionFormat' but",
"present in the wheel filename '{wheel}'\" .format(dep=dependency_name, wheel=version) ) if not ValidDependencyVersionRegex.MAJOR_MINOR_PATCH.value.match(wheel_version) and",
"- 'latest' or 'LATEST'\" \"\\n - Final release format (see https://www.python.org/dev/peps/pep-0440/#final-releases)\" \"\\n -",
"version.startswith(\"^\"): # Allow minor updates version = version.replace(\"^\", \"\") return \"~={}.0\".format(version) # ~=X.0",
"- .tar.gz Packages\" .format(dep=dependency_name) ) def generate_pip_ready_dependency(dependency_name: str, version: str) -> PipReadyDependency: \"\"\"",
"Packages\" .format(dep=dependency_name) ) def generate_pip_ready_dependency(dependency_name: str, version: str) -> PipReadyDependency: \"\"\" Raises: InvalidDependencyVersionFormat",
"return ValidDependencyVersionRegex.LATEST wheel_info = ValidDependencyVersionRegex.WHEEL.value.match(version) if wheel_info: wheel = wheel_info.group(\"wheel\") wheel_version = wheel_info.group(\"version\")",
"ValidDependencyVersionRegex = _get_dependency_version_format( dependency_name=dependency_name, version=version ) if dependency_regex == ValidDependencyVersionRegex.MAJOR_MINOR_PATCH: # (^|~) X.X.X",
"- Final release format (see https://www.python.org/dev/peps/pep-0440/#final-releases)\" \"\\n - Wheel Binary Packages (see https://www.python.org/dev/peps/pep-0491/#file-format)\"",
"== ValidDependencyVersionRegex.LATEST: return dependency_name.lower() elif dependency_regex == ValidDependencyVersionRegex.WHEEL: return version elif dependency_regex ==",
"# Allow exact version return \"=={}\".format(version) # ==X.X.X elif dependency_regex == ValidDependencyVersionRegex.MAJOR_MINOR: if",
"ValidDependencyVersionRegex.MAJOR_MINOR.value.match(version): return ValidDependencyVersionRegex.MAJOR_MINOR if ValidDependencyVersionRegex.MAJOR.value.match(version): return ValidDependencyVersionRegex.MAJOR if ValidDependencyVersionRegex.LATEST.value.match(version): return ValidDependencyVersionRegex.LATEST wheel_info =",
"ValidDependencyVersionRegex.MAJOR_MINOR: if version.startswith(\"~\"): # Allow patch updates version = version.replace(\"~\", \"\") major, minor",
"caos._internal.exceptions import InvalidDependencyVersionFormat, UnexpectedError from typing import NewType PipReadyDependency = NewType(name=\"PipReadyDependency\", tp=str) def",
"'{dep}' is not present in the wheel filename '{wheel}'\" .format(dep=dependency_name, wheel=version) ) if",
"ValidDependencyVersionRegex.LATEST.value.match(version): return ValidDependencyVersionRegex.LATEST wheel_info = ValidDependencyVersionRegex.WHEEL.value.match(version) if wheel_info: wheel = wheel_info.group(\"wheel\") wheel_version =",
"elif dependency_regex == ValidDependencyVersionRegex.MAJOR_MINOR: if version.startswith(\"~\"): # Allow patch updates version = version.replace(\"~\",",
"if version.startswith(\"~\"): # Allow patch updates return version.replace(\"~\", \"~=\") # ~=X.X.X elif version.startswith(\"^\"):",
"str, version: str) -> ValidDependencyVersionRegex: \"\"\" Raises: InvalidDependencyVersionFormat \"\"\" if ValidDependencyVersionRegex.MAJOR_MINOR_PATCH.value.match(version): return ValidDependencyVersionRegex.MAJOR_MINOR_PATCH",
"# Allow patch updates return version.replace(\"~\", \"~=\") # ~=X.X.X elif version.startswith(\"^\"): # Allow",
"from caos._internal.exceptions import InvalidDependencyVersionFormat, UnexpectedError from typing import NewType PipReadyDependency = NewType(name=\"PipReadyDependency\", tp=str)",
"version elif dependency_regex == ValidDependencyVersionRegex.TARGZ: return version raise UnexpectedError(\"The dependency given should have",
"'latest' or 'LATEST'\" \"\\n - Final release format (see https://www.python.org/dev/peps/pep-0440/#final-releases)\" \"\\n - Wheel",
"\"~={}.{}.0\".format(major, minor) # ~=X.X.0 elif version.startswith(\"^\"): # Allow minor updates version = version.replace(\"^\",",
".format(dep=dependency_name) ) return ValidDependencyVersionRegex.WHEEL if ValidDependencyVersionRegex.TARGZ.value.match(version): return ValidDependencyVersionRegex.TARGZ raise InvalidDependencyVersionFormat( \"\\nInvalid version format",
"if version.startswith(\"~\"): # Allow patch updates version = version.replace(\"~\", \"\") return \"~={}.0.0\".format(version) #",
"wheel_info: wheel = wheel_info.group(\"wheel\") wheel_version = wheel_info.group(\"version\") if not _is_dependency_name_in_wheel(dependency_name=dependency_name, wheel=wheel, version=wheel_version): raise",
"# Allow patch updates version = version.replace(\"~\", \"\") major, minor = version.split(\".\") return",
"UnexpectedError from typing import NewType PipReadyDependency = NewType(name=\"PipReadyDependency\", tp=str) def _is_dependency_name_in_wheel(dependency_name: str, wheel:",
"if ValidDependencyVersionRegex.MAJOR_MINOR.value.match(version): return ValidDependencyVersionRegex.MAJOR_MINOR if ValidDependencyVersionRegex.MAJOR.value.match(version): return ValidDependencyVersionRegex.MAJOR if ValidDependencyVersionRegex.LATEST.value.match(version): return ValidDependencyVersionRegex.LATEST wheel_info",
"Wheel Binary Packages (see https://www.python.org/dev/peps/pep-0491/#file-format)\" \"\\n - .tar.gz Packages\" .format(dep=dependency_name) ) def generate_pip_ready_dependency(dependency_name:",
"str) -> ValidDependencyVersionRegex: \"\"\" Raises: InvalidDependencyVersionFormat \"\"\" if ValidDependencyVersionRegex.MAJOR_MINOR_PATCH.value.match(version): return ValidDependencyVersionRegex.MAJOR_MINOR_PATCH if ValidDependencyVersionRegex.MAJOR_MINOR.value.match(version):",
"~=X.X.X elif version.startswith(\"^\"): # Allow minor updates version = version.replace(\"^\", \"\") major, minor,",
"str, version: str) -> PipReadyDependency: \"\"\" Raises: InvalidDependencyVersionFormat UnexpectedError \"\"\" dependency_regex: ValidDependencyVersionRegex =",
"return ValidDependencyVersionRegex.MAJOR_MINOR_PATCH if ValidDependencyVersionRegex.MAJOR_MINOR.value.match(version): return ValidDependencyVersionRegex.MAJOR_MINOR if ValidDependencyVersionRegex.MAJOR.value.match(version): return ValidDependencyVersionRegex.MAJOR if ValidDependencyVersionRegex.LATEST.value.match(version): return",
"PipReadyDependency: \"\"\" Raises: InvalidDependencyVersionFormat UnexpectedError \"\"\" dependency_regex: ValidDependencyVersionRegex = _get_dependency_version_format( dependency_name=dependency_name, version=version )",
"version = version.replace(\"~\", \"\") return \"~={}.0.0\".format(version) # ~=X.0.0 elif version.startswith(\"^\"): # Allow minor",
"ValidDependencyVersionRegex.WHEEL.value.match(version) if wheel_info: wheel = wheel_info.group(\"wheel\") wheel_version = wheel_info.group(\"version\") if not _is_dependency_name_in_wheel(dependency_name=dependency_name, wheel=wheel,",
"dependency '{dep}'. Only the following formats are allowed:\" \"\\n - 'latest' or 'LATEST'\"",
"UnexpectedError \"\"\" dependency_regex: ValidDependencyVersionRegex = _get_dependency_version_format( dependency_name=dependency_name, version=version ) if dependency_regex == ValidDependencyVersionRegex.MAJOR_MINOR_PATCH:",
"\\ not ValidDependencyVersionRegex.MAJOR.value.match(wheel_version): raise InvalidDependencyVersionFormat( \"\\nThe version format for the wheel dependency '{dep}'",
"str, wheel: str, version: str) -> bool: wheel = wheel[:-1*len(\"-{}\".format(version))]\\ .replace(\"_\", \"-\")\\ .lower()",
"version.replace(\"~\", \"~=\") # ~=X.X.X elif version.startswith(\"^\"): # Allow minor updates version = version.replace(\"^\",",
"and \\ not ValidDependencyVersionRegex.MAJOR.value.match(wheel_version): raise InvalidDependencyVersionFormat( \"\\nThe version format for the wheel dependency",
"X.X.X if version.startswith(\"~\"): # Allow patch updates return version.replace(\"~\", \"~=\") # ~=X.X.X elif",
"= version.replace(\"~\", \"\") return \"~={}.0.0\".format(version) # ~=X.0.0 elif version.startswith(\"^\"): # Allow minor updates",
"\"=={}\".format(version) # ==X.X elif dependency_regex == ValidDependencyVersionRegex.MAJOR: if version.startswith(\"~\"): # Allow patch updates",
"str, version: str) -> bool: wheel = wheel[:-1*len(\"-{}\".format(version))]\\ .replace(\"_\", \"-\")\\ .lower() return wheel.endswith(dependency_name.replace(\"_\",",
"Allow exact version return \"=={}\".format(version) # ==X elif dependency_regex == ValidDependencyVersionRegex.LATEST: return dependency_name.lower()",
"\"\") major, minor, patch = version.split(\".\") return \"~={}.{}\".format(major, minor) # ~=X.X else: #",
"or 'LATEST'\" \"\\n - Final release format (see https://www.python.org/dev/peps/pep-0440/#final-releases)\" \"\\n - Wheel Binary",
"== ValidDependencyVersionRegex.MAJOR_MINOR_PATCH: # (^|~) X.X.X if version.startswith(\"~\"): # Allow patch updates return version.replace(\"~\",",
"ValidDependencyVersionRegex.WHEEL: return version elif dependency_regex == ValidDependencyVersionRegex.TARGZ: return version raise UnexpectedError(\"The dependency given",
"InvalidDependencyVersionFormat, UnexpectedError from typing import NewType PipReadyDependency = NewType(name=\"PipReadyDependency\", tp=str) def _is_dependency_name_in_wheel(dependency_name: str,",
"= wheel_info.group(\"version\") if not _is_dependency_name_in_wheel(dependency_name=dependency_name, wheel=wheel, version=wheel_version): raise InvalidDependencyVersionFormat( \"The dependency '{dep}' is",
"'{dep}' is invalid. Use a 'Final release' format \" \"(see https://www.python.org/dev/peps/pep-0440/#final-releases)\" .format(dep=dependency_name) )",
"# Allow patch updates version = version.replace(\"~\", \"\") return \"~={}.0.0\".format(version) # ~=X.0.0 elif",
"\"-\").lower()) def _get_dependency_version_format(dependency_name: str, version: str) -> ValidDependencyVersionRegex: \"\"\" Raises: InvalidDependencyVersionFormat \"\"\" if",
"not ValidDependencyVersionRegex.MAJOR.value.match(wheel_version): raise InvalidDependencyVersionFormat( \"\\nThe version format for the wheel dependency '{dep}' is",
".replace(\"_\", \"-\")\\ .lower() return wheel.endswith(dependency_name.replace(\"_\", \"-\").lower()) def _get_dependency_version_format(dependency_name: str, version: str) -> ValidDependencyVersionRegex:",
"-> bool: wheel = wheel[:-1*len(\"-{}\".format(version))]\\ .replace(\"_\", \"-\")\\ .lower() return wheel.endswith(dependency_name.replace(\"_\", \"-\").lower()) def _get_dependency_version_format(dependency_name:",
"patch updates version = version.replace(\"~\", \"\") major, minor = version.split(\".\") return \"~={}.{}.0\".format(major, minor)",
"if ValidDependencyVersionRegex.TARGZ.value.match(version): return ValidDependencyVersionRegex.TARGZ raise InvalidDependencyVersionFormat( \"\\nInvalid version format for the dependency '{dep}'.",
"else: # Allow exact version return \"=={}\".format(version) # ==X elif dependency_regex == ValidDependencyVersionRegex.LATEST:",
"Allow exact version return \"=={}\".format(version) # ==X.X elif dependency_regex == ValidDependencyVersionRegex.MAJOR: if version.startswith(\"~\"):",
"\"\\nThe version format for the wheel dependency '{dep}' is invalid. Use a 'Final",
"updates version = version.replace(\"^\", \"~=\") return version # ~=X.X else: # Allow exact",
"the wheel filename '{wheel}'\" .format(dep=dependency_name, wheel=version) ) if not ValidDependencyVersionRegex.MAJOR_MINOR_PATCH.value.match(wheel_version) and \\ not",
"\"~={}.0\".format(version) # ~=X.0 else: # Allow exact version return \"=={}\".format(version) # ==X elif",
"dependency_regex == ValidDependencyVersionRegex.LATEST: return dependency_name.lower() elif dependency_regex == ValidDependencyVersionRegex.WHEEL: return version elif dependency_regex",
"return ValidDependencyVersionRegex.MAJOR if ValidDependencyVersionRegex.LATEST.value.match(version): return ValidDependencyVersionRegex.LATEST wheel_info = ValidDependencyVersionRegex.WHEEL.value.match(version) if wheel_info: wheel =",
"wheel.endswith(dependency_name.replace(\"_\", \"-\").lower()) def _get_dependency_version_format(dependency_name: str, version: str) -> ValidDependencyVersionRegex: \"\"\" Raises: InvalidDependencyVersionFormat \"\"\"",
"~=X.0.0 elif version.startswith(\"^\"): # Allow minor updates version = version.replace(\"^\", \"\") return \"~={}.0\".format(version)",
") if not ValidDependencyVersionRegex.MAJOR_MINOR_PATCH.value.match(wheel_version) and \\ not ValidDependencyVersionRegex.MAJOR_MINOR.value.match(wheel_version) and \\ not ValidDependencyVersionRegex.MAJOR.value.match(wheel_version): raise",
"ValidDependencyVersionRegex.LATEST wheel_info = ValidDependencyVersionRegex.WHEEL.value.match(version) if wheel_info: wheel = wheel_info.group(\"wheel\") wheel_version = wheel_info.group(\"version\") if",
"not present in the wheel filename '{wheel}'\" .format(dep=dependency_name, wheel=version) ) if not ValidDependencyVersionRegex.MAJOR_MINOR_PATCH.value.match(wheel_version)",
"version format for the dependency '{dep}'. Only the following formats are allowed:\" \"\\n",
"Raises: InvalidDependencyVersionFormat UnexpectedError \"\"\" dependency_regex: ValidDependencyVersionRegex = _get_dependency_version_format( dependency_name=dependency_name, version=version ) if dependency_regex",
"import NewType PipReadyDependency = NewType(name=\"PipReadyDependency\", tp=str) def _is_dependency_name_in_wheel(dependency_name: str, wheel: str, version: str)",
"~=X.X else: # Allow exact version return \"=={}\".format(version) # ==X.X elif dependency_regex ==",
"version.replace(\"^\", \"\") major, minor, patch = version.split(\".\") return \"~={}.{}\".format(major, minor) # ~=X.X else:",
"dependency_regex == ValidDependencyVersionRegex.MAJOR: if version.startswith(\"~\"): # Allow patch updates version = version.replace(\"~\", \"\")",
"# ~=X.X else: # Allow exact version return \"=={}\".format(version) # ==X.X.X elif dependency_regex",
"wheel dependency '{dep}' is invalid. Use a 'Final release' format \" \"(see https://www.python.org/dev/peps/pep-0440/#final-releases)\"",
"version return \"=={}\".format(version) # ==X.X elif dependency_regex == ValidDependencyVersionRegex.MAJOR: if version.startswith(\"~\"): # Allow",
"return dependency_name.lower() elif dependency_regex == ValidDependencyVersionRegex.WHEEL: return version elif dependency_regex == ValidDependencyVersionRegex.TARGZ: return",
"format (see https://www.python.org/dev/peps/pep-0440/#final-releases)\" \"\\n - Wheel Binary Packages (see https://www.python.org/dev/peps/pep-0491/#file-format)\" \"\\n - .tar.gz",
"-> PipReadyDependency: \"\"\" Raises: InvalidDependencyVersionFormat UnexpectedError \"\"\" dependency_regex: ValidDependencyVersionRegex = _get_dependency_version_format( dependency_name=dependency_name, version=version",
"minor) # ~=X.X.0 elif version.startswith(\"^\"): # Allow minor updates version = version.replace(\"^\", \"~=\")",
"ValidDependencyVersionRegex.MAJOR_MINOR_PATCH.value.match(wheel_version) and \\ not ValidDependencyVersionRegex.MAJOR_MINOR.value.match(wheel_version) and \\ not ValidDependencyVersionRegex.MAJOR.value.match(wheel_version): raise InvalidDependencyVersionFormat( \"\\nThe version",
"the following formats are allowed:\" \"\\n - 'latest' or 'LATEST'\" \"\\n - Final",
"wheel = wheel_info.group(\"wheel\") wheel_version = wheel_info.group(\"version\") if not _is_dependency_name_in_wheel(dependency_name=dependency_name, wheel=wheel, version=wheel_version): raise InvalidDependencyVersionFormat(",
"raise InvalidDependencyVersionFormat( \"\\nInvalid version format for the dependency '{dep}'. Only the following formats",
"version: str) -> ValidDependencyVersionRegex: \"\"\" Raises: InvalidDependencyVersionFormat \"\"\" if ValidDependencyVersionRegex.MAJOR_MINOR_PATCH.value.match(version): return ValidDependencyVersionRegex.MAJOR_MINOR_PATCH if",
"str) -> bool: wheel = wheel[:-1*len(\"-{}\".format(version))]\\ .replace(\"_\", \"-\")\\ .lower() return wheel.endswith(dependency_name.replace(\"_\", \"-\").lower()) def",
"wheel[:-1*len(\"-{}\".format(version))]\\ .replace(\"_\", \"-\")\\ .lower() return wheel.endswith(dependency_name.replace(\"_\", \"-\").lower()) def _get_dependency_version_format(dependency_name: str, version: str) ->",
"version = version.replace(\"^\", \"\") return \"~={}.0\".format(version) # ~=X.0 else: # Allow exact version",
"= version.replace(\"^\", \"~=\") return version # ~=X.X else: # Allow exact version return",
"wheel_info = ValidDependencyVersionRegex.WHEEL.value.match(version) if wheel_info: wheel = wheel_info.group(\"wheel\") wheel_version = wheel_info.group(\"version\") if not",
"# ~=X.X.X elif version.startswith(\"^\"): # Allow minor updates version = version.replace(\"^\", \"\") major,",
"PipReadyDependency = NewType(name=\"PipReadyDependency\", tp=str) def _is_dependency_name_in_wheel(dependency_name: str, wheel: str, version: str) -> bool:",
"\"\"\" dependency_regex: ValidDependencyVersionRegex = _get_dependency_version_format( dependency_name=dependency_name, version=version ) if dependency_regex == ValidDependencyVersionRegex.MAJOR_MINOR_PATCH: #",
"InvalidDependencyVersionFormat( \"\\nThe version format for the wheel dependency '{dep}' is invalid. Use a",
"# Allow exact version return \"=={}\".format(version) # ==X elif dependency_regex == ValidDependencyVersionRegex.LATEST: return",
"are allowed:\" \"\\n - 'latest' or 'LATEST'\" \"\\n - Final release format (see",
"# Allow minor updates version = version.replace(\"^\", \"\") return \"~={}.0\".format(version) # ~=X.0 else:",
"if ValidDependencyVersionRegex.MAJOR_MINOR_PATCH.value.match(version): return ValidDependencyVersionRegex.MAJOR_MINOR_PATCH if ValidDependencyVersionRegex.MAJOR_MINOR.value.match(version): return ValidDependencyVersionRegex.MAJOR_MINOR if ValidDependencyVersionRegex.MAJOR.value.match(version): return ValidDependencyVersionRegex.MAJOR if",
"wheel_info.group(\"wheel\") wheel_version = wheel_info.group(\"version\") if not _is_dependency_name_in_wheel(dependency_name=dependency_name, wheel=wheel, version=wheel_version): raise InvalidDependencyVersionFormat( \"The dependency",
"\"\\nInvalid version format for the dependency '{dep}'. Only the following formats are allowed:\"",
"_get_dependency_version_format(dependency_name: str, version: str) -> ValidDependencyVersionRegex: \"\"\" Raises: InvalidDependencyVersionFormat \"\"\" if ValidDependencyVersionRegex.MAJOR_MINOR_PATCH.value.match(version): return",
"allowed:\" \"\\n - 'latest' or 'LATEST'\" \"\\n - Final release format (see https://www.python.org/dev/peps/pep-0440/#final-releases)\"",
"# ~=X.X else: # Allow exact version return \"=={}\".format(version) # ==X.X elif dependency_regex",
"wheel=wheel, version=wheel_version): raise InvalidDependencyVersionFormat( \"The dependency '{dep}' is not present in the wheel",
"minor updates version = version.replace(\"^\", \"\") return \"~={}.0\".format(version) # ~=X.0 else: # Allow",
"Binary Packages (see https://www.python.org/dev/peps/pep-0491/#file-format)\" \"\\n - .tar.gz Packages\" .format(dep=dependency_name) ) def generate_pip_ready_dependency(dependency_name: str,",
"major, minor, patch = version.split(\".\") return \"~={}.{}\".format(major, minor) # ~=X.X else: # Allow",
"def _is_dependency_name_in_wheel(dependency_name: str, wheel: str, version: str) -> bool: wheel = wheel[:-1*len(\"-{}\".format(version))]\\ .replace(\"_\",",
"if not _is_dependency_name_in_wheel(dependency_name=dependency_name, wheel=wheel, version=wheel_version): raise InvalidDependencyVersionFormat( \"The dependency '{dep}' is not present",
"= NewType(name=\"PipReadyDependency\", tp=str) def _is_dependency_name_in_wheel(dependency_name: str, wheel: str, version: str) -> bool: wheel",
"= wheel_info.group(\"wheel\") wheel_version = wheel_info.group(\"version\") if not _is_dependency_name_in_wheel(dependency_name=dependency_name, wheel=wheel, version=wheel_version): raise InvalidDependencyVersionFormat( \"The",
"version.replace(\"^\", \"\") return \"~={}.0\".format(version) # ~=X.0 else: # Allow exact version return \"=={}\".format(version)",
"ValidDependencyVersionRegex.MAJOR_MINOR_PATCH: # (^|~) X.X.X if version.startswith(\"~\"): # Allow patch updates return version.replace(\"~\", \"~=\")",
"Allow minor updates version = version.replace(\"^\", \"\") return \"~={}.0\".format(version) # ~=X.0 else: #",
"(see https://www.python.org/dev/peps/pep-0440/#final-releases)\" \"\\n - Wheel Binary Packages (see https://www.python.org/dev/peps/pep-0491/#file-format)\" \"\\n - .tar.gz Packages\"",
"Packages (see https://www.python.org/dev/peps/pep-0491/#file-format)\" \"\\n - .tar.gz Packages\" .format(dep=dependency_name) ) def generate_pip_ready_dependency(dependency_name: str, version:",
"filename '{wheel}'\" .format(dep=dependency_name, wheel=version) ) if not ValidDependencyVersionRegex.MAJOR_MINOR_PATCH.value.match(wheel_version) and \\ not ValidDependencyVersionRegex.MAJOR_MINOR.value.match(wheel_version) and",
"is invalid. Use a 'Final release' format \" \"(see https://www.python.org/dev/peps/pep-0440/#final-releases)\" .format(dep=dependency_name) ) return",
"version.replace(\"^\", \"~=\") return version # ~=X.X else: # Allow exact version return \"=={}\".format(version)",
"Allow exact version return \"=={}\".format(version) # ==X.X.X elif dependency_regex == ValidDependencyVersionRegex.MAJOR_MINOR: if version.startswith(\"~\"):",
"in the wheel filename '{wheel}'\" .format(dep=dependency_name, wheel=version) ) if not ValidDependencyVersionRegex.MAJOR_MINOR_PATCH.value.match(wheel_version) and \\",
"~=X.0 else: # Allow exact version return \"=={}\".format(version) # ==X elif dependency_regex ==",
"elif dependency_regex == ValidDependencyVersionRegex.LATEST: return dependency_name.lower() elif dependency_regex == ValidDependencyVersionRegex.WHEEL: return version elif",
"= version.replace(\"~\", \"\") major, minor = version.split(\".\") return \"~={}.{}.0\".format(major, minor) # ~=X.X.0 elif",
"ValidDependencyVersionRegex.MAJOR_MINOR_PATCH.value.match(version): return ValidDependencyVersionRegex.MAJOR_MINOR_PATCH if ValidDependencyVersionRegex.MAJOR_MINOR.value.match(version): return ValidDependencyVersionRegex.MAJOR_MINOR if ValidDependencyVersionRegex.MAJOR.value.match(version): return ValidDependencyVersionRegex.MAJOR if ValidDependencyVersionRegex.LATEST.value.match(version):",
"def _get_dependency_version_format(dependency_name: str, version: str) -> ValidDependencyVersionRegex: \"\"\" Raises: InvalidDependencyVersionFormat \"\"\" if ValidDependencyVersionRegex.MAJOR_MINOR_PATCH.value.match(version):",
".format(dep=dependency_name) ) def generate_pip_ready_dependency(dependency_name: str, version: str) -> PipReadyDependency: \"\"\" Raises: InvalidDependencyVersionFormat UnexpectedError",
".lower() return wheel.endswith(dependency_name.replace(\"_\", \"-\").lower()) def _get_dependency_version_format(dependency_name: str, version: str) -> ValidDependencyVersionRegex: \"\"\" Raises:",
"wheel_info.group(\"version\") if not _is_dependency_name_in_wheel(dependency_name=dependency_name, wheel=wheel, version=wheel_version): raise InvalidDependencyVersionFormat( \"The dependency '{dep}' is not",
"\"\\n - 'latest' or 'LATEST'\" \"\\n - Final release format (see https://www.python.org/dev/peps/pep-0440/#final-releases)\" \"\\n",
"ValidDependencyVersionRegex.MAJOR: if version.startswith(\"~\"): # Allow patch updates version = version.replace(\"~\", \"\") return \"~={}.0.0\".format(version)",
"updates version = version.replace(\"~\", \"\") return \"~={}.0.0\".format(version) # ~=X.0.0 elif version.startswith(\"^\"): # Allow",
"exact version return \"=={}\".format(version) # ==X elif dependency_regex == ValidDependencyVersionRegex.LATEST: return dependency_name.lower() elif",
"version=wheel_version): raise InvalidDependencyVersionFormat( \"The dependency '{dep}' is not present in the wheel filename",
"return version.replace(\"~\", \"~=\") # ~=X.X.X elif version.startswith(\"^\"): # Allow minor updates version =",
"if ValidDependencyVersionRegex.LATEST.value.match(version): return ValidDependencyVersionRegex.LATEST wheel_info = ValidDependencyVersionRegex.WHEEL.value.match(version) if wheel_info: wheel = wheel_info.group(\"wheel\") wheel_version",
".format(dep=dependency_name, wheel=version) ) if not ValidDependencyVersionRegex.MAJOR_MINOR_PATCH.value.match(wheel_version) and \\ not ValidDependencyVersionRegex.MAJOR_MINOR.value.match(wheel_version) and \\ not",
"Only the following formats are allowed:\" \"\\n - 'latest' or 'LATEST'\" \"\\n -",
"\"\") return \"~={}.0\".format(version) # ~=X.0 else: # Allow exact version return \"=={}\".format(version) #",
"format \" \"(see https://www.python.org/dev/peps/pep-0440/#final-releases)\" .format(dep=dependency_name) ) return ValidDependencyVersionRegex.WHEEL if ValidDependencyVersionRegex.TARGZ.value.match(version): return ValidDependencyVersionRegex.TARGZ raise",
"if not ValidDependencyVersionRegex.MAJOR_MINOR_PATCH.value.match(wheel_version) and \\ not ValidDependencyVersionRegex.MAJOR_MINOR.value.match(wheel_version) and \\ not ValidDependencyVersionRegex.MAJOR.value.match(wheel_version): raise InvalidDependencyVersionFormat(",
"# ~=X.X.0 elif version.startswith(\"^\"): # Allow minor updates version = version.replace(\"^\", \"~=\") return",
"= version.replace(\"^\", \"\") return \"~={}.0\".format(version) # ~=X.0 else: # Allow exact version return",
"InvalidDependencyVersionFormat \"\"\" if ValidDependencyVersionRegex.MAJOR_MINOR_PATCH.value.match(version): return ValidDependencyVersionRegex.MAJOR_MINOR_PATCH if ValidDependencyVersionRegex.MAJOR_MINOR.value.match(version): return ValidDependencyVersionRegex.MAJOR_MINOR if ValidDependencyVersionRegex.MAJOR.value.match(version): return",
"= wheel[:-1*len(\"-{}\".format(version))]\\ .replace(\"_\", \"-\")\\ .lower() return wheel.endswith(dependency_name.replace(\"_\", \"-\").lower()) def _get_dependency_version_format(dependency_name: str, version: str)",
"wheel filename '{wheel}'\" .format(dep=dependency_name, wheel=version) ) if not ValidDependencyVersionRegex.MAJOR_MINOR_PATCH.value.match(wheel_version) and \\ not ValidDependencyVersionRegex.MAJOR_MINOR.value.match(wheel_version)",
"NewType PipReadyDependency = NewType(name=\"PipReadyDependency\", tp=str) def _is_dependency_name_in_wheel(dependency_name: str, wheel: str, version: str) ->",
"version.startswith(\"^\"): # Allow minor updates version = version.replace(\"^\", \"\") major, minor, patch =",
"==X.X.X elif dependency_regex == ValidDependencyVersionRegex.MAJOR_MINOR: if version.startswith(\"~\"): # Allow patch updates version =",
"formats are allowed:\" \"\\n - 'latest' or 'LATEST'\" \"\\n - Final release format",
"# ~=X.0 else: # Allow exact version return \"=={}\".format(version) # ==X elif dependency_regex",
"return \"=={}\".format(version) # ==X.X.X elif dependency_regex == ValidDependencyVersionRegex.MAJOR_MINOR: if version.startswith(\"~\"): # Allow patch",
"# ==X elif dependency_regex == ValidDependencyVersionRegex.LATEST: return dependency_name.lower() elif dependency_regex == ValidDependencyVersionRegex.WHEEL: return",
"if ValidDependencyVersionRegex.MAJOR.value.match(version): return ValidDependencyVersionRegex.MAJOR if ValidDependencyVersionRegex.LATEST.value.match(version): return ValidDependencyVersionRegex.LATEST wheel_info = ValidDependencyVersionRegex.WHEEL.value.match(version) if wheel_info:",
"else: # Allow exact version return \"=={}\".format(version) # ==X.X.X elif dependency_regex == ValidDependencyVersionRegex.MAJOR_MINOR:",
"release' format \" \"(see https://www.python.org/dev/peps/pep-0440/#final-releases)\" .format(dep=dependency_name) ) return ValidDependencyVersionRegex.WHEEL if ValidDependencyVersionRegex.TARGZ.value.match(version): return ValidDependencyVersionRegex.TARGZ",
"elif dependency_regex == ValidDependencyVersionRegex.MAJOR: if version.startswith(\"~\"): # Allow patch updates version = version.replace(\"~\",",
"InvalidDependencyVersionFormat( \"\\nInvalid version format for the dependency '{dep}'. Only the following formats are",
"and \\ not ValidDependencyVersionRegex.MAJOR_MINOR.value.match(wheel_version) and \\ not ValidDependencyVersionRegex.MAJOR.value.match(wheel_version): raise InvalidDependencyVersionFormat( \"\\nThe version format",
"'Final release' format \" \"(see https://www.python.org/dev/peps/pep-0440/#final-releases)\" .format(dep=dependency_name) ) return ValidDependencyVersionRegex.WHEEL if ValidDependencyVersionRegex.TARGZ.value.match(version): return",
"_is_dependency_name_in_wheel(dependency_name: str, wheel: str, version: str) -> bool: wheel = wheel[:-1*len(\"-{}\".format(version))]\\ .replace(\"_\", \"-\")\\",
"==X elif dependency_regex == ValidDependencyVersionRegex.LATEST: return dependency_name.lower() elif dependency_regex == ValidDependencyVersionRegex.WHEEL: return version",
"version.startswith(\"~\"): # Allow patch updates version = version.replace(\"~\", \"\") return \"~={}.0.0\".format(version) # ~=X.0.0",
"generate_pip_ready_dependency(dependency_name: str, version: str) -> PipReadyDependency: \"\"\" Raises: InvalidDependencyVersionFormat UnexpectedError \"\"\" dependency_regex: ValidDependencyVersionRegex",
"version = version.replace(\"^\", \"\") major, minor, patch = version.split(\".\") return \"~={}.{}\".format(major, minor) #",
") def generate_pip_ready_dependency(dependency_name: str, version: str) -> PipReadyDependency: \"\"\" Raises: InvalidDependencyVersionFormat UnexpectedError \"\"\"",
"https://www.python.org/dev/peps/pep-0440/#final-releases)\" .format(dep=dependency_name) ) return ValidDependencyVersionRegex.WHEEL if ValidDependencyVersionRegex.TARGZ.value.match(version): return ValidDependencyVersionRegex.TARGZ raise InvalidDependencyVersionFormat( \"\\nInvalid version",
"= ValidDependencyVersionRegex.WHEEL.value.match(version) if wheel_info: wheel = wheel_info.group(\"wheel\") wheel_version = wheel_info.group(\"version\") if not _is_dependency_name_in_wheel(dependency_name=dependency_name,",
"exact version return \"=={}\".format(version) # ==X.X.X elif dependency_regex == ValidDependencyVersionRegex.MAJOR_MINOR: if version.startswith(\"~\"): #",
"\\ not ValidDependencyVersionRegex.MAJOR_MINOR.value.match(wheel_version) and \\ not ValidDependencyVersionRegex.MAJOR.value.match(wheel_version): raise InvalidDependencyVersionFormat( \"\\nThe version format for",
"exact version return \"=={}\".format(version) # ==X.X elif dependency_regex == ValidDependencyVersionRegex.MAJOR: if version.startswith(\"~\"): #",
"following formats are allowed:\" \"\\n - 'latest' or 'LATEST'\" \"\\n - Final release",
"minor updates version = version.replace(\"^\", \"\") major, minor, patch = version.split(\".\") return \"~={}.{}\".format(major,",
"return \"=={}\".format(version) # ==X.X elif dependency_regex == ValidDependencyVersionRegex.MAJOR: if version.startswith(\"~\"): # Allow patch",
"return version raise UnexpectedError(\"The dependency given should have thrown 'InvalidDependencyVersionFormat' but it did",
"version raise UnexpectedError(\"The dependency given should have thrown 'InvalidDependencyVersionFormat' but it did not\")",
"version format for the wheel dependency '{dep}' is invalid. Use a 'Final release'",
"raise InvalidDependencyVersionFormat( \"The dependency '{dep}' is not present in the wheel filename '{wheel}'\"",
"# (^|~) X.X.X if version.startswith(\"~\"): # Allow patch updates return version.replace(\"~\", \"~=\") #",
"==X.X elif dependency_regex == ValidDependencyVersionRegex.MAJOR: if version.startswith(\"~\"): # Allow patch updates version =",
"\"\\n - Wheel Binary Packages (see https://www.python.org/dev/peps/pep-0491/#file-format)\" \"\\n - .tar.gz Packages\" .format(dep=dependency_name) )",
"https://www.python.org/dev/peps/pep-0440/#final-releases)\" \"\\n - Wheel Binary Packages (see https://www.python.org/dev/peps/pep-0491/#file-format)\" \"\\n - .tar.gz Packages\" .format(dep=dependency_name)",
"import InvalidDependencyVersionFormat, UnexpectedError from typing import NewType PipReadyDependency = NewType(name=\"PipReadyDependency\", tp=str) def _is_dependency_name_in_wheel(dependency_name:",
"def generate_pip_ready_dependency(dependency_name: str, version: str) -> PipReadyDependency: \"\"\" Raises: InvalidDependencyVersionFormat UnexpectedError \"\"\" dependency_regex:",
"format for the wheel dependency '{dep}' is invalid. Use a 'Final release' format",
"ValidDependencyVersionRegex from caos._internal.exceptions import InvalidDependencyVersionFormat, UnexpectedError from typing import NewType PipReadyDependency = NewType(name=\"PipReadyDependency\",",
"return \"~={}.{}.0\".format(major, minor) # ~=X.X.0 elif version.startswith(\"^\"): # Allow minor updates version =",
"a 'Final release' format \" \"(see https://www.python.org/dev/peps/pep-0440/#final-releases)\" .format(dep=dependency_name) ) return ValidDependencyVersionRegex.WHEEL if ValidDependencyVersionRegex.TARGZ.value.match(version):",
"dependency_regex == ValidDependencyVersionRegex.WHEEL: return version elif dependency_regex == ValidDependencyVersionRegex.TARGZ: return version raise UnexpectedError(\"The",
"# Allow minor updates version = version.replace(\"^\", \"\") major, minor, patch = version.split(\".\")",
"not ValidDependencyVersionRegex.MAJOR_MINOR_PATCH.value.match(wheel_version) and \\ not ValidDependencyVersionRegex.MAJOR_MINOR.value.match(wheel_version) and \\ not ValidDependencyVersionRegex.MAJOR.value.match(wheel_version): raise InvalidDependencyVersionFormat( \"\\nThe",
"Allow patch updates version = version.replace(\"~\", \"\") major, minor = version.split(\".\") return \"~={}.{}.0\".format(major,",
"elif version.startswith(\"^\"): # Allow minor updates version = version.replace(\"^\", \"\") major, minor, patch",
"ValidDependencyVersionRegex.MAJOR if ValidDependencyVersionRegex.LATEST.value.match(version): return ValidDependencyVersionRegex.LATEST wheel_info = ValidDependencyVersionRegex.WHEEL.value.match(version) if wheel_info: wheel = wheel_info.group(\"wheel\")",
"ValidDependencyVersionRegex.WHEEL if ValidDependencyVersionRegex.TARGZ.value.match(version): return ValidDependencyVersionRegex.TARGZ raise InvalidDependencyVersionFormat( \"\\nInvalid version format for the dependency",
"ValidDependencyVersionRegex.MAJOR_MINOR_PATCH if ValidDependencyVersionRegex.MAJOR_MINOR.value.match(version): return ValidDependencyVersionRegex.MAJOR_MINOR if ValidDependencyVersionRegex.MAJOR.value.match(version): return ValidDependencyVersionRegex.MAJOR if ValidDependencyVersionRegex.LATEST.value.match(version): return ValidDependencyVersionRegex.LATEST",
"= version.split(\".\") return \"~={}.{}\".format(major, minor) # ~=X.X else: # Allow exact version return",
"elif dependency_regex == ValidDependencyVersionRegex.WHEEL: return version elif dependency_regex == ValidDependencyVersionRegex.TARGZ: return version raise",
"wheel: str, version: str) -> bool: wheel = wheel[:-1*len(\"-{}\".format(version))]\\ .replace(\"_\", \"-\")\\ .lower() return",
"# ==X.X elif dependency_regex == ValidDependencyVersionRegex.MAJOR: if version.startswith(\"~\"): # Allow patch updates version",
"typing import NewType PipReadyDependency = NewType(name=\"PipReadyDependency\", tp=str) def _is_dependency_name_in_wheel(dependency_name: str, wheel: str, version:",
"ValidDependencyVersionRegex.MAJOR.value.match(version): return ValidDependencyVersionRegex.MAJOR if ValidDependencyVersionRegex.LATEST.value.match(version): return ValidDependencyVersionRegex.LATEST wheel_info = ValidDependencyVersionRegex.WHEEL.value.match(version) if wheel_info: wheel"
] |
[
"game = form.save(commit=False) game.game = gamelication if 'icon' not in request.POST: game.icon =",
"GameCategory.objects.all() if request.method == 'POST': form = UploadGameForm(request.POST) gamelication = request.FILES['game'] if form.is_valid():",
"= GameCommentForm() subForm = SubGCommentForm() c = game.gamecomment_set.all() comments = [] for comment",
"content['category'] game.inTro = content['inTro'] if 'icon' not in request.POST: game.icon = request.FILES['icon'] if",
"os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def portfllio(request): categories = GameCategory.objects.all().order_by(\"name\") gameList = [] for cate in categories:",
"game.category.pk = content['category'] game.inTro = content['inTro'] if 'icon' not in request.POST: game.icon =",
"in request.POST: game.game = request.FILES['game'] game.save() return redirect(\"/user/\") context = {'categories': categories,'game': game}",
"gamelication if 'icon' not in request.POST: game.icon = request.FILES['icon'] if 'foreImg' not in",
"from comment.models import SubGComment from .forms import UploadGameForm BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def portfllio(request):",
"= request.FILES['icon'] if 'foreImg' not in request.POST: game.foreImg = request.FILES['foreImg'] if 'game' not",
"open(url, 'rb') response = FileResponse(file) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename=\"{0}\"'.format(name) gameObj.increase_times() return",
"gameList}) def gameInfo(request,pk): game = get_object_or_404(Game, pk=pk) form = GameCommentForm() subForm = SubGCommentForm()",
"context=context) def downloadGame(request, pk): gameObj = get_object_or_404(Game, pk=pk) url = BASE_DIR+str(gameObj.game.url).replace('/', '\\\\') name",
"get_object_or_404(Game, pk=pk) form = GameCommentForm() subForm = SubGCommentForm() c = game.gamecomment_set.all() comments =",
"= request.FILES['game'] if form.is_valid(): game = form.save(commit=False) game.game = gamelication if 'icon' not",
"{ 'game': game, 'form': form, 'subForm': subForm, 'comments': comments, } return render(request, 'game/game.html',",
"form.is_valid(): game = form.save(commit=False) game.game = gamelication if 'icon' not in request.POST: game.icon",
"= open(url, 'rb') response = FileResponse(file) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename=\"{0}\"'.format(name) gameObj.increase_times()",
"= [] for cate in categories: games = Game.objects.filter(category = cate.pk).order_by(\"-createTime\") temp =",
"if 'icon' not in request.POST: game.icon = request.FILES['icon'] if 'foreImg' not in request.POST:",
"return redirect(\"/user/\") def editGame(request, pk): categories = GameCategory.objects.all() game = get_object_or_404(Game, pk=pk) if",
"BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def portfllio(request): categories = GameCategory.objects.all().order_by(\"name\") gameList = [] for cate",
"= get_object_or_404(Game, pk=pk) if request.method == 'POST': content = request.POST game.name = content['name']",
"= SubGComment.objects.filter(parentComment=comment.pk).order_by(\"createTime\") temp = (comment,subComment) comments.append(temp) context = { 'game': game, 'form': form,",
"pk=pk) if request.method == 'POST': content = request.POST game.name = content['name'] game.version =",
"UploadGameForm BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def portfllio(request): categories = GameCategory.objects.all().order_by(\"name\") gameList = [] for",
"= FileResponse(file) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename=\"{0}\"'.format(name) gameObj.increase_times() return response def uploadGame(request):",
"gameInfo(request,pk): game = get_object_or_404(Game, pk=pk) form = GameCommentForm() subForm = SubGCommentForm() c =",
"form, 'subForm': subForm, 'comments': comments, } return render(request, 'game/game.html', context=context) def downloadGame(request, pk):",
"'game/upload.html', context={'form': form, 'categories': categories}) def deleteGame(request, pk): Game.objects.filter(pk=pk).delete() return redirect(\"/user/\") def editGame(request,",
"pk): Game.objects.filter(pk=pk).delete() return redirect(\"/user/\") def editGame(request, pk): categories = GameCategory.objects.all() game = get_object_or_404(Game,",
"= Game.objects.filter(category = cate.pk).order_by(\"-createTime\") temp = (cate,games) gameList.append(temp) return render(request, 'home/portfolio.html', context={'gameList': gameList})",
"return render(request, 'home/portfolio.html', context={'gameList': gameList}) def gameInfo(request,pk): game = get_object_or_404(Game, pk=pk) form =",
"redirect('/') else: form = UploadGameForm() return render(request, 'game/upload.html', context={'form': form, 'categories': categories}) def",
"= UploadGameForm() return render(request, 'game/upload.html', context={'form': form, 'categories': categories}) def deleteGame(request, pk): Game.objects.filter(pk=pk).delete()",
"render,get_object_or_404, redirect from django.http import FileResponse from .models import GameCategory, Game from comment.forms",
"not in request.POST: game.foreImg = request.FILES['foreImg'] game.save() return redirect('/') else: form = UploadGameForm()",
"request.FILES['icon'] if 'foreImg' not in request.POST: game.foreImg = request.FILES['foreImg'] if 'game' not in",
"if request.method == 'POST': content = request.POST game.name = content['name'] game.version = content['version']",
"context = { 'game': game, 'form': form, 'subForm': subForm, 'comments': comments, } return",
"comments, } return render(request, 'game/game.html', context=context) def downloadGame(request, pk): gameObj = get_object_or_404(Game, pk=pk)",
"'subForm': subForm, 'comments': comments, } return render(request, 'game/game.html', context=context) def downloadGame(request, pk): gameObj",
"not in request.POST: game.icon = request.FILES['icon'] if 'foreImg' not in request.POST: game.foreImg =",
"'game/game.html', context=context) def downloadGame(request, pk): gameObj = get_object_or_404(Game, pk=pk) url = BASE_DIR+str(gameObj.game.url).replace('/', '\\\\')",
"Game.objects.filter(category = cate.pk).order_by(\"-createTime\") temp = (cate,games) gameList.append(temp) return render(request, 'home/portfolio.html', context={'gameList': gameList}) def",
"context={'gameList': gameList}) def gameInfo(request,pk): game = get_object_or_404(Game, pk=pk) form = GameCommentForm() subForm =",
"in request.POST: game.foreImg = request.FILES['foreImg'] if 'game' not in request.POST: game.game = request.FILES['game']",
"GameCategory, Game from comment.forms import GameCommentForm,SubGCommentForm from comment.models import SubGComment from .forms import",
"get_object_or_404(Game, pk=pk) url = BASE_DIR+str(gameObj.game.url).replace('/', '\\\\') name = str(gameObj.game) file = open(url, 'rb')",
"= os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def portfllio(request): categories = GameCategory.objects.all().order_by(\"name\") gameList = [] for cate in",
"response def uploadGame(request): categories = GameCategory.objects.all() if request.method == 'POST': form = UploadGameForm(request.POST)",
"'POST': form = UploadGameForm(request.POST) gamelication = request.FILES['game'] if form.is_valid(): game = form.save(commit=False) game.game",
"== 'POST': form = UploadGameForm(request.POST) gamelication = request.FILES['game'] if form.is_valid(): game = form.save(commit=False)",
"return response def uploadGame(request): categories = GameCategory.objects.all() if request.method == 'POST': form =",
"request.FILES['game'] if form.is_valid(): game = form.save(commit=False) game.game = gamelication if 'icon' not in",
"game.game = gamelication if 'icon' not in request.POST: game.icon = request.FILES['icon'] if 'foreImg'",
"portfllio(request): categories = GameCategory.objects.all().order_by(\"name\") gameList = [] for cate in categories: games =",
"request.FILES['icon'] if 'foreImg' not in request.POST: game.foreImg = request.FILES['foreImg'] game.save() return redirect('/') else:",
"import GameCommentForm,SubGCommentForm from comment.models import SubGComment from .forms import UploadGameForm BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))",
"if 'foreImg' not in request.POST: game.foreImg = request.FILES['foreImg'] game.save() return redirect('/') else: form",
"url = BASE_DIR+str(gameObj.game.url).replace('/', '\\\\') name = str(gameObj.game) file = open(url, 'rb') response =",
"= request.FILES['game'] game.save() return redirect(\"/user/\") context = {'categories': categories,'game': game} return render(request, 'game/edit.html',context=context)",
"Game.objects.filter(pk=pk).delete() return redirect(\"/user/\") def editGame(request, pk): categories = GameCategory.objects.all() game = get_object_or_404(Game, pk=pk)",
"= gamelication if 'icon' not in request.POST: game.icon = request.FILES['icon'] if 'foreImg' not",
"'foreImg' not in request.POST: game.foreImg = request.FILES['foreImg'] if 'game' not in request.POST: game.game",
"redirect(\"/user/\") def editGame(request, pk): categories = GameCategory.objects.all() game = get_object_or_404(Game, pk=pk) if request.method",
"'comments': comments, } return render(request, 'game/game.html', context=context) def downloadGame(request, pk): gameObj = get_object_or_404(Game,",
"request.POST game.name = content['name'] game.version = content['version'] game.category.pk = content['category'] game.inTro = content['inTro']",
"comment.forms import GameCommentForm,SubGCommentForm from comment.models import SubGComment from .forms import UploadGameForm BASE_DIR =",
"(comment,subComment) comments.append(temp) context = { 'game': game, 'form': form, 'subForm': subForm, 'comments': comments,",
"= str(gameObj.game) file = open(url, 'rb') response = FileResponse(file) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition']",
"= [] for comment in c: subComment = SubGComment.objects.filter(parentComment=comment.pk).order_by(\"createTime\") temp = (comment,subComment) comments.append(temp)",
"categories = GameCategory.objects.all() game = get_object_or_404(Game, pk=pk) if request.method == 'POST': content =",
"content['name'] game.version = content['version'] game.category.pk = content['category'] game.inTro = content['inTro'] if 'icon' not",
".models import GameCategory, Game from comment.forms import GameCommentForm,SubGCommentForm from comment.models import SubGComment from",
"if form.is_valid(): game = form.save(commit=False) game.game = gamelication if 'icon' not in request.POST:",
"pk=pk) form = GameCommentForm() subForm = SubGCommentForm() c = game.gamecomment_set.all() comments = []",
"name = str(gameObj.game) file = open(url, 'rb') response = FileResponse(file) response['Content-Type'] = 'application/octet-stream'",
"in request.POST: game.foreImg = request.FILES['foreImg'] game.save() return redirect('/') else: form = UploadGameForm() return",
"c = game.gamecomment_set.all() comments = [] for comment in c: subComment = SubGComment.objects.filter(parentComment=comment.pk).order_by(\"createTime\")",
"= get_object_or_404(Game, pk=pk) url = BASE_DIR+str(gameObj.game.url).replace('/', '\\\\') name = str(gameObj.game) file = open(url,",
"temp = (cate,games) gameList.append(temp) return render(request, 'home/portfolio.html', context={'gameList': gameList}) def gameInfo(request,pk): game =",
"content = request.POST game.name = content['name'] game.version = content['version'] game.category.pk = content['category'] game.inTro",
"FileResponse from .models import GameCategory, Game from comment.forms import GameCommentForm,SubGCommentForm from comment.models import",
"def uploadGame(request): categories = GameCategory.objects.all() if request.method == 'POST': form = UploadGameForm(request.POST) gamelication",
".forms import UploadGameForm BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def portfllio(request): categories = GameCategory.objects.all().order_by(\"name\") gameList =",
"game.foreImg = request.FILES['foreImg'] game.save() return redirect('/') else: form = UploadGameForm() return render(request, 'game/upload.html',",
"def downloadGame(request, pk): gameObj = get_object_or_404(Game, pk=pk) url = BASE_DIR+str(gameObj.game.url).replace('/', '\\\\') name =",
"from .models import GameCategory, Game from comment.forms import GameCommentForm,SubGCommentForm from comment.models import SubGComment",
"c: subComment = SubGComment.objects.filter(parentComment=comment.pk).order_by(\"createTime\") temp = (comment,subComment) comments.append(temp) context = { 'game': game,",
"form = UploadGameForm() return render(request, 'game/upload.html', context={'form': form, 'categories': categories}) def deleteGame(request, pk):",
"not in request.POST: game.game = request.FILES['game'] game.save() return redirect(\"/user/\") context = {'categories': categories,'game':",
"form = GameCommentForm() subForm = SubGCommentForm() c = game.gamecomment_set.all() comments = [] for",
"request.POST: game.game = request.FILES['game'] game.save() return redirect(\"/user/\") context = {'categories': categories,'game': game} return",
"game, 'form': form, 'subForm': subForm, 'comments': comments, } return render(request, 'game/game.html', context=context) def",
"form.save(commit=False) game.game = gamelication if 'icon' not in request.POST: game.icon = request.FILES['icon'] if",
"'game': game, 'form': form, 'subForm': subForm, 'comments': comments, } return render(request, 'game/game.html', context=context)",
"gameObj = get_object_or_404(Game, pk=pk) url = BASE_DIR+str(gameObj.game.url).replace('/', '\\\\') name = str(gameObj.game) file =",
"= GameCategory.objects.all().order_by(\"name\") gameList = [] for cate in categories: games = Game.objects.filter(category =",
"= SubGCommentForm() c = game.gamecomment_set.all() comments = [] for comment in c: subComment",
"= GameCategory.objects.all() game = get_object_or_404(Game, pk=pk) if request.method == 'POST': content = request.POST",
"django.shortcuts import render,get_object_or_404, redirect from django.http import FileResponse from .models import GameCategory, Game",
"GameCategory.objects.all().order_by(\"name\") gameList = [] for cate in categories: games = Game.objects.filter(category = cate.pk).order_by(\"-createTime\")",
"comments.append(temp) context = { 'game': game, 'form': form, 'subForm': subForm, 'comments': comments, }",
"form, 'categories': categories}) def deleteGame(request, pk): Game.objects.filter(pk=pk).delete() return redirect(\"/user/\") def editGame(request, pk): categories",
"categories: games = Game.objects.filter(category = cate.pk).order_by(\"-createTime\") temp = (cate,games) gameList.append(temp) return render(request, 'home/portfolio.html',",
"= { 'game': game, 'form': form, 'subForm': subForm, 'comments': comments, } return render(request,",
"response = FileResponse(file) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename=\"{0}\"'.format(name) gameObj.increase_times() return response def",
"django.http import FileResponse from .models import GameCategory, Game from comment.forms import GameCommentForm,SubGCommentForm from",
"'form': form, 'subForm': subForm, 'comments': comments, } return render(request, 'game/game.html', context=context) def downloadGame(request,",
"game.version = content['version'] game.category.pk = content['category'] game.inTro = content['inTro'] if 'icon' not in",
"'categories': categories}) def deleteGame(request, pk): Game.objects.filter(pk=pk).delete() return redirect(\"/user/\") def editGame(request, pk): categories =",
"SubGComment.objects.filter(parentComment=comment.pk).order_by(\"createTime\") temp = (comment,subComment) comments.append(temp) context = { 'game': game, 'form': form, 'subForm':",
"= BASE_DIR+str(gameObj.game.url).replace('/', '\\\\') name = str(gameObj.game) file = open(url, 'rb') response = FileResponse(file)",
"SubGCommentForm() c = game.gamecomment_set.all() comments = [] for comment in c: subComment =",
"editGame(request, pk): categories = GameCategory.objects.all() game = get_object_or_404(Game, pk=pk) if request.method == 'POST':",
"request.POST: game.foreImg = request.FILES['foreImg'] if 'game' not in request.POST: game.game = request.FILES['game'] game.save()",
"request.POST: game.foreImg = request.FILES['foreImg'] game.save() return redirect('/') else: form = UploadGameForm() return render(request,",
"'home/portfolio.html', context={'gameList': gameList}) def gameInfo(request,pk): game = get_object_or_404(Game, pk=pk) form = GameCommentForm() subForm",
"SubGComment from .forms import UploadGameForm BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def portfllio(request): categories = GameCategory.objects.all().order_by(\"name\")",
"BASE_DIR+str(gameObj.game.url).replace('/', '\\\\') name = str(gameObj.game) file = open(url, 'rb') response = FileResponse(file) response['Content-Type']",
"'attachment;filename=\"{0}\"'.format(name) gameObj.increase_times() return response def uploadGame(request): categories = GameCategory.objects.all() if request.method == 'POST':",
"in request.POST: game.icon = request.FILES['icon'] if 'foreImg' not in request.POST: game.foreImg = request.FILES['foreImg']",
"subComment = SubGComment.objects.filter(parentComment=comment.pk).order_by(\"createTime\") temp = (comment,subComment) comments.append(temp) context = { 'game': game, 'form':",
"in categories: games = Game.objects.filter(category = cate.pk).order_by(\"-createTime\") temp = (cate,games) gameList.append(temp) return render(request,",
"request.POST: game.icon = request.FILES['icon'] if 'foreImg' not in request.POST: game.foreImg = request.FILES['foreImg'] if",
"gamelication = request.FILES['game'] if form.is_valid(): game = form.save(commit=False) game.game = gamelication if 'icon'",
"pk): categories = GameCategory.objects.all() game = get_object_or_404(Game, pk=pk) if request.method == 'POST': content",
"GameCommentForm,SubGCommentForm from comment.models import SubGComment from .forms import UploadGameForm BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def",
"categories = GameCategory.objects.all().order_by(\"name\") gameList = [] for cate in categories: games = Game.objects.filter(category",
"def portfllio(request): categories = GameCategory.objects.all().order_by(\"name\") gameList = [] for cate in categories: games",
"cate.pk).order_by(\"-createTime\") temp = (cate,games) gameList.append(temp) return render(request, 'home/portfolio.html', context={'gameList': gameList}) def gameInfo(request,pk): game",
"[] for comment in c: subComment = SubGComment.objects.filter(parentComment=comment.pk).order_by(\"createTime\") temp = (comment,subComment) comments.append(temp) context",
"in c: subComment = SubGComment.objects.filter(parentComment=comment.pk).order_by(\"createTime\") temp = (comment,subComment) comments.append(temp) context = { 'game':",
"render(request, 'game/upload.html', context={'form': form, 'categories': categories}) def deleteGame(request, pk): Game.objects.filter(pk=pk).delete() return redirect(\"/user/\") def",
"content['inTro'] if 'icon' not in request.POST: game.icon = request.FILES['icon'] if 'foreImg' not in",
"response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename=\"{0}\"'.format(name) gameObj.increase_times() return response def uploadGame(request): categories =",
"else: form = UploadGameForm() return render(request, 'game/upload.html', context={'form': form, 'categories': categories}) def deleteGame(request,",
"import GameCategory, Game from comment.forms import GameCommentForm,SubGCommentForm from comment.models import SubGComment from .forms",
"form = UploadGameForm(request.POST) gamelication = request.FILES['game'] if form.is_valid(): game = form.save(commit=False) game.game =",
"game.icon = request.FILES['icon'] if 'foreImg' not in request.POST: game.foreImg = request.FILES['foreImg'] game.save() return",
"game.icon = request.FILES['icon'] if 'foreImg' not in request.POST: game.foreImg = request.FILES['foreImg'] if 'game'",
"gameList.append(temp) return render(request, 'home/portfolio.html', context={'gameList': gameList}) def gameInfo(request,pk): game = get_object_or_404(Game, pk=pk) form",
"= content['category'] game.inTro = content['inTro'] if 'icon' not in request.POST: game.icon = request.FILES['icon']",
"} return render(request, 'game/game.html', context=context) def downloadGame(request, pk): gameObj = get_object_or_404(Game, pk=pk) url",
"get_object_or_404(Game, pk=pk) if request.method == 'POST': content = request.POST game.name = content['name'] game.version",
"not in request.POST: game.foreImg = request.FILES['foreImg'] if 'game' not in request.POST: game.game =",
"= (cate,games) gameList.append(temp) return render(request, 'home/portfolio.html', context={'gameList': gameList}) def gameInfo(request,pk): game = get_object_or_404(Game,",
"def editGame(request, pk): categories = GameCategory.objects.all() game = get_object_or_404(Game, pk=pk) if request.method ==",
"'icon' not in request.POST: game.icon = request.FILES['icon'] if 'foreImg' not in request.POST: game.foreImg",
"game.name = content['name'] game.version = content['version'] game.category.pk = content['category'] game.inTro = content['inTro'] if",
"= get_object_or_404(Game, pk=pk) form = GameCommentForm() subForm = SubGCommentForm() c = game.gamecomment_set.all() comments",
"game.gamecomment_set.all() comments = [] for comment in c: subComment = SubGComment.objects.filter(parentComment=comment.pk).order_by(\"createTime\") temp =",
"if request.method == 'POST': form = UploadGameForm(request.POST) gamelication = request.FILES['game'] if form.is_valid(): game",
"= request.FILES['foreImg'] if 'game' not in request.POST: game.game = request.FILES['game'] game.save() return redirect(\"/user/\")",
"gameList = [] for cate in categories: games = Game.objects.filter(category = cate.pk).order_by(\"-createTime\") temp",
"os from django.shortcuts import render,get_object_or_404, redirect from django.http import FileResponse from .models import",
"from .forms import UploadGameForm BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def portfllio(request): categories = GameCategory.objects.all().order_by(\"name\") gameList",
"for cate in categories: games = Game.objects.filter(category = cate.pk).order_by(\"-createTime\") temp = (cate,games) gameList.append(temp)",
"FileResponse(file) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename=\"{0}\"'.format(name) gameObj.increase_times() return response def uploadGame(request): categories",
"= 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename=\"{0}\"'.format(name) gameObj.increase_times() return response def uploadGame(request): categories = GameCategory.objects.all()",
"content['version'] game.category.pk = content['category'] game.inTro = content['inTro'] if 'icon' not in request.POST: game.icon",
"if 'foreImg' not in request.POST: game.foreImg = request.FILES['foreImg'] if 'game' not in request.POST:",
"GameCommentForm() subForm = SubGCommentForm() c = game.gamecomment_set.all() comments = [] for comment in",
"game.inTro = content['inTro'] if 'icon' not in request.POST: game.icon = request.FILES['icon'] if 'foreImg'",
"comment.models import SubGComment from .forms import UploadGameForm BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def portfllio(request): categories",
"subForm = SubGCommentForm() c = game.gamecomment_set.all() comments = [] for comment in c:",
"game = get_object_or_404(Game, pk=pk) if request.method == 'POST': content = request.POST game.name =",
"cate in categories: games = Game.objects.filter(category = cate.pk).order_by(\"-createTime\") temp = (cate,games) gameList.append(temp) return",
"= content['name'] game.version = content['version'] game.category.pk = content['category'] game.inTro = content['inTro'] if 'icon'",
"game = get_object_or_404(Game, pk=pk) form = GameCommentForm() subForm = SubGCommentForm() c = game.gamecomment_set.all()",
"[] for cate in categories: games = Game.objects.filter(category = cate.pk).order_by(\"-createTime\") temp = (cate,games)",
"request.FILES['foreImg'] game.save() return redirect('/') else: form = UploadGameForm() return render(request, 'game/upload.html', context={'form': form,",
"= (comment,subComment) comments.append(temp) context = { 'game': game, 'form': form, 'subForm': subForm, 'comments':",
"request.FILES['foreImg'] if 'game' not in request.POST: game.game = request.FILES['game'] game.save() return redirect(\"/user/\") context",
"from django.http import FileResponse from .models import GameCategory, Game from comment.forms import GameCommentForm,SubGCommentForm",
"return render(request, 'game/upload.html', context={'form': form, 'categories': categories}) def deleteGame(request, pk): Game.objects.filter(pk=pk).delete() return redirect(\"/user/\")",
"def deleteGame(request, pk): Game.objects.filter(pk=pk).delete() return redirect(\"/user/\") def editGame(request, pk): categories = GameCategory.objects.all() game",
"= game.gamecomment_set.all() comments = [] for comment in c: subComment = SubGComment.objects.filter(parentComment=comment.pk).order_by(\"createTime\") temp",
"request.method == 'POST': form = UploadGameForm(request.POST) gamelication = request.FILES['game'] if form.is_valid(): game =",
"= UploadGameForm(request.POST) gamelication = request.FILES['game'] if form.is_valid(): game = form.save(commit=False) game.game = gamelication",
"response['Content-Disposition'] = 'attachment;filename=\"{0}\"'.format(name) gameObj.increase_times() return response def uploadGame(request): categories = GameCategory.objects.all() if request.method",
"'POST': content = request.POST game.name = content['name'] game.version = content['version'] game.category.pk = content['category']",
"game.save() return redirect('/') else: form = UploadGameForm() return render(request, 'game/upload.html', context={'form': form, 'categories':",
"Game from comment.forms import GameCommentForm,SubGCommentForm from comment.models import SubGComment from .forms import UploadGameForm",
"from comment.forms import GameCommentForm,SubGCommentForm from comment.models import SubGComment from .forms import UploadGameForm BASE_DIR",
"import os from django.shortcuts import render,get_object_or_404, redirect from django.http import FileResponse from .models",
"= request.POST game.name = content['name'] game.version = content['version'] game.category.pk = content['category'] game.inTro =",
"render(request, 'game/game.html', context=context) def downloadGame(request, pk): gameObj = get_object_or_404(Game, pk=pk) url = BASE_DIR+str(gameObj.game.url).replace('/',",
"= form.save(commit=False) game.game = gamelication if 'icon' not in request.POST: game.icon = request.FILES['icon']",
"UploadGameForm() return render(request, 'game/upload.html', context={'form': form, 'categories': categories}) def deleteGame(request, pk): Game.objects.filter(pk=pk).delete() return",
"'foreImg' not in request.POST: game.foreImg = request.FILES['foreImg'] game.save() return redirect('/') else: form =",
"import UploadGameForm BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def portfllio(request): categories = GameCategory.objects.all().order_by(\"name\") gameList = []",
"request.method == 'POST': content = request.POST game.name = content['name'] game.version = content['version'] game.category.pk",
"def gameInfo(request,pk): game = get_object_or_404(Game, pk=pk) form = GameCommentForm() subForm = SubGCommentForm() c",
"game.foreImg = request.FILES['foreImg'] if 'game' not in request.POST: game.game = request.FILES['game'] game.save() return",
"render(request, 'home/portfolio.html', context={'gameList': gameList}) def gameInfo(request,pk): game = get_object_or_404(Game, pk=pk) form = GameCommentForm()",
"return redirect('/') else: form = UploadGameForm() return render(request, 'game/upload.html', context={'form': form, 'categories': categories})",
"comments = [] for comment in c: subComment = SubGComment.objects.filter(parentComment=comment.pk).order_by(\"createTime\") temp = (comment,subComment)",
"request.POST: game.icon = request.FILES['icon'] if 'foreImg' not in request.POST: game.foreImg = request.FILES['foreImg'] game.save()",
"'rb') response = FileResponse(file) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename=\"{0}\"'.format(name) gameObj.increase_times() return response",
"from django.shortcuts import render,get_object_or_404, redirect from django.http import FileResponse from .models import GameCategory,",
"'game' not in request.POST: game.game = request.FILES['game'] game.save() return redirect(\"/user/\") context = {'categories':",
"import SubGComment from .forms import UploadGameForm BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def portfllio(request): categories =",
"return render(request, 'game/game.html', context=context) def downloadGame(request, pk): gameObj = get_object_or_404(Game, pk=pk) url =",
"temp = (comment,subComment) comments.append(temp) context = { 'game': game, 'form': form, 'subForm': subForm,",
"= request.FILES['foreImg'] game.save() return redirect('/') else: form = UploadGameForm() return render(request, 'game/upload.html', context={'form':",
"UploadGameForm(request.POST) gamelication = request.FILES['game'] if form.is_valid(): game = form.save(commit=False) game.game = gamelication if",
"pk=pk) url = BASE_DIR+str(gameObj.game.url).replace('/', '\\\\') name = str(gameObj.game) file = open(url, 'rb') response",
"subForm, 'comments': comments, } return render(request, 'game/game.html', context=context) def downloadGame(request, pk): gameObj =",
"import FileResponse from .models import GameCategory, Game from comment.forms import GameCommentForm,SubGCommentForm from comment.models",
"= request.FILES['icon'] if 'foreImg' not in request.POST: game.foreImg = request.FILES['foreImg'] game.save() return redirect('/')",
"import render,get_object_or_404, redirect from django.http import FileResponse from .models import GameCategory, Game from",
"context={'form': form, 'categories': categories}) def deleteGame(request, pk): Game.objects.filter(pk=pk).delete() return redirect(\"/user/\") def editGame(request, pk):",
"categories}) def deleteGame(request, pk): Game.objects.filter(pk=pk).delete() return redirect(\"/user/\") def editGame(request, pk): categories = GameCategory.objects.all()",
"deleteGame(request, pk): Game.objects.filter(pk=pk).delete() return redirect(\"/user/\") def editGame(request, pk): categories = GameCategory.objects.all() game =",
"(cate,games) gameList.append(temp) return render(request, 'home/portfolio.html', context={'gameList': gameList}) def gameInfo(request,pk): game = get_object_or_404(Game, pk=pk)",
"file = open(url, 'rb') response = FileResponse(file) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename=\"{0}\"'.format(name)",
"= cate.pk).order_by(\"-createTime\") temp = (cate,games) gameList.append(temp) return render(request, 'home/portfolio.html', context={'gameList': gameList}) def gameInfo(request,pk):",
"= GameCategory.objects.all() if request.method == 'POST': form = UploadGameForm(request.POST) gamelication = request.FILES['game'] if",
"redirect from django.http import FileResponse from .models import GameCategory, Game from comment.forms import",
"games = Game.objects.filter(category = cate.pk).order_by(\"-createTime\") temp = (cate,games) gameList.append(temp) return render(request, 'home/portfolio.html', context={'gameList':",
"downloadGame(request, pk): gameObj = get_object_or_404(Game, pk=pk) url = BASE_DIR+str(gameObj.game.url).replace('/', '\\\\') name = str(gameObj.game)",
"gameObj.increase_times() return response def uploadGame(request): categories = GameCategory.objects.all() if request.method == 'POST': form",
"GameCategory.objects.all() game = get_object_or_404(Game, pk=pk) if request.method == 'POST': content = request.POST game.name",
"for comment in c: subComment = SubGComment.objects.filter(parentComment=comment.pk).order_by(\"createTime\") temp = (comment,subComment) comments.append(temp) context =",
"pk): gameObj = get_object_or_404(Game, pk=pk) url = BASE_DIR+str(gameObj.game.url).replace('/', '\\\\') name = str(gameObj.game) file",
"= content['inTro'] if 'icon' not in request.POST: game.icon = request.FILES['icon'] if 'foreImg' not",
"== 'POST': content = request.POST game.name = content['name'] game.version = content['version'] game.category.pk =",
"'application/octet-stream' response['Content-Disposition'] = 'attachment;filename=\"{0}\"'.format(name) gameObj.increase_times() return response def uploadGame(request): categories = GameCategory.objects.all() if",
"comment in c: subComment = SubGComment.objects.filter(parentComment=comment.pk).order_by(\"createTime\") temp = (comment,subComment) comments.append(temp) context = {",
"str(gameObj.game) file = open(url, 'rb') response = FileResponse(file) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] =",
"categories = GameCategory.objects.all() if request.method == 'POST': form = UploadGameForm(request.POST) gamelication = request.FILES['game']",
"= content['version'] game.category.pk = content['category'] game.inTro = content['inTro'] if 'icon' not in request.POST:",
"game.game = request.FILES['game'] game.save() return redirect(\"/user/\") context = {'categories': categories,'game': game} return render(request,",
"'\\\\') name = str(gameObj.game) file = open(url, 'rb') response = FileResponse(file) response['Content-Type'] =",
"if 'game' not in request.POST: game.game = request.FILES['game'] game.save() return redirect(\"/user/\") context =",
"= 'attachment;filename=\"{0}\"'.format(name) gameObj.increase_times() return response def uploadGame(request): categories = GameCategory.objects.all() if request.method ==",
"uploadGame(request): categories = GameCategory.objects.all() if request.method == 'POST': form = UploadGameForm(request.POST) gamelication ="
] |
[
"script to replace numactl in testing environment # import argparse import subprocess print(\"Using",
"in testing environment # import argparse import subprocess print(\"Using dummy numactl\") parser =",
"numactl in testing environment # import argparse import subprocess print(\"Using dummy numactl\") parser",
"Dummy script to replace numactl in testing environment # import argparse import subprocess",
"import subprocess print(\"Using dummy numactl\") parser = argparse.ArgumentParser() parser.add_argument(\"cmd\", nargs=\"*\") args, unknown =",
"# import argparse import subprocess print(\"Using dummy numactl\") parser = argparse.ArgumentParser() parser.add_argument(\"cmd\", nargs=\"*\")",
"parser = argparse.ArgumentParser() parser.add_argument(\"cmd\", nargs=\"*\") args, unknown = parser.parse_known_args() p = subprocess.Popen(args.cmd) p.wait()",
"to replace numactl in testing environment # import argparse import subprocess print(\"Using dummy",
"numactl\") parser = argparse.ArgumentParser() parser.add_argument(\"cmd\", nargs=\"*\") args, unknown = parser.parse_known_args() p = subprocess.Popen(args.cmd)",
"# Dummy script to replace numactl in testing environment # import argparse import",
"argparse import subprocess print(\"Using dummy numactl\") parser = argparse.ArgumentParser() parser.add_argument(\"cmd\", nargs=\"*\") args, unknown",
"import argparse import subprocess print(\"Using dummy numactl\") parser = argparse.ArgumentParser() parser.add_argument(\"cmd\", nargs=\"*\") args,",
"environment # import argparse import subprocess print(\"Using dummy numactl\") parser = argparse.ArgumentParser() parser.add_argument(\"cmd\",",
"# # Dummy script to replace numactl in testing environment # import argparse",
"subprocess print(\"Using dummy numactl\") parser = argparse.ArgumentParser() parser.add_argument(\"cmd\", nargs=\"*\") args, unknown = parser.parse_known_args()",
"print(\"Using dummy numactl\") parser = argparse.ArgumentParser() parser.add_argument(\"cmd\", nargs=\"*\") args, unknown = parser.parse_known_args() p",
"#!/usr/bin/env python # # Dummy script to replace numactl in testing environment #",
"dummy numactl\") parser = argparse.ArgumentParser() parser.add_argument(\"cmd\", nargs=\"*\") args, unknown = parser.parse_known_args() p =",
"replace numactl in testing environment # import argparse import subprocess print(\"Using dummy numactl\")",
"python # # Dummy script to replace numactl in testing environment # import",
"testing environment # import argparse import subprocess print(\"Using dummy numactl\") parser = argparse.ArgumentParser()"
] |
[
"not yet annotated if not annotation['annotations']: continue for tweet_id, tweet in tweet_dict.items(): if",
"= Path(os.path.join(default_raw_path, anno_data_file)) agree_path = Path(os.path.join(default_raw_path, agree_file)) disagree_path = Path(os.path.join(default_raw_path, disagree_file)) with anno_data_path.open(encoding='utf-8')",
"\"Error in claim labels, must contain either '1' or '2', denominating 'claim'\" \\",
"err_msg.format(annotation['annotations'])) if 2 in annotation['annotations']: tweet['Claim'] = False else: tweet['Claim'] = True if",
"7: 'False'} if 1 or 2 not in annotation['annotations']: err_msg = \"Error in",
"in annotation['annotations']: err_msg = \"Error in claim labels, must contain either '3' or",
"one allowed\" raise RuntimeError( err_msg.format(len(annotation['annotations']))) tweet['SDQC_Submission'] = sdqc_map[annotation['annotations'][0]] def integrate_label_data(anno_data_path: Path, database_path: Path,",
"# Data-point not yet annotated if not annotation['annotations']: continue for tweet_id, tweet in",
"else: tweet['Verifiability'] = 'Verifiable' if 5 or 6 or 7 not in annotation['annotations']:",
"= Path(unlabeled_data_path, stance_out_name) claim_out_path = Path(unlabeled_data_path, claim_out_name) with file_path.open() as data, stance_out_path.open(mode='w') as",
"tweet_dict = json.loads(line.split('\\t')[1]) source_tweet = tweet_dict[line.split('\\t')[0]] source_tweet['text'] = source_tweet['full_text'] source_tweet['labels'] = [] json.dump(source_tweet,",
"either '3' or '4', denominating \" \\ \"'verifiable' and 'subjective' respectively. Given labels:",
"\"Error in claim labels, must contain either '3' or '4', denominating \" \\",
"2 in annotation['annotations']: tweet['Claim'] = False else: tweet['Claim'] = True if 3 or",
"either '1' or '2', denominating 'claim'\" \\ \" and 'non-claim' respectively. Given labels:",
"Path(os.path.join(default_raw_path, agree_file)) disagree_path = Path(os.path.join(default_raw_path, disagree_file)) with anno_data_path.open(encoding='utf-8') as anno_data, agree_path.open(mode='w', encoding='utf-8') as",
"in claim labels, must contain either '3' or '4', denominating \" \\ \"'verifiable'",
"2: 'Denying', 3: 'Querying', 4: 'Commenting'} if len(annotation['annotations']) > 1: err_msg = \"{}",
"{}'.format(source_tweet['full_text'], tweet['full_text']) tweet['labels'] = [] json.dump(tweet, stance_out) stance_out.write('\\n') def anno_agreement_check(anno_data_file: str, agree_file: str,",
"or 'claim'\" raise RuntimeError( err_msg.format(label_scheme)) with anno_data_path.open(encoding='utf-8') as labeled_data, database_path.open(encoding='utf-8') as database: data",
"= [] json.dump(tweet, stance_out) stance_out.write('\\n') def anno_agreement_check(anno_data_file: str, agree_file: str, disagree_file: str): anno_data_path",
"contain either '1' or '2', denominating 'claim'\" \\ \" and 'non-claim' respectively. Given",
"RuntimeError( err_msg.format(annotation['annotations'])) if 2 in annotation['annotations']: tweet['Claim'] = False else: tweet['Claim'] = True",
"= False else: tweet['Claim'] = True if 3 or 4 not in annotation['annotations']:",
"raise RuntimeError( err_msg.format(label_scheme)) with anno_data_path.open(encoding='utf-8') as labeled_data, database_path.open(encoding='utf-8') as database: data = []",
"disagreement = True break if disagreement: break if not disagreement: line = json.loads(line)",
"{5: 'True', 6: 'Unverified', 7: 'False'} if 1 or 2 not in annotation['annotations']:",
"for x in [5, 6, 7]: if x in annotation['annotations']: tweet['TruthStatus'] = veracity_map[x]",
"False annotations = json.loads(line)['annotations'] if len(annotations) == 1: line = json.loads(line) line['annotations'] =",
"= {1: 'Supporting', 2: 'Denying', 3: 'Querying', 4: 'Commenting'} if len(annotation['annotations']) > 1:",
"disagree_path = Path(os.path.join(default_raw_path, disagree_file)) with anno_data_path.open(encoding='utf-8') as anno_data, agree_path.open(mode='w', encoding='utf-8') as agree_data, disagree_path.open(",
"= True if 3 or 4 not in annotation['annotations']: err_msg = \"Error in",
"label_scheme == 'sdqc': integrate_sdqc_label(annotation, tweet) not_altered = False break if not_altered: data.append(line) else:",
"yet annotated if not annotation['annotations']: continue for tweet_id, tweet in tweet_dict.items(): if tweet['full_text']",
"user_id_b, labels_b in user_labels.items(): if labels_a != labels_b: disagree_data.write(line) disagreement = True break",
"in annotation['annotations']: err_msg = \"Error in claim labels, must contain either '1' or",
"disagree_file: str): anno_data_path = Path(os.path.join(default_raw_path, anno_data_file)) agree_path = Path(os.path.join(default_raw_path, agree_file)) disagree_path = Path(os.path.join(default_raw_path,",
"err_msg.format(len(annotation['annotations']))) tweet['SDQC_Submission'] = sdqc_map[annotation['annotations'][0]] def integrate_label_data(anno_data_path: Path, database_path: Path, label_scheme: str): if label_scheme",
"{}\" raise RuntimeError( err_msg.format(annotation['annotations'])) if 4 in annotation['annotations']: tweet['Verifiability'] = 'Subjective' else: tweet['Verifiability']",
"{}, please use 'sdqc' or 'claim'\" raise RuntimeError( err_msg.format(label_scheme)) with anno_data_path.open(encoding='utf-8') as labeled_data,",
"file_path.open() as data, stance_out_path.open(mode='w') as stance_out, claim_out_path.open(mode='w') as claim_out: for line in data:",
"json.loads(line)['annotations'] if len(annotations) == 1: line = json.loads(line) line['annotations'] = [annotations[0]['label']] json.dump(line, agree_data)",
"not in ['claim', 'sdqc']: err_msg = \"Unrecognized label scheme: {}, please use 'sdqc'",
"stance_out) stance_out.write('\\n') def anno_agreement_check(anno_data_file: str, agree_file: str, disagree_file: str): anno_data_path = Path(os.path.join(default_raw_path, anno_data_file))",
"if 5 or 6 or 7 not in annotation['annotations']: err_msg = \"Error in",
"def integrate_label_data(anno_data_path: Path, database_path: Path, label_scheme: str): if label_scheme not in ['claim', 'sdqc']:",
"in data: tweet_dict = json.loads(line.split('\\t')[1]) source_tweet = tweet_dict[line.split('\\t')[0]] source_tweet['text'] = source_tweet['full_text'] source_tweet['labels'] =",
"annotation in labeled_data: annotation = json.loads(annotation) # Data-point not yet annotated if not",
"os from pathlib import Path current_path = os.path.abspath(__file__) default_raw_path = os.path.join(current_path, '../../data/datasets/twitter/raw/') unlabeled_data_path",
"or '4', denominating \" \\ \"'verifiable' and 'subjective' respectively. Given labels: {}\" raise",
"integrate_sdqc_label(annotation, tweet) not_altered = False break if not_altered: data.append(line) else: data.append(line.split('\\t')[0] + '\\t'",
"raise RuntimeError( err_msg.format(annotation['annotations'])) for x in [5, 6, 7]: if x in annotation['annotations']:",
"\" \\ \"denominating 'True', 'Unverified' and 'False' respectively. Given \" \\ \"labels: {}\"",
"encoding='utf-8') as database: for line in data: database.write(line) #anno_agreement_check(Path('test.json'), Path('agree.json'), Path('disagree.json')) #generate_label_data(test_data, 'stance.jsonl',",
"user_id_a, labels_a in user_labels.items(): for user_id_b, labels_b in user_labels.items(): if labels_a != labels_b:",
"disagree_file)) with anno_data_path.open(encoding='utf-8') as anno_data, agree_path.open(mode='w', encoding='utf-8') as agree_data, disagree_path.open( mode='w', encoding='utf-8') as",
"4 in annotation['annotations']: tweet['Verifiability'] = 'Subjective' else: tweet['Verifiability'] = 'Verifiable' if 5 or",
"must contain either '3' or '4', denominating \" \\ \"'verifiable' and 'subjective' respectively.",
"source_tweet == tweet: continue tweet['text'] = 'Source: {}\\n\\nReply: {}'.format(source_tweet['full_text'], tweet['full_text']) tweet['labels'] = []",
"line in data: tweet_dict = json.loads(line.split('\\t')[1]) source_tweet = tweet_dict[line.split('\\t')[0]] source_tweet['text'] = source_tweet['full_text'] source_tweet['labels']",
"in annotation['annotations']: tweet['TruthStatus'] = veracity_map[x] def integrate_sdqc_label(annotation, tweet): sdqc_map = {1: 'Supporting', 2:",
"agree_data) agree_data.write('\\n') def integrate_claim_label(annotation, tweet): veracity_map = {5: 'True', 6: 'Unverified', 7: 'False'}",
"veracity_map[x] def integrate_sdqc_label(annotation, tweet): sdqc_map = {1: 'Supporting', 2: 'Denying', 3: 'Querying', 4:",
"err_msg = \"Error in claim labels, must contain either '1' or '2', denominating",
"line in database: not_altered = True tweet_dict = json.loads(line.split('\\t')[1]) for annotation in labeled_data:",
"json.dump(line, agree_data) agree_data.write('\\n') else: user_labels = {} for annotation in annotations: user_labels.setdefault(annotation['user'], set()).add(annotation['label'])",
"err_msg.format(annotation['annotations'])) if 4 in annotation['annotations']: tweet['Verifiability'] = 'Subjective' else: tweet['Verifiability'] = 'Verifiable' if",
"str): anno_data_path = Path(os.path.join(default_raw_path, anno_data_file)) agree_path = Path(os.path.join(default_raw_path, agree_file)) disagree_path = Path(os.path.join(default_raw_path, disagree_file))",
"only one allowed\" raise RuntimeError( err_msg.format(len(annotation['annotations']))) tweet['SDQC_Submission'] = sdqc_map[annotation['annotations'][0]] def integrate_label_data(anno_data_path: Path, database_path:",
"stance_out_path = Path(unlabeled_data_path, stance_out_name) claim_out_path = Path(unlabeled_data_path, claim_out_name) with file_path.open() as data, stance_out_path.open(mode='w')",
"source_tweet['full_text'] source_tweet['labels'] = [] json.dump(source_tweet, claim_out) claim_out.write('\\n') for tweet_id, tweet in tweet_dict.items(): if",
"must contain either '1' or '2', denominating 'claim'\" \\ \" and 'non-claim' respectively.",
"as data, stance_out_path.open(mode='w') as stance_out, claim_out_path.open(mode='w') as claim_out: for line in data: tweet_dict",
"unlabeled_data_path = Path(os.path.join(os.path.abspath(__file__), '../../../data/datasets/twitter/raw/unlabeled')) def generate_label_data(file_name: str, stance_out_name: str, claim_out_name: str): file_path =",
"= os.path.join(current_path, '../../data/datasets/twitter/raw/') unlabeled_data_path = Path(os.path.join(os.path.abspath(__file__), '../../../data/datasets/twitter/raw/unlabeled')) def generate_label_data(file_name: str, stance_out_name: str, claim_out_name:",
"labels_a != labels_b: disagree_data.write(line) disagreement = True break if disagreement: break if not",
"'Unverified' and 'False' respectively. Given \" \\ \"labels: {}\" raise RuntimeError( err_msg.format(annotation['annotations'])) for",
"3: 'Querying', 4: 'Commenting'} if len(annotation['annotations']) > 1: err_msg = \"{} SDQC labels",
"[] json.dump(source_tweet, claim_out) claim_out.write('\\n') for tweet_id, tweet in tweet_dict.items(): if source_tweet == tweet:",
"agree_data, disagree_path.open( mode='w', encoding='utf-8') as disagree_data: for line in anno_data: disagreement = False",
"= Path(unlabeled_data_path, claim_out_name) with file_path.open() as data, stance_out_path.open(mode='w') as stance_out, claim_out_path.open(mode='w') as claim_out:",
"Path(os.path.join(default_raw_path, anno_data_file)) agree_path = Path(os.path.join(default_raw_path, agree_file)) disagree_path = Path(os.path.join(default_raw_path, disagree_file)) with anno_data_path.open(encoding='utf-8') as",
"annotation['annotations']: continue for tweet_id, tweet in tweet_dict.items(): if tweet['full_text'] == annotation['text']: if label_scheme",
"disagree_path.open( mode='w', encoding='utf-8') as disagree_data: for line in anno_data: disagreement = False annotations",
"database: data = [] for line in database: not_altered = True tweet_dict =",
"labels: {}\" raise RuntimeError( err_msg.format(annotation['annotations'])) if 4 in annotation['annotations']: tweet['Verifiability'] = 'Subjective' else:",
"RuntimeError( err_msg.format(len(annotation['annotations']))) tweet['SDQC_Submission'] = sdqc_map[annotation['annotations'][0]] def integrate_label_data(anno_data_path: Path, database_path: Path, label_scheme: str): if",
"label_scheme: str): if label_scheme not in ['claim', 'sdqc']: err_msg = \"Unrecognized label scheme:",
"user_labels.setdefault(annotation['user'], set()).add(annotation['label']) for user_id_a, labels_a in user_labels.items(): for user_id_b, labels_b in user_labels.items(): if",
"\"labels: {}\" raise RuntimeError( err_msg.format(annotation['annotations'])) for x in [5, 6, 7]: if x",
"file_path = Path(unlabeled_data_path, file_name) stance_out_path = Path(unlabeled_data_path, stance_out_name) claim_out_path = Path(unlabeled_data_path, claim_out_name) with",
"disagreement: break if not disagreement: line = json.loads(line) if user_labels: line['annotations'] = list(user_labels[1])",
"disagreement: print(line) json.dump(line, agree_data) agree_data.write('\\n') def integrate_claim_label(annotation, tweet): veracity_map = {5: 'True', 6:",
"file_name) stance_out_path = Path(unlabeled_data_path, stance_out_name) claim_out_path = Path(unlabeled_data_path, claim_out_name) with file_path.open() as data,",
"respectively. Given labels: {}\" raise RuntimeError( err_msg.format(annotation['annotations'])) if 2 in annotation['annotations']: tweet['Claim'] =",
"labels, must contain either '3' or '4', denominating \" \\ \"'verifiable' and 'subjective'",
"\" \\ \"labels: {}\" raise RuntimeError( err_msg.format(annotation['annotations'])) for x in [5, 6, 7]:",
"if 1 or 2 not in annotation['annotations']: err_msg = \"Error in claim labels,",
"7]: if x in annotation['annotations']: tweet['TruthStatus'] = veracity_map[x] def integrate_sdqc_label(annotation, tweet): sdqc_map =",
"\"{} SDQC labels found, only one allowed\" raise RuntimeError( err_msg.format(len(annotation['annotations']))) tweet['SDQC_Submission'] = sdqc_map[annotation['annotations'][0]]",
"claim_out_path.open(mode='w') as claim_out: for line in data: tweet_dict = json.loads(line.split('\\t')[1]) source_tweet = tweet_dict[line.split('\\t')[0]]",
"anno_agreement_check(anno_data_file: str, agree_file: str, disagree_file: str): anno_data_path = Path(os.path.join(default_raw_path, anno_data_file)) agree_path = Path(os.path.join(default_raw_path,",
"if 4 in annotation['annotations']: tweet['Verifiability'] = 'Subjective' else: tweet['Verifiability'] = 'Verifiable' if 5",
"6 or 7 not in annotation['annotations']: err_msg = \"Error in claim labels, must",
"json.dump(line, agree_data) agree_data.write('\\n') def integrate_claim_label(annotation, tweet): veracity_map = {5: 'True', 6: 'Unverified', 7:",
"err_msg = \"Error in claim labels, must contain either '3' or '4', denominating",
"= json.loads(line) line['annotations'] = [annotations[0]['label']] json.dump(line, agree_data) agree_data.write('\\n') else: user_labels = {} for",
"source_tweet['labels'] = [] json.dump(source_tweet, claim_out) claim_out.write('\\n') for tweet_id, tweet in tweet_dict.items(): if source_tweet",
"integrate_label_data(anno_data_path: Path, database_path: Path, label_scheme: str): if label_scheme not in ['claim', 'sdqc']: err_msg",
"\\ \"denominating 'True', 'Unverified' and 'False' respectively. Given \" \\ \"labels: {}\" raise",
"'sdqc': integrate_sdqc_label(annotation, tweet) not_altered = False break if not_altered: data.append(line) else: data.append(line.split('\\t')[0] +",
"1: err_msg = \"{} SDQC labels found, only one allowed\" raise RuntimeError( err_msg.format(len(annotation['annotations'])))",
"{}\" raise RuntimeError( err_msg.format(annotation['annotations'])) if 2 in annotation['annotations']: tweet['Claim'] = False else: tweet['Claim']",
"line = json.loads(line) line['annotations'] = [annotations[0]['label']] json.dump(line, agree_data) agree_data.write('\\n') else: user_labels = {}",
"sdqc_map[annotation['annotations'][0]] def integrate_label_data(anno_data_path: Path, database_path: Path, label_scheme: str): if label_scheme not in ['claim',",
"labels_b in user_labels.items(): if labels_a != labels_b: disagree_data.write(line) disagreement = True break if",
"'../../data/datasets/twitter/raw/') unlabeled_data_path = Path(os.path.join(os.path.abspath(__file__), '../../../data/datasets/twitter/raw/unlabeled')) def generate_label_data(file_name: str, stance_out_name: str, claim_out_name: str): file_path",
"print(line) json.dump(line, agree_data) agree_data.write('\\n') def integrate_claim_label(annotation, tweet): veracity_map = {5: 'True', 6: 'Unverified',",
"annotations = json.loads(line)['annotations'] if len(annotations) == 1: line = json.loads(line) line['annotations'] = [annotations[0]['label']]",
"tweet_dict.items(): if tweet['full_text'] == annotation['text']: if label_scheme == 'claim': integrate_claim_label(annotation, tweet) if label_scheme",
"def integrate_sdqc_label(annotation, tweet): sdqc_map = {1: 'Supporting', 2: 'Denying', 3: 'Querying', 4: 'Commenting'}",
"True if 3 or 4 not in annotation['annotations']: err_msg = \"Error in claim",
"'True', 'Unverified' and 'False' respectively. Given \" \\ \"labels: {}\" raise RuntimeError( err_msg.format(annotation['annotations']))",
"'Supporting', 2: 'Denying', 3: 'Querying', 4: 'Commenting'} if len(annotation['annotations']) > 1: err_msg =",
"os.path.abspath(__file__) default_raw_path = os.path.join(current_path, '../../data/datasets/twitter/raw/') unlabeled_data_path = Path(os.path.join(os.path.abspath(__file__), '../../../data/datasets/twitter/raw/unlabeled')) def generate_label_data(file_name: str, stance_out_name:",
"raise RuntimeError( err_msg.format(annotation['annotations'])) if 2 in annotation['annotations']: tweet['Claim'] = False else: tweet['Claim'] =",
"4 not in annotation['annotations']: err_msg = \"Error in claim labels, must contain either",
"str): file_path = Path(unlabeled_data_path, file_name) stance_out_path = Path(unlabeled_data_path, stance_out_name) claim_out_path = Path(unlabeled_data_path, claim_out_name)",
"disagreement: line = json.loads(line) if user_labels: line['annotations'] = list(user_labels[1]) if not disagreement: print(line)",
"= json.loads(line)['annotations'] if len(annotations) == 1: line = json.loads(line) line['annotations'] = [annotations[0]['label']] json.dump(line,",
"+ '\\t' + json.dumps(tweet_dict)) with database_path.open(mode='w', encoding='utf-8') as database: for line in data:",
"scheme: {}, please use 'sdqc' or 'claim'\" raise RuntimeError( err_msg.format(label_scheme)) with anno_data_path.open(encoding='utf-8') as",
"in database: not_altered = True tweet_dict = json.loads(line.split('\\t')[1]) for annotation in labeled_data: annotation",
"= True break if disagreement: break if not disagreement: line = json.loads(line) if",
"6: 'Unverified', 7: 'False'} if 1 or 2 not in annotation['annotations']: err_msg =",
"tweet) if label_scheme == 'sdqc': integrate_sdqc_label(annotation, tweet) not_altered = False break if not_altered:",
"json.loads(line.split('\\t')[1]) for annotation in labeled_data: annotation = json.loads(annotation) # Data-point not yet annotated",
"'Unverified', 7: 'False'} if 1 or 2 not in annotation['annotations']: err_msg = \"Error",
"if len(annotation['annotations']) > 1: err_msg = \"{} SDQC labels found, only one allowed\"",
"as database: for line in data: database.write(line) #anno_agreement_check(Path('test.json'), Path('agree.json'), Path('disagree.json')) #generate_label_data(test_data, 'stance.jsonl', 'claim.jsonl')",
"= 'Source: {}\\n\\nReply: {}'.format(source_tweet['full_text'], tweet['full_text']) tweet['labels'] = [] json.dump(tweet, stance_out) stance_out.write('\\n') def anno_agreement_check(anno_data_file:",
"for line in data: tweet_dict = json.loads(line.split('\\t')[1]) source_tweet = tweet_dict[line.split('\\t')[0]] source_tweet['text'] = source_tweet['full_text']",
"disagree_data.write(line) disagreement = True break if disagreement: break if not disagreement: line =",
"user_labels: line['annotations'] = list(user_labels[1]) if not disagreement: print(line) json.dump(line, agree_data) agree_data.write('\\n') def integrate_claim_label(annotation,",
"'True', 6: 'Unverified', 7: 'False'} if 1 or 2 not in annotation['annotations']: err_msg",
"str, claim_out_name: str): file_path = Path(unlabeled_data_path, file_name) stance_out_path = Path(unlabeled_data_path, stance_out_name) claim_out_path =",
"anno_data_path.open(encoding='utf-8') as anno_data, agree_path.open(mode='w', encoding='utf-8') as agree_data, disagree_path.open( mode='w', encoding='utf-8') as disagree_data: for",
"{}\\n\\nReply: {}'.format(source_tweet['full_text'], tweet['full_text']) tweet['labels'] = [] json.dump(tweet, stance_out) stance_out.write('\\n') def anno_agreement_check(anno_data_file: str, agree_file:",
"in claim labels, must contain either '1' or '2', denominating 'claim'\" \\ \"",
"annotation['text']: if label_scheme == 'claim': integrate_claim_label(annotation, tweet) if label_scheme == 'sdqc': integrate_sdqc_label(annotation, tweet)",
"stance_out_name) claim_out_path = Path(unlabeled_data_path, claim_out_name) with file_path.open() as data, stance_out_path.open(mode='w') as stance_out, claim_out_path.open(mode='w')",
"if source_tweet == tweet: continue tweet['text'] = 'Source: {}\\n\\nReply: {}'.format(source_tweet['full_text'], tweet['full_text']) tweet['labels'] =",
"from pathlib import Path current_path = os.path.abspath(__file__) default_raw_path = os.path.join(current_path, '../../data/datasets/twitter/raw/') unlabeled_data_path =",
"source_tweet['text'] = source_tweet['full_text'] source_tweet['labels'] = [] json.dump(source_tweet, claim_out) claim_out.write('\\n') for tweet_id, tweet in",
"stance_out_path.open(mode='w') as stance_out, claim_out_path.open(mode='w') as claim_out: for line in data: tweet_dict = json.loads(line.split('\\t')[1])",
"stance_out.write('\\n') def anno_agreement_check(anno_data_file: str, agree_file: str, disagree_file: str): anno_data_path = Path(os.path.join(default_raw_path, anno_data_file)) agree_path",
"mode='w', encoding='utf-8') as disagree_data: for line in anno_data: disagreement = False annotations =",
"tweet['labels'] = [] json.dump(tweet, stance_out) stance_out.write('\\n') def anno_agreement_check(anno_data_file: str, agree_file: str, disagree_file: str):",
"if user_labels: line['annotations'] = list(user_labels[1]) if not disagreement: print(line) json.dump(line, agree_data) agree_data.write('\\n') def",
"if tweet['full_text'] == annotation['text']: if label_scheme == 'claim': integrate_claim_label(annotation, tweet) if label_scheme ==",
"'Denying', 3: 'Querying', 4: 'Commenting'} if len(annotation['annotations']) > 1: err_msg = \"{} SDQC",
"for annotation in annotations: user_labels.setdefault(annotation['user'], set()).add(annotation['label']) for user_id_a, labels_a in user_labels.items(): for user_id_b,",
"if 2 in annotation['annotations']: tweet['Claim'] = False else: tweet['Claim'] = True if 3",
"'5', '6' or '7', \" \\ \"denominating 'True', 'Unverified' and 'False' respectively. Given",
"5 or 6 or 7 not in annotation['annotations']: err_msg = \"Error in claim",
"with database_path.open(mode='w', encoding='utf-8') as database: for line in data: database.write(line) #anno_agreement_check(Path('test.json'), Path('agree.json'), Path('disagree.json'))",
"respectively. Given labels: {}\" raise RuntimeError( err_msg.format(annotation['annotations'])) if 4 in annotation['annotations']: tweet['Verifiability'] =",
"or 7 not in annotation['annotations']: err_msg = \"Error in claim labels, must contain",
"'\\t' + json.dumps(tweet_dict)) with database_path.open(mode='w', encoding='utf-8') as database: for line in data: database.write(line)",
"label_scheme not in ['claim', 'sdqc']: err_msg = \"Unrecognized label scheme: {}, please use",
"False else: tweet['Claim'] = True if 3 or 4 not in annotation['annotations']: err_msg",
"claim_out_path = Path(unlabeled_data_path, claim_out_name) with file_path.open() as data, stance_out_path.open(mode='w') as stance_out, claim_out_path.open(mode='w') as",
"err_msg = \"{} SDQC labels found, only one allowed\" raise RuntimeError( err_msg.format(len(annotation['annotations']))) tweet['SDQC_Submission']",
"anno_data_path = Path(os.path.join(default_raw_path, anno_data_file)) agree_path = Path(os.path.join(default_raw_path, agree_file)) disagree_path = Path(os.path.join(default_raw_path, disagree_file)) with",
"line['annotations'] = list(user_labels[1]) if not disagreement: print(line) json.dump(line, agree_data) agree_data.write('\\n') def integrate_claim_label(annotation, tweet):",
"claim labels, must contain either '5', '6' or '7', \" \\ \"denominating 'True',",
"disagree_data: for line in anno_data: disagreement = False annotations = json.loads(line)['annotations'] if len(annotations)",
"in tweet_dict.items(): if tweet['full_text'] == annotation['text']: if label_scheme == 'claim': integrate_claim_label(annotation, tweet) if",
"pathlib import Path current_path = os.path.abspath(__file__) default_raw_path = os.path.join(current_path, '../../data/datasets/twitter/raw/') unlabeled_data_path = Path(os.path.join(os.path.abspath(__file__),",
"agree_data.write('\\n') else: user_labels = {} for annotation in annotations: user_labels.setdefault(annotation['user'], set()).add(annotation['label']) for user_id_a,",
"'claim'\" raise RuntimeError( err_msg.format(label_scheme)) with anno_data_path.open(encoding='utf-8') as labeled_data, database_path.open(encoding='utf-8') as database: data =",
"disagreement = False annotations = json.loads(line)['annotations'] if len(annotations) == 1: line = json.loads(line)",
"in labeled_data: annotation = json.loads(annotation) # Data-point not yet annotated if not annotation['annotations']:",
"'Commenting'} if len(annotation['annotations']) > 1: err_msg = \"{} SDQC labels found, only one",
"labeled_data, database_path.open(encoding='utf-8') as database: data = [] for line in database: not_altered =",
"respectively. Given \" \\ \"labels: {}\" raise RuntimeError( err_msg.format(annotation['annotations'])) for x in [5,",
"import Path current_path = os.path.abspath(__file__) default_raw_path = os.path.join(current_path, '../../data/datasets/twitter/raw/') unlabeled_data_path = Path(os.path.join(os.path.abspath(__file__), '../../../data/datasets/twitter/raw/unlabeled'))",
"= {} for annotation in annotations: user_labels.setdefault(annotation['user'], set()).add(annotation['label']) for user_id_a, labels_a in user_labels.items():",
"agree_path = Path(os.path.join(default_raw_path, agree_file)) disagree_path = Path(os.path.join(default_raw_path, disagree_file)) with anno_data_path.open(encoding='utf-8') as anno_data, agree_path.open(mode='w',",
"Path(unlabeled_data_path, stance_out_name) claim_out_path = Path(unlabeled_data_path, claim_out_name) with file_path.open() as data, stance_out_path.open(mode='w') as stance_out,",
"or '7', \" \\ \"denominating 'True', 'Unverified' and 'False' respectively. Given \" \\",
"and 'subjective' respectively. Given labels: {}\" raise RuntimeError( err_msg.format(annotation['annotations'])) if 4 in annotation['annotations']:",
"tweet['full_text'] == annotation['text']: if label_scheme == 'claim': integrate_claim_label(annotation, tweet) if label_scheme == 'sdqc':",
"'2', denominating 'claim'\" \\ \" and 'non-claim' respectively. Given labels: {}\" raise RuntimeError(",
"tweet_dict.items(): if source_tweet == tweet: continue tweet['text'] = 'Source: {}\\n\\nReply: {}'.format(source_tweet['full_text'], tweet['full_text']) tweet['labels']",
"tweet['SDQC_Submission'] = sdqc_map[annotation['annotations'][0]] def integrate_label_data(anno_data_path: Path, database_path: Path, label_scheme: str): if label_scheme not",
"in annotation['annotations']: tweet['Verifiability'] = 'Subjective' else: tweet['Verifiability'] = 'Verifiable' if 5 or 6",
"= json.loads(line.split('\\t')[1]) source_tweet = tweet_dict[line.split('\\t')[0]] source_tweet['text'] = source_tweet['full_text'] source_tweet['labels'] = [] json.dump(source_tweet, claim_out)",
"break if disagreement: break if not disagreement: line = json.loads(line) if user_labels: line['annotations']",
"claim labels, must contain either '3' or '4', denominating \" \\ \"'verifiable' and",
"in user_labels.items(): for user_id_b, labels_b in user_labels.items(): if labels_a != labels_b: disagree_data.write(line) disagreement",
"as database: data = [] for line in database: not_altered = True tweet_dict",
"= [] for line in database: not_altered = True tweet_dict = json.loads(line.split('\\t')[1]) for",
"in annotation['annotations']: tweet['Claim'] = False else: tweet['Claim'] = True if 3 or 4",
"if not_altered: data.append(line) else: data.append(line.split('\\t')[0] + '\\t' + json.dumps(tweet_dict)) with database_path.open(mode='w', encoding='utf-8') as",
"integrate_claim_label(annotation, tweet): veracity_map = {5: 'True', 6: 'Unverified', 7: 'False'} if 1 or",
"for tweet_id, tweet in tweet_dict.items(): if tweet['full_text'] == annotation['text']: if label_scheme == 'claim':",
"found, only one allowed\" raise RuntimeError( err_msg.format(len(annotation['annotations']))) tweet['SDQC_Submission'] = sdqc_map[annotation['annotations'][0]] def integrate_label_data(anno_data_path: Path,",
"not annotation['annotations']: continue for tweet_id, tweet in tweet_dict.items(): if tweet['full_text'] == annotation['text']: if",
"data.append(line.split('\\t')[0] + '\\t' + json.dumps(tweet_dict)) with database_path.open(mode='w', encoding='utf-8') as database: for line in",
"tweet['Verifiability'] = 'Verifiable' if 5 or 6 or 7 not in annotation['annotations']: err_msg",
"False break if not_altered: data.append(line) else: data.append(line.split('\\t')[0] + '\\t' + json.dumps(tweet_dict)) with database_path.open(mode='w',",
"user_labels.items(): if labels_a != labels_b: disagree_data.write(line) disagreement = True break if disagreement: break",
"or 4 not in annotation['annotations']: err_msg = \"Error in claim labels, must contain",
"tweet['full_text']) tweet['labels'] = [] json.dump(tweet, stance_out) stance_out.write('\\n') def anno_agreement_check(anno_data_file: str, agree_file: str, disagree_file:",
"tweet) not_altered = False break if not_altered: data.append(line) else: data.append(line.split('\\t')[0] + '\\t' +",
"labeled_data: annotation = json.loads(annotation) # Data-point not yet annotated if not annotation['annotations']: continue",
"data, stance_out_path.open(mode='w') as stance_out, claim_out_path.open(mode='w') as claim_out: for line in data: tweet_dict =",
"line['annotations'] = [annotations[0]['label']] json.dump(line, agree_data) agree_data.write('\\n') else: user_labels = {} for annotation in",
"as agree_data, disagree_path.open( mode='w', encoding='utf-8') as disagree_data: for line in anno_data: disagreement =",
"annotation['annotations']: err_msg = \"Error in claim labels, must contain either '5', '6' or",
"tweet: continue tweet['text'] = 'Source: {}\\n\\nReply: {}'.format(source_tweet['full_text'], tweet['full_text']) tweet['labels'] = [] json.dump(tweet, stance_out)",
"Path(unlabeled_data_path, file_name) stance_out_path = Path(unlabeled_data_path, stance_out_name) claim_out_path = Path(unlabeled_data_path, claim_out_name) with file_path.open() as",
"import json import os from pathlib import Path current_path = os.path.abspath(__file__) default_raw_path =",
"else: tweet['Claim'] = True if 3 or 4 not in annotation['annotations']: err_msg =",
"= \"{} SDQC labels found, only one allowed\" raise RuntimeError( err_msg.format(len(annotation['annotations']))) tweet['SDQC_Submission'] =",
"True break if disagreement: break if not disagreement: line = json.loads(line) if user_labels:",
"import os from pathlib import Path current_path = os.path.abspath(__file__) default_raw_path = os.path.join(current_path, '../../data/datasets/twitter/raw/')",
"json.loads(annotation) # Data-point not yet annotated if not annotation['annotations']: continue for tweet_id, tweet",
"if not annotation['annotations']: continue for tweet_id, tweet in tweet_dict.items(): if tweet['full_text'] == annotation['text']:",
"= \"Error in claim labels, must contain either '1' or '2', denominating 'claim'\"",
"else: user_labels = {} for annotation in annotations: user_labels.setdefault(annotation['user'], set()).add(annotation['label']) for user_id_a, labels_a",
"data: tweet_dict = json.loads(line.split('\\t')[1]) source_tweet = tweet_dict[line.split('\\t')[0]] source_tweet['text'] = source_tweet['full_text'] source_tweet['labels'] = []",
"contain either '5', '6' or '7', \" \\ \"denominating 'True', 'Unverified' and 'False'",
"and 'False' respectively. Given \" \\ \"labels: {}\" raise RuntimeError( err_msg.format(annotation['annotations'])) for x",
"current_path = os.path.abspath(__file__) default_raw_path = os.path.join(current_path, '../../data/datasets/twitter/raw/') unlabeled_data_path = Path(os.path.join(os.path.abspath(__file__), '../../../data/datasets/twitter/raw/unlabeled')) def generate_label_data(file_name:",
"in annotation['annotations']: err_msg = \"Error in claim labels, must contain either '5', '6'",
"with anno_data_path.open(encoding='utf-8') as labeled_data, database_path.open(encoding='utf-8') as database: data = [] for line in",
"annotations: user_labels.setdefault(annotation['user'], set()).add(annotation['label']) for user_id_a, labels_a in user_labels.items(): for user_id_b, labels_b in user_labels.items():",
"database: not_altered = True tweet_dict = json.loads(line.split('\\t')[1]) for annotation in labeled_data: annotation =",
"denominating 'claim'\" \\ \" and 'non-claim' respectively. Given labels: {}\" raise RuntimeError( err_msg.format(annotation['annotations']))",
"integrate_claim_label(annotation, tweet) if label_scheme == 'sdqc': integrate_sdqc_label(annotation, tweet) not_altered = False break if",
"agree_file)) disagree_path = Path(os.path.join(default_raw_path, disagree_file)) with anno_data_path.open(encoding='utf-8') as anno_data, agree_path.open(mode='w', encoding='utf-8') as agree_data,",
"= \"Error in claim labels, must contain either '5', '6' or '7', \"",
"== 1: line = json.loads(line) line['annotations'] = [annotations[0]['label']] json.dump(line, agree_data) agree_data.write('\\n') else: user_labels",
"'1' or '2', denominating 'claim'\" \\ \" and 'non-claim' respectively. Given labels: {}\"",
"tweet['Claim'] = True if 3 or 4 not in annotation['annotations']: err_msg = \"Error",
"'False' respectively. Given \" \\ \"labels: {}\" raise RuntimeError( err_msg.format(annotation['annotations'])) for x in",
"anno_data, agree_path.open(mode='w', encoding='utf-8') as agree_data, disagree_path.open( mode='w', encoding='utf-8') as disagree_data: for line in",
"Given \" \\ \"labels: {}\" raise RuntimeError( err_msg.format(annotation['annotations'])) for x in [5, 6,",
"not_altered: data.append(line) else: data.append(line.split('\\t')[0] + '\\t' + json.dumps(tweet_dict)) with database_path.open(mode='w', encoding='utf-8') as database:",
"as anno_data, agree_path.open(mode='w', encoding='utf-8') as agree_data, disagree_path.open( mode='w', encoding='utf-8') as disagree_data: for line",
"str, stance_out_name: str, claim_out_name: str): file_path = Path(unlabeled_data_path, file_name) stance_out_path = Path(unlabeled_data_path, stance_out_name)",
"not in annotation['annotations']: err_msg = \"Error in claim labels, must contain either '1'",
"Path(unlabeled_data_path, claim_out_name) with file_path.open() as data, stance_out_path.open(mode='w') as stance_out, claim_out_path.open(mode='w') as claim_out: for",
"'Querying', 4: 'Commenting'} if len(annotation['annotations']) > 1: err_msg = \"{} SDQC labels found,",
"\"denominating 'True', 'Unverified' and 'False' respectively. Given \" \\ \"labels: {}\" raise RuntimeError(",
"'3' or '4', denominating \" \\ \"'verifiable' and 'subjective' respectively. Given labels: {}\"",
"continue for tweet_id, tweet in tweet_dict.items(): if tweet['full_text'] == annotation['text']: if label_scheme ==",
"not_altered = False break if not_altered: data.append(line) else: data.append(line.split('\\t')[0] + '\\t' + json.dumps(tweet_dict))",
"1 or 2 not in annotation['annotations']: err_msg = \"Error in claim labels, must",
"'Verifiable' if 5 or 6 or 7 not in annotation['annotations']: err_msg = \"Error",
"= Path(os.path.join(default_raw_path, agree_file)) disagree_path = Path(os.path.join(default_raw_path, disagree_file)) with anno_data_path.open(encoding='utf-8') as anno_data, agree_path.open(mode='w', encoding='utf-8')",
"== tweet: continue tweet['text'] = 'Source: {}\\n\\nReply: {}'.format(source_tweet['full_text'], tweet['full_text']) tweet['labels'] = [] json.dump(tweet,",
"'claim'\" \\ \" and 'non-claim' respectively. Given labels: {}\" raise RuntimeError( err_msg.format(annotation['annotations'])) if",
"denominating \" \\ \"'verifiable' and 'subjective' respectively. Given labels: {}\" raise RuntimeError( err_msg.format(annotation['annotations']))",
"tweet in tweet_dict.items(): if source_tweet == tweet: continue tweet['text'] = 'Source: {}\\n\\nReply: {}'.format(source_tweet['full_text'],",
"[] for line in database: not_altered = True tweet_dict = json.loads(line.split('\\t')[1]) for annotation",
"annotation = json.loads(annotation) # Data-point not yet annotated if not annotation['annotations']: continue for",
"Given labels: {}\" raise RuntimeError( err_msg.format(annotation['annotations'])) if 2 in annotation['annotations']: tweet['Claim'] = False",
"'../../../data/datasets/twitter/raw/unlabeled')) def generate_label_data(file_name: str, stance_out_name: str, claim_out_name: str): file_path = Path(unlabeled_data_path, file_name) stance_out_path",
"['claim', 'sdqc']: err_msg = \"Unrecognized label scheme: {}, please use 'sdqc' or 'claim'\"",
"annotation['annotations']: tweet['Verifiability'] = 'Subjective' else: tweet['Verifiability'] = 'Verifiable' if 5 or 6 or",
"for line in anno_data: disagreement = False annotations = json.loads(line)['annotations'] if len(annotations) ==",
"annotation['annotations']: tweet['TruthStatus'] = veracity_map[x] def integrate_sdqc_label(annotation, tweet): sdqc_map = {1: 'Supporting', 2: 'Denying',",
"tweet['Claim'] = False else: tweet['Claim'] = True if 3 or 4 not in",
"as disagree_data: for line in anno_data: disagreement = False annotations = json.loads(line)['annotations'] if",
"or '2', denominating 'claim'\" \\ \" and 'non-claim' respectively. Given labels: {}\" raise",
"agree_path.open(mode='w', encoding='utf-8') as agree_data, disagree_path.open( mode='w', encoding='utf-8') as disagree_data: for line in anno_data:",
"in [5, 6, 7]: if x in annotation['annotations']: tweet['TruthStatus'] = veracity_map[x] def integrate_sdqc_label(annotation,",
"labels found, only one allowed\" raise RuntimeError( err_msg.format(len(annotation['annotations']))) tweet['SDQC_Submission'] = sdqc_map[annotation['annotations'][0]] def integrate_label_data(anno_data_path:",
"user_labels = {} for annotation in annotations: user_labels.setdefault(annotation['user'], set()).add(annotation['label']) for user_id_a, labels_a in",
"2 not in annotation['annotations']: err_msg = \"Error in claim labels, must contain either",
"'sdqc' or 'claim'\" raise RuntimeError( err_msg.format(label_scheme)) with anno_data_path.open(encoding='utf-8') as labeled_data, database_path.open(encoding='utf-8') as database:",
"allowed\" raise RuntimeError( err_msg.format(len(annotation['annotations']))) tweet['SDQC_Submission'] = sdqc_map[annotation['annotations'][0]] def integrate_label_data(anno_data_path: Path, database_path: Path, label_scheme:",
"= [annotations[0]['label']] json.dump(line, agree_data) agree_data.write('\\n') else: user_labels = {} for annotation in annotations:",
"json.dump(source_tweet, claim_out) claim_out.write('\\n') for tweet_id, tweet in tweet_dict.items(): if source_tweet == tweet: continue",
"contain either '3' or '4', denominating \" \\ \"'verifiable' and 'subjective' respectively. Given",
"SDQC labels found, only one allowed\" raise RuntimeError( err_msg.format(len(annotation['annotations']))) tweet['SDQC_Submission'] = sdqc_map[annotation['annotations'][0]] def",
"default_raw_path = os.path.join(current_path, '../../data/datasets/twitter/raw/') unlabeled_data_path = Path(os.path.join(os.path.abspath(__file__), '../../../data/datasets/twitter/raw/unlabeled')) def generate_label_data(file_name: str, stance_out_name: str,",
"as stance_out, claim_out_path.open(mode='w') as claim_out: for line in data: tweet_dict = json.loads(line.split('\\t')[1]) source_tweet",
"err_msg = \"Unrecognized label scheme: {}, please use 'sdqc' or 'claim'\" raise RuntimeError(",
"not in annotation['annotations']: err_msg = \"Error in claim labels, must contain either '5',",
"in ['claim', 'sdqc']: err_msg = \"Unrecognized label scheme: {}, please use 'sdqc' or",
"RuntimeError( err_msg.format(annotation['annotations'])) if 4 in annotation['annotations']: tweet['Verifiability'] = 'Subjective' else: tweet['Verifiability'] = 'Verifiable'",
"\"Error in claim labels, must contain either '5', '6' or '7', \" \\",
"== annotation['text']: if label_scheme == 'claim': integrate_claim_label(annotation, tweet) if label_scheme == 'sdqc': integrate_sdqc_label(annotation,",
"'Source: {}\\n\\nReply: {}'.format(source_tweet['full_text'], tweet['full_text']) tweet['labels'] = [] json.dump(tweet, stance_out) stance_out.write('\\n') def anno_agreement_check(anno_data_file: str,",
"integrate_sdqc_label(annotation, tweet): sdqc_map = {1: 'Supporting', 2: 'Denying', 3: 'Querying', 4: 'Commenting'} if",
"> 1: err_msg = \"{} SDQC labels found, only one allowed\" raise RuntimeError(",
"data = [] for line in database: not_altered = True tweet_dict = json.loads(line.split('\\t')[1])",
"if label_scheme == 'claim': integrate_claim_label(annotation, tweet) if label_scheme == 'sdqc': integrate_sdqc_label(annotation, tweet) not_altered",
"len(annotation['annotations']) > 1: err_msg = \"{} SDQC labels found, only one allowed\" raise",
"set()).add(annotation['label']) for user_id_a, labels_a in user_labels.items(): for user_id_b, labels_b in user_labels.items(): if labels_a",
"and 'non-claim' respectively. Given labels: {}\" raise RuntimeError( err_msg.format(annotation['annotations'])) if 2 in annotation['annotations']:",
"os.path.join(current_path, '../../data/datasets/twitter/raw/') unlabeled_data_path = Path(os.path.join(os.path.abspath(__file__), '../../../data/datasets/twitter/raw/unlabeled')) def generate_label_data(file_name: str, stance_out_name: str, claim_out_name: str):",
"Path, label_scheme: str): if label_scheme not in ['claim', 'sdqc']: err_msg = \"Unrecognized label",
"if len(annotations) == 1: line = json.loads(line) line['annotations'] = [annotations[0]['label']] json.dump(line, agree_data) agree_data.write('\\n')",
"= \"Unrecognized label scheme: {}, please use 'sdqc' or 'claim'\" raise RuntimeError( err_msg.format(label_scheme))",
"RuntimeError( err_msg.format(annotation['annotations'])) for x in [5, 6, 7]: if x in annotation['annotations']: tweet['TruthStatus']",
"{}\" raise RuntimeError( err_msg.format(annotation['annotations'])) for x in [5, 6, 7]: if x in",
"json.loads(line) line['annotations'] = [annotations[0]['label']] json.dump(line, agree_data) agree_data.write('\\n') else: user_labels = {} for annotation",
"str): if label_scheme not in ['claim', 'sdqc']: err_msg = \"Unrecognized label scheme: {},",
"tweet['Verifiability'] = 'Subjective' else: tweet['Verifiability'] = 'Verifiable' if 5 or 6 or 7",
"not disagreement: print(line) json.dump(line, agree_data) agree_data.write('\\n') def integrate_claim_label(annotation, tweet): veracity_map = {5: 'True',",
"True tweet_dict = json.loads(line.split('\\t')[1]) for annotation in labeled_data: annotation = json.loads(annotation) # Data-point",
"in user_labels.items(): if labels_a != labels_b: disagree_data.write(line) disagreement = True break if disagreement:",
"for line in database: not_altered = True tweet_dict = json.loads(line.split('\\t')[1]) for annotation in",
"{1: 'Supporting', 2: 'Denying', 3: 'Querying', 4: 'Commenting'} if len(annotation['annotations']) > 1: err_msg",
"Path current_path = os.path.abspath(__file__) default_raw_path = os.path.join(current_path, '../../data/datasets/twitter/raw/') unlabeled_data_path = Path(os.path.join(os.path.abspath(__file__), '../../../data/datasets/twitter/raw/unlabeled')) def",
"= list(user_labels[1]) if not disagreement: print(line) json.dump(line, agree_data) agree_data.write('\\n') def integrate_claim_label(annotation, tweet): veracity_map",
"for annotation in labeled_data: annotation = json.loads(annotation) # Data-point not yet annotated if",
"or 6 or 7 not in annotation['annotations']: err_msg = \"Error in claim labels,",
"json.loads(line) if user_labels: line['annotations'] = list(user_labels[1]) if not disagreement: print(line) json.dump(line, agree_data) agree_data.write('\\n')",
"json import os from pathlib import Path current_path = os.path.abspath(__file__) default_raw_path = os.path.join(current_path,",
"continue tweet['text'] = 'Source: {}\\n\\nReply: {}'.format(source_tweet['full_text'], tweet['full_text']) tweet['labels'] = [] json.dump(tweet, stance_out) stance_out.write('\\n')",
"= json.loads(line.split('\\t')[1]) for annotation in labeled_data: annotation = json.loads(annotation) # Data-point not yet",
"'sdqc']: err_msg = \"Unrecognized label scheme: {}, please use 'sdqc' or 'claim'\" raise",
"tweet in tweet_dict.items(): if tweet['full_text'] == annotation['text']: if label_scheme == 'claim': integrate_claim_label(annotation, tweet)",
"\" \\ \"'verifiable' and 'subjective' respectively. Given labels: {}\" raise RuntimeError( err_msg.format(annotation['annotations'])) if",
"as labeled_data, database_path.open(encoding='utf-8') as database: data = [] for line in database: not_altered",
"claim_out: for line in data: tweet_dict = json.loads(line.split('\\t')[1]) source_tweet = tweet_dict[line.split('\\t')[0]] source_tweet['text'] =",
"as claim_out: for line in data: tweet_dict = json.loads(line.split('\\t')[1]) source_tweet = tweet_dict[line.split('\\t')[0]] source_tweet['text']",
"'subjective' respectively. Given labels: {}\" raise RuntimeError( err_msg.format(annotation['annotations'])) if 4 in annotation['annotations']: tweet['Verifiability']",
"tweet['TruthStatus'] = veracity_map[x] def integrate_sdqc_label(annotation, tweet): sdqc_map = {1: 'Supporting', 2: 'Denying', 3:",
"in anno_data: disagreement = False annotations = json.loads(line)['annotations'] if len(annotations) == 1: line",
"please use 'sdqc' or 'claim'\" raise RuntimeError( err_msg.format(label_scheme)) with anno_data_path.open(encoding='utf-8') as labeled_data, database_path.open(encoding='utf-8')",
"line in anno_data: disagreement = False annotations = json.loads(line)['annotations'] if len(annotations) == 1:",
"annotation['annotations']: tweet['Claim'] = False else: tweet['Claim'] = True if 3 or 4 not",
"Data-point not yet annotated if not annotation['annotations']: continue for tweet_id, tweet in tweet_dict.items():",
"tweet_id, tweet in tweet_dict.items(): if source_tweet == tweet: continue tweet['text'] = 'Source: {}\\n\\nReply:",
"= source_tweet['full_text'] source_tweet['labels'] = [] json.dump(source_tweet, claim_out) claim_out.write('\\n') for tweet_id, tweet in tweet_dict.items():",
"claim_out_name: str): file_path = Path(unlabeled_data_path, file_name) stance_out_path = Path(unlabeled_data_path, stance_out_name) claim_out_path = Path(unlabeled_data_path,",
"\\ \"'verifiable' and 'subjective' respectively. Given labels: {}\" raise RuntimeError( err_msg.format(annotation['annotations'])) if 4",
"if disagreement: break if not disagreement: line = json.loads(line) if user_labels: line['annotations'] =",
"if label_scheme == 'sdqc': integrate_sdqc_label(annotation, tweet) not_altered = False break if not_altered: data.append(line)",
"if labels_a != labels_b: disagree_data.write(line) disagreement = True break if disagreement: break if",
"[] json.dump(tweet, stance_out) stance_out.write('\\n') def anno_agreement_check(anno_data_file: str, agree_file: str, disagree_file: str): anno_data_path =",
"if label_scheme not in ['claim', 'sdqc']: err_msg = \"Unrecognized label scheme: {}, please",
"list(user_labels[1]) if not disagreement: print(line) json.dump(line, agree_data) agree_data.write('\\n') def integrate_claim_label(annotation, tweet): veracity_map =",
"in claim labels, must contain either '5', '6' or '7', \" \\ \"denominating",
"str, disagree_file: str): anno_data_path = Path(os.path.join(default_raw_path, anno_data_file)) agree_path = Path(os.path.join(default_raw_path, agree_file)) disagree_path =",
"label scheme: {}, please use 'sdqc' or 'claim'\" raise RuntimeError( err_msg.format(label_scheme)) with anno_data_path.open(encoding='utf-8')",
"json.dumps(tweet_dict)) with database_path.open(mode='w', encoding='utf-8') as database: for line in data: database.write(line) #anno_agreement_check(Path('test.json'), Path('agree.json'),",
"else: data.append(line.split('\\t')[0] + '\\t' + json.dumps(tweet_dict)) with database_path.open(mode='w', encoding='utf-8') as database: for line",
"encoding='utf-8') as agree_data, disagree_path.open( mode='w', encoding='utf-8') as disagree_data: for line in anno_data: disagreement",
"err_msg.format(annotation['annotations'])) for x in [5, 6, 7]: if x in annotation['annotations']: tweet['TruthStatus'] =",
"not disagreement: line = json.loads(line) if user_labels: line['annotations'] = list(user_labels[1]) if not disagreement:",
"use 'sdqc' or 'claim'\" raise RuntimeError( err_msg.format(label_scheme)) with anno_data_path.open(encoding='utf-8') as labeled_data, database_path.open(encoding='utf-8') as",
"\\ \"labels: {}\" raise RuntimeError( err_msg.format(annotation['annotations'])) for x in [5, 6, 7]: if",
"tweet): sdqc_map = {1: 'Supporting', 2: 'Denying', 3: 'Querying', 4: 'Commenting'} if len(annotation['annotations'])",
"not_altered = True tweet_dict = json.loads(line.split('\\t')[1]) for annotation in labeled_data: annotation = json.loads(annotation)",
"= Path(os.path.join(os.path.abspath(__file__), '../../../data/datasets/twitter/raw/unlabeled')) def generate_label_data(file_name: str, stance_out_name: str, claim_out_name: str): file_path = Path(unlabeled_data_path,",
"not in annotation['annotations']: err_msg = \"Error in claim labels, must contain either '3'",
"stance_out_name: str, claim_out_name: str): file_path = Path(unlabeled_data_path, file_name) stance_out_path = Path(unlabeled_data_path, stance_out_name) claim_out_path",
"must contain either '5', '6' or '7', \" \\ \"denominating 'True', 'Unverified' and",
"Path(os.path.join(default_raw_path, disagree_file)) with anno_data_path.open(encoding='utf-8') as anno_data, agree_path.open(mode='w', encoding='utf-8') as agree_data, disagree_path.open( mode='w', encoding='utf-8')",
"anno_data_file)) agree_path = Path(os.path.join(default_raw_path, agree_file)) disagree_path = Path(os.path.join(default_raw_path, disagree_file)) with anno_data_path.open(encoding='utf-8') as anno_data,",
"labels, must contain either '5', '6' or '7', \" \\ \"denominating 'True', 'Unverified'",
"4: 'Commenting'} if len(annotation['annotations']) > 1: err_msg = \"{} SDQC labels found, only",
"\"'verifiable' and 'subjective' respectively. Given labels: {}\" raise RuntimeError( err_msg.format(annotation['annotations'])) if 4 in",
"err_msg = \"Error in claim labels, must contain either '5', '6' or '7',",
"generate_label_data(file_name: str, stance_out_name: str, claim_out_name: str): file_path = Path(unlabeled_data_path, file_name) stance_out_path = Path(unlabeled_data_path,",
"labels_a in user_labels.items(): for user_id_b, labels_b in user_labels.items(): if labels_a != labels_b: disagree_data.write(line)",
"= 'Verifiable' if 5 or 6 or 7 not in annotation['annotations']: err_msg =",
"\" and 'non-claim' respectively. Given labels: {}\" raise RuntimeError( err_msg.format(annotation['annotations'])) if 2 in",
"= json.loads(line) if user_labels: line['annotations'] = list(user_labels[1]) if not disagreement: print(line) json.dump(line, agree_data)",
"source_tweet = tweet_dict[line.split('\\t')[0]] source_tweet['text'] = source_tweet['full_text'] source_tweet['labels'] = [] json.dump(source_tweet, claim_out) claim_out.write('\\n') for",
"labels_b: disagree_data.write(line) disagreement = True break if disagreement: break if not disagreement: line",
"\\ \" and 'non-claim' respectively. Given labels: {}\" raise RuntimeError( err_msg.format(annotation['annotations'])) if 2",
"= Path(os.path.join(default_raw_path, disagree_file)) with anno_data_path.open(encoding='utf-8') as anno_data, agree_path.open(mode='w', encoding='utf-8') as agree_data, disagree_path.open( mode='w',",
"= False break if not_altered: data.append(line) else: data.append(line.split('\\t')[0] + '\\t' + json.dumps(tweet_dict)) with",
"break if not_altered: data.append(line) else: data.append(line.split('\\t')[0] + '\\t' + json.dumps(tweet_dict)) with database_path.open(mode='w', encoding='utf-8')",
"in tweet_dict.items(): if source_tweet == tweet: continue tweet['text'] = 'Source: {}\\n\\nReply: {}'.format(source_tweet['full_text'], tweet['full_text'])",
"= veracity_map[x] def integrate_sdqc_label(annotation, tweet): sdqc_map = {1: 'Supporting', 2: 'Denying', 3: 'Querying',",
"1: line = json.loads(line) line['annotations'] = [annotations[0]['label']] json.dump(line, agree_data) agree_data.write('\\n') else: user_labels =",
"claim_out_name) with file_path.open() as data, stance_out_path.open(mode='w') as stance_out, claim_out_path.open(mode='w') as claim_out: for line",
"claim labels, must contain either '1' or '2', denominating 'claim'\" \\ \" and",
"'non-claim' respectively. Given labels: {}\" raise RuntimeError( err_msg.format(annotation['annotations'])) if 2 in annotation['annotations']: tweet['Claim']",
"sdqc_map = {1: 'Supporting', 2: 'Denying', 3: 'Querying', 4: 'Commenting'} if len(annotation['annotations']) >",
"stance_out, claim_out_path.open(mode='w') as claim_out: for line in data: tweet_dict = json.loads(line.split('\\t')[1]) source_tweet =",
"= os.path.abspath(__file__) default_raw_path = os.path.join(current_path, '../../data/datasets/twitter/raw/') unlabeled_data_path = Path(os.path.join(os.path.abspath(__file__), '../../../data/datasets/twitter/raw/unlabeled')) def generate_label_data(file_name: str,",
"def anno_agreement_check(anno_data_file: str, agree_file: str, disagree_file: str): anno_data_path = Path(os.path.join(default_raw_path, anno_data_file)) agree_path =",
"veracity_map = {5: 'True', 6: 'Unverified', 7: 'False'} if 1 or 2 not",
"= \"Error in claim labels, must contain either '3' or '4', denominating \"",
"x in annotation['annotations']: tweet['TruthStatus'] = veracity_map[x] def integrate_sdqc_label(annotation, tweet): sdqc_map = {1: 'Supporting',",
"str, agree_file: str, disagree_file: str): anno_data_path = Path(os.path.join(default_raw_path, anno_data_file)) agree_path = Path(os.path.join(default_raw_path, agree_file))",
"tweet): veracity_map = {5: 'True', 6: 'Unverified', 7: 'False'} if 1 or 2",
"Path, database_path: Path, label_scheme: str): if label_scheme not in ['claim', 'sdqc']: err_msg =",
"labels: {}\" raise RuntimeError( err_msg.format(annotation['annotations'])) if 2 in annotation['annotations']: tweet['Claim'] = False else:",
"= {5: 'True', 6: 'Unverified', 7: 'False'} if 1 or 2 not in",
"= tweet_dict[line.split('\\t')[0]] source_tweet['text'] = source_tweet['full_text'] source_tweet['labels'] = [] json.dump(source_tweet, claim_out) claim_out.write('\\n') for tweet_id,",
"annotation['annotations']: err_msg = \"Error in claim labels, must contain either '1' or '2',",
"6, 7]: if x in annotation['annotations']: tweet['TruthStatus'] = veracity_map[x] def integrate_sdqc_label(annotation, tweet): sdqc_map",
"line = json.loads(line) if user_labels: line['annotations'] = list(user_labels[1]) if not disagreement: print(line) json.dump(line,",
"json.dump(tweet, stance_out) stance_out.write('\\n') def anno_agreement_check(anno_data_file: str, agree_file: str, disagree_file: str): anno_data_path = Path(os.path.join(default_raw_path,",
"annotation['annotations']: err_msg = \"Error in claim labels, must contain either '3' or '4',",
"= json.loads(annotation) # Data-point not yet annotated if not annotation['annotations']: continue for tweet_id,",
"for user_id_a, labels_a in user_labels.items(): for user_id_b, labels_b in user_labels.items(): if labels_a !=",
"Given labels: {}\" raise RuntimeError( err_msg.format(annotation['annotations'])) if 4 in annotation['annotations']: tweet['Verifiability'] = 'Subjective'",
"label_scheme == 'claim': integrate_claim_label(annotation, tweet) if label_scheme == 'sdqc': integrate_sdqc_label(annotation, tweet) not_altered =",
"if not disagreement: line = json.loads(line) if user_labels: line['annotations'] = list(user_labels[1]) if not",
"def integrate_claim_label(annotation, tweet): veracity_map = {5: 'True', 6: 'Unverified', 7: 'False'} if 1",
"if not disagreement: print(line) json.dump(line, agree_data) agree_data.write('\\n') def integrate_claim_label(annotation, tweet): veracity_map = {5:",
"'claim': integrate_claim_label(annotation, tweet) if label_scheme == 'sdqc': integrate_sdqc_label(annotation, tweet) not_altered = False break",
"anno_data: disagreement = False annotations = json.loads(line)['annotations'] if len(annotations) == 1: line =",
"encoding='utf-8') as disagree_data: for line in anno_data: disagreement = False annotations = json.loads(line)['annotations']",
"= sdqc_map[annotation['annotations'][0]] def integrate_label_data(anno_data_path: Path, database_path: Path, label_scheme: str): if label_scheme not in",
"with file_path.open() as data, stance_out_path.open(mode='w') as stance_out, claim_out_path.open(mode='w') as claim_out: for line in",
"tweet['text'] = 'Source: {}\\n\\nReply: {}'.format(source_tweet['full_text'], tweet['full_text']) tweet['labels'] = [] json.dump(tweet, stance_out) stance_out.write('\\n') def",
"tweet_id, tweet in tweet_dict.items(): if tweet['full_text'] == annotation['text']: if label_scheme == 'claim': integrate_claim_label(annotation,",
"labels, must contain either '1' or '2', denominating 'claim'\" \\ \" and 'non-claim'",
"\"Unrecognized label scheme: {}, please use 'sdqc' or 'claim'\" raise RuntimeError( err_msg.format(label_scheme)) with",
"Path(os.path.join(os.path.abspath(__file__), '../../../data/datasets/twitter/raw/unlabeled')) def generate_label_data(file_name: str, stance_out_name: str, claim_out_name: str): file_path = Path(unlabeled_data_path, file_name)",
"= Path(unlabeled_data_path, file_name) stance_out_path = Path(unlabeled_data_path, stance_out_name) claim_out_path = Path(unlabeled_data_path, claim_out_name) with file_path.open()",
"'4', denominating \" \\ \"'verifiable' and 'subjective' respectively. Given labels: {}\" raise RuntimeError(",
"for user_id_b, labels_b in user_labels.items(): if labels_a != labels_b: disagree_data.write(line) disagreement = True",
"'False'} if 1 or 2 not in annotation['annotations']: err_msg = \"Error in claim",
"== 'sdqc': integrate_sdqc_label(annotation, tweet) not_altered = False break if not_altered: data.append(line) else: data.append(line.split('\\t')[0]",
"== 'claim': integrate_claim_label(annotation, tweet) if label_scheme == 'sdqc': integrate_sdqc_label(annotation, tweet) not_altered = False",
"tweet_dict = json.loads(line.split('\\t')[1]) for annotation in labeled_data: annotation = json.loads(annotation) # Data-point not",
"'Subjective' else: tweet['Verifiability'] = 'Verifiable' if 5 or 6 or 7 not in",
"7 not in annotation['annotations']: err_msg = \"Error in claim labels, must contain either",
"[5, 6, 7]: if x in annotation['annotations']: tweet['TruthStatus'] = veracity_map[x] def integrate_sdqc_label(annotation, tweet):",
"tweet_dict[line.split('\\t')[0]] source_tweet['text'] = source_tweet['full_text'] source_tweet['labels'] = [] json.dump(source_tweet, claim_out) claim_out.write('\\n') for tweet_id, tweet",
"RuntimeError( err_msg.format(label_scheme)) with anno_data_path.open(encoding='utf-8') as labeled_data, database_path.open(encoding='utf-8') as database: data = [] for",
"user_labels.items(): for user_id_b, labels_b in user_labels.items(): if labels_a != labels_b: disagree_data.write(line) disagreement =",
"{} for annotation in annotations: user_labels.setdefault(annotation['user'], set()).add(annotation['label']) for user_id_a, labels_a in user_labels.items(): for",
"annotation in annotations: user_labels.setdefault(annotation['user'], set()).add(annotation['label']) for user_id_a, labels_a in user_labels.items(): for user_id_b, labels_b",
"!= labels_b: disagree_data.write(line) disagreement = True break if disagreement: break if not disagreement:",
"either '5', '6' or '7', \" \\ \"denominating 'True', 'Unverified' and 'False' respectively.",
"[annotations[0]['label']] json.dump(line, agree_data) agree_data.write('\\n') else: user_labels = {} for annotation in annotations: user_labels.setdefault(annotation['user'],",
"3 or 4 not in annotation['annotations']: err_msg = \"Error in claim labels, must",
"agree_data) agree_data.write('\\n') else: user_labels = {} for annotation in annotations: user_labels.setdefault(annotation['user'], set()).add(annotation['label']) for",
"raise RuntimeError( err_msg.format(annotation['annotations'])) if 4 in annotation['annotations']: tweet['Verifiability'] = 'Subjective' else: tweet['Verifiability'] =",
"json.loads(line.split('\\t')[1]) source_tweet = tweet_dict[line.split('\\t')[0]] source_tweet['text'] = source_tweet['full_text'] source_tweet['labels'] = [] json.dump(source_tweet, claim_out) claim_out.write('\\n')",
"in annotations: user_labels.setdefault(annotation['user'], set()).add(annotation['label']) for user_id_a, labels_a in user_labels.items(): for user_id_b, labels_b in",
"database_path: Path, label_scheme: str): if label_scheme not in ['claim', 'sdqc']: err_msg = \"Unrecognized",
"x in [5, 6, 7]: if x in annotation['annotations']: tweet['TruthStatus'] = veracity_map[x] def",
"database_path.open(encoding='utf-8') as database: data = [] for line in database: not_altered = True",
"def generate_label_data(file_name: str, stance_out_name: str, claim_out_name: str): file_path = Path(unlabeled_data_path, file_name) stance_out_path =",
"raise RuntimeError( err_msg.format(len(annotation['annotations']))) tweet['SDQC_Submission'] = sdqc_map[annotation['annotations'][0]] def integrate_label_data(anno_data_path: Path, database_path: Path, label_scheme: str):",
"= True tweet_dict = json.loads(line.split('\\t')[1]) for annotation in labeled_data: annotation = json.loads(annotation) #",
"agree_data.write('\\n') def integrate_claim_label(annotation, tweet): veracity_map = {5: 'True', 6: 'Unverified', 7: 'False'} if",
"= 'Subjective' else: tweet['Verifiability'] = 'Verifiable' if 5 or 6 or 7 not",
"= [] json.dump(source_tweet, claim_out) claim_out.write('\\n') for tweet_id, tweet in tweet_dict.items(): if source_tweet ==",
"if x in annotation['annotations']: tweet['TruthStatus'] = veracity_map[x] def integrate_sdqc_label(annotation, tweet): sdqc_map = {1:",
"or 2 not in annotation['annotations']: err_msg = \"Error in claim labels, must contain",
"err_msg.format(label_scheme)) with anno_data_path.open(encoding='utf-8') as labeled_data, database_path.open(encoding='utf-8') as database: data = [] for line",
"agree_file: str, disagree_file: str): anno_data_path = Path(os.path.join(default_raw_path, anno_data_file)) agree_path = Path(os.path.join(default_raw_path, agree_file)) disagree_path",
"'6' or '7', \" \\ \"denominating 'True', 'Unverified' and 'False' respectively. Given \"",
"data.append(line) else: data.append(line.split('\\t')[0] + '\\t' + json.dumps(tweet_dict)) with database_path.open(mode='w', encoding='utf-8') as database: for",
"claim_out.write('\\n') for tweet_id, tweet in tweet_dict.items(): if source_tweet == tweet: continue tweet['text'] =",
"+ json.dumps(tweet_dict)) with database_path.open(mode='w', encoding='utf-8') as database: for line in data: database.write(line) #anno_agreement_check(Path('test.json'),",
"annotated if not annotation['annotations']: continue for tweet_id, tweet in tweet_dict.items(): if tweet['full_text'] ==",
"for tweet_id, tweet in tweet_dict.items(): if source_tweet == tweet: continue tweet['text'] = 'Source:",
"claim_out) claim_out.write('\\n') for tweet_id, tweet in tweet_dict.items(): if source_tweet == tweet: continue tweet['text']",
"anno_data_path.open(encoding='utf-8') as labeled_data, database_path.open(encoding='utf-8') as database: data = [] for line in database:",
"'7', \" \\ \"denominating 'True', 'Unverified' and 'False' respectively. Given \" \\ \"labels:",
"len(annotations) == 1: line = json.loads(line) line['annotations'] = [annotations[0]['label']] json.dump(line, agree_data) agree_data.write('\\n') else:",
"with anno_data_path.open(encoding='utf-8') as anno_data, agree_path.open(mode='w', encoding='utf-8') as agree_data, disagree_path.open( mode='w', encoding='utf-8') as disagree_data:",
"if 3 or 4 not in annotation['annotations']: err_msg = \"Error in claim labels,",
"= False annotations = json.loads(line)['annotations'] if len(annotations) == 1: line = json.loads(line) line['annotations']",
"database_path.open(mode='w', encoding='utf-8') as database: for line in data: database.write(line) #anno_agreement_check(Path('test.json'), Path('agree.json'), Path('disagree.json')) #generate_label_data(test_data,",
"break if not disagreement: line = json.loads(line) if user_labels: line['annotations'] = list(user_labels[1]) if"
] |
[
"= 1 # nums_to_select 的设定 new_nums_to_select = min(math.ceil(len(u_data) * math.pow((step + 1), args.q)",
"type=str, metavar='PATH',default=os.path.join(working_dir, 'logs')) # 保持日志根目录 parser.add_argument('--exp_name',type=str,default=\"nlvm-b1\") parser.add_argument('--exp_order',type=str,default=\"1\") parser.add_argument('--resume', type=str, default=None) parser.add_argument('--mode', type=str, choices=[\"Classification\",",
"%02d:%02d:%02.6f\" % ( h, m, s)) time_file.close() if __name__ == '__main__': parser =",
"nums_to_select = min(math.ceil(len(u_data) * math.pow((step), args.q) * args.EF / 100), len(u_data)) step_size =",
"= train_time+estimate_time time_file.write(\"step:{} train:{} evaluate:{} estimate:{} epoch:{}\\n\".format(int(step+1),train_time,evaluate_time,estimate_time,epoch_time)) if args.gdraw: gd.draw(nums_to_select/len(u_data),top1,mAP,label_pre,select_pre) nums_to_select = new_nums_to_select",
"= 0,0,0,0 pred_y, pred_score, label_pre, dists = eug.estimate_label() estimate_end = time.time() # 循环退出判断",
"# mAP, top1, top5, top10, top20 = 0,0,0,0,0 mAP,top1,top5,top10,top20 = eug.evaluate(dataset_all.query, dataset_all.gallery) #",
"mAP, top1, top5,top10,top20,nums_to_select, expend_nums_to_select,nums_to_select/len(u_data),label_pre,select_pre)) print( \"step:{} mAP:{:.2%} top1:{:.2%} top5:{:.2%} top10:{:.2%} top20:{:.2%} nums_selected:{} expend_nums_to_select:{}",
"np import torch import argparse import os from reid.utils.logging import Logger import os.path",
"'' if args.resume: # 重新训练的时候用 resume_step, ckpt_file = resume(args) # initial the EUG",
"指定输出文件 # 第三部分要说明关键参数的设定 sys.stdout = Logger(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'log'+time.strftime(\".%m_%d_%H-%M-%S\")+'.txt')) data_file =codecs.open(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'data.txt'),mode='a') if args.clock :",
"NN + len(l_data))) + 2 # big start 策略 # 输出该轮训练关键的提示信息 print(\"{} training",
"if args.resume: step = resume_step nums_to_select = min(math.ceil(len(u_data) * math.pow((step), args.q) * args.EF",
"parser.add_argument('--percent_vari', type=float, default=0.8) # 方差的筛选范围. working_dir = os.path.dirname(os.path.abspath(__file__)) parser.add_argument('--data_dir', type=str, metavar='PATH',default=os.path.join(working_dir, 'data')) #",
"nums_to_select = 0 expend_nums_to_select = 0 new_train_data = l_data step = 0 if",
"0 expend_nums_to_select = 0 new_train_data = l_data step = 0 if args.resume: step",
"pred_y, pred_score, label_pre, id_num = 0,0,0,0 pred_y, pred_score, label_pre, dists = eug.estimate_label() estimate_end",
"#是否实时绘图 #下面是暂时不知道用来做什么的参数 parser.add_argument('-a', '--arch', type=str, default='avg_pool',choices=models.names()) #eug model_name parser.add_argument('-i', '--iter-step', type=int, default=5) parser.add_argument('-g',",
"cudnn from reid.utils.serialization import load_checkpoint from torch import nn import time import math",
"args.EF), (1 / args.q))) # 这里应该取上限或者 +2 多一轮进行one-shot训练的 # EUG base 采样策略 #",
"pred_y, pred_score, label_pre, dists = eug.estimate_label() estimate_end = time.time() # 循环退出判断 if nums_to_select",
"args.resume: step = resume_step nums_to_select = min(math.ceil(len(u_data) * math.pow((step), args.q) * args.EF /",
"import sys from torch.backends import cudnn from reid.utils.serialization import load_checkpoint from torch import",
"print( \"step:{} mAP:{:.2%} top1:{:.2%} top5:{:.2%} top10:{:.2%} top20:{:.2%} nums_selected:{} expend_nums_to_select:{} selected_percent:{:.2%} label_pre:{:.2%} select_pre:{:.2%}\\n\".format( int(step+1),",
"default=False) #是否实时绘图 #下面是暂时不知道用来做什么的参数 parser.add_argument('-a', '--arch', type=str, default='avg_pool',choices=models.names()) #eug model_name parser.add_argument('-i', '--iter-step', type=int, default=5)",
"0,0,0,0,0 mAP,top1,top5,top10,top20 = eug.evaluate(dataset_all.query, dataset_all.gallery) # 标签估计 estimate_start = time.time() # pred_y, pred_score,",
"min(math.ceil(len(u_data) * math.pow((step), args.q) * args.EF / 100), len(u_data)) step_size = [] isout",
"= get_one_shot_in_cam1(dataset_all, load_path=\"./examples/oneshot_{}_used_in_paper.pickle\".format( dataset_all.name)) NN = len(l_data) + len(u_data) # 总的训练step数的计算 total_step =",
"parser.add_argument('--mode', type=str, choices=[\"Classification\", \"Dissimilarity\"], default=\"Dissimilarity\") #这个考虑要不要取消掉 parser.add_argument('--max_frames', type=int, default=400) parser.add_argument('--clock',type=bool, default=True) #是否记时 parser.add_argument('--gdraw',type=bool,",
"time_file.close() if __name__ == '__main__': parser = argparse.ArgumentParser(description='Snatch Strategy') parser.add_argument('-d', '--dataset', type=str, default='DukeMTMC-VideoReID',choices=datasets.names())",
"os import codecs from common_tool import * def main(args): # 声明动态绘图器 gd =",
"over, cost %02d:%02d:%02.6f\" % ( h, m, s)) time_file.close() if __name__ == '__main__':",
"import math import pickle import time import matplotlib.pyplot as plt import os import",
"pickle import time import matplotlib.pyplot as plt import os import codecs from common_tool",
"#下面是暂时不知道用来做什么的参数 parser.add_argument('-a', '--arch', type=str, default='avg_pool',choices=models.names()) #eug model_name parser.add_argument('-i', '--iter-step', type=int, default=5) parser.add_argument('-g', '--gamma',",
"= -1, '' if args.resume: # 重新训练的时候用 resume_step, ckpt_file = resume(args) # initial",
"id_num = 0,0,0,0 pred_y, pred_score, label_pre, dists = eug.estimate_label() estimate_end = time.time() #",
"= min(len(u_data), math.ceil(new_nums_to_select / args.percent_vari)) selected_idx = eug.select_top_data_nlvm_b1(pred_score,dists, new_expend_nums_to_select,new_nums_to_select) new_train_data, select_pre = eug.generate_new_train_data(selected_idx,",
"print(\"experiment is over, cost %02d:%02d:%02.6f\" % ( h, m, s)) time_file.close() if __name__",
"type=float, default=0.8) # 方差的筛选范围. working_dir = os.path.dirname(os.path.abspath(__file__)) parser.add_argument('--data_dir', type=str, metavar='PATH',default=os.path.join(working_dir, 'data')) # 加载数据集的根目录",
"reid import datasets from reid import models import numpy as np import torch",
"top20 = 0,0,0,0,0 mAP,top1,top5,top10,top20 = eug.evaluate(dataset_all.query, dataset_all.gallery) # 标签估计 estimate_start = time.time() #",
"NN = len(l_data) + len(u_data) # 总的训练step数的计算 total_step = math.ceil(math.pow((100 / args.EF), (1",
"train_time = evaluate_start-train_start evaluate_time = estimate_start - evaluate_start estimate_time = estimate_end-estimate_start epoch_time =",
"args.epoch,step+1,total_step+1,save_path)) print(\"key parameters contain EF:{},q:{},percent_vari:{}. Nums_been_selected:{}\".format(args.EF,args.q,args.percent_vari,nums_to_select)) # 开始训练 train_start = time.time() eug.train(new_train_data, step,",
"* args.EF / 100),len(u_data)) # EUG 基础指数渐进策略 # new_nums_to_select = min(math.ceil((len(u_data)-args.yita)*(step-1)/(total_step-2))+args.yita,len(u_data)) # big",
"expend_nums_to_select:{} selected_percent:{:.2%} label_pre:{:.2%} select_pre:{:.2%}\\n\".format( int(step+1), mAP, top1, top5,top10,top20,nums_to_select, expend_nums_to_select,nums_to_select/len(u_data),label_pre,select_pre)) print( \"step:{} mAP:{:.2%} top1:{:.2%}",
"absolute_import from reid.snatch import * from reid import datasets from reid import models",
"* NN * args.step_s + args.yita + len(u_data)) / (args.yita + NN +",
"采样策略 # total_step = math.ceil((2 * NN * args.step_s + args.yita + len(u_data))",
"# 加载数据集的根目录 parser.add_argument('--logs_dir', type=str, metavar='PATH',default=os.path.join(working_dir, 'logs')) # 保持日志根目录 parser.add_argument('--exp_name',type=str,default=\"nlvm-b1\") parser.add_argument('--exp_order',type=str,default=\"1\") parser.add_argument('--resume', type=str, default=None)",
"= changetoHSM(exp_time) print(\"experiment is over, cost %02d:%02d:%02.6f\" % ( h, m, s)) time_file.close()",
"labeled and unlabeled data for training dataset_all = datasets.create(args.dataset, osp.join(args.data_dir, args.dataset)) l_data, u_data",
"EUG algorithm eug = EUG(model_name=args.arch, batch_size=args.batch_size, mode=args.mode, num_classes=dataset_all.num_train_ids, data_dir=dataset_all.images_dir, l_data=l_data, u_data=u_data, save_path=save_path, max_frames=args.max_frames)",
"加载数据集的根目录 parser.add_argument('--logs_dir', type=str, metavar='PATH',default=os.path.join(working_dir, 'logs')) # 保持日志根目录 parser.add_argument('--exp_name',type=str,default=\"nlvm-b1\") parser.add_argument('--exp_order',type=str,default=\"1\") parser.add_argument('--resume', type=str, default=None) parser.add_argument('--mode',",
"import * from reid import datasets from reid import models import numpy as",
"= math.ceil(math.pow((100 / args.EF), (1 / args.q))) # 这里应该取上限或者 +2 多一轮进行one-shot训练的 # EUG",
"args.dataset)) l_data, u_data = get_one_shot_in_cam1(dataset_all, load_path=\"./examples/oneshot_{}_used_in_paper.pickle\".format( dataset_all.name)) NN = len(l_data) + len(u_data) #",
"resume(args) # initial the EUG algorithm eug = EUG(model_name=args.arch, batch_size=args.batch_size, mode=args.mode, num_classes=dataset_all.num_train_ids, data_dir=dataset_all.images_dir,",
"#这个考虑要不要取消掉 parser.add_argument('--max_frames', type=int, default=400) parser.add_argument('--clock',type=bool, default=True) #是否记时 parser.add_argument('--gdraw',type=bool, default=False) #是否实时绘图 #下面是暂时不知道用来做什么的参数 parser.add_argument('-a', '--arch',",
"resume_step, ckpt_file = resume(args) # initial the EUG algorithm eug = EUG(model_name=args.arch, batch_size=args.batch_size,",
"= resume(args) # initial the EUG algorithm eug = EUG(model_name=args.arch, batch_size=args.batch_size, mode=args.mode, num_classes=dataset_all.num_train_ids,",
"# 循环退出判断 if nums_to_select == len(u_data): isout = 1 # nums_to_select 的设定 new_nums_to_select",
"# initial the EUG algorithm eug = EUG(model_name=args.arch, batch_size=args.batch_size, mode=args.mode, num_classes=dataset_all.num_train_ids, data_dir=dataset_all.images_dir, l_data=l_data,",
"load_checkpoint from torch import nn import time import math import pickle import time",
"step + 1 data_file.close() if (args.clock): exp_end = time.time() exp_time = exp_end -",
"model_name parser.add_argument('-i', '--iter-step', type=int, default=5) parser.add_argument('-g', '--gamma', type=float, default=0.3) parser.add_argument('-l', '--l', type=float) parser.add_argument('--continuous',",
"# 总的训练step数的计算 total_step = math.ceil(math.pow((100 / args.EF), (1 / args.q))) # 这里应该取上限或者 +2",
"print(\"key parameters contain EF:{},q:{},percent_vari:{}. Nums_been_selected:{}\".format(args.EF,args.q,args.percent_vari,nums_to_select)) # 开始训练 train_start = time.time() eug.train(new_train_data, step, epochs=args.epoch,",
"if args.clock : time_file =codecs.open(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'time.txt'),mode='a') save_path = osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order) resume_step, ckpt_file =",
"# EUG base 采样策略 # total_step = math.ceil((2 * NN * args.step_s +",
"time_file =codecs.open(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'time.txt'),mode='a') save_path = osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order) resume_step, ckpt_file = -1, '' if",
"# 开始评估 evaluate_start = time.time() # mAP, top1, top5, top10, top20 = 0,0,0,0,0",
"default='avg_pool',choices=models.names()) #eug model_name parser.add_argument('-i', '--iter-step', type=int, default=5) parser.add_argument('-g', '--gamma', type=float, default=0.3) parser.add_argument('-l', '--l',",
"= step + 1 data_file.close() if (args.clock): exp_end = time.time() exp_time = exp_end",
"= osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order) resume_step, ckpt_file = -1, '' if args.resume: # 重新训练的时候用 resume_step,",
"方差的筛选范围. working_dir = os.path.dirname(os.path.abspath(__file__)) parser.add_argument('--data_dir', type=str, metavar='PATH',default=os.path.join(working_dir, 'data')) # 加载数据集的根目录 parser.add_argument('--logs_dir', type=str, metavar='PATH',default=os.path.join(working_dir,",
"sys.stdout = Logger(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'log'+time.strftime(\".%m_%d_%H-%M-%S\")+'.txt')) data_file =codecs.open(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'data.txt'),mode='a') if args.clock : time_file =codecs.open(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'time.txt'),mode='a')",
"h, m, s)) time_file.close() if __name__ == '__main__': parser = argparse.ArgumentParser(description='Snatch Strategy') parser.add_argument('-d',",
"epochs=args.epoch, step_size=args.step_size, init_lr=0.1) if step != resume_step else eug.resume(ckpt_file, step) # 开始评估 evaluate_start",
"* def main(args): # 声明动态绘图器 gd = gif_drawer() cudnn.benchmark = True cudnn.enabled =",
"2 # big start 策略 # 输出该轮训练关键的提示信息 print(\"{} training begin with dataset:{},batch_size:{},epoch:{},step_size:{},max_frames:{},total_step:{},EF:{},q:{},percent_vari:{}\".format(args.exp_name,args.dataset,args.batch_size,args.epoch,args.step_size,args.max_frames,total_step+1,args.EF,args.q,args.percent_vari)) #",
"label_pre:{:.2%} select_pre:{:.2%}\\n\".format( int(step+1), mAP, top1, top5,top10,top20,nums_to_select, expend_nums_to_select,nums_to_select/len(u_data),label_pre,select_pre)) print( \"step:{} mAP:{:.2%} top1:{:.2%} top5:{:.2%} top10:{:.2%}",
"get_one_shot_in_cam1(dataset_all, load_path=\"./examples/oneshot_{}_used_in_paper.pickle\".format( dataset_all.name)) NN = len(l_data) + len(u_data) # 总的训练step数的计算 total_step = math.ceil(math.pow((100",
"'logs')) # 保持日志根目录 parser.add_argument('--exp_name',type=str,default=\"nlvm-b1\") parser.add_argument('--exp_order',type=str,default=\"1\") parser.add_argument('--resume', type=str, default=None) parser.add_argument('--mode', type=str, choices=[\"Classification\", \"Dissimilarity\"], default=\"Dissimilarity\")",
"nums_to_select == len(u_data): isout = 1 # nums_to_select 的设定 new_nums_to_select = min(math.ceil(len(u_data) *",
"import os import codecs from common_tool import * def main(args): # 声明动态绘图器 gd",
"l_data, u_data = get_one_shot_in_cam1(dataset_all, load_path=\"./examples/oneshot_{}_used_in_paper.pickle\".format( dataset_all.name)) NN = len(l_data) + len(u_data) # 总的训练step数的计算",
"gif_drawer() cudnn.benchmark = True cudnn.enabled = True # get all the labeled and",
"- evaluate_start estimate_time = estimate_end-estimate_start epoch_time = train_time+estimate_time time_file.write(\"step:{} train:{} evaluate:{} estimate:{} epoch:{}\\n\".format(int(step+1),train_time,evaluate_time,estimate_time,epoch_time))",
"min(math.ceil(len(u_data) * math.pow((step + 1), args.q) * args.EF / 100),len(u_data)) # EUG 基础指数渐进策略",
"= True # get all the labeled and unlabeled data for training dataset_all",
"训练之前初始化数据 nums_to_select = 0 expend_nums_to_select = 0 new_train_data = l_data step = 0",
"+ len(u_data) # 总的训练step数的计算 total_step = math.ceil(math.pow((100 / args.EF), (1 / args.q))) #",
"cudnn.benchmark = True cudnn.enabled = True # get all the labeled and unlabeled",
"select_pre = eug.generate_new_train_data(selected_idx, pred_y) # select_pre =0 # 输出该epoch的信息 data_file.write(\"step:{} mAP:{:.2%} top1:{:.2%} top5:{:.2%}",
"# big start new_expend_nums_to_select = min(len(u_data), math.ceil(new_nums_to_select / args.percent_vari)) selected_idx = eug.select_top_data_nlvm_b1(pred_score,dists, new_expend_nums_to_select,new_nums_to_select)",
"choices=[\"Classification\", \"Dissimilarity\"], default=\"Dissimilarity\") #这个考虑要不要取消掉 parser.add_argument('--max_frames', type=int, default=400) parser.add_argument('--clock',type=bool, default=True) #是否记时 parser.add_argument('--gdraw',type=bool, default=False) #是否实时绘图",
"/ args.percent_vari)) selected_idx = eug.select_top_data_nlvm_b1(pred_score,dists, new_expend_nums_to_select,new_nums_to_select) new_train_data, select_pre = eug.generate_new_train_data(selected_idx, pred_y) # select_pre",
"= 0 if args.resume: step = resume_step nums_to_select = min(math.ceil(len(u_data) * math.pow((step), args.q)",
"/ len(u_data), label_pre,select_pre)) if args.clock: train_time = evaluate_start-train_start evaluate_time = estimate_start - evaluate_start",
"声明动态绘图器 gd = gif_drawer() cudnn.benchmark = True cudnn.enabled = True # get all",
"type=int, default=400) parser.add_argument('--clock',type=bool, default=True) #是否记时 parser.add_argument('--gdraw',type=bool, default=False) #是否实时绘图 #下面是暂时不知道用来做什么的参数 parser.add_argument('-a', '--arch', type=str, default='avg_pool',choices=models.names())",
"reid.utils.logging import Logger import os.path as osp import sys from torch.backends import cudnn",
"new_expend_nums_to_select = min(len(u_data), math.ceil(new_nums_to_select / args.percent_vari)) selected_idx = eug.select_top_data_nlvm_b1(pred_score,dists, new_expend_nums_to_select,new_nums_to_select) new_train_data, select_pre =",
"* math.pow((step), args.q) * args.EF / 100), len(u_data)) step_size = [] isout =",
"new_expend_nums_to_select step = step + 1 data_file.close() if (args.clock): exp_end = time.time() exp_time",
"top5,top10,top20,nums_to_select, expend_nums_to_select,nums_to_select/len(u_data),label_pre,select_pre)) print( \"step:{} mAP:{:.2%} top1:{:.2%} top5:{:.2%} top10:{:.2%} top20:{:.2%} nums_selected:{} expend_nums_to_select:{} selected_percent:{:.2%} label_pre:{:.2%}",
"args.clock : time_file =codecs.open(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'time.txt'),mode='a') save_path = osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order) resume_step, ckpt_file = -1,",
"args.dataset,args.exp_name,args.exp_order,'time.txt'),mode='a') save_path = osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order) resume_step, ckpt_file = -1, '' if args.resume: #",
"l_data=l_data, u_data=u_data, save_path=save_path, max_frames=args.max_frames) # 训练之前初始化数据 nums_to_select = 0 expend_nums_to_select = 0 new_train_data",
"evaluate:{} estimate:{} epoch:{}\\n\".format(int(step+1),train_time,evaluate_time,estimate_time,epoch_time)) if args.gdraw: gd.draw(nums_to_select/len(u_data),top1,mAP,label_pre,select_pre) nums_to_select = new_nums_to_select expend_nums_to_select = new_expend_nums_to_select step",
"\"Dissimilarity\"], default=\"Dissimilarity\") #这个考虑要不要取消掉 parser.add_argument('--max_frames', type=int, default=400) parser.add_argument('--clock',type=bool, default=True) #是否记时 parser.add_argument('--gdraw',type=bool, default=False) #是否实时绘图 #下面是暂时不知道用来做什么的参数",
"= eug.estimate_label() estimate_end = time.time() # 循环退出判断 if nums_to_select == len(u_data): isout =",
"/ args.q))) # 这里应该取上限或者 +2 多一轮进行one-shot训练的 # EUG base 采样策略 # total_step =",
"int(step+1), mAP, top1, top5,top10,top20,nums_to_select, expend_nums_to_select,nums_to_select/len(u_data),label_pre,select_pre)) print( \"step:{} mAP:{:.2%} top1:{:.2%} top5:{:.2%} top10:{:.2%} top20:{:.2%} nums_selected:{}",
"from reid import datasets from reid import models import numpy as np import",
"top1, top5, top10, top20 = 0,0,0,0,0 mAP,top1,top5,top10,top20 = eug.evaluate(dataset_all.query, dataset_all.gallery) # 标签估计 estimate_start",
"evaluate_start estimate_time = estimate_end-estimate_start epoch_time = train_time+estimate_time time_file.write(\"step:{} train:{} evaluate:{} estimate:{} epoch:{}\\n\".format(int(step+1),train_time,evaluate_time,estimate_time,epoch_time)) if",
"math.ceil(math.pow((100 / args.EF), (1 / args.q))) # 这里应该取上限或者 +2 多一轮进行one-shot训练的 # EUG base",
"这里应该取上限或者 +2 多一轮进行one-shot训练的 # EUG base 采样策略 # total_step = math.ceil((2 * NN",
"= new_nums_to_select expend_nums_to_select = new_expend_nums_to_select step = step + 1 data_file.close() if (args.clock):",
"from common_tool import * def main(args): # 声明动态绘图器 gd = gif_drawer() cudnn.benchmark =",
"cost %02d:%02d:%02.6f\" % ( h, m, s)) time_file.close() if __name__ == '__main__': parser",
"expend_nums_to_select,nums_to_select/len(u_data),label_pre,select_pre)) print( \"step:{} mAP:{:.2%} top1:{:.2%} top5:{:.2%} top10:{:.2%} top20:{:.2%} nums_selected:{} expend_nums_to_select:{} selected_percent:{:.2%} label_pre:{:.2%} select_pre:{:.2%}\\n\".format(",
"* math.pow((step + 1), args.q) * args.EF / 100),len(u_data)) # EUG 基础指数渐进策略 #",
"exp_start h, m, s = changetoHSM(exp_time) print(\"experiment is over, cost %02d:%02d:%02.6f\" % (",
"nums_selected:{} expend_nums_to_select:{} selected_percent:{:.2%} label_pre:{:.2%} select_pre:{:.2%}\\n\".format( int(step+1), mAP, top1, top5,top10,top20,nums_to_select, expend_nums_to_select,nums_to_select/len(u_data),label_pre,select_pre)) print( \"step:{} mAP:{:.2%}",
"import cudnn from reid.utils.serialization import load_checkpoint from torch import nn import time import",
"= 0 #用来标记是否应该结束训练 # 开始的时间记录 exp_start = time.time() while(not isout): print(\"{} training begin",
"sys from torch.backends import cudnn from reid.utils.serialization import load_checkpoint from torch import nn",
"estimate_start - evaluate_start estimate_time = estimate_end-estimate_start epoch_time = train_time+estimate_time time_file.write(\"step:{} train:{} evaluate:{} estimate:{}",
"0 if args.resume: step = resume_step nums_to_select = min(math.ceil(len(u_data) * math.pow((step), args.q) *",
"selected_idx = eug.select_top_data_nlvm_b1(pred_score,dists, new_expend_nums_to_select,new_nums_to_select) new_train_data, select_pre = eug.generate_new_train_data(selected_idx, pred_y) # select_pre =0 #",
"parser = argparse.ArgumentParser(description='Snatch Strategy') parser.add_argument('-d', '--dataset', type=str, default='DukeMTMC-VideoReID',choices=datasets.names()) #DukeMTMC-VideoReID \\mars parser.add_argument('-b', '--batch-size', type=int,",
"selected_percent:{:.2%} label_pre:{:.2%} select_pre:{:.2%}\\n\".format( int(step+1), mAP, top1, top5,top10,top20,nums_to_select, expend_nums_to_select,nums_to_select/len(u_data),label_pre,select_pre)) print( \"step:{} mAP:{:.2%} top1:{:.2%} top5:{:.2%}",
"NN * args.step_s + args.yita + len(u_data)) / (args.yita + NN + len(l_data)))",
"if args.gdraw: gd.draw(nums_to_select/len(u_data),top1,mAP,label_pre,select_pre) nums_to_select = new_nums_to_select expend_nums_to_select = new_expend_nums_to_select step = step +",
"isout = 0 #用来标记是否应该结束训练 # 开始的时间记录 exp_start = time.time() while(not isout): print(\"{} training",
"重新训练的时候用 resume_step, ckpt_file = resume(args) # initial the EUG algorithm eug = EUG(model_name=args.arch,",
"eug.evaluate(dataset_all.query, dataset_all.gallery) # 标签估计 estimate_start = time.time() # pred_y, pred_score, label_pre, id_num =",
"os.path.dirname(os.path.abspath(__file__)) parser.add_argument('--data_dir', type=str, metavar='PATH',default=os.path.join(working_dir, 'data')) # 加载数据集的根目录 parser.add_argument('--logs_dir', type=str, metavar='PATH',default=os.path.join(working_dir, 'logs')) # 保持日志根目录",
"type=str, default='avg_pool',choices=models.names()) #eug model_name parser.add_argument('-i', '--iter-step', type=int, default=5) parser.add_argument('-g', '--gamma', type=float, default=0.3) parser.add_argument('-l',",
"top5, top10, top20 = 0,0,0,0,0 mAP,top1,top5,top10,top20 = eug.evaluate(dataset_all.query, dataset_all.gallery) # 标签估计 estimate_start =",
"args.dataset,args.exp_name,args.exp_order,'log'+time.strftime(\".%m_%d_%H-%M-%S\")+'.txt')) data_file =codecs.open(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'data.txt'),mode='a') if args.clock : time_file =codecs.open(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'time.txt'),mode='a') save_path = osp.join(args.logs_dir,",
"top1, top5, top10, top20, nums_to_select, expend_nums_to_select,nums_to_select / len(u_data), label_pre,select_pre)) if args.clock: train_time =",
"default=None) parser.add_argument('--mode', type=str, choices=[\"Classification\", \"Dissimilarity\"], default=\"Dissimilarity\") #这个考虑要不要取消掉 parser.add_argument('--max_frames', type=int, default=400) parser.add_argument('--clock',type=bool, default=True) #是否记时",
"new_train_data, select_pre = eug.generate_new_train_data(selected_idx, pred_y) # select_pre =0 # 输出该epoch的信息 data_file.write(\"step:{} mAP:{:.2%} top1:{:.2%}",
"for training dataset_all = datasets.create(args.dataset, osp.join(args.data_dir, args.dataset)) l_data, u_data = get_one_shot_in_cam1(dataset_all, load_path=\"./examples/oneshot_{}_used_in_paper.pickle\".format( dataset_all.name))",
"parser.add_argument('--step_size',type=int,default=30) parser.add_argument('--EF', type=float, default=10) # 渐进采样系数 parser.add_argument('--q', type=float, default=1) # 渐进采样指数 parser.add_argument('--percent_vari', type=float,",
"select_pre:{:.2%}\\n\".format( int(step+1), mAP, top1, top5,top10,top20,nums_to_select, expend_nums_to_select,nums_to_select/len(u_data),label_pre,select_pre)) print( \"step:{} mAP:{:.2%} top1:{:.2%} top5:{:.2%} top10:{:.2%} top20:{:.2%}",
"基础指数渐进策略 # new_nums_to_select = min(math.ceil((len(u_data)-args.yita)*(step-1)/(total_step-2))+args.yita,len(u_data)) # big start new_expend_nums_to_select = min(len(u_data), math.ceil(new_nums_to_select /",
"第三部分要说明关键参数的设定 sys.stdout = Logger(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'log'+time.strftime(\".%m_%d_%H-%M-%S\")+'.txt')) data_file =codecs.open(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'data.txt'),mode='a') if args.clock : time_file =codecs.open(osp.join(args.logs_dir,",
"osp.join(args.data_dir, args.dataset)) l_data, u_data = get_one_shot_in_cam1(dataset_all, load_path=\"./examples/oneshot_{}_used_in_paper.pickle\".format( dataset_all.name)) NN = len(l_data) + len(u_data)",
"reid.utils.serialization import load_checkpoint from torch import nn import time import math import pickle",
"import codecs from common_tool import * def main(args): # 声明动态绘图器 gd = gif_drawer()",
"evaluate_start-train_start evaluate_time = estimate_start - evaluate_start estimate_time = estimate_end-estimate_start epoch_time = train_time+estimate_time time_file.write(\"step:{}",
"100),len(u_data)) # EUG 基础指数渐进策略 # new_nums_to_select = min(math.ceil((len(u_data)-args.yita)*(step-1)/(total_step-2))+args.yita,len(u_data)) # big start new_expend_nums_to_select =",
"parser.add_argument('-i', '--iter-step', type=int, default=5) parser.add_argument('-g', '--gamma', type=float, default=0.3) parser.add_argument('-l', '--l', type=float) parser.add_argument('--continuous', action=\"store_true\")",
"# 开始训练 train_start = time.time() eug.train(new_train_data, step, epochs=args.epoch, step_size=args.step_size, init_lr=0.1) if step !=",
"eug.generate_new_train_data(selected_idx, pred_y) # select_pre =0 # 输出该epoch的信息 data_file.write(\"step:{} mAP:{:.2%} top1:{:.2%} top5:{:.2%} top10:{:.2%} top20:{:.2%}",
"math import pickle import time import matplotlib.pyplot as plt import os import codecs",
"- exp_start h, m, s = changetoHSM(exp_time) print(\"experiment is over, cost %02d:%02d:%02.6f\" %",
"step = step + 1 data_file.close() if (args.clock): exp_end = time.time() exp_time =",
"import models import numpy as np import torch import argparse import os from",
"'--dataset', type=str, default='DukeMTMC-VideoReID',choices=datasets.names()) #DukeMTMC-VideoReID \\mars parser.add_argument('-b', '--batch-size', type=int, default=16) parser.add_argument('--epoch',type=int,default=40) parser.add_argument('--step_size',type=int,default=30) parser.add_argument('--EF', type=float,",
"= min(math.ceil(len(u_data) * math.pow((step + 1), args.q) * args.EF / 100),len(u_data)) # EUG",
"= 0 new_train_data = l_data step = 0 if args.resume: step = resume_step",
"torch.backends import cudnn from reid.utils.serialization import load_checkpoint from torch import nn import time",
"top1:{:.2%} top5:{:.2%} top10:{:.2%} top20:{:.2%} nums_selected:{} expend_nums_to_select:{} selected_percent:{:.2%} label_pre:{:.2%} select_pre:{:.2%}\\n\".format( int(step+1), mAP, top1, top5,top10,top20,nums_to_select,",
"expend_nums_to_select = 0 new_train_data = l_data step = 0 if args.resume: step =",
"# EUG 基础指数渐进策略 # new_nums_to_select = min(math.ceil((len(u_data)-args.yita)*(step-1)/(total_step-2))+args.yita,len(u_data)) # big start new_expend_nums_to_select = min(len(u_data),",
"get all the labeled and unlabeled data for training dataset_all = datasets.create(args.dataset, osp.join(args.data_dir,",
"= time.time() exp_time = exp_end - exp_start h, m, s = changetoHSM(exp_time) print(\"experiment",
"nn import time import math import pickle import time import matplotlib.pyplot as plt",
"top1:{:.2%} top5:{:.2%} top10:{:.2%} top20:{:.2%} nums_selected:{} expend_nums_to_select:{} selected_percent:{:.2%} label_pre:{:.2%} select_pre:{:.2%}\\n\".format( int(step+1), mAP, top1, top5,",
"exp_end = time.time() exp_time = exp_end - exp_start h, m, s = changetoHSM(exp_time)",
"math.ceil(new_nums_to_select / args.percent_vari)) selected_idx = eug.select_top_data_nlvm_b1(pred_score,dists, new_expend_nums_to_select,new_nums_to_select) new_train_data, select_pre = eug.generate_new_train_data(selected_idx, pred_y) #",
"if (args.clock): exp_end = time.time() exp_time = exp_end - exp_start h, m, s",
"开始的时间记录 exp_start = time.time() while(not isout): print(\"{} training begin with dataset:{},batch_size:{},epoch:{},step:{}/{} saved to",
"args.q))) # 这里应该取上限或者 +2 多一轮进行one-shot训练的 # EUG base 采样策略 # total_step = math.ceil((2",
"=codecs.open(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'data.txt'),mode='a') if args.clock : time_file =codecs.open(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'time.txt'),mode='a') save_path = osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order) resume_step,",
"time import matplotlib.pyplot as plt import os import codecs from common_tool import *",
"cudnn.enabled = True # get all the labeled and unlabeled data for training",
"and unlabeled data for training dataset_all = datasets.create(args.dataset, osp.join(args.data_dir, args.dataset)) l_data, u_data =",
"math.pow((step + 1), args.q) * args.EF / 100),len(u_data)) # EUG 基础指数渐进策略 # new_nums_to_select",
"输出该epoch的信息 data_file.write(\"step:{} mAP:{:.2%} top1:{:.2%} top5:{:.2%} top10:{:.2%} top20:{:.2%} nums_selected:{} expend_nums_to_select:{} selected_percent:{:.2%} label_pre:{:.2%} select_pre:{:.2%}\\n\".format( int(step+1),",
"step) # 开始评估 evaluate_start = time.time() # mAP, top1, top5, top10, top20 =",
"num_classes=dataset_all.num_train_ids, data_dir=dataset_all.images_dir, l_data=l_data, u_data=u_data, save_path=save_path, max_frames=args.max_frames) # 训练之前初始化数据 nums_to_select = 0 expend_nums_to_select =",
"'__main__': parser = argparse.ArgumentParser(description='Snatch Strategy') parser.add_argument('-d', '--dataset', type=str, default='DukeMTMC-VideoReID',choices=datasets.names()) #DukeMTMC-VideoReID \\mars parser.add_argument('-b', '--batch-size',",
"#用来标记是否应该结束训练 # 开始的时间记录 exp_start = time.time() while(not isout): print(\"{} training begin with dataset:{},batch_size:{},epoch:{},step:{}/{}",
"top5:{:.2%} top10:{:.2%} top20:{:.2%} nums_selected:{} expend_nums_to_select:{} selected_percent:{:.2%} label_pre:{:.2%} select_pre:{:.2%}\\n\".format( int(step+1), mAP, top1, top5,top10,top20,nums_to_select, expend_nums_to_select,nums_to_select/len(u_data),label_pre,select_pre))",
"initial the EUG algorithm eug = EUG(model_name=args.arch, batch_size=args.batch_size, mode=args.mode, num_classes=dataset_all.num_train_ids, data_dir=dataset_all.images_dir, l_data=l_data, u_data=u_data,",
"argparse.ArgumentParser(description='Snatch Strategy') parser.add_argument('-d', '--dataset', type=str, default='DukeMTMC-VideoReID',choices=datasets.names()) #DukeMTMC-VideoReID \\mars parser.add_argument('-b', '--batch-size', type=int, default=16) parser.add_argument('--epoch',type=int,default=40)",
"the EUG algorithm eug = EUG(model_name=args.arch, batch_size=args.batch_size, mode=args.mode, num_classes=dataset_all.num_train_ids, data_dir=dataset_all.images_dir, l_data=l_data, u_data=u_data, save_path=save_path,",
"len(u_data), label_pre,select_pre)) if args.clock: train_time = evaluate_start-train_start evaluate_time = estimate_start - evaluate_start estimate_time",
"time.time() # pred_y, pred_score, label_pre, id_num = 0,0,0,0 pred_y, pred_score, label_pre, dists =",
"# 训练之前初始化数据 nums_to_select = 0 expend_nums_to_select = 0 new_train_data = l_data step =",
"(args.clock): exp_end = time.time() exp_time = exp_end - exp_start h, m, s =",
"to {}.\".format(args.exp_name,args.dataset,args.batch_size, args.epoch,step+1,total_step+1,save_path)) print(\"key parameters contain EF:{},q:{},percent_vari:{}. Nums_been_selected:{}\".format(args.EF,args.q,args.percent_vari,nums_to_select)) # 开始训练 train_start = time.time()",
"time import math import pickle import time import matplotlib.pyplot as plt import os",
"expend_nums_to_select:{} selected_percent:{:.2%} label_pre:{:.2%} select_pre:{:.2%}\\n\".format( int(step+1), mAP, top1, top5, top10, top20, nums_to_select, expend_nums_to_select,nums_to_select /",
"= min(math.ceil(len(u_data) * math.pow((step), args.q) * args.EF / 100), len(u_data)) step_size = []",
"is over, cost %02d:%02d:%02.6f\" % ( h, m, s)) time_file.close() if __name__ ==",
"EF:{},q:{},percent_vari:{}. Nums_been_selected:{}\".format(args.EF,args.q,args.percent_vari,nums_to_select)) # 开始训练 train_start = time.time() eug.train(new_train_data, step, epochs=args.epoch, step_size=args.step_size, init_lr=0.1) if",
"import numpy as np import torch import argparse import os from reid.utils.logging import",
"# 声明动态绘图器 gd = gif_drawer() cudnn.benchmark = True cudnn.enabled = True # get",
"* args.step_s + args.yita + len(u_data)) / (args.yita + NN + len(l_data))) +",
"m, s)) time_file.close() if __name__ == '__main__': parser = argparse.ArgumentParser(description='Snatch Strategy') parser.add_argument('-d', '--dataset',",
"save_path=save_path, max_frames=args.max_frames) # 训练之前初始化数据 nums_to_select = 0 expend_nums_to_select = 0 new_train_data = l_data",
"EUG(model_name=args.arch, batch_size=args.batch_size, mode=args.mode, num_classes=dataset_all.num_train_ids, data_dir=dataset_all.images_dir, l_data=l_data, u_data=u_data, save_path=save_path, max_frames=args.max_frames) # 训练之前初始化数据 nums_to_select =",
"\"step:{} mAP:{:.2%} top1:{:.2%} top5:{:.2%} top10:{:.2%} top20:{:.2%} nums_selected:{} expend_nums_to_select:{} selected_percent:{:.2%} label_pre:{:.2%} select_pre:{:.2%}\\n\".format( int(step+1), mAP,",
"math.ceil((2 * NN * args.step_s + args.yita + len(u_data)) / (args.yita + NN",
"/ (args.yita + NN + len(l_data))) + 2 # big start 策略 #",
"1 data_file.close() if (args.clock): exp_end = time.time() exp_time = exp_end - exp_start h,",
"= time.time() eug.train(new_train_data, step, epochs=args.epoch, step_size=args.step_size, init_lr=0.1) if step != resume_step else eug.resume(ckpt_file,",
"from torch import nn import time import math import pickle import time import",
"if args.resume: # 重新训练的时候用 resume_step, ckpt_file = resume(args) # initial the EUG algorithm",
"mAP, top1, top5, top10, top20 = 0,0,0,0,0 mAP,top1,top5,top10,top20 = eug.evaluate(dataset_all.query, dataset_all.gallery) # 标签估计",
"top10, top20 = 0,0,0,0,0 mAP,top1,top5,top10,top20 = eug.evaluate(dataset_all.query, dataset_all.gallery) # 标签估计 estimate_start = time.time()",
"top5, top10, top20, nums_to_select, expend_nums_to_select,nums_to_select / len(u_data), label_pre,select_pre)) if args.clock: train_time = evaluate_start-train_start",
"\\mars parser.add_argument('-b', '--batch-size', type=int, default=16) parser.add_argument('--epoch',type=int,default=40) parser.add_argument('--step_size',type=int,default=30) parser.add_argument('--EF', type=float, default=10) # 渐进采样系数 parser.add_argument('--q',",
"ckpt_file = -1, '' if args.resume: # 重新训练的时候用 resume_step, ckpt_file = resume(args) #",
"plt import os import codecs from common_tool import * def main(args): # 声明动态绘图器",
"import matplotlib.pyplot as plt import os import codecs from common_tool import * def",
"% ( h, m, s)) time_file.close() if __name__ == '__main__': parser = argparse.ArgumentParser(description='Snatch",
"/ 100),len(u_data)) # EUG 基础指数渐进策略 # new_nums_to_select = min(math.ceil((len(u_data)-args.yita)*(step-1)/(total_step-2))+args.yita,len(u_data)) # big start new_expend_nums_to_select",
"= exp_end - exp_start h, m, s = changetoHSM(exp_time) print(\"experiment is over, cost",
"new_nums_to_select = min(math.ceil((len(u_data)-args.yita)*(step-1)/(total_step-2))+args.yita,len(u_data)) # big start new_expend_nums_to_select = min(len(u_data), math.ceil(new_nums_to_select / args.percent_vari)) selected_idx",
"isout): print(\"{} training begin with dataset:{},batch_size:{},epoch:{},step:{}/{} saved to {}.\".format(args.exp_name,args.dataset,args.batch_size, args.epoch,step+1,total_step+1,save_path)) print(\"key parameters contain",
"from __future__ import print_function, absolute_import from reid.snatch import * from reid import datasets",
"estimate_start = time.time() # pred_y, pred_score, label_pre, id_num = 0,0,0,0 pred_y, pred_score, label_pre,",
"+ len(u_data)) / (args.yita + NN + len(l_data))) + 2 # big start",
"u_data = get_one_shot_in_cam1(dataset_all, load_path=\"./examples/oneshot_{}_used_in_paper.pickle\".format( dataset_all.name)) NN = len(l_data) + len(u_data) # 总的训练step数的计算 total_step",
"输出该轮训练关键的提示信息 print(\"{} training begin with dataset:{},batch_size:{},epoch:{},step_size:{},max_frames:{},total_step:{},EF:{},q:{},percent_vari:{}\".format(args.exp_name,args.dataset,args.batch_size,args.epoch,args.step_size,args.max_frames,total_step+1,args.EF,args.q,args.percent_vari)) # 指定输出文件 # 第三部分要说明关键参数的设定 sys.stdout = Logger(osp.join(args.logs_dir,",
"begin with dataset:{},batch_size:{},epoch:{},step_size:{},max_frames:{},total_step:{},EF:{},q:{},percent_vari:{}\".format(args.exp_name,args.dataset,args.batch_size,args.epoch,args.step_size,args.max_frames,total_step+1,args.EF,args.q,args.percent_vari)) # 指定输出文件 # 第三部分要说明关键参数的设定 sys.stdout = Logger(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'log'+time.strftime(\".%m_%d_%H-%M-%S\")+'.txt')) data_file =codecs.open(osp.join(args.logs_dir,",
"1), args.q) * args.EF / 100),len(u_data)) # EUG 基础指数渐进策略 # new_nums_to_select = min(math.ceil((len(u_data)-args.yita)*(step-1)/(total_step-2))+args.yita,len(u_data))",
": time_file =codecs.open(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'time.txt'),mode='a') save_path = osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order) resume_step, ckpt_file = -1, ''",
"pred_score, label_pre, id_num = 0,0,0,0 pred_y, pred_score, label_pre, dists = eug.estimate_label() estimate_end =",
"h, m, s = changetoHSM(exp_time) print(\"experiment is over, cost %02d:%02d:%02.6f\" % ( h,",
"selected_percent:{:.2%} label_pre:{:.2%} select_pre:{:.2%}\\n\".format( int(step+1), mAP, top1, top5, top10, top20, nums_to_select, expend_nums_to_select,nums_to_select / len(u_data),",
"= gif_drawer() cudnn.benchmark = True cudnn.enabled = True # get all the labeled",
"#DukeMTMC-VideoReID \\mars parser.add_argument('-b', '--batch-size', type=int, default=16) parser.add_argument('--epoch',type=int,default=40) parser.add_argument('--step_size',type=int,default=30) parser.add_argument('--EF', type=float, default=10) # 渐进采样系数",
"from torch.backends import cudnn from reid.utils.serialization import load_checkpoint from torch import nn import",
"type=float, default=10) # 渐进采样系数 parser.add_argument('--q', type=float, default=1) # 渐进采样指数 parser.add_argument('--percent_vari', type=float, default=0.8) #",
"dists = eug.estimate_label() estimate_end = time.time() # 循环退出判断 if nums_to_select == len(u_data): isout",
"while(not isout): print(\"{} training begin with dataset:{},batch_size:{},epoch:{},step:{}/{} saved to {}.\".format(args.exp_name,args.dataset,args.batch_size, args.epoch,step+1,total_step+1,save_path)) print(\"key parameters",
"reid.snatch import * from reid import datasets from reid import models import numpy",
"total_step = math.ceil((2 * NN * args.step_s + args.yita + len(u_data)) / (args.yita",
"eug.resume(ckpt_file, step) # 开始评估 evaluate_start = time.time() # mAP, top1, top5, top10, top20",
"= argparse.ArgumentParser(description='Snatch Strategy') parser.add_argument('-d', '--dataset', type=str, default='DukeMTMC-VideoReID',choices=datasets.names()) #DukeMTMC-VideoReID \\mars parser.add_argument('-b', '--batch-size', type=int, default=16)",
"args.step_s + args.yita + len(u_data)) / (args.yita + NN + len(l_data))) + 2",
"dataset:{},batch_size:{},epoch:{},step_size:{},max_frames:{},total_step:{},EF:{},q:{},percent_vari:{}\".format(args.exp_name,args.dataset,args.batch_size,args.epoch,args.step_size,args.max_frames,total_step+1,args.EF,args.q,args.percent_vari)) # 指定输出文件 # 第三部分要说明关键参数的设定 sys.stdout = Logger(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'log'+time.strftime(\".%m_%d_%H-%M-%S\")+'.txt')) data_file =codecs.open(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'data.txt'),mode='a') if",
"os.path as osp import sys from torch.backends import cudnn from reid.utils.serialization import load_checkpoint",
"/ args.EF), (1 / args.q))) # 这里应该取上限或者 +2 多一轮进行one-shot训练的 # EUG base 采样策略",
"+ NN + len(l_data))) + 2 # big start 策略 # 输出该轮训练关键的提示信息 print(\"{}",
"的设定 new_nums_to_select = min(math.ceil(len(u_data) * math.pow((step + 1), args.q) * args.EF / 100),len(u_data))",
"step != resume_step else eug.resume(ckpt_file, step) # 开始评估 evaluate_start = time.time() # mAP,",
"label_pre, id_num = 0,0,0,0 pred_y, pred_score, label_pre, dists = eug.estimate_label() estimate_end = time.time()",
"resume_step, ckpt_file = -1, '' if args.resume: # 重新训练的时候用 resume_step, ckpt_file = resume(args)",
"= time.time() # mAP, top1, top5, top10, top20 = 0,0,0,0,0 mAP,top1,top5,top10,top20 = eug.evaluate(dataset_all.query,",
"label_pre,select_pre)) if args.clock: train_time = evaluate_start-train_start evaluate_time = estimate_start - evaluate_start estimate_time =",
"codecs from common_tool import * def main(args): # 声明动态绘图器 gd = gif_drawer() cudnn.benchmark",
"+ 1), args.q) * args.EF / 100),len(u_data)) # EUG 基础指数渐进策略 # new_nums_to_select =",
"top20, nums_to_select, expend_nums_to_select,nums_to_select / len(u_data), label_pre,select_pre)) if args.clock: train_time = evaluate_start-train_start evaluate_time =",
"=0 # 输出该epoch的信息 data_file.write(\"step:{} mAP:{:.2%} top1:{:.2%} top5:{:.2%} top10:{:.2%} top20:{:.2%} nums_selected:{} expend_nums_to_select:{} selected_percent:{:.2%} label_pre:{:.2%}",
"print_function, absolute_import from reid.snatch import * from reid import datasets from reid import",
"+ args.yita + len(u_data)) / (args.yita + NN + len(l_data))) + 2 #",
"total_step = math.ceil(math.pow((100 / args.EF), (1 / args.q))) # 这里应该取上限或者 +2 多一轮进行one-shot训练的 #",
"!= resume_step else eug.resume(ckpt_file, step) # 开始评估 evaluate_start = time.time() # mAP, top1,",
"working_dir = os.path.dirname(os.path.abspath(__file__)) parser.add_argument('--data_dir', type=str, metavar='PATH',default=os.path.join(working_dir, 'data')) # 加载数据集的根目录 parser.add_argument('--logs_dir', type=str, metavar='PATH',default=os.path.join(working_dir, 'logs'))",
"int(step+1), mAP, top1, top5, top10, top20, nums_to_select, expend_nums_to_select,nums_to_select / len(u_data), label_pre,select_pre)) if args.clock:",
"step = 0 if args.resume: step = resume_step nums_to_select = min(math.ceil(len(u_data) * math.pow((step),",
"= [] isout = 0 #用来标记是否应该结束训练 # 开始的时间记录 exp_start = time.time() while(not isout):",
"label_pre, dists = eug.estimate_label() estimate_end = time.time() # 循环退出判断 if nums_to_select == len(u_data):",
"== '__main__': parser = argparse.ArgumentParser(description='Snatch Strategy') parser.add_argument('-d', '--dataset', type=str, default='DukeMTMC-VideoReID',choices=datasets.names()) #DukeMTMC-VideoReID \\mars parser.add_argument('-b',",
"mAP, top1, top5, top10, top20, nums_to_select, expend_nums_to_select,nums_to_select / len(u_data), label_pre,select_pre)) if args.clock: train_time",
"True # get all the labeled and unlabeled data for training dataset_all =",
"开始训练 train_start = time.time() eug.train(new_train_data, step, epochs=args.epoch, step_size=args.step_size, init_lr=0.1) if step != resume_step",
"if nums_to_select == len(u_data): isout = 1 # nums_to_select 的设定 new_nums_to_select = min(math.ceil(len(u_data)",
"# new_nums_to_select = min(math.ceil((len(u_data)-args.yita)*(step-1)/(total_step-2))+args.yita,len(u_data)) # big start new_expend_nums_to_select = min(len(u_data), math.ceil(new_nums_to_select / args.percent_vari))",
"print(\"{} training begin with dataset:{},batch_size:{},epoch:{},step_size:{},max_frames:{},total_step:{},EF:{},q:{},percent_vari:{}\".format(args.exp_name,args.dataset,args.batch_size,args.epoch,args.step_size,args.max_frames,total_step+1,args.EF,args.q,args.percent_vari)) # 指定输出文件 # 第三部分要说明关键参数的设定 sys.stdout = Logger(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'log'+time.strftime(\".%m_%d_%H-%M-%S\")+'.txt'))",
"start 策略 # 输出该轮训练关键的提示信息 print(\"{} training begin with dataset:{},batch_size:{},epoch:{},step_size:{},max_frames:{},total_step:{},EF:{},q:{},percent_vari:{}\".format(args.exp_name,args.dataset,args.batch_size,args.epoch,args.step_size,args.max_frames,total_step+1,args.EF,args.q,args.percent_vari)) # 指定输出文件 # 第三部分要说明关键参数的设定",
"= EUG(model_name=args.arch, batch_size=args.batch_size, mode=args.mode, num_classes=dataset_all.num_train_ids, data_dir=dataset_all.images_dir, l_data=l_data, u_data=u_data, save_path=save_path, max_frames=args.max_frames) # 训练之前初始化数据 nums_to_select",
"from reid.snatch import * from reid import datasets from reid import models import",
"save_path = osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order) resume_step, ckpt_file = -1, '' if args.resume: # 重新训练的时候用",
"contain EF:{},q:{},percent_vari:{}. Nums_been_selected:{}\".format(args.EF,args.q,args.percent_vari,nums_to_select)) # 开始训练 train_start = time.time() eug.train(new_train_data, step, epochs=args.epoch, step_size=args.step_size, init_lr=0.1)",
"# 指定输出文件 # 第三部分要说明关键参数的设定 sys.stdout = Logger(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'log'+time.strftime(\".%m_%d_%H-%M-%S\")+'.txt')) data_file =codecs.open(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'data.txt'),mode='a') if args.clock",
"import os from reid.utils.logging import Logger import os.path as osp import sys from",
"load_path=\"./examples/oneshot_{}_used_in_paper.pickle\".format( dataset_all.name)) NN = len(l_data) + len(u_data) # 总的训练step数的计算 total_step = math.ceil(math.pow((100 /",
"= True cudnn.enabled = True # get all the labeled and unlabeled data",
"train_start = time.time() eug.train(new_train_data, step, epochs=args.epoch, step_size=args.step_size, init_lr=0.1) if step != resume_step else",
"new_nums_to_select = min(math.ceil(len(u_data) * math.pow((step + 1), args.q) * args.EF / 100),len(u_data)) #",
"args.percent_vari)) selected_idx = eug.select_top_data_nlvm_b1(pred_score,dists, new_expend_nums_to_select,new_nums_to_select) new_train_data, select_pre = eug.generate_new_train_data(selected_idx, pred_y) # select_pre =0",
"args.EF / 100),len(u_data)) # EUG 基础指数渐进策略 # new_nums_to_select = min(math.ceil((len(u_data)-args.yita)*(step-1)/(total_step-2))+args.yita,len(u_data)) # big start",
"top10:{:.2%} top20:{:.2%} nums_selected:{} expend_nums_to_select:{} selected_percent:{:.2%} label_pre:{:.2%} select_pre:{:.2%}\\n\".format( int(step+1), mAP, top1, top5, top10, top20,",
"parser.add_argument('-a', '--arch', type=str, default='avg_pool',choices=models.names()) #eug model_name parser.add_argument('-i', '--iter-step', type=int, default=5) parser.add_argument('-g', '--gamma', type=float,",
"100), len(u_data)) step_size = [] isout = 0 #用来标记是否应该结束训练 # 开始的时间记录 exp_start =",
"0,0,0,0 pred_y, pred_score, label_pre, dists = eug.estimate_label() estimate_end = time.time() # 循环退出判断 if",
"default=0.8) # 方差的筛选范围. working_dir = os.path.dirname(os.path.abspath(__file__)) parser.add_argument('--data_dir', type=str, metavar='PATH',default=os.path.join(working_dir, 'data')) # 加载数据集的根目录 parser.add_argument('--logs_dir',",
"s)) time_file.close() if __name__ == '__main__': parser = argparse.ArgumentParser(description='Snatch Strategy') parser.add_argument('-d', '--dataset', type=str,",
"as plt import os import codecs from common_tool import * def main(args): #",
"args.q) * args.EF / 100),len(u_data)) # EUG 基础指数渐进策略 # new_nums_to_select = min(math.ceil((len(u_data)-args.yita)*(step-1)/(total_step-2))+args.yita,len(u_data)) #",
"dataset_all.gallery) # 标签估计 estimate_start = time.time() # pred_y, pred_score, label_pre, id_num = 0,0,0,0",
"osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order) resume_step, ckpt_file = -1, '' if args.resume: # 重新训练的时候用 resume_step, ckpt_file",
"# 重新训练的时候用 resume_step, ckpt_file = resume(args) # initial the EUG algorithm eug =",
"data_file.write(\"step:{} mAP:{:.2%} top1:{:.2%} top5:{:.2%} top10:{:.2%} top20:{:.2%} nums_selected:{} expend_nums_to_select:{} selected_percent:{:.2%} label_pre:{:.2%} select_pre:{:.2%}\\n\".format( int(step+1), mAP,",
"nums_to_select 的设定 new_nums_to_select = min(math.ceil(len(u_data) * math.pow((step + 1), args.q) * args.EF /",
"unlabeled data for training dataset_all = datasets.create(args.dataset, osp.join(args.data_dir, args.dataset)) l_data, u_data = get_one_shot_in_cam1(dataset_all,",
"EUG base 采样策略 # total_step = math.ceil((2 * NN * args.step_s + args.yita",
"nums_selected:{} expend_nums_to_select:{} selected_percent:{:.2%} label_pre:{:.2%} select_pre:{:.2%}\\n\".format( int(step+1), mAP, top1, top5, top10, top20, nums_to_select, expend_nums_to_select,nums_to_select",
"= len(l_data) + len(u_data) # 总的训练step数的计算 total_step = math.ceil(math.pow((100 / args.EF), (1 /",
"parser.add_argument('--q', type=float, default=1) # 渐进采样指数 parser.add_argument('--percent_vari', type=float, default=0.8) # 方差的筛选范围. working_dir = os.path.dirname(os.path.abspath(__file__))",
"True cudnn.enabled = True # get all the labeled and unlabeled data for",
"# nums_to_select 的设定 new_nums_to_select = min(math.ceil(len(u_data) * math.pow((step + 1), args.q) * args.EF",
"* from reid import datasets from reid import models import numpy as np",
"= eug.generate_new_train_data(selected_idx, pred_y) # select_pre =0 # 输出该epoch的信息 data_file.write(\"step:{} mAP:{:.2%} top1:{:.2%} top5:{:.2%} top10:{:.2%}",
"= resume_step nums_to_select = min(math.ceil(len(u_data) * math.pow((step), args.q) * args.EF / 100), len(u_data))",
"(1 / args.q))) # 这里应该取上限或者 +2 多一轮进行one-shot训练的 # EUG base 采样策略 # total_step",
"= datasets.create(args.dataset, osp.join(args.data_dir, args.dataset)) l_data, u_data = get_one_shot_in_cam1(dataset_all, load_path=\"./examples/oneshot_{}_used_in_paper.pickle\".format( dataset_all.name)) NN = len(l_data)",
"args.yita + len(u_data)) / (args.yita + NN + len(l_data))) + 2 # big",
"循环退出判断 if nums_to_select == len(u_data): isout = 1 # nums_to_select 的设定 new_nums_to_select =",
"isout = 1 # nums_to_select 的设定 new_nums_to_select = min(math.ceil(len(u_data) * math.pow((step + 1),",
"parser.add_argument('--epoch',type=int,default=40) parser.add_argument('--step_size',type=int,default=30) parser.add_argument('--EF', type=float, default=10) # 渐进采样系数 parser.add_argument('--q', type=float, default=1) # 渐进采样指数 parser.add_argument('--percent_vari',",
"time.time() exp_time = exp_end - exp_start h, m, s = changetoHSM(exp_time) print(\"experiment is",
"print(\"{} training begin with dataset:{},batch_size:{},epoch:{},step:{}/{} saved to {}.\".format(args.exp_name,args.dataset,args.batch_size, args.epoch,step+1,total_step+1,save_path)) print(\"key parameters contain EF:{},q:{},percent_vari:{}.",
"eug.select_top_data_nlvm_b1(pred_score,dists, new_expend_nums_to_select,new_nums_to_select) new_train_data, select_pre = eug.generate_new_train_data(selected_idx, pred_y) # select_pre =0 # 输出该epoch的信息 data_file.write(\"step:{}",
"if args.clock: train_time = evaluate_start-train_start evaluate_time = estimate_start - evaluate_start estimate_time = estimate_end-estimate_start",
"default=1) # 渐进采样指数 parser.add_argument('--percent_vari', type=float, default=0.8) # 方差的筛选范围. working_dir = os.path.dirname(os.path.abspath(__file__)) parser.add_argument('--data_dir', type=str,",
"models import numpy as np import torch import argparse import os from reid.utils.logging",
"# 保持日志根目录 parser.add_argument('--exp_name',type=str,default=\"nlvm-b1\") parser.add_argument('--exp_order',type=str,default=\"1\") parser.add_argument('--resume', type=str, default=None) parser.add_argument('--mode', type=str, choices=[\"Classification\", \"Dissimilarity\"], default=\"Dissimilarity\") #这个考虑要不要取消掉",
"expend_nums_to_select,nums_to_select / len(u_data), label_pre,select_pre)) if args.clock: train_time = evaluate_start-train_start evaluate_time = estimate_start -",
"default=\"Dissimilarity\") #这个考虑要不要取消掉 parser.add_argument('--max_frames', type=int, default=400) parser.add_argument('--clock',type=bool, default=True) #是否记时 parser.add_argument('--gdraw',type=bool, default=False) #是否实时绘图 #下面是暂时不知道用来做什么的参数 parser.add_argument('-a',",
"changetoHSM(exp_time) print(\"experiment is over, cost %02d:%02d:%02.6f\" % ( h, m, s)) time_file.close() if",
"training begin with dataset:{},batch_size:{},epoch:{},step:{}/{} saved to {}.\".format(args.exp_name,args.dataset,args.batch_size, args.epoch,step+1,total_step+1,save_path)) print(\"key parameters contain EF:{},q:{},percent_vari:{}. Nums_been_selected:{}\".format(args.EF,args.q,args.percent_vari,nums_to_select))",
"len(l_data))) + 2 # big start 策略 # 输出该轮训练关键的提示信息 print(\"{} training begin with",
"(args.yita + NN + len(l_data))) + 2 # big start 策略 # 输出该轮训练关键的提示信息",
"= l_data step = 0 if args.resume: step = resume_step nums_to_select = min(math.ceil(len(u_data)",
"# 标签估计 estimate_start = time.time() # pred_y, pred_score, label_pre, id_num = 0,0,0,0 pred_y,",
"= estimate_end-estimate_start epoch_time = train_time+estimate_time time_file.write(\"step:{} train:{} evaluate:{} estimate:{} epoch:{}\\n\".format(int(step+1),train_time,evaluate_time,estimate_time,epoch_time)) if args.gdraw: gd.draw(nums_to_select/len(u_data),top1,mAP,label_pre,select_pre)",
"math.pow((step), args.q) * args.EF / 100), len(u_data)) step_size = [] isout = 0",
"<reponame>joselynzhao/One-shot-Person-Re-ID-with-Variance-Subsampling-Method from __future__ import print_function, absolute_import from reid.snatch import * from reid import",
"gd.draw(nums_to_select/len(u_data),top1,mAP,label_pre,select_pre) nums_to_select = new_nums_to_select expend_nums_to_select = new_expend_nums_to_select step = step + 1 data_file.close()",
"__future__ import print_function, absolute_import from reid.snatch import * from reid import datasets from",
"training dataset_all = datasets.create(args.dataset, osp.join(args.data_dir, args.dataset)) l_data, u_data = get_one_shot_in_cam1(dataset_all, load_path=\"./examples/oneshot_{}_used_in_paper.pickle\".format( dataset_all.name)) NN",
"= eug.evaluate(dataset_all.query, dataset_all.gallery) # 标签估计 estimate_start = time.time() # pred_y, pred_score, label_pre, id_num",
"args.gdraw: gd.draw(nums_to_select/len(u_data),top1,mAP,label_pre,select_pre) nums_to_select = new_nums_to_select expend_nums_to_select = new_expend_nums_to_select step = step + 1",
"data for training dataset_all = datasets.create(args.dataset, osp.join(args.data_dir, args.dataset)) l_data, u_data = get_one_shot_in_cam1(dataset_all, load_path=\"./examples/oneshot_{}_used_in_paper.pickle\".format(",
"eug = EUG(model_name=args.arch, batch_size=args.batch_size, mode=args.mode, num_classes=dataset_all.num_train_ids, data_dir=dataset_all.images_dir, l_data=l_data, u_data=u_data, save_path=save_path, max_frames=args.max_frames) # 训练之前初始化数据",
"time_file.write(\"step:{} train:{} evaluate:{} estimate:{} epoch:{}\\n\".format(int(step+1),train_time,evaluate_time,estimate_time,epoch_time)) if args.gdraw: gd.draw(nums_to_select/len(u_data),top1,mAP,label_pre,select_pre) nums_to_select = new_nums_to_select expend_nums_to_select =",
"import load_checkpoint from torch import nn import time import math import pickle import",
"the labeled and unlabeled data for training dataset_all = datasets.create(args.dataset, osp.join(args.data_dir, args.dataset)) l_data,",
"top1, top5,top10,top20,nums_to_select, expend_nums_to_select,nums_to_select/len(u_data),label_pre,select_pre)) print( \"step:{} mAP:{:.2%} top1:{:.2%} top5:{:.2%} top10:{:.2%} top20:{:.2%} nums_selected:{} expend_nums_to_select:{} selected_percent:{:.2%}",
"max_frames=args.max_frames) # 训练之前初始化数据 nums_to_select = 0 expend_nums_to_select = 0 new_train_data = l_data step",
"import datasets from reid import models import numpy as np import torch import",
"开始评估 evaluate_start = time.time() # mAP, top1, top5, top10, top20 = 0,0,0,0,0 mAP,top1,top5,top10,top20",
"with dataset:{},batch_size:{},epoch:{},step:{}/{} saved to {}.\".format(args.exp_name,args.dataset,args.batch_size, args.epoch,step+1,total_step+1,save_path)) print(\"key parameters contain EF:{},q:{},percent_vari:{}. Nums_been_selected:{}\".format(args.EF,args.q,args.percent_vari,nums_to_select)) # 开始训练",
"import time import matplotlib.pyplot as plt import os import codecs from common_tool import",
"parser.add_argument('--max_frames', type=int, default=400) parser.add_argument('--clock',type=bool, default=True) #是否记时 parser.add_argument('--gdraw',type=bool, default=False) #是否实时绘图 #下面是暂时不知道用来做什么的参数 parser.add_argument('-a', '--arch', type=str,",
"len(u_data) # 总的训练step数的计算 total_step = math.ceil(math.pow((100 / args.EF), (1 / args.q))) # 这里应该取上限或者",
"( h, m, s)) time_file.close() if __name__ == '__main__': parser = argparse.ArgumentParser(description='Snatch Strategy')",
"big start new_expend_nums_to_select = min(len(u_data), math.ceil(new_nums_to_select / args.percent_vari)) selected_idx = eug.select_top_data_nlvm_b1(pred_score,dists, new_expend_nums_to_select,new_nums_to_select) new_train_data,",
"'--batch-size', type=int, default=16) parser.add_argument('--epoch',type=int,default=40) parser.add_argument('--step_size',type=int,default=30) parser.add_argument('--EF', type=float, default=10) # 渐进采样系数 parser.add_argument('--q', type=float, default=1)",
"all the labeled and unlabeled data for training dataset_all = datasets.create(args.dataset, osp.join(args.data_dir, args.dataset))",
"import nn import time import math import pickle import time import matplotlib.pyplot as",
"dataset_all = datasets.create(args.dataset, osp.join(args.data_dir, args.dataset)) l_data, u_data = get_one_shot_in_cam1(dataset_all, load_path=\"./examples/oneshot_{}_used_in_paper.pickle\".format( dataset_all.name)) NN =",
"len(u_data)) step_size = [] isout = 0 #用来标记是否应该结束训练 # 开始的时间记录 exp_start = time.time()",
"# big start 策略 # 输出该轮训练关键的提示信息 print(\"{} training begin with dataset:{},batch_size:{},epoch:{},step_size:{},max_frames:{},total_step:{},EF:{},q:{},percent_vari:{}\".format(args.exp_name,args.dataset,args.batch_size,args.epoch,args.step_size,args.max_frames,total_step+1,args.EF,args.q,args.percent_vari)) # 指定输出文件",
"time.time() eug.train(new_train_data, step, epochs=args.epoch, step_size=args.step_size, init_lr=0.1) if step != resume_step else eug.resume(ckpt_file, step)",
"= Logger(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'log'+time.strftime(\".%m_%d_%H-%M-%S\")+'.txt')) data_file =codecs.open(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'data.txt'),mode='a') if args.clock : time_file =codecs.open(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'time.txt'),mode='a') save_path",
"l_data step = 0 if args.resume: step = resume_step nums_to_select = min(math.ceil(len(u_data) *",
"# 渐进采样指数 parser.add_argument('--percent_vari', type=float, default=0.8) # 方差的筛选范围. working_dir = os.path.dirname(os.path.abspath(__file__)) parser.add_argument('--data_dir', type=str, metavar='PATH',default=os.path.join(working_dir,",
"type=int, default=16) parser.add_argument('--epoch',type=int,default=40) parser.add_argument('--step_size',type=int,default=30) parser.add_argument('--EF', type=float, default=10) # 渐进采样系数 parser.add_argument('--q', type=float, default=1) #",
"step, epochs=args.epoch, step_size=args.step_size, init_lr=0.1) if step != resume_step else eug.resume(ckpt_file, step) # 开始评估",
"default=10) # 渐进采样系数 parser.add_argument('--q', type=float, default=1) # 渐进采样指数 parser.add_argument('--percent_vari', type=float, default=0.8) # 方差的筛选范围.",
"parser.add_argument('-b', '--batch-size', type=int, default=16) parser.add_argument('--epoch',type=int,default=40) parser.add_argument('--step_size',type=int,default=30) parser.add_argument('--EF', type=float, default=10) # 渐进采样系数 parser.add_argument('--q', type=float,",
"nums_to_select, expend_nums_to_select,nums_to_select / len(u_data), label_pre,select_pre)) if args.clock: train_time = evaluate_start-train_start evaluate_time = estimate_start",
"parser.add_argument('--exp_order',type=str,default=\"1\") parser.add_argument('--resume', type=str, default=None) parser.add_argument('--mode', type=str, choices=[\"Classification\", \"Dissimilarity\"], default=\"Dissimilarity\") #这个考虑要不要取消掉 parser.add_argument('--max_frames', type=int, default=400)",
"as np import torch import argparse import os from reid.utils.logging import Logger import",
"0 new_train_data = l_data step = 0 if args.resume: step = resume_step nums_to_select",
"0 #用来标记是否应该结束训练 # 开始的时间记录 exp_start = time.time() while(not isout): print(\"{} training begin with",
"# 第三部分要说明关键参数的设定 sys.stdout = Logger(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'log'+time.strftime(\".%m_%d_%H-%M-%S\")+'.txt')) data_file =codecs.open(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'data.txt'),mode='a') if args.clock : time_file",
"min(len(u_data), math.ceil(new_nums_to_select / args.percent_vari)) selected_idx = eug.select_top_data_nlvm_b1(pred_score,dists, new_expend_nums_to_select,new_nums_to_select) new_train_data, select_pre = eug.generate_new_train_data(selected_idx, pred_y)",
"# 输出该epoch的信息 data_file.write(\"step:{} mAP:{:.2%} top1:{:.2%} top5:{:.2%} top10:{:.2%} top20:{:.2%} nums_selected:{} expend_nums_to_select:{} selected_percent:{:.2%} label_pre:{:.2%} select_pre:{:.2%}\\n\".format(",
"import print_function, absolute_import from reid.snatch import * from reid import datasets from reid",
"标签估计 estimate_start = time.time() # pred_y, pred_score, label_pre, id_num = 0,0,0,0 pred_y, pred_score,",
"gd = gif_drawer() cudnn.benchmark = True cudnn.enabled = True # get all the",
"+ 2 # big start 策略 # 输出该轮训练关键的提示信息 print(\"{} training begin with dataset:{},batch_size:{},epoch:{},step_size:{},max_frames:{},total_step:{},EF:{},q:{},percent_vari:{}\".format(args.exp_name,args.dataset,args.batch_size,args.epoch,args.step_size,args.max_frames,total_step+1,args.EF,args.q,args.percent_vari))",
"main(args): # 声明动态绘图器 gd = gif_drawer() cudnn.benchmark = True cudnn.enabled = True #",
"parameters contain EF:{},q:{},percent_vari:{}. Nums_been_selected:{}\".format(args.EF,args.q,args.percent_vari,nums_to_select)) # 开始训练 train_start = time.time() eug.train(new_train_data, step, epochs=args.epoch, step_size=args.step_size,",
"import time import math import pickle import time import matplotlib.pyplot as plt import",
"argparse import os from reid.utils.logging import Logger import os.path as osp import sys",
"evaluate_time = estimate_start - evaluate_start estimate_time = estimate_end-estimate_start epoch_time = train_time+estimate_time time_file.write(\"step:{} train:{}",
"策略 # 输出该轮训练关键的提示信息 print(\"{} training begin with dataset:{},batch_size:{},epoch:{},step_size:{},max_frames:{},total_step:{},EF:{},q:{},percent_vari:{}\".format(args.exp_name,args.dataset,args.batch_size,args.epoch,args.step_size,args.max_frames,total_step+1,args.EF,args.q,args.percent_vari)) # 指定输出文件 # 第三部分要说明关键参数的设定 sys.stdout",
"step_size=args.step_size, init_lr=0.1) if step != resume_step else eug.resume(ckpt_file, step) # 开始评估 evaluate_start =",
"args.dataset,args.exp_name,args.exp_order,'data.txt'),mode='a') if args.clock : time_file =codecs.open(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'time.txt'),mode='a') save_path = osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order) resume_step, ckpt_file",
"exp_start = time.time() while(not isout): print(\"{} training begin with dataset:{},batch_size:{},epoch:{},step:{}/{} saved to {}.\".format(args.exp_name,args.dataset,args.batch_size,",
"= time.time() # pred_y, pred_score, label_pre, id_num = 0,0,0,0 pred_y, pred_score, label_pre, dists",
"= time.time() # 循环退出判断 if nums_to_select == len(u_data): isout = 1 # nums_to_select",
"nums_to_select = new_nums_to_select expend_nums_to_select = new_expend_nums_to_select step = step + 1 data_file.close() if",
"parser.add_argument('--resume', type=str, default=None) parser.add_argument('--mode', type=str, choices=[\"Classification\", \"Dissimilarity\"], default=\"Dissimilarity\") #这个考虑要不要取消掉 parser.add_argument('--max_frames', type=int, default=400) parser.add_argument('--clock',type=bool,",
"base 采样策略 # total_step = math.ceil((2 * NN * args.step_s + args.yita +",
"= time.time() while(not isout): print(\"{} training begin with dataset:{},batch_size:{},epoch:{},step:{}/{} saved to {}.\".format(args.exp_name,args.dataset,args.batch_size, args.epoch,step+1,total_step+1,save_path))",
"= 0 expend_nums_to_select = 0 new_train_data = l_data step = 0 if args.resume:",
"saved to {}.\".format(args.exp_name,args.dataset,args.batch_size, args.epoch,step+1,total_step+1,save_path)) print(\"key parameters contain EF:{},q:{},percent_vari:{}. Nums_been_selected:{}\".format(args.EF,args.q,args.percent_vari,nums_to_select)) # 开始训练 train_start =",
"'--iter-step', type=int, default=5) parser.add_argument('-g', '--gamma', type=float, default=0.3) parser.add_argument('-l', '--l', type=float) parser.add_argument('--continuous', action=\"store_true\") main(parser.parse_args())",
"-1, '' if args.resume: # 重新训练的时候用 resume_step, ckpt_file = resume(args) # initial the",
"= new_expend_nums_to_select step = step + 1 data_file.close() if (args.clock): exp_end = time.time()",
"if __name__ == '__main__': parser = argparse.ArgumentParser(description='Snatch Strategy') parser.add_argument('-d', '--dataset', type=str, default='DukeMTMC-VideoReID',choices=datasets.names()) #DukeMTMC-VideoReID",
"mAP,top1,top5,top10,top20 = eug.evaluate(dataset_all.query, dataset_all.gallery) # 标签估计 estimate_start = time.time() # pred_y, pred_score, label_pre,",
"metavar='PATH',default=os.path.join(working_dir, 'data')) # 加载数据集的根目录 parser.add_argument('--logs_dir', type=str, metavar='PATH',default=os.path.join(working_dir, 'logs')) # 保持日志根目录 parser.add_argument('--exp_name',type=str,default=\"nlvm-b1\") parser.add_argument('--exp_order',type=str,default=\"1\") parser.add_argument('--resume',",
"datasets.create(args.dataset, osp.join(args.data_dir, args.dataset)) l_data, u_data = get_one_shot_in_cam1(dataset_all, load_path=\"./examples/oneshot_{}_used_in_paper.pickle\".format( dataset_all.name)) NN = len(l_data) +",
"= os.path.dirname(os.path.abspath(__file__)) parser.add_argument('--data_dir', type=str, metavar='PATH',default=os.path.join(working_dir, 'data')) # 加载数据集的根目录 parser.add_argument('--logs_dir', type=str, metavar='PATH',default=os.path.join(working_dir, 'logs')) #",
"Logger(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'log'+time.strftime(\".%m_%d_%H-%M-%S\")+'.txt')) data_file =codecs.open(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'data.txt'),mode='a') if args.clock : time_file =codecs.open(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'time.txt'),mode='a') save_path =",
"time.time() while(not isout): print(\"{} training begin with dataset:{},batch_size:{},epoch:{},step:{}/{} saved to {}.\".format(args.exp_name,args.dataset,args.batch_size, args.epoch,step+1,total_step+1,save_path)) print(\"key",
"training begin with dataset:{},batch_size:{},epoch:{},step_size:{},max_frames:{},total_step:{},EF:{},q:{},percent_vari:{}\".format(args.exp_name,args.dataset,args.batch_size,args.epoch,args.step_size,args.max_frames,total_step+1,args.EF,args.q,args.percent_vari)) # 指定输出文件 # 第三部分要说明关键参数的设定 sys.stdout = Logger(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'log'+time.strftime(\".%m_%d_%H-%M-%S\")+'.txt')) data_file",
"import pickle import time import matplotlib.pyplot as plt import os import codecs from",
"batch_size=args.batch_size, mode=args.mode, num_classes=dataset_all.num_train_ids, data_dir=dataset_all.images_dir, l_data=l_data, u_data=u_data, save_path=save_path, max_frames=args.max_frames) # 训练之前初始化数据 nums_to_select = 0",
"step = resume_step nums_to_select = min(math.ceil(len(u_data) * math.pow((step), args.q) * args.EF / 100),",
"EUG 基础指数渐进策略 # new_nums_to_select = min(math.ceil((len(u_data)-args.yita)*(step-1)/(total_step-2))+args.yita,len(u_data)) # big start new_expend_nums_to_select = min(len(u_data), math.ceil(new_nums_to_select",
"top10:{:.2%} top20:{:.2%} nums_selected:{} expend_nums_to_select:{} selected_percent:{:.2%} label_pre:{:.2%} select_pre:{:.2%}\\n\".format( int(step+1), mAP, top1, top5,top10,top20,nums_to_select, expend_nums_to_select,nums_to_select/len(u_data),label_pre,select_pre)) print(",
"as osp import sys from torch.backends import cudnn from reid.utils.serialization import load_checkpoint from",
"with dataset:{},batch_size:{},epoch:{},step_size:{},max_frames:{},total_step:{},EF:{},q:{},percent_vari:{}\".format(args.exp_name,args.dataset,args.batch_size,args.epoch,args.step_size,args.max_frames,total_step+1,args.EF,args.q,args.percent_vari)) # 指定输出文件 # 第三部分要说明关键参数的设定 sys.stdout = Logger(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'log'+time.strftime(\".%m_%d_%H-%M-%S\")+'.txt')) data_file =codecs.open(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'data.txt'),mode='a')",
"data_file =codecs.open(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'data.txt'),mode='a') if args.clock : time_file =codecs.open(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'time.txt'),mode='a') save_path = osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order)",
"= 0,0,0,0,0 mAP,top1,top5,top10,top20 = eug.evaluate(dataset_all.query, dataset_all.gallery) # 标签估计 estimate_start = time.time() # pred_y,",
"{}.\".format(args.exp_name,args.dataset,args.batch_size, args.epoch,step+1,total_step+1,save_path)) print(\"key parameters contain EF:{},q:{},percent_vari:{}. Nums_been_selected:{}\".format(args.EF,args.q,args.percent_vari,nums_to_select)) # 开始训练 train_start = time.time() eug.train(new_train_data,",
"top20:{:.2%} nums_selected:{} expend_nums_to_select:{} selected_percent:{:.2%} label_pre:{:.2%} select_pre:{:.2%}\\n\".format( int(step+1), mAP, top1, top5,top10,top20,nums_to_select, expend_nums_to_select,nums_to_select/len(u_data),label_pre,select_pre)) print( \"step:{}",
"dataset:{},batch_size:{},epoch:{},step:{}/{} saved to {}.\".format(args.exp_name,args.dataset,args.batch_size, args.epoch,step+1,total_step+1,save_path)) print(\"key parameters contain EF:{},q:{},percent_vari:{}. Nums_been_selected:{}\".format(args.EF,args.q,args.percent_vari,nums_to_select)) # 开始训练 train_start",
"= evaluate_start-train_start evaluate_time = estimate_start - evaluate_start estimate_time = estimate_end-estimate_start epoch_time = train_time+estimate_time",
"big start 策略 # 输出该轮训练关键的提示信息 print(\"{} training begin with dataset:{},batch_size:{},epoch:{},step_size:{},max_frames:{},total_step:{},EF:{},q:{},percent_vari:{}\".format(args.exp_name,args.dataset,args.batch_size,args.epoch,args.step_size,args.max_frames,total_step+1,args.EF,args.q,args.percent_vari)) # 指定输出文件 #",
"+ 1 data_file.close() if (args.clock): exp_end = time.time() exp_time = exp_end - exp_start",
"import torch import argparse import os from reid.utils.logging import Logger import os.path as",
"import Logger import os.path as osp import sys from torch.backends import cudnn from",
"# pred_y, pred_score, label_pre, id_num = 0,0,0,0 pred_y, pred_score, label_pre, dists = eug.estimate_label()",
"总的训练step数的计算 total_step = math.ceil(math.pow((100 / args.EF), (1 / args.q))) # 这里应该取上限或者 +2 多一轮进行one-shot训练的",
"保持日志根目录 parser.add_argument('--exp_name',type=str,default=\"nlvm-b1\") parser.add_argument('--exp_order',type=str,default=\"1\") parser.add_argument('--resume', type=str, default=None) parser.add_argument('--mode', type=str, choices=[\"Classification\", \"Dissimilarity\"], default=\"Dissimilarity\") #这个考虑要不要取消掉 parser.add_argument('--max_frames',",
"default=True) #是否记时 parser.add_argument('--gdraw',type=bool, default=False) #是否实时绘图 #下面是暂时不知道用来做什么的参数 parser.add_argument('-a', '--arch', type=str, default='avg_pool',choices=models.names()) #eug model_name parser.add_argument('-i',",
"# 开始的时间记录 exp_start = time.time() while(not isout): print(\"{} training begin with dataset:{},batch_size:{},epoch:{},step:{}/{} saved",
"epoch:{}\\n\".format(int(step+1),train_time,evaluate_time,estimate_time,epoch_time)) if args.gdraw: gd.draw(nums_to_select/len(u_data),top1,mAP,label_pre,select_pre) nums_to_select = new_nums_to_select expend_nums_to_select = new_expend_nums_to_select step = step",
"data_dir=dataset_all.images_dir, l_data=l_data, u_data=u_data, save_path=save_path, max_frames=args.max_frames) # 训练之前初始化数据 nums_to_select = 0 expend_nums_to_select = 0",
"args.resume: # 重新训练的时候用 resume_step, ckpt_file = resume(args) # initial the EUG algorithm eug",
"= eug.select_top_data_nlvm_b1(pred_score,dists, new_expend_nums_to_select,new_nums_to_select) new_train_data, select_pre = eug.generate_new_train_data(selected_idx, pred_y) # select_pre =0 # 输出该epoch的信息",
"step_size = [] isout = 0 #用来标记是否应该结束训练 # 开始的时间记录 exp_start = time.time() while(not",
"= estimate_start - evaluate_start estimate_time = estimate_end-estimate_start epoch_time = train_time+estimate_time time_file.write(\"step:{} train:{} evaluate:{}",
"Logger import os.path as osp import sys from torch.backends import cudnn from reid.utils.serialization",
"type=str, default=None) parser.add_argument('--mode', type=str, choices=[\"Classification\", \"Dissimilarity\"], default=\"Dissimilarity\") #这个考虑要不要取消掉 parser.add_argument('--max_frames', type=int, default=400) parser.add_argument('--clock',type=bool, default=True)",
"type=str, default='DukeMTMC-VideoReID',choices=datasets.names()) #DukeMTMC-VideoReID \\mars parser.add_argument('-b', '--batch-size', type=int, default=16) parser.add_argument('--epoch',type=int,default=40) parser.add_argument('--step_size',type=int,default=30) parser.add_argument('--EF', type=float, default=10)",
"+ len(l_data))) + 2 # big start 策略 # 输出该轮训练关键的提示信息 print(\"{} training begin",
"expend_nums_to_select = new_expend_nums_to_select step = step + 1 data_file.close() if (args.clock): exp_end =",
"resume_step nums_to_select = min(math.ceil(len(u_data) * math.pow((step), args.q) * args.EF / 100), len(u_data)) step_size",
"#是否记时 parser.add_argument('--gdraw',type=bool, default=False) #是否实时绘图 #下面是暂时不知道用来做什么的参数 parser.add_argument('-a', '--arch', type=str, default='avg_pool',choices=models.names()) #eug model_name parser.add_argument('-i', '--iter-step',",
"default='DukeMTMC-VideoReID',choices=datasets.names()) #DukeMTMC-VideoReID \\mars parser.add_argument('-b', '--batch-size', type=int, default=16) parser.add_argument('--epoch',type=int,default=40) parser.add_argument('--step_size',type=int,default=30) parser.add_argument('--EF', type=float, default=10) #",
"eug.estimate_label() estimate_end = time.time() # 循环退出判断 if nums_to_select == len(u_data): isout = 1",
"top20:{:.2%} nums_selected:{} expend_nums_to_select:{} selected_percent:{:.2%} label_pre:{:.2%} select_pre:{:.2%}\\n\".format( int(step+1), mAP, top1, top5, top10, top20, nums_to_select,",
"from reid import models import numpy as np import torch import argparse import",
"reid import models import numpy as np import torch import argparse import os",
"__name__ == '__main__': parser = argparse.ArgumentParser(description='Snatch Strategy') parser.add_argument('-d', '--dataset', type=str, default='DukeMTMC-VideoReID',choices=datasets.names()) #DukeMTMC-VideoReID \\mars",
"[] isout = 0 #用来标记是否应该结束训练 # 开始的时间记录 exp_start = time.time() while(not isout): print(\"{}",
"exp_time = exp_end - exp_start h, m, s = changetoHSM(exp_time) print(\"experiment is over,",
"parser.add_argument('--data_dir', type=str, metavar='PATH',default=os.path.join(working_dir, 'data')) # 加载数据集的根目录 parser.add_argument('--logs_dir', type=str, metavar='PATH',default=os.path.join(working_dir, 'logs')) # 保持日志根目录 parser.add_argument('--exp_name',type=str,default=\"nlvm-b1\")",
"len(u_data): isout = 1 # nums_to_select 的设定 new_nums_to_select = min(math.ceil(len(u_data) * math.pow((step +",
"top5:{:.2%} top10:{:.2%} top20:{:.2%} nums_selected:{} expend_nums_to_select:{} selected_percent:{:.2%} label_pre:{:.2%} select_pre:{:.2%}\\n\".format( int(step+1), mAP, top1, top5, top10,",
"多一轮进行one-shot训练的 # EUG base 采样策略 # total_step = math.ceil((2 * NN * args.step_s",
"# get all the labeled and unlabeled data for training dataset_all = datasets.create(args.dataset,",
"estimate_end-estimate_start epoch_time = train_time+estimate_time time_file.write(\"step:{} train:{} evaluate:{} estimate:{} epoch:{}\\n\".format(int(step+1),train_time,evaluate_time,estimate_time,epoch_time)) if args.gdraw: gd.draw(nums_to_select/len(u_data),top1,mAP,label_pre,select_pre) nums_to_select",
"渐进采样指数 parser.add_argument('--percent_vari', type=float, default=0.8) # 方差的筛选范围. working_dir = os.path.dirname(os.path.abspath(__file__)) parser.add_argument('--data_dir', type=str, metavar='PATH',default=os.path.join(working_dir, 'data'))",
"+2 多一轮进行one-shot训练的 # EUG base 采样策略 # total_step = math.ceil((2 * NN *",
"estimate_time = estimate_end-estimate_start epoch_time = train_time+estimate_time time_file.write(\"step:{} train:{} evaluate:{} estimate:{} epoch:{}\\n\".format(int(step+1),train_time,evaluate_time,estimate_time,epoch_time)) if args.gdraw:",
"else eug.resume(ckpt_file, step) # 开始评估 evaluate_start = time.time() # mAP, top1, top5, top10,",
"estimate_end = time.time() # 循环退出判断 if nums_to_select == len(u_data): isout = 1 #",
"* args.EF / 100), len(u_data)) step_size = [] isout = 0 #用来标记是否应该结束训练 #",
"'--arch', type=str, default='avg_pool',choices=models.names()) #eug model_name parser.add_argument('-i', '--iter-step', type=int, default=5) parser.add_argument('-g', '--gamma', type=float, default=0.3)",
"common_tool import * def main(args): # 声明动态绘图器 gd = gif_drawer() cudnn.benchmark = True",
"mAP:{:.2%} top1:{:.2%} top5:{:.2%} top10:{:.2%} top20:{:.2%} nums_selected:{} expend_nums_to_select:{} selected_percent:{:.2%} label_pre:{:.2%} select_pre:{:.2%}\\n\".format( int(step+1), mAP, top1,",
"new_nums_to_select expend_nums_to_select = new_expend_nums_to_select step = step + 1 data_file.close() if (args.clock): exp_end",
"args.clock: train_time = evaluate_start-train_start evaluate_time = estimate_start - evaluate_start estimate_time = estimate_end-estimate_start epoch_time",
"import argparse import os from reid.utils.logging import Logger import os.path as osp import",
"== len(u_data): isout = 1 # nums_to_select 的设定 new_nums_to_select = min(math.ceil(len(u_data) * math.pow((step",
"args.EF / 100), len(u_data)) step_size = [] isout = 0 #用来标记是否应该结束训练 # 开始的时间记录",
"/ 100), len(u_data)) step_size = [] isout = 0 #用来标记是否应该结束训练 # 开始的时间记录 exp_start",
"new_expend_nums_to_select,new_nums_to_select) new_train_data, select_pre = eug.generate_new_train_data(selected_idx, pred_y) # select_pre =0 # 输出该epoch的信息 data_file.write(\"step:{} mAP:{:.2%}",
"len(l_data) + len(u_data) # 总的训练step数的计算 total_step = math.ceil(math.pow((100 / args.EF), (1 / args.q)))",
"top10, top20, nums_to_select, expend_nums_to_select,nums_to_select / len(u_data), label_pre,select_pre)) if args.clock: train_time = evaluate_start-train_start evaluate_time",
"data_file.close() if (args.clock): exp_end = time.time() exp_time = exp_end - exp_start h, m,",
"default=16) parser.add_argument('--epoch',type=int,default=40) parser.add_argument('--step_size',type=int,default=30) parser.add_argument('--EF', type=float, default=10) # 渐进采样系数 parser.add_argument('--q', type=float, default=1) # 渐进采样指数",
"exp_end - exp_start h, m, s = changetoHSM(exp_time) print(\"experiment is over, cost %02d:%02d:%02.6f\"",
"= math.ceil((2 * NN * args.step_s + args.yita + len(u_data)) / (args.yita +",
"algorithm eug = EUG(model_name=args.arch, batch_size=args.batch_size, mode=args.mode, num_classes=dataset_all.num_train_ids, data_dir=dataset_all.images_dir, l_data=l_data, u_data=u_data, save_path=save_path, max_frames=args.max_frames) #",
"mode=args.mode, num_classes=dataset_all.num_train_ids, data_dir=dataset_all.images_dir, l_data=l_data, u_data=u_data, save_path=save_path, max_frames=args.max_frames) # 训练之前初始化数据 nums_to_select = 0 expend_nums_to_select",
"if step != resume_step else eug.resume(ckpt_file, step) # 开始评估 evaluate_start = time.time() #",
"# 方差的筛选范围. working_dir = os.path.dirname(os.path.abspath(__file__)) parser.add_argument('--data_dir', type=str, metavar='PATH',default=os.path.join(working_dir, 'data')) # 加载数据集的根目录 parser.add_argument('--logs_dir', type=str,",
"'data')) # 加载数据集的根目录 parser.add_argument('--logs_dir', type=str, metavar='PATH',default=os.path.join(working_dir, 'logs')) # 保持日志根目录 parser.add_argument('--exp_name',type=str,default=\"nlvm-b1\") parser.add_argument('--exp_order',type=str,default=\"1\") parser.add_argument('--resume', type=str,",
"parser.add_argument('--EF', type=float, default=10) # 渐进采样系数 parser.add_argument('--q', type=float, default=1) # 渐进采样指数 parser.add_argument('--percent_vari', type=float, default=0.8)",
"from reid.utils.serialization import load_checkpoint from torch import nn import time import math import",
"evaluate_start = time.time() # mAP, top1, top5, top10, top20 = 0,0,0,0,0 mAP,top1,top5,top10,top20 =",
"torch import argparse import os from reid.utils.logging import Logger import os.path as osp",
"os from reid.utils.logging import Logger import os.path as osp import sys from torch.backends",
"parser.add_argument('--logs_dir', type=str, metavar='PATH',default=os.path.join(working_dir, 'logs')) # 保持日志根目录 parser.add_argument('--exp_name',type=str,default=\"nlvm-b1\") parser.add_argument('--exp_order',type=str,default=\"1\") parser.add_argument('--resume', type=str, default=None) parser.add_argument('--mode', type=str,",
"numpy as np import torch import argparse import os from reid.utils.logging import Logger",
"type=str, metavar='PATH',default=os.path.join(working_dir, 'data')) # 加载数据集的根目录 parser.add_argument('--logs_dir', type=str, metavar='PATH',default=os.path.join(working_dir, 'logs')) # 保持日志根目录 parser.add_argument('--exp_name',type=str,default=\"nlvm-b1\") parser.add_argument('--exp_order',type=str,default=\"1\")",
"select_pre:{:.2%}\\n\".format( int(step+1), mAP, top1, top5, top10, top20, nums_to_select, expend_nums_to_select,nums_to_select / len(u_data), label_pre,select_pre)) if",
"ckpt_file = resume(args) # initial the EUG algorithm eug = EUG(model_name=args.arch, batch_size=args.batch_size, mode=args.mode,",
"m, s = changetoHSM(exp_time) print(\"experiment is over, cost %02d:%02d:%02.6f\" % ( h, m,",
"# total_step = math.ceil((2 * NN * args.step_s + args.yita + len(u_data)) /",
"resume_step else eug.resume(ckpt_file, step) # 开始评估 evaluate_start = time.time() # mAP, top1, top5,",
"parser.add_argument('--exp_name',type=str,default=\"nlvm-b1\") parser.add_argument('--exp_order',type=str,default=\"1\") parser.add_argument('--resume', type=str, default=None) parser.add_argument('--mode', type=str, choices=[\"Classification\", \"Dissimilarity\"], default=\"Dissimilarity\") #这个考虑要不要取消掉 parser.add_argument('--max_frames', type=int,",
"datasets from reid import models import numpy as np import torch import argparse",
"#eug model_name parser.add_argument('-i', '--iter-step', type=int, default=5) parser.add_argument('-g', '--gamma', type=float, default=0.3) parser.add_argument('-l', '--l', type=float)",
"default=400) parser.add_argument('--clock',type=bool, default=True) #是否记时 parser.add_argument('--gdraw',type=bool, default=False) #是否实时绘图 #下面是暂时不知道用来做什么的参数 parser.add_argument('-a', '--arch', type=str, default='avg_pool',choices=models.names()) #eug",
"渐进采样系数 parser.add_argument('--q', type=float, default=1) # 渐进采样指数 parser.add_argument('--percent_vari', type=float, default=0.8) # 方差的筛选范围. working_dir =",
"osp import sys from torch.backends import cudnn from reid.utils.serialization import load_checkpoint from torch",
"args.dataset,args.exp_name,args.exp_order) resume_step, ckpt_file = -1, '' if args.resume: # 重新训练的时候用 resume_step, ckpt_file =",
"s = changetoHSM(exp_time) print(\"experiment is over, cost %02d:%02d:%02.6f\" % ( h, m, s))",
"# 这里应该取上限或者 +2 多一轮进行one-shot训练的 # EUG base 采样策略 # total_step = math.ceil((2 *",
"# select_pre =0 # 输出该epoch的信息 data_file.write(\"step:{} mAP:{:.2%} top1:{:.2%} top5:{:.2%} top10:{:.2%} top20:{:.2%} nums_selected:{} expend_nums_to_select:{}",
"eug.train(new_train_data, step, epochs=args.epoch, step_size=args.step_size, init_lr=0.1) if step != resume_step else eug.resume(ckpt_file, step) #",
"Strategy') parser.add_argument('-d', '--dataset', type=str, default='DukeMTMC-VideoReID',choices=datasets.names()) #DukeMTMC-VideoReID \\mars parser.add_argument('-b', '--batch-size', type=int, default=16) parser.add_argument('--epoch',type=int,default=40) parser.add_argument('--step_size',type=int,default=30)",
"min(math.ceil((len(u_data)-args.yita)*(step-1)/(total_step-2))+args.yita,len(u_data)) # big start new_expend_nums_to_select = min(len(u_data), math.ceil(new_nums_to_select / args.percent_vari)) selected_idx = eug.select_top_data_nlvm_b1(pred_score,dists,",
"train_time+estimate_time time_file.write(\"step:{} train:{} evaluate:{} estimate:{} epoch:{}\\n\".format(int(step+1),train_time,evaluate_time,estimate_time,epoch_time)) if args.gdraw: gd.draw(nums_to_select/len(u_data),top1,mAP,label_pre,select_pre) nums_to_select = new_nums_to_select expend_nums_to_select",
"train:{} evaluate:{} estimate:{} epoch:{}\\n\".format(int(step+1),train_time,evaluate_time,estimate_time,epoch_time)) if args.gdraw: gd.draw(nums_to_select/len(u_data),top1,mAP,label_pre,select_pre) nums_to_select = new_nums_to_select expend_nums_to_select = new_expend_nums_to_select",
"start new_expend_nums_to_select = min(len(u_data), math.ceil(new_nums_to_select / args.percent_vari)) selected_idx = eug.select_top_data_nlvm_b1(pred_score,dists, new_expend_nums_to_select,new_nums_to_select) new_train_data, select_pre",
"begin with dataset:{},batch_size:{},epoch:{},step:{}/{} saved to {}.\".format(args.exp_name,args.dataset,args.batch_size, args.epoch,step+1,total_step+1,save_path)) print(\"key parameters contain EF:{},q:{},percent_vari:{}. Nums_been_selected:{}\".format(args.EF,args.q,args.percent_vari,nums_to_select)) #",
"time.time() # 循环退出判断 if nums_to_select == len(u_data): isout = 1 # nums_to_select 的设定",
"import * def main(args): # 声明动态绘图器 gd = gif_drawer() cudnn.benchmark = True cudnn.enabled",
"u_data=u_data, save_path=save_path, max_frames=args.max_frames) # 训练之前初始化数据 nums_to_select = 0 expend_nums_to_select = 0 new_train_data =",
"pred_y) # select_pre =0 # 输出该epoch的信息 data_file.write(\"step:{} mAP:{:.2%} top1:{:.2%} top5:{:.2%} top10:{:.2%} top20:{:.2%} nums_selected:{}",
"# 渐进采样系数 parser.add_argument('--q', type=float, default=1) # 渐进采样指数 parser.add_argument('--percent_vari', type=float, default=0.8) # 方差的筛选范围. working_dir",
"=codecs.open(osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order,'time.txt'),mode='a') save_path = osp.join(args.logs_dir, args.dataset,args.exp_name,args.exp_order) resume_step, ckpt_file = -1, '' if args.resume:",
"estimate:{} epoch:{}\\n\".format(int(step+1),train_time,evaluate_time,estimate_time,epoch_time)) if args.gdraw: gd.draw(nums_to_select/len(u_data),top1,mAP,label_pre,select_pre) nums_to_select = new_nums_to_select expend_nums_to_select = new_expend_nums_to_select step =",
"matplotlib.pyplot as plt import os import codecs from common_tool import * def main(args):",
"select_pre =0 # 输出该epoch的信息 data_file.write(\"step:{} mAP:{:.2%} top1:{:.2%} top5:{:.2%} top10:{:.2%} top20:{:.2%} nums_selected:{} expend_nums_to_select:{} selected_percent:{:.2%}",
"def main(args): # 声明动态绘图器 gd = gif_drawer() cudnn.benchmark = True cudnn.enabled = True",
"pred_score, label_pre, dists = eug.estimate_label() estimate_end = time.time() # 循环退出判断 if nums_to_select ==",
"parser.add_argument('--gdraw',type=bool, default=False) #是否实时绘图 #下面是暂时不知道用来做什么的参数 parser.add_argument('-a', '--arch', type=str, default='avg_pool',choices=models.names()) #eug model_name parser.add_argument('-i', '--iter-step', type=int,",
"parser.add_argument('-d', '--dataset', type=str, default='DukeMTMC-VideoReID',choices=datasets.names()) #DukeMTMC-VideoReID \\mars parser.add_argument('-b', '--batch-size', type=int, default=16) parser.add_argument('--epoch',type=int,default=40) parser.add_argument('--step_size',type=int,default=30) parser.add_argument('--EF',",
"type=float, default=1) # 渐进采样指数 parser.add_argument('--percent_vari', type=float, default=0.8) # 方差的筛选范围. working_dir = os.path.dirname(os.path.abspath(__file__)) parser.add_argument('--data_dir',",
"new_train_data = l_data step = 0 if args.resume: step = resume_step nums_to_select =",
"label_pre:{:.2%} select_pre:{:.2%}\\n\".format( int(step+1), mAP, top1, top5, top10, top20, nums_to_select, expend_nums_to_select,nums_to_select / len(u_data), label_pre,select_pre))",
"epoch_time = train_time+estimate_time time_file.write(\"step:{} train:{} evaluate:{} estimate:{} epoch:{}\\n\".format(int(step+1),train_time,evaluate_time,estimate_time,epoch_time)) if args.gdraw: gd.draw(nums_to_select/len(u_data),top1,mAP,label_pre,select_pre) nums_to_select =",
"type=str, choices=[\"Classification\", \"Dissimilarity\"], default=\"Dissimilarity\") #这个考虑要不要取消掉 parser.add_argument('--max_frames', type=int, default=400) parser.add_argument('--clock',type=bool, default=True) #是否记时 parser.add_argument('--gdraw',type=bool, default=False)",
"init_lr=0.1) if step != resume_step else eug.resume(ckpt_file, step) # 开始评估 evaluate_start = time.time()",
"= min(math.ceil((len(u_data)-args.yita)*(step-1)/(total_step-2))+args.yita,len(u_data)) # big start new_expend_nums_to_select = min(len(u_data), math.ceil(new_nums_to_select / args.percent_vari)) selected_idx =",
"parser.add_argument('--clock',type=bool, default=True) #是否记时 parser.add_argument('--gdraw',type=bool, default=False) #是否实时绘图 #下面是暂时不知道用来做什么的参数 parser.add_argument('-a', '--arch', type=str, default='avg_pool',choices=models.names()) #eug model_name",
"torch import nn import time import math import pickle import time import matplotlib.pyplot",
"from reid.utils.logging import Logger import os.path as osp import sys from torch.backends import",
"time.time() # mAP, top1, top5, top10, top20 = 0,0,0,0,0 mAP,top1,top5,top10,top20 = eug.evaluate(dataset_all.query, dataset_all.gallery)",
"metavar='PATH',default=os.path.join(working_dir, 'logs')) # 保持日志根目录 parser.add_argument('--exp_name',type=str,default=\"nlvm-b1\") parser.add_argument('--exp_order',type=str,default=\"1\") parser.add_argument('--resume', type=str, default=None) parser.add_argument('--mode', type=str, choices=[\"Classification\", \"Dissimilarity\"],",
"dataset_all.name)) NN = len(l_data) + len(u_data) # 总的训练step数的计算 total_step = math.ceil(math.pow((100 / args.EF),",
"1 # nums_to_select 的设定 new_nums_to_select = min(math.ceil(len(u_data) * math.pow((step + 1), args.q) *",
"# 输出该轮训练关键的提示信息 print(\"{} training begin with dataset:{},batch_size:{},epoch:{},step_size:{},max_frames:{},total_step:{},EF:{},q:{},percent_vari:{}\".format(args.exp_name,args.dataset,args.batch_size,args.epoch,args.step_size,args.max_frames,total_step+1,args.EF,args.q,args.percent_vari)) # 指定输出文件 # 第三部分要说明关键参数的设定 sys.stdout =",
"Nums_been_selected:{}\".format(args.EF,args.q,args.percent_vari,nums_to_select)) # 开始训练 train_start = time.time() eug.train(new_train_data, step, epochs=args.epoch, step_size=args.step_size, init_lr=0.1) if step",
"args.q) * args.EF / 100), len(u_data)) step_size = [] isout = 0 #用来标记是否应该结束训练",
"import os.path as osp import sys from torch.backends import cudnn from reid.utils.serialization import",
"len(u_data)) / (args.yita + NN + len(l_data))) + 2 # big start 策略"
] |
[
"- start} secs; msg len = {len(msg)}\") def transmit(): while True: # global",
"start = time.time() def process_message(msg): print(msg) # print(f\"Time passed: {time.time() - start} secs;",
"from Raspberry Pi!\\n\") time.sleep(1) def receive(): while True: line = port.readline().decode('utf-8').rstrip() process_message(line) tx_thread",
"threading.Thread(target=transmit) # rx_thread = threading.Thread(target=receive) tx_thread.start() # rx_thread.start() # transmit() receive() tx_thread.join() #",
"{len(msg)}\") def transmit(): while True: # global start # start = time.time() port.write(b\"Hello",
"port.flush() start = time.time() def process_message(msg): print(msg) # print(f\"Time passed: {time.time() - start}",
"python3 import serial import time import threading if __name__ == '__main__': port =",
"time.time() port.write(b\"Hello from Raspberry Pi!\\n\") time.sleep(1) def receive(): while True: line = port.readline().decode('utf-8').rstrip()",
"process_message(msg): print(msg) # print(f\"Time passed: {time.time() - start} secs; msg len = {len(msg)}\")",
"msg len = {len(msg)}\") def transmit(): while True: # global start # start",
"# global start # start = time.time() port.write(b\"Hello from Raspberry Pi!\\n\") time.sleep(1) def",
"print(f\"Time passed: {time.time() - start} secs; msg len = {len(msg)}\") def transmit(): while",
"Pi!\\n\") time.sleep(1) def receive(): while True: line = port.readline().decode('utf-8').rstrip() process_message(line) tx_thread = threading.Thread(target=transmit)",
"= port.readline().decode('utf-8').rstrip() process_message(line) tx_thread = threading.Thread(target=transmit) # rx_thread = threading.Thread(target=receive) tx_thread.start() # rx_thread.start()",
"receive(): while True: line = port.readline().decode('utf-8').rstrip() process_message(line) tx_thread = threading.Thread(target=transmit) # rx_thread =",
"port.write(b\"Hello from Raspberry Pi!\\n\") time.sleep(1) def receive(): while True: line = port.readline().decode('utf-8').rstrip() process_message(line)",
"import serial import time import threading if __name__ == '__main__': port = serial.Serial('/dev/ttyACM0',",
"115200) port.flush() start = time.time() def process_message(msg): print(msg) # print(f\"Time passed: {time.time() -",
"transmit(): while True: # global start # start = time.time() port.write(b\"Hello from Raspberry",
"time import threading if __name__ == '__main__': port = serial.Serial('/dev/ttyACM0', 115200) port.flush() start",
"start # start = time.time() port.write(b\"Hello from Raspberry Pi!\\n\") time.sleep(1) def receive(): while",
"#!/usr/bin/env python3 import serial import time import threading if __name__ == '__main__': port",
"global start # start = time.time() port.write(b\"Hello from Raspberry Pi!\\n\") time.sleep(1) def receive():",
"= time.time() port.write(b\"Hello from Raspberry Pi!\\n\") time.sleep(1) def receive(): while True: line =",
"= threading.Thread(target=transmit) # rx_thread = threading.Thread(target=receive) tx_thread.start() # rx_thread.start() # transmit() receive() tx_thread.join()",
"def receive(): while True: line = port.readline().decode('utf-8').rstrip() process_message(line) tx_thread = threading.Thread(target=transmit) # rx_thread",
"= serial.Serial('/dev/ttyACM0', 115200) port.flush() start = time.time() def process_message(msg): print(msg) # print(f\"Time passed:",
"__name__ == '__main__': port = serial.Serial('/dev/ttyACM0', 115200) port.flush() start = time.time() def process_message(msg):",
"<filename>draft/serial/serial_threaded.py #!/usr/bin/env python3 import serial import time import threading if __name__ == '__main__':",
"# rx_thread = threading.Thread(target=receive) tx_thread.start() # rx_thread.start() # transmit() receive() tx_thread.join() # rx_thread.join()",
"while True: line = port.readline().decode('utf-8').rstrip() process_message(line) tx_thread = threading.Thread(target=transmit) # rx_thread = threading.Thread(target=receive)",
"'__main__': port = serial.Serial('/dev/ttyACM0', 115200) port.flush() start = time.time() def process_message(msg): print(msg) #",
"start = time.time() port.write(b\"Hello from Raspberry Pi!\\n\") time.sleep(1) def receive(): while True: line",
"line = port.readline().decode('utf-8').rstrip() process_message(line) tx_thread = threading.Thread(target=transmit) # rx_thread = threading.Thread(target=receive) tx_thread.start() #",
"threading if __name__ == '__main__': port = serial.Serial('/dev/ttyACM0', 115200) port.flush() start = time.time()",
"import time import threading if __name__ == '__main__': port = serial.Serial('/dev/ttyACM0', 115200) port.flush()",
"time.sleep(1) def receive(): while True: line = port.readline().decode('utf-8').rstrip() process_message(line) tx_thread = threading.Thread(target=transmit) #",
"tx_thread = threading.Thread(target=transmit) # rx_thread = threading.Thread(target=receive) tx_thread.start() # rx_thread.start() # transmit() receive()",
"secs; msg len = {len(msg)}\") def transmit(): while True: # global start #",
"= {len(msg)}\") def transmit(): while True: # global start # start = time.time()",
"len = {len(msg)}\") def transmit(): while True: # global start # start =",
"== '__main__': port = serial.Serial('/dev/ttyACM0', 115200) port.flush() start = time.time() def process_message(msg): print(msg)",
"# print(f\"Time passed: {time.time() - start} secs; msg len = {len(msg)}\") def transmit():",
"if __name__ == '__main__': port = serial.Serial('/dev/ttyACM0', 115200) port.flush() start = time.time() def",
"# start = time.time() port.write(b\"Hello from Raspberry Pi!\\n\") time.sleep(1) def receive(): while True:",
"serial.Serial('/dev/ttyACM0', 115200) port.flush() start = time.time() def process_message(msg): print(msg) # print(f\"Time passed: {time.time()",
"time.time() def process_message(msg): print(msg) # print(f\"Time passed: {time.time() - start} secs; msg len",
"import threading if __name__ == '__main__': port = serial.Serial('/dev/ttyACM0', 115200) port.flush() start =",
"def transmit(): while True: # global start # start = time.time() port.write(b\"Hello from",
"True: # global start # start = time.time() port.write(b\"Hello from Raspberry Pi!\\n\") time.sleep(1)",
"port = serial.Serial('/dev/ttyACM0', 115200) port.flush() start = time.time() def process_message(msg): print(msg) # print(f\"Time",
"True: line = port.readline().decode('utf-8').rstrip() process_message(line) tx_thread = threading.Thread(target=transmit) # rx_thread = threading.Thread(target=receive) tx_thread.start()",
"serial import time import threading if __name__ == '__main__': port = serial.Serial('/dev/ttyACM0', 115200)",
"def process_message(msg): print(msg) # print(f\"Time passed: {time.time() - start} secs; msg len =",
"{time.time() - start} secs; msg len = {len(msg)}\") def transmit(): while True: #",
"Raspberry Pi!\\n\") time.sleep(1) def receive(): while True: line = port.readline().decode('utf-8').rstrip() process_message(line) tx_thread =",
"= time.time() def process_message(msg): print(msg) # print(f\"Time passed: {time.time() - start} secs; msg",
"process_message(line) tx_thread = threading.Thread(target=transmit) # rx_thread = threading.Thread(target=receive) tx_thread.start() # rx_thread.start() # transmit()",
"start} secs; msg len = {len(msg)}\") def transmit(): while True: # global start",
"port.readline().decode('utf-8').rstrip() process_message(line) tx_thread = threading.Thread(target=transmit) # rx_thread = threading.Thread(target=receive) tx_thread.start() # rx_thread.start() #",
"while True: # global start # start = time.time() port.write(b\"Hello from Raspberry Pi!\\n\")",
"passed: {time.time() - start} secs; msg len = {len(msg)}\") def transmit(): while True:",
"print(msg) # print(f\"Time passed: {time.time() - start} secs; msg len = {len(msg)}\") def"
] |
[
"returns False. Otherwise, returns the new board state with the locked piece. Args:",
"<= 4): return False elif board_state['tetromino'] == 'I': i_offset = I_OFFSETS[i_rotate*5 + k]",
"(4 + new_rotation_idx - current_rotation_idx) % 4 assert(iterations != 2) dim = int(len(tetromino)**0.5)",
"List[int], List[int], int, bool, ] TETROMINOES = [ [ # I 0, 0,",
"score # TODO: write this function pass def pop(board_state: Board) -> Board: #",
"nested function returns the new index for a given index after a #",
"If the piece should not be locked, returns False. Otherwise, returns the new",
"is not None: board = move(board, KEYMAP[event]) display(board) if (time.perf_counter() - t_i) >",
"f_offset[1] - i_offset[1] kicked_board_state = rotated_board_state.copy() kicked_board_state['x'] += x_kick kicked_board_state['y'] += y_kick return",
"'__main__': TICK = 0.5 board = initialize_board() with keyboard.Events() as events: t_i =",
"Union, Optional import time from pynput import keyboard Board = Dict[ Optional[str], str,",
"= '0.0.1' __maintainer__ = '<NAME>' __email__ = '<EMAIL>' __status__ = 'Development' \"\"\" Docstring",
"function pass def store(board_state: Board) -> Board: \"\"\"Attempt to store the current piece.",
"I 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,",
"Returns: The new board state \"\"\" translations = set('up', 'down', 'left', 'right') rotations",
"1, 1, 1, 0, 0, 0, ], [ # L 0, 0, 1,",
"presses allowed: 'up', 'down', 'left', 'right', 'clockwise', 'counterclockwise', 'store'. Args: board_state: Dictionary containing",
"kicked_board_state = rotated_board_state.copy() kicked_board_state['x'] += x_kick kicked_board_state['y'] += y_kick return kicked_board_state def rotate(board_state:",
"direction. Args: board_state: direction: Returns: A new board state. \"\"\" rotate_offset = DIRECTION_INT[direction]",
"None, 'rotation': '0', 'x': 0, 'y': 0, 'stored': None, 'stack': [], 'queue': [],",
"elif ~(0 <= k <= 4): return False elif board_state['tetromino'] == 'I': i_offset",
"0, 0, 0, 0, 0, 0, ], [ # J 1, 0, 0,",
"initialize_board() with keyboard.Events() as events: t_i = time.perf_counter() while ~game_over(board): event = events.get(TICK)",
"dim))*dim + idx//dim tetromino_idx = TETROMINO_INT[board_state['tetromino']] tetromino = TETROMINOES[tetromino_idx] current_rotation_idx = ROTATE_INT[board_state['rotation']] new_rotation_idx",
"{'0': 0, 'R': 1, '2': 2, 'L': 3} INT_ROTATE = ('0', 'R', '2',",
"'O': if k != 0: return False i_offset = O_OFFSETS[i_rotate] f_offset = O_OFFSETS[f_rotate]",
"__email__ = '<EMAIL>' __status__ = 'Development' \"\"\" Docstring \"\"\" from typing import Dict,",
"[ # O 0, 1, 1, 0, 1, 1, 0, 0, 0, ],",
"tetromino] return tetromino def collision(board_state: Board) -> bool: \"\"\"Checks if given board results",
"[ [ # I 0, 0, 0, 0, 0, 0, 0, 0, 0,",
"pass def lock(board_state: Board) -> Union[bool, Board]: \"\"\"Checks to see if the current",
"pass def kick(board_state: Board, rotated_board_state: Board, k: int, ) -> Union[bool, Board]: \"\"\"Translates",
"piece should be locked. If the piece should not be locked, returns False.",
"# TODO: initialize queue return board_state def game_over(board_state: Board) -> bool: # TODO:",
"kicked_board_state['y'] += y_kick return kicked_board_state def rotate(board_state: Board, direction: str = 'clockwise') ->",
"rotate the current piece in the given direction. Args: board_state: direction: Returns: A",
"# elif key == 'store': return store(board_state) if __name__ == '__main__': TICK =",
"the new index for a given index after a # clockwise rotation. def",
"the offset tables. Returns the kicked board if there is a kick available.",
"new board state with the locked piece. Args: board_state: Returns: \"\"\" # TODO:",
"# TODO: write this function def true_rotate(board_state: Board, new_rotation: str = '0') ->",
"Returns the kicked board if there is a kick available. Otherwise, returns False.",
"= 'Copyright 2020 <NAME>' __credits__ = ['<NAME>'] __license__ = 'Apache License 2.0' __version__",
"TETROMINO_INT[board_state['tetromino']] tetromino = TETROMINOES[tetromino_idx] current_rotation_idx = ROTATE_INT[board_state['rotation']] new_rotation_idx = ROTATE_INT[new_rotation] iterations = (4",
"= {'0': 0, 'R': 1, '2': 2, 'L': 3} INT_ROTATE = ('0', 'R',",
"__status__ = 'Development' \"\"\" Docstring \"\"\" from typing import Dict, List, Union, Optional",
"0), (0, 0), (0, 0), (0, 0), # 0 (0, 0), (1, 0),",
"ROTATE_INT[board_state['rotation']] new_rotation_idx = ROTATE_INT[new_rotation] iterations = (4 + new_rotation_idx - current_rotation_idx) % 4",
"Returns: A new board state. \"\"\" rotate_offset = DIRECTION_INT[direction] current_rotate = ROTATE_INT[Board['rotation']] new_rotate",
"t_i = time.perf_counter() board = move(board) display(board) print('GAME OVER') input(\"Press the <ENTER> key",
"the board state. \"\"\" # TODO: write this function def true_rotate(board_state: Board, new_rotation:",
"board state. \"\"\" # TODO: write this function pass def store(board_state: Board) ->",
"'T': 5, 'Z': 6} DIRECTION_INT = {'clockwise': 1, 'counterclockwise': -1} KEYMAP = {",
"+ k] else: i_offset = OFFSETS[i_rotate*5 + k] f_offset = OFFSETS[f_rotate*5 + k]",
"0, 0, 0, 0, 0, ], [ # J 1, 0, 0, 1,",
"0, 1, 1, 1, 0, 0, 0, ], [ # Z 1, 1,",
"+ new_rotation_idx - current_rotation_idx) % 4 assert(iterations != 2) dim = int(len(tetromino)**0.5) for",
"Union[bool, Board]: \"\"\"Translates the rotated board using the offset tables. Returns the kicked",
"2), # L ] O_OFFSETS = [ (0, 0), # 0 (0, -1),",
"def rotate(board_state: Board, direction: str = 'clockwise') -> Board: \"\"\"Attempts to rotate the",
"(0, 0), # 2 (0, 0), (-1, 0), (-1, -1), (0, 2), (-1,",
"-> Board: \"\"\"Attempts to rotate the current piece in the given direction. Args:",
"= translate(board_state, key) if locked_board_state := lock(translated_board_state): return locked_board_state return translate(board_state, key) elif",
"the keys to the correct strings 'up': 'up', 'down': 'down', 'left': 'left', 'right':",
"key in translations: if board_state['tetromino'] is None: return pop(board_state) translated_board_state = translate(board_state, key)",
"Optional import time from pynput import keyboard Board = Dict[ Optional[str], str, int,",
"def lock(board_state: Board) -> Union[bool, Board]: \"\"\"Checks to see if the current piece",
"from typing import Dict, List, Union, Optional import time from pynput import keyboard",
"of the key pressed. Returns: The new board state \"\"\" translations = set('up',",
"as events: t_i = time.perf_counter() while ~game_over(board): event = events.get(TICK) if event is",
"'Copyright 2020 <NAME>' __credits__ = ['<NAME>'] __license__ = 'Apache License 2.0' __version__ =",
"state. \"\"\" # TODO: write this function pass def lock(board_state: Board) -> Union[bool,",
"events: t_i = time.perf_counter() while ~game_over(board): event = events.get(TICK) if event is not",
"# TODO: update score # TODO: write this function pass def pop(board_state: Board)",
"board_state: Returns: \"\"\" # TODO: make sure to clear lines # TODO: update",
"elif key in rotations: return rotate(board_state, key) else: # elif key == 'store':",
"key pressed. Returns: The new board state \"\"\" translations = set('up', 'down', 'left',",
"-1), # 2 (-1, 0), # L ] ROTATE_INT = {'0': 0, 'R':",
"if kicked_board_state := kick(board_state, rotated_board_state, k): continue else: return board_state return kicked_board_state def",
"f_offset = O_OFFSETS[f_rotate] elif ~(0 <= k <= 4): return False elif board_state['tetromino']",
"0), (0, 0), # 2 (0, 0), (-1, 0), (-1, -1), (0, 2),",
"else: return board_state return kicked_board_state def translate(board_state: Board, direction: str = 'down') ->",
"Returns: \"\"\" # TODO: make sure to clear lines # TODO: update score",
"- 1 - (idx % dim))*dim + idx//dim tetromino_idx = TETROMINO_INT[board_state['tetromino']] tetromino =",
"current_rotation_idx = ROTATE_INT[board_state['rotation']] new_rotation_idx = ROTATE_INT[new_rotation] iterations = (4 + new_rotation_idx - current_rotation_idx)",
"0, 0, ], ] OFFSETS = [ (0, 0), (0, 0), (0, 0),",
"see if the current piece should be locked. If the piece should not",
"'queue': [], 'score': 0, 'store_flag': False, } # TODO: initialize stack # TODO:",
"(2, 0), # 0 (-1, 0), (0, 0), (0, 0), (0, 1), (0,",
"locked_board_state := lock(translated_board_state): return locked_board_state return translate(board_state, key) elif key in rotations: return",
"direction: str = 'clockwise') -> Board: \"\"\"Attempts to rotate the current piece in",
"# TODO: write this function pass def store(board_state: Board) -> Board: \"\"\"Attempt to",
"0, 0, 0, 0, 0, 0, 0, ], [ # J 1, 0,",
"0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,",
"key: str = 'down') -> Board: \"\"\"Attempts to move the active piece based",
"'clockwise': 'clockwise', 'counterclockwise': 'counterclockwise', 'store': 'store', } def display(board_state: Board) -> None: \"\"\"Displays",
"simply printing to console. update to use curses. Args: board_state: Dictionary containing the",
"Optional[str], str, int, int, Optional[str], List[int], List[int], int, bool, ] TETROMINOES = [",
"rot(idx: int, dim: int) -> int: return (dim - 1 - (idx %",
"= TETROMINOES[tetromino_idx] current_rotation_idx = ROTATE_INT[board_state['rotation']] new_rotation_idx = ROTATE_INT[new_rotation] iterations = (4 + new_rotation_idx",
"R (-1, -1), # 2 (-1, 0), # L ] ROTATE_INT = {'0':",
"None: board = move(board, KEYMAP[event]) display(board) if (time.perf_counter() - t_i) > TICK: t_i",
"1), (0, 1), (0, -1), (0, 2), # L ] O_OFFSETS = [",
"0 (0, 0), (1, 0), (1, -1), (0, 2), (1, 2), # R",
"the new board state with the locked piece. Args: board_state: Returns: \"\"\" #",
"(0, 1), (0, 1), (0, 1), (0, -1), (0, 2), # L ]",
"2020 <NAME>' __credits__ = ['<NAME>'] __license__ = 'Apache License 2.0' __version__ = '0.0.1'",
"update to use curses. Args: board_state: Dictionary containing the board state. \"\"\" #",
"list representation of the rotated tetromino Raises: AssertionError: \"\"\" # This nested function",
"I_OFFSETS[i_rotate*5 + k] f_offset = I_OFFSETS[f_rotate*5 + k] else: i_offset = OFFSETS[i_rotate*5 +",
"], [ # J 1, 0, 0, 1, 1, 1, 0, 0, 0,",
"(0, 0), # 0 (0, -1), # R (-1, -1), # 2 (-1,",
"Board, new_rotation: str = '0') -> List[int]: \"\"\"Rotates a given tetromino clockwise and",
"'0', 'x': 0, 'y': 0, 'stored': None, 'stack': [], 'queue': [], 'score': 0,",
"int(len(tetromino)**0.5) for _ in range(iterations): tetromino = [tetromino[rot(i, dim)] for i in tetromino]",
"k): continue else: return board_state return kicked_board_state def translate(board_state: Board, direction: str =",
"collision(board_state: Board) -> bool: \"\"\"Checks if given board results in a collision. Args:",
"given board results in a collision. Args: board_state: Returns: True if there is",
"state. key: A strign representation of the key pressed. Returns: The new board",
"= [tetromino[rot(i, dim)] for i in tetromino] return tetromino def collision(board_state: Board) ->",
"] O_OFFSETS = [ (0, 0), # 0 (0, -1), # R (-1,",
"assert(iterations != 2) dim = int(len(tetromino)**0.5) for _ in range(iterations): tetromino = [tetromino[rot(i,",
"1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,",
"board_state: Returns: True if there is a collision, False if there is not.",
"\"\"\"Checks to see if the current piece should be locked. If the piece",
"1, 'counterclockwise': -1} KEYMAP = { # TODO: change the keys to the",
"(-1, 0), (2, 0), (-1, 0), (2, 0), # 0 (-1, 0), (0,",
"'right', 'clockwise': 'clockwise', 'counterclockwise': 'counterclockwise', 'store': 'store', } def display(board_state: Board) -> None:",
"lock(translated_board_state): return locked_board_state return translate(board_state, key) elif key in rotations: return rotate(board_state, key)",
"(0, 0), (0, 0), # 0 (0, 0), (1, 0), (1, -1), (0,",
"piece. Args: board_state: Returns: \"\"\" # TODO: make sure to clear lines #",
"Args: board_state: direction: Returns: A new board state. \"\"\" # TODO: write this",
"'left', 'right': 'right', 'clockwise': 'clockwise', 'counterclockwise': 'counterclockwise', 'store': 'store', } def display(board_state: Board)",
"if the current piece should be locked. If the piece should not be",
"collision. Args: board_state: Returns: True if there is a collision, False if there",
"I_OFFSETS = [ (0, 0), (-1, 0), (2, 0), (-1, 0), (2, 0),",
"if __name__ == '__main__': TICK = 0.5 board = initialize_board() with keyboard.Events() as",
"ROTATE_INT[rotated_board_state['rotation']] if board_state['tetromino'] == 'O': if k != 0: return False i_offset =",
"pass def pop(board_state: Board) -> Board: # TODO: make sure to reset the",
"store(board_state) if __name__ == '__main__': TICK = 0.5 board = initialize_board() with keyboard.Events()",
"def display(board_state: Board) -> None: \"\"\"Displays the current board state. TODO: currently simply",
"(1, -1), (0, 2), (1, 2), # R (0, 0), (0, 0), (0,",
"L ] I_OFFSETS = [ (0, 0), (-1, 0), (2, 0), (-1, 0),",
"'S': 4, 'T': 5, 'Z': 6} DIRECTION_INT = {'clockwise': 1, 'counterclockwise': -1} KEYMAP",
"1, 0, 0, 0, ], [ # Z 1, 1, 0, 0, 1,",
"offset tables. Returns the kicked board if there is a kick available. Otherwise,",
"pass def initialize_board() -> Board: \"\"\" \"\"\" board_state = { 'tetromino': None, 'rotation':",
"1, 1, 0, 1, 1, 0, 0, 0, ], [ # S 0,",
"write this function pass def lock(board_state: Board) -> Union[bool, Board]: \"\"\"Checks to see",
"rotated_board_state, k): continue else: return board_state return kicked_board_state def translate(board_state: Board, direction: str",
"should not be locked, returns False. Otherwise, returns the new board state with",
"] I_OFFSETS = [ (0, 0), (-1, 0), (2, 0), (-1, 0), (2,",
"return board_state return kicked_board_state def translate(board_state: Board, direction: str = 'down') -> Board:",
"(1, 0), (1, -1), (0, 2), (1, 2), # R (0, 0), (0,",
"\"\"\" board_state = { 'tetromino': None, 'rotation': '0', 'x': 0, 'y': 0, 'stored':",
"available. Otherwise, returns False. Args: board_state: rotated_board_state: k: The offset index to use.",
"'down') -> Board: \"\"\"Attempts to move the active piece based on the key.",
"direction. Args: board_state: direction: Returns: A new board state. \"\"\" # TODO: write",
"T 0, 1, 0, 1, 1, 1, 0, 0, 0, ], [ #",
"Args: board_state: Returns: \"\"\" # TODO: make sure to clear lines # TODO:",
"elif board_state['tetromino'] == 'I': i_offset = I_OFFSETS[i_rotate*5 + k] f_offset = I_OFFSETS[f_rotate*5 +",
"TODO: write this function pass def move(board_state: Board, key: str = 'down') ->",
"2), # L ] I_OFFSETS = [ (0, 0), (-1, 0), (2, 0),",
"Board, k: int, ) -> Union[bool, Board]: \"\"\"Translates the rotated board using the",
"\"\"\" # TODO: write this function def true_rotate(board_state: Board, new_rotation: str = '0')",
"= ROTATE_INT[board_state['rotation']] new_rotation_idx = ROTATE_INT[new_rotation] iterations = (4 + new_rotation_idx - current_rotation_idx) %",
"'down': 'down', 'left': 'left', 'right': 'right', 'clockwise': 'clockwise', 'counterclockwise': 'counterclockwise', 'store': 'store', }",
"current piece. Args: board_state: Returns: A new board state. \"\"\" # TODO: write",
"state. \"\"\" # TODO: write this function def true_rotate(board_state: Board, new_rotation: str =",
"'store_flag': False, } # TODO: initialize stack # TODO: initialize queue return board_state",
"Dict[ Optional[str], str, int, int, Optional[str], List[int], List[int], int, bool, ] TETROMINOES =",
"J 1, 0, 0, 1, 1, 1, 0, 0, 0, ], [ #",
"locked_board_state return translate(board_state, key) elif key in rotations: return rotate(board_state, key) else: #",
"(0, 0), (0, 0), (0, 0), (0, 0), (0, 0), # 2 (0,",
"0, 0, ], [ # S 0, 1, 1, 1, 1, 0, 0,",
"5, 'Z': 6} DIRECTION_INT = {'clockwise': 1, 'counterclockwise': -1} KEYMAP = { #",
"keys to the correct strings 'up': 'up', 'down': 'down', 'left': 'left', 'right': 'right',",
"k = 0 kicked_board_state = kick(board_state, rotated_board_state, k) while collision(kicked_board_state): k += 1",
"given direction. Args: board_state: direction: Returns: A new board state. \"\"\" # TODO:",
"(dim - 1 - (idx % dim))*dim + idx//dim tetromino_idx = TETROMINO_INT[board_state['tetromino']] tetromino",
"1, 0, 1, 1, 0, 0, 0, ], [ # S 0, 1,",
"1), (0, 1), (0, 1), (0, -1), (0, 2), # L ] O_OFFSETS",
"# R (-1, -1), # 2 (-1, 0), # L ] ROTATE_INT =",
"the current piece in the given direction. Args: board_state: direction: Returns: A new",
"# TODO: write this function pass def kick(board_state: Board, rotated_board_state: Board, k: int,",
"board_state: Dictionary containing the board state. \"\"\" # TODO: write this function def",
"DIRECTION_INT = {'clockwise': 1, 'counterclockwise': -1} KEYMAP = { # TODO: change the",
"key in rotations: return rotate(board_state, key) else: # elif key == 'store': return",
"= (current_rotate + rotate_offset) % 4 rotated_board_state = board_state.copy() rotated_board_state['rotation'] = INT_ROTATE[new_rotate] k",
"'<NAME>' __copyright__ = 'Copyright 2020 <NAME>' __credits__ = ['<NAME>'] __license__ = 'Apache License",
"'<EMAIL>' __status__ = 'Development' \"\"\" Docstring \"\"\" from typing import Dict, List, Union,",
"2, 'O': 3, 'S': 4, 'T': 5, 'Z': 6} DIRECTION_INT = {'clockwise': 1,",
"board_state: new_rotation: Returns: A list representation of the rotated tetromino Raises: AssertionError: \"\"\"",
"0, 0, 1, 1, 1, 0, 0, 0, ], [ # L 0,",
"there is a kick available. Otherwise, returns False. Args: board_state: rotated_board_state: k: The",
"Board: \"\"\"Attempts to move the active piece based on the key. Key presses",
"def rot(idx: int, dim: int) -> int: return (dim - 1 - (idx",
"k] else: i_offset = OFFSETS[i_rotate*5 + k] f_offset = OFFSETS[f_rotate*5 + k] x_kick",
"'right', 'clockwise', 'counterclockwise', 'store'. Args: board_state: Dictionary containing the board state. key: A",
"rotated_board_state.copy() kicked_board_state['x'] += x_kick kicked_board_state['y'] += y_kick return kicked_board_state def rotate(board_state: Board, direction:",
"= ROTATE_INT[Board['rotation']] new_rotate = (current_rotate + rotate_offset) % 4 rotated_board_state = board_state.copy() rotated_board_state['rotation']",
"% dim))*dim + idx//dim tetromino_idx = TETROMINO_INT[board_state['tetromino']] tetromino = TETROMINOES[tetromino_idx] current_rotation_idx = ROTATE_INT[board_state['rotation']]",
"'right') rotations = set('clockwise', 'counterclockwise') if key in translations: if board_state['tetromino'] is None:",
"translations: if board_state['tetromino'] is None: return pop(board_state) translated_board_state = translate(board_state, key) if locked_board_state",
"correct strings 'up': 'up', 'down': 'down', 'left': 'left', 'right': 'right', 'clockwise': 'clockwise', 'counterclockwise':",
"t_i) > TICK: t_i = time.perf_counter() board = move(board) display(board) print('GAME OVER') input(\"Press",
"containing the board state. \"\"\" # TODO: write this function def true_rotate(board_state: Board,",
"true_rotate(board_state: Board, new_rotation: str = '0') -> List[int]: \"\"\"Rotates a given tetromino clockwise",
"'0.0.1' __maintainer__ = '<NAME>' __email__ = '<EMAIL>' __status__ = 'Development' \"\"\" Docstring \"\"\"",
"1, 1, 1, 1, 0, 0, 0, 0, ], [ # T 0,",
"\"\"\" # TODO: write this function pass def lock(board_state: Board) -> Union[bool, Board]:",
"i_offset = OFFSETS[i_rotate*5 + k] f_offset = OFFSETS[f_rotate*5 + k] x_kick = f_offset[0]",
"= 'down') -> Board: \"\"\"Attempts to move the active piece based on the",
"on the key. Key presses allowed: 'up', 'down', 'left', 'right', 'clockwise', 'counterclockwise', 'store'.",
"List[int], int, bool, ] TETROMINOES = [ [ # I 0, 0, 0,",
"a kick available. Otherwise, returns False. Args: board_state: rotated_board_state: k: The offset index",
"time from pynput import keyboard Board = Dict[ Optional[str], str, int, int, Optional[str],",
"O 0, 1, 1, 0, 1, 1, 0, 0, 0, ], [ #",
"kicked_board_state def translate(board_state: Board, direction: str = 'down') -> Board: \"\"\"Attempts to translate",
"# 0 (-1, 0), (0, 0), (0, 0), (0, 1), (0, -2), #",
"3, 'S': 4, 'T': 5, 'Z': 6} DIRECTION_INT = {'clockwise': 1, 'counterclockwise': -1}",
"tables. Returns the kicked board if there is a kick available. Otherwise, returns",
"Board, direction: str = 'down') -> Board: \"\"\"Attempts to translate the current piece",
"0, 1, 1, 1, 0, 0, 0, ], [ # L 0, 0,",
"if there is a kick available. Otherwise, returns False. Args: board_state: rotated_board_state: k:",
"import keyboard Board = Dict[ Optional[str], str, int, int, Optional[str], List[int], List[int], int,",
"0), (2, 0), # 0 (-1, 0), (0, 0), (0, 0), (0, 1),",
"direction: str = 'down') -> Board: \"\"\"Attempts to translate the current piece in",
"(0, 0), (0, 0), (0, 0), # 2 (0, 0), (-1, 0), (-1,",
"A list representation of the rotated tetromino Raises: AssertionError: \"\"\" # This nested",
"strings 'up': 'up', 'down': 'down', 'left': 'left', 'right': 'right', 'clockwise': 'clockwise', 'counterclockwise': 'counterclockwise',",
"0, ], [ # S 0, 1, 1, 1, 1, 0, 0, 0,",
"ROTATE_INT = {'0': 0, 'R': 1, '2': 2, 'L': 3} INT_ROTATE = ('0',",
"0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,",
"if board_state['tetromino'] == 'O': if k != 0: return False i_offset = O_OFFSETS[i_rotate]",
"0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,",
"TODO: write this function def true_rotate(board_state: Board, new_rotation: str = '0') -> List[int]:",
"the rotated one. Args: board_state: new_rotation: Returns: A list representation of the rotated",
"'2', 'L') TETROMINO_INT = {'I': 0, 'J': 1, 'L': 2, 'O': 3, 'S':",
"= set('clockwise', 'counterclockwise') if key in translations: if board_state['tetromino'] is None: return pop(board_state)",
"[ # Z 1, 1, 0, 0, 1, 1, 0, 0, 0, ],",
"-> Board: \"\"\"Attempts to translate the current piece in the given direction. Args:",
"the correct strings 'up': 'up', 'down': 'down', 'left': 'left', 'right': 'right', 'clockwise': 'clockwise',",
"move the active piece based on the key. Key presses allowed: 'up', 'down',",
"after a # clockwise rotation. def rot(idx: int, dim: int) -> int: return",
"0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1,",
"0, 1, 0, 1, 1, 1, 0, 0, 0, ], [ # Z",
"2 (-1, 0), # L ] ROTATE_INT = {'0': 0, 'R': 1, '2':",
"str, int, int, Optional[str], List[int], List[int], int, bool, ] TETROMINOES = [ [",
"= [ [ # I 0, 0, 0, 0, 0, 0, 0, 0,",
"translate(board_state, key) elif key in rotations: return rotate(board_state, key) else: # elif key",
"INT_ROTATE[new_rotate] k = 0 kicked_board_state = kick(board_state, rotated_board_state, k) while collision(kicked_board_state): k +=",
"# 0 (0, -1), # R (-1, -1), # 2 (-1, 0), #",
"-> Union[bool, Board]: \"\"\"Translates the rotated board using the offset tables. Returns the",
"-2), # R (-1, 1), (1, 1), (-2, 1), (1, 0), (-2, 0),",
"0, 0, 0, ], [ # T 0, 1, 0, 1, 1, 1,",
"# T 0, 1, 0, 1, 1, 1, 0, 0, 0, ], [",
"of the rotated tetromino Raises: AssertionError: \"\"\" # This nested function returns the",
"time.perf_counter() while ~game_over(board): event = events.get(TICK) if event is not None: board =",
"OFFSETS[i_rotate*5 + k] f_offset = OFFSETS[f_rotate*5 + k] x_kick = f_offset[0] - i_offset[0]",
"'down', 'left', 'right') rotations = set('clockwise', 'counterclockwise') if key in translations: if board_state['tetromino']",
"0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [ #",
"current piece in the given direction. Args: board_state: direction: Returns: A new board",
"+ k] f_offset = OFFSETS[f_rotate*5 + k] x_kick = f_offset[0] - i_offset[0] y_kick",
"1, 0, 0, 0, 0, ], [ # T 0, 1, 0, 1,",
"None, 'stack': [], 'queue': [], 'score': 0, 'store_flag': False, } # TODO: initialize",
"rotate(board_state, key) else: # elif key == 'store': return store(board_state) if __name__ ==",
"0, 0, 1, 1, 1, 1, 0, 0, 0, ], [ # O",
"= 'down') -> Board: \"\"\"Attempts to translate the current piece in the given",
"(-1, 0), (2, 0), # 0 (-1, 0), (0, 0), (0, 0), (0,",
"rotate_offset) % 4 rotated_board_state = board_state.copy() rotated_board_state['rotation'] = INT_ROTATE[new_rotate] k = 0 kicked_board_state",
"1), (1, 0), (-2, 0), # 2 (0, 1), (0, 1), (0, 1),",
"flag # TODO: write this function pass def initialize_board() -> Board: \"\"\" \"\"\"",
"0, 0, 0, 0, ], [ # T 0, 1, 0, 1, 1,",
"Board: \"\"\" \"\"\" board_state = { 'tetromino': None, 'rotation': '0', 'x': 0, 'y':",
"'R', '2', 'L') TETROMINO_INT = {'I': 0, 'J': 1, 'L': 2, 'O': 3,",
"TETROMINOES[tetromino_idx] current_rotation_idx = ROTATE_INT[board_state['rotation']] new_rotation_idx = ROTATE_INT[new_rotation] iterations = (4 + new_rotation_idx -",
"TODO: write this function pass def kick(board_state: Board, rotated_board_state: Board, k: int, )",
"write this function pass def kick(board_state: Board, rotated_board_state: Board, k: int, ) ->",
"to use. Returns: \"\"\" i_rotate = ROTATE_INT[board_state['rotation']] f_rotate = ROTATE_INT[rotated_board_state['rotation']] if board_state['tetromino'] ==",
"2), # R (0, 0), (0, 0), (0, 0), (0, 0), (0, 0),",
"0, 1, 1, 0, 0, 0, ], [ # S 0, 1, 1,",
"O_OFFSETS[f_rotate] elif ~(0 <= k <= 4): return False elif board_state['tetromino'] == 'I':",
"'I': i_offset = I_OFFSETS[i_rotate*5 + k] f_offset = I_OFFSETS[f_rotate*5 + k] else: i_offset",
"# I 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,",
"Args: board_state: Dictionary containing the board state. \"\"\" # TODO: write this function",
"lock(board_state: Board) -> Union[bool, Board]: \"\"\"Checks to see if the current piece should",
"License 2.0' __version__ = '0.0.1' __maintainer__ = '<NAME>' __email__ = '<EMAIL>' __status__ =",
"for a given index after a # clockwise rotation. def rot(idx: int, dim:",
"] ROTATE_INT = {'0': 0, 'R': 1, '2': 2, 'L': 3} INT_ROTATE =",
"2), (-1, 2), # L ] I_OFFSETS = [ (0, 0), (-1, 0),",
"'0') -> List[int]: \"\"\"Rotates a given tetromino clockwise and returns the rotated one.",
"(-1, 0), (-1, -1), (0, 2), (-1, 2), # L ] I_OFFSETS =",
"TICK: t_i = time.perf_counter() board = move(board) display(board) print('GAME OVER') input(\"Press the <ENTER>",
"new_rotate = (current_rotate + rotate_offset) % 4 rotated_board_state = board_state.copy() rotated_board_state['rotation'] = INT_ROTATE[new_rotate]",
"i in tetromino] return tetromino def collision(board_state: Board) -> bool: \"\"\"Checks if given",
"Optional[str], List[int], List[int], int, bool, ] TETROMINOES = [ [ # I 0,",
"== 'I': i_offset = I_OFFSETS[i_rotate*5 + k] f_offset = I_OFFSETS[f_rotate*5 + k] else:",
"kicked_board_state := kick(board_state, rotated_board_state, k): continue else: return board_state return kicked_board_state def translate(board_state:",
"locked, returns False. Otherwise, returns the new board state with the locked piece.",
"make sure to clear lines # TODO: update score # TODO: write this",
"clear lines # TODO: update score # TODO: write this function pass def",
"state. \"\"\" # TODO: write this function pass def store(board_state: Board) -> Board:",
"0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0,",
"# clockwise rotation. def rot(idx: int, dim: int) -> int: return (dim -",
"\"\"\"Attempts to translate the current piece in the given direction. Args: board_state: direction:",
"TODO: change the keys to the correct strings 'up': 'up', 'down': 'down', 'left':",
"'x': 0, 'y': 0, 'stored': None, 'stack': [], 'queue': [], 'score': 0, 'store_flag':",
"TETROMINO_INT = {'I': 0, 'J': 1, 'L': 2, 'O': 3, 'S': 4, 'T':",
"there is a collision, False if there is not. \"\"\" # TODO: write",
"!= 0: return False i_offset = O_OFFSETS[i_rotate] f_offset = O_OFFSETS[f_rotate] elif ~(0 <=",
"1, 0, 0, 0, ], [ # S 0, 1, 1, 1, 1,",
"0, 'J': 1, 'L': 2, 'O': 3, 'S': 4, 'T': 5, 'Z': 6}",
"TODO: make sure to clear lines # TODO: update score # TODO: write",
"<filename>tetris/tetris.py<gh_stars>0 __author__ = '<NAME>' __copyright__ = 'Copyright 2020 <NAME>' __credits__ = ['<NAME>'] __license__",
"'R': 1, '2': 2, 'L': 3} INT_ROTATE = ('0', 'R', '2', 'L') TETROMINO_INT",
"-> int: return (dim - 1 - (idx % dim))*dim + idx//dim tetromino_idx",
"currently simply printing to console. update to use curses. Args: board_state: Dictionary containing",
"pop(board_state: Board) -> Board: # TODO: make sure to reset the store flag",
"y_kick return kicked_board_state def rotate(board_state: Board, direction: str = 'clockwise') -> Board: \"\"\"Attempts",
"'right': 'right', 'clockwise': 'clockwise', 'counterclockwise': 'counterclockwise', 'store': 'store', } def display(board_state: Board) ->",
"def initialize_board() -> Board: \"\"\" \"\"\" board_state = { 'tetromino': None, 'rotation': '0',",
"'rotation': '0', 'x': 0, 'y': 0, 'stored': None, 'stack': [], 'queue': [], 'score':",
"0), (0, 0), (0, 0), # 0 (0, 0), (1, 0), (1, -1),",
"events.get(TICK) if event is not None: board = move(board, KEYMAP[event]) display(board) if (time.perf_counter()",
"tetromino = TETROMINOES[tetromino_idx] current_rotation_idx = ROTATE_INT[board_state['rotation']] new_rotation_idx = ROTATE_INT[new_rotation] iterations = (4 +",
"[ (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), # 0",
"0, ], [ # L 0, 0, 1, 1, 1, 1, 0, 0,",
"(-2, 0), # 2 (0, 1), (0, 1), (0, 1), (0, -1), (0,",
"translations = set('up', 'down', 'left', 'right') rotations = set('clockwise', 'counterclockwise') if key in",
"= rotated_board_state.copy() kicked_board_state['x'] += x_kick kicked_board_state['y'] += y_kick return kicked_board_state def rotate(board_state: Board,",
"direction: Returns: A new board state. \"\"\" # TODO: write this function pass",
"0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,",
"current_rotation_idx) % 4 assert(iterations != 2) dim = int(len(tetromino)**0.5) for _ in range(iterations):",
"\"\"\" translations = set('up', 'down', 'left', 'right') rotations = set('clockwise', 'counterclockwise') if key",
"0), (-1, 0), (2, 0), # 0 (-1, 0), (0, 0), (0, 0),",
"state. \"\"\" rotate_offset = DIRECTION_INT[direction] current_rotate = ROTATE_INT[Board['rotation']] new_rotate = (current_rotate + rotate_offset)",
"ROTATE_INT[Board['rotation']] new_rotate = (current_rotate + rotate_offset) % 4 rotated_board_state = board_state.copy() rotated_board_state['rotation'] =",
"def collision(board_state: Board) -> bool: \"\"\"Checks if given board results in a collision.",
"keyboard.Events() as events: t_i = time.perf_counter() while ~game_over(board): event = events.get(TICK) if event",
"-1), (0, 2), (1, 2), # R (0, 0), (0, 0), (0, 0),",
"given tetromino clockwise and returns the rotated one. Args: board_state: new_rotation: Returns: A",
"Board = Dict[ Optional[str], str, int, int, Optional[str], List[int], List[int], int, bool, ]",
"0, 0, ], [ # L 0, 0, 1, 1, 1, 1, 0,",
"board = move(board, KEYMAP[event]) display(board) if (time.perf_counter() - t_i) > TICK: t_i =",
"Raises: AssertionError: \"\"\" # This nested function returns the new index for a",
"Board, direction: str = 'clockwise') -> Board: \"\"\"Attempts to rotate the current piece",
"def store(board_state: Board) -> Board: \"\"\"Attempt to store the current piece. Args: board_state:",
"key: A strign representation of the key pressed. Returns: The new board state",
"in tetromino] return tetromino def collision(board_state: Board) -> bool: \"\"\"Checks if given board",
"= set('up', 'down', 'left', 'right') rotations = set('clockwise', 'counterclockwise') if key in translations:",
"0, ], [ # T 0, 1, 0, 1, 1, 1, 0, 0,",
"board if there is a kick available. Otherwise, returns False. Args: board_state: rotated_board_state:",
"4 rotated_board_state = board_state.copy() rotated_board_state['rotation'] = INT_ROTATE[new_rotate] k = 0 kicked_board_state = kick(board_state,",
"Args: board_state: rotated_board_state: k: The offset index to use. Returns: \"\"\" i_rotate =",
"keyboard Board = Dict[ Optional[str], str, int, int, Optional[str], List[int], List[int], int, bool,",
"L 0, 0, 1, 1, 1, 1, 0, 0, 0, ], [ #",
"(0, 2), (-1, 2), # L ] I_OFFSETS = [ (0, 0), (-1,",
"k += 1 if kicked_board_state := kick(board_state, rotated_board_state, k): continue else: return board_state",
"-> Board: \"\"\"Attempts to move the active piece based on the key. Key",
"board state. \"\"\" # TODO: write this function def true_rotate(board_state: Board, new_rotation: str",
"[ # J 1, 0, 0, 1, 1, 1, 0, 0, 0, ],",
"0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0,",
"0, 0, 1, 1, 0, 0, 0, ], ] OFFSETS = [ (0,",
"-1), (0, 2), (-1, 2), # L ] I_OFFSETS = [ (0, 0),",
"to the correct strings 'up': 'up', 'down': 'down', 'left': 'left', 'right': 'right', 'clockwise':",
"the piece should not be locked, returns False. Otherwise, returns the new board",
"0, 0, 0, ], [ # S 0, 1, 1, 1, 1, 0,",
"2, 'L': 3} INT_ROTATE = ('0', 'R', '2', 'L') TETROMINO_INT = {'I': 0,",
"board using the offset tables. Returns the kicked board if there is a",
"k] f_offset = I_OFFSETS[f_rotate*5 + k] else: i_offset = OFFSETS[i_rotate*5 + k] f_offset",
"0, 0, ], [ # O 0, 1, 1, 0, 1, 1, 0,",
"new board state. \"\"\" # TODO: write this function pass def lock(board_state: Board)",
"return tetromino def collision(board_state: Board) -> bool: \"\"\"Checks if given board results in",
"'L': 2, 'O': 3, 'S': 4, 'T': 5, 'Z': 6} DIRECTION_INT = {'clockwise':",
"2 (0, 1), (0, 1), (0, 1), (0, -1), (0, 2), # L",
"Dictionary containing the board state. \"\"\" # TODO: write this function def true_rotate(board_state:",
"# S 0, 1, 1, 1, 1, 0, 0, 0, 0, ], [",
"return False i_offset = O_OFFSETS[i_rotate] f_offset = O_OFFSETS[f_rotate] elif ~(0 <= k <=",
"rotated tetromino Raises: AssertionError: \"\"\" # This nested function returns the new index",
"rotated_board_state, k) while collision(kicked_board_state): k += 1 if kicked_board_state := kick(board_state, rotated_board_state, k):",
"return pop(board_state) translated_board_state = translate(board_state, key) if locked_board_state := lock(translated_board_state): return locked_board_state return",
"= '0') -> List[int]: \"\"\"Rotates a given tetromino clockwise and returns the rotated",
"Board, rotated_board_state: Board, k: int, ) -> Union[bool, Board]: \"\"\"Translates the rotated board",
"0, 'stored': None, 'stack': [], 'queue': [], 'score': 0, 'store_flag': False, } #",
"Dictionary containing the board state. key: A strign representation of the key pressed.",
"0, 0, 0, 0, 0, 0, 0, 0, ], [ # J 1,",
"this function pass def kick(board_state: Board, rotated_board_state: Board, k: int, ) -> Union[bool,",
"'J': 1, 'L': 2, 'O': 3, 'S': 4, 'T': 5, 'Z': 6} DIRECTION_INT",
"(0, 1), (0, -1), (0, 2), # L ] O_OFFSETS = [ (0,",
"write this function def true_rotate(board_state: Board, new_rotation: str = '0') -> List[int]: \"\"\"Rotates",
"__license__ = 'Apache License 2.0' __version__ = '0.0.1' __maintainer__ = '<NAME>' __email__ =",
"= [ (0, 0), # 0 (0, -1), # R (-1, -1), #",
"this function def true_rotate(board_state: Board, new_rotation: str = '0') -> List[int]: \"\"\"Rotates a",
"return rotate(board_state, key) else: # elif key == 'store': return store(board_state) if __name__",
"the store flag # TODO: write this function pass def initialize_board() -> Board:",
"rotate_offset = DIRECTION_INT[direction] current_rotate = ROTATE_INT[Board['rotation']] new_rotate = (current_rotate + rotate_offset) % 4",
"active piece based on the key. Key presses allowed: 'up', 'down', 'left', 'right',",
"\"\"\"Translates the rotated board using the offset tables. Returns the kicked board if",
"k != 0: return False i_offset = O_OFFSETS[i_rotate] f_offset = O_OFFSETS[f_rotate] elif ~(0",
"function pass def pop(board_state: Board) -> Board: # TODO: make sure to reset",
"0, 0, ], [ # T 0, 1, 0, 1, 1, 1, 0,",
"0, 0, 0, ], [ # Z 1, 1, 0, 0, 1, 1,",
"a collision. Args: board_state: Returns: True if there is a collision, False if",
"1 if kicked_board_state := kick(board_state, rotated_board_state, k): continue else: return board_state return kicked_board_state",
"console. update to use curses. Args: board_state: Dictionary containing the board state. \"\"\"",
"(0, -1), # R (-1, -1), # 2 (-1, 0), # L ]",
"to see if the current piece should be locked. If the piece should",
"L ] ROTATE_INT = {'0': 0, 'R': 1, '2': 2, 'L': 3} INT_ROTATE",
"key == 'store': return store(board_state) if __name__ == '__main__': TICK = 0.5 board",
"1, 0, 0, 0, ], [ # O 0, 1, 1, 0, 1,",
"0), (1, 0), (1, -1), (0, 2), (1, 2), # R (0, 0),",
"i_rotate = ROTATE_INT[board_state['rotation']] f_rotate = ROTATE_INT[rotated_board_state['rotation']] if board_state['tetromino'] == 'O': if k !=",
"], [ # T 0, 1, 0, 1, 1, 1, 0, 0, 0,",
"Board) -> Board: \"\"\"Attempt to store the current piece. Args: board_state: Returns: A",
"(-1, -1), # 2 (-1, 0), # L ] ROTATE_INT = {'0': 0,",
"i_offset = O_OFFSETS[i_rotate] f_offset = O_OFFSETS[f_rotate] elif ~(0 <= k <= 4): return",
"= kick(board_state, rotated_board_state, k) while collision(kicked_board_state): k += 1 if kicked_board_state := kick(board_state,",
"locked. If the piece should not be locked, returns False. Otherwise, returns the",
"0, ], [ # Z 1, 1, 0, 0, 1, 1, 0, 0,",
"-> List[int]: \"\"\"Rotates a given tetromino clockwise and returns the rotated one. Args:",
"Board]: \"\"\"Translates the rotated board using the offset tables. Returns the kicked board",
"{ # TODO: change the keys to the correct strings 'up': 'up', 'down':",
"key) elif key in rotations: return rotate(board_state, key) else: # elif key ==",
"int, bool, ] TETROMINOES = [ [ # I 0, 0, 0, 0,",
"(0, 0), (0, 0), # 2 (0, 0), (-1, 0), (-1, -1), (0,",
"[ (0, 0), # 0 (0, -1), # R (-1, -1), # 2",
"'left', 'right', 'clockwise', 'counterclockwise', 'store'. Args: board_state: Dictionary containing the board state. key:",
"'down') -> Board: \"\"\"Attempts to translate the current piece in the given direction.",
"time.perf_counter() board = move(board) display(board) print('GAME OVER') input(\"Press the <ENTER> key to continue...\")",
"str = 'down') -> Board: \"\"\"Attempts to move the active piece based on",
"board_state = { 'tetromino': None, 'rotation': '0', 'x': 0, 'y': 0, 'stored': None,",
"= 'Apache License 2.0' __version__ = '0.0.1' __maintainer__ = '<NAME>' __email__ = '<EMAIL>'",
"write this function pass def initialize_board() -> Board: \"\"\" \"\"\" board_state = {",
"Returns: A new board state. \"\"\" # TODO: write this function pass def",
"[ (0, 0), (-1, 0), (2, 0), (-1, 0), (2, 0), # 0",
"Board) -> Board: # TODO: make sure to reset the store flag #",
"(1, 2), # R (0, 0), (0, 0), (0, 0), (0, 0), (0,",
"'up', 'down', 'left', 'right', 'clockwise', 'counterclockwise', 'store'. Args: board_state: Dictionary containing the board",
"current_rotate = ROTATE_INT[Board['rotation']] new_rotate = (current_rotate + rotate_offset) % 4 rotated_board_state = board_state.copy()",
"the key pressed. Returns: The new board state \"\"\" translations = set('up', 'down',",
"= 0.5 board = initialize_board() with keyboard.Events() as events: t_i = time.perf_counter() while",
"(0, 0), (1, 0), (1, -1), (0, 2), (1, 2), # R (0,",
"rotated one. Args: board_state: new_rotation: Returns: A list representation of the rotated tetromino",
"(0, 0), (0, 0), (0, 0), # 0 (0, 0), (1, 0), (1,",
"returns the new board state with the locked piece. Args: board_state: Returns: \"\"\"",
"'tetromino': None, 'rotation': '0', 'x': 0, 'y': 0, 'stored': None, 'stack': [], 'queue':",
"'y': 0, 'stored': None, 'stack': [], 'queue': [], 'score': 0, 'store_flag': False, }",
"pop(board_state) translated_board_state = translate(board_state, key) if locked_board_state := lock(translated_board_state): return locked_board_state return translate(board_state,",
"# TODO: write this function pass def initialize_board() -> Board: \"\"\" \"\"\" board_state",
"'L': 3} INT_ROTATE = ('0', 'R', '2', 'L') TETROMINO_INT = {'I': 0, 'J':",
"int) -> int: return (dim - 1 - (idx % dim))*dim + idx//dim",
"to rotate the current piece in the given direction. Args: board_state: direction: Returns:",
"x_kick = f_offset[0] - i_offset[0] y_kick = f_offset[1] - i_offset[1] kicked_board_state = rotated_board_state.copy()",
"TODO: update score # TODO: write this function pass def pop(board_state: Board) ->",
"new board state \"\"\" translations = set('up', 'down', 'left', 'right') rotations = set('clockwise',",
"TODO: write this function pass def lock(board_state: Board) -> Union[bool, Board]: \"\"\"Checks to",
"-> None: \"\"\"Displays the current board state. TODO: currently simply printing to console.",
"rotated_board_state['rotation'] = INT_ROTATE[new_rotate] k = 0 kicked_board_state = kick(board_state, rotated_board_state, k) while collision(kicked_board_state):",
"translate the current piece in the given direction. Args: board_state: direction: Returns: A",
"= ROTATE_INT[rotated_board_state['rotation']] if board_state['tetromino'] == 'O': if k != 0: return False i_offset",
"else: i_offset = OFFSETS[i_rotate*5 + k] f_offset = OFFSETS[f_rotate*5 + k] x_kick =",
"based on the key. Key presses allowed: 'up', 'down', 'left', 'right', 'clockwise', 'counterclockwise',",
"new board state. \"\"\" # TODO: write this function pass def store(board_state: Board)",
"Board: # TODO: make sure to reset the store flag # TODO: write",
"this function pass def initialize_board() -> Board: \"\"\" \"\"\" board_state = { 'tetromino':",
"f_offset = I_OFFSETS[f_rotate*5 + k] else: i_offset = OFFSETS[i_rotate*5 + k] f_offset =",
"'Development' \"\"\" Docstring \"\"\" from typing import Dict, List, Union, Optional import time",
"display(board_state: Board) -> None: \"\"\"Displays the current board state. TODO: currently simply printing",
"(0, 0), # 0 (0, 0), (1, 0), (1, -1), (0, 2), (1,",
"returns the new index for a given index after a # clockwise rotation.",
"index after a # clockwise rotation. def rot(idx: int, dim: int) -> int:",
"= Dict[ Optional[str], str, int, int, Optional[str], List[int], List[int], int, bool, ] TETROMINOES",
"bool: \"\"\"Checks if given board results in a collision. Args: board_state: Returns: True",
"there is not. \"\"\" # TODO: write this function pass def kick(board_state: Board,",
"set('clockwise', 'counterclockwise') if key in translations: if board_state['tetromino'] is None: return pop(board_state) translated_board_state",
"0, 0, 0, ], [ # O 0, 1, 1, 0, 1, 1,",
"is not. \"\"\" # TODO: write this function pass def kick(board_state: Board, rotated_board_state:",
"Returns: \"\"\" i_rotate = ROTATE_INT[board_state['rotation']] f_rotate = ROTATE_INT[rotated_board_state['rotation']] if board_state['tetromino'] == 'O': if",
"'store': return store(board_state) if __name__ == '__main__': TICK = 0.5 board = initialize_board()",
"0, 0, ], [ # Z 1, 1, 0, 0, 1, 1, 0,",
"'down', 'left', 'right', 'clockwise', 'counterclockwise', 'store'. Args: board_state: Dictionary containing the board state.",
"bool: # TODO: write this function pass def move(board_state: Board, key: str =",
"], [ # L 0, 0, 1, 1, 1, 1, 0, 0, 0,",
"to store the current piece. Args: board_state: Returns: A new board state. \"\"\"",
"the active piece based on the key. Key presses allowed: 'up', 'down', 'left',",
"representation of the rotated tetromino Raises: AssertionError: \"\"\" # This nested function returns",
"-> Board: \"\"\" \"\"\" board_state = { 'tetromino': None, 'rotation': '0', 'x': 0,",
"0 (0, -1), # R (-1, -1), # 2 (-1, 0), # L",
"'left', 'right') rotations = set('clockwise', 'counterclockwise') if key in translations: if board_state['tetromino'] is",
"> TICK: t_i = time.perf_counter() board = move(board) display(board) print('GAME OVER') input(\"Press the",
"in translations: if board_state['tetromino'] is None: return pop(board_state) translated_board_state = translate(board_state, key) if",
"'clockwise') -> Board: \"\"\"Attempts to rotate the current piece in the given direction.",
"__version__ = '0.0.1' __maintainer__ = '<NAME>' __email__ = '<EMAIL>' __status__ = 'Development' \"\"\"",
"k] x_kick = f_offset[0] - i_offset[0] y_kick = f_offset[1] - i_offset[1] kicked_board_state =",
"returns the rotated one. Args: board_state: new_rotation: Returns: A list representation of the",
"is None: return pop(board_state) translated_board_state = translate(board_state, key) if locked_board_state := lock(translated_board_state): return",
"(current_rotate + rotate_offset) % 4 rotated_board_state = board_state.copy() rotated_board_state['rotation'] = INT_ROTATE[new_rotate] k =",
"-1} KEYMAP = { # TODO: change the keys to the correct strings",
"Board) -> None: \"\"\"Displays the current board state. TODO: currently simply printing to",
"a given tetromino clockwise and returns the rotated one. Args: board_state: new_rotation: Returns:",
"# This nested function returns the new index for a given index after",
"k] f_offset = OFFSETS[f_rotate*5 + k] x_kick = f_offset[0] - i_offset[0] y_kick =",
":= kick(board_state, rotated_board_state, k): continue else: return board_state return kicked_board_state def translate(board_state: Board,",
"A new board state. \"\"\" # TODO: write this function pass def store(board_state:",
"-> Union[bool, Board]: \"\"\"Checks to see if the current piece should be locked.",
"write this function pass def pop(board_state: Board) -> Board: # TODO: make sure",
"0), # 2 (0, 0), (-1, 0), (-1, -1), (0, 2), (-1, 2),",
"0, 0, 0, ], [ # J 1, 0, 0, 1, 1, 1,",
"if board_state['tetromino'] is None: return pop(board_state) translated_board_state = translate(board_state, key) if locked_board_state :=",
"TODO: write this function pass def pop(board_state: Board) -> Board: # TODO: make",
"1, 1, 0, 0, 0, ], ] OFFSETS = [ (0, 0), (0,",
"1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [",
"initialize stack # TODO: initialize queue return board_state def game_over(board_state: Board) -> bool:",
"the current piece. Args: board_state: Returns: A new board state. \"\"\" # TODO:",
"and returns the rotated one. Args: board_state: new_rotation: Returns: A list representation of",
"game_over(board_state: Board) -> bool: # TODO: write this function pass def move(board_state: Board,",
"kicked board if there is a kick available. Otherwise, returns False. Args: board_state:",
"0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,",
"= '<NAME>' __email__ = '<EMAIL>' __status__ = 'Development' \"\"\" Docstring \"\"\" from typing",
"1, 1, 1, 0, 0, 0, 0, ], [ # T 0, 1,",
"initialize_board() -> Board: \"\"\" \"\"\" board_state = { 'tetromino': None, 'rotation': '0', 'x':",
"0), (-1, 0), (2, 0), (-1, 0), (2, 0), # 0 (-1, 0),",
"a # clockwise rotation. def rot(idx: int, dim: int) -> int: return (dim",
"2.0' __version__ = '0.0.1' __maintainer__ = '<NAME>' __email__ = '<EMAIL>' __status__ = 'Development'",
"translate(board_state, key) if locked_board_state := lock(translated_board_state): return locked_board_state return translate(board_state, key) elif key",
"change the keys to the correct strings 'up': 'up', 'down': 'down', 'left': 'left',",
"+ rotate_offset) % 4 rotated_board_state = board_state.copy() rotated_board_state['rotation'] = INT_ROTATE[new_rotate] k = 0",
"if given board results in a collision. Args: board_state: Returns: True if there",
"= { # TODO: change the keys to the correct strings 'up': 'up',",
"be locked, returns False. Otherwise, returns the new board state with the locked",
"0, 1, 1, 0, 1, 1, 0, 0, 0, ], [ # S",
") -> Union[bool, Board]: \"\"\"Translates the rotated board using the offset tables. Returns",
"TODO: make sure to reset the store flag # TODO: write this function",
"= initialize_board() with keyboard.Events() as events: t_i = time.perf_counter() while ~game_over(board): event =",
"1), (0, -2), # R (-1, 1), (1, 1), (-2, 1), (1, 0),",
"piece should not be locked, returns False. Otherwise, returns the new board state",
"2), (1, 2), # R (0, 0), (0, 0), (0, 0), (0, 0),",
"function def true_rotate(board_state: Board, new_rotation: str = '0') -> List[int]: \"\"\"Rotates a given",
"= ROTATE_INT[new_rotation] iterations = (4 + new_rotation_idx - current_rotation_idx) % 4 assert(iterations !=",
"OFFSETS = [ (0, 0), (0, 0), (0, 0), (0, 0), (0, 0),",
"+= 1 if kicked_board_state := kick(board_state, rotated_board_state, k): continue else: return board_state return",
"= f_offset[0] - i_offset[0] y_kick = f_offset[1] - i_offset[1] kicked_board_state = rotated_board_state.copy() kicked_board_state['x']",
"def kick(board_state: Board, rotated_board_state: Board, k: int, ) -> Union[bool, Board]: \"\"\"Translates the",
"\"\"\" rotate_offset = DIRECTION_INT[direction] current_rotate = ROTATE_INT[Board['rotation']] new_rotate = (current_rotate + rotate_offset) %",
"rotated_board_state: Board, k: int, ) -> Union[bool, Board]: \"\"\"Translates the rotated board using",
"int, ) -> Union[bool, Board]: \"\"\"Translates the rotated board using the offset tables.",
"state \"\"\" translations = set('up', 'down', 'left', 'right') rotations = set('clockwise', 'counterclockwise') if",
"__copyright__ = 'Copyright 2020 <NAME>' __credits__ = ['<NAME>'] __license__ = 'Apache License 2.0'",
"= I_OFFSETS[f_rotate*5 + k] else: i_offset = OFFSETS[i_rotate*5 + k] f_offset = OFFSETS[f_rotate*5",
"board state \"\"\" translations = set('up', 'down', 'left', 'right') rotations = set('clockwise', 'counterclockwise')",
"1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,",
"0, 'R': 1, '2': 2, 'L': 3} INT_ROTATE = ('0', 'R', '2', 'L')",
"[tetromino[rot(i, dim)] for i in tetromino] return tetromino def collision(board_state: Board) -> bool:",
"\"\"\" # This nested function returns the new index for a given index",
"<= k <= 4): return False elif board_state['tetromino'] == 'I': i_offset = I_OFFSETS[i_rotate*5",
"\"\"\" from typing import Dict, List, Union, Optional import time from pynput import",
"not. \"\"\" # TODO: write this function pass def kick(board_state: Board, rotated_board_state: Board,",
"\"\"\"Displays the current board state. TODO: currently simply printing to console. update to",
"2) dim = int(len(tetromino)**0.5) for _ in range(iterations): tetromino = [tetromino[rot(i, dim)] for",
"current piece should be locked. If the piece should not be locked, returns",
"else: # elif key == 'store': return store(board_state) if __name__ == '__main__': TICK",
"0), # L ] ROTATE_INT = {'0': 0, 'R': 1, '2': 2, 'L':",
"typing import Dict, List, Union, Optional import time from pynput import keyboard Board",
"'up', 'down': 'down', 'left': 'left', 'right': 'right', 'clockwise': 'clockwise', 'counterclockwise': 'counterclockwise', 'store': 'store',",
"0), (-2, 0), # 2 (0, 1), (0, 1), (0, 1), (0, -1),",
"i_offset[0] y_kick = f_offset[1] - i_offset[1] kicked_board_state = rotated_board_state.copy() kicked_board_state['x'] += x_kick kicked_board_state['y']",
"= ['<NAME>'] __license__ = 'Apache License 2.0' __version__ = '0.0.1' __maintainer__ = '<NAME>'",
"kick available. Otherwise, returns False. Args: board_state: rotated_board_state: k: The offset index to",
"None: \"\"\"Displays the current board state. TODO: currently simply printing to console. update",
"str = 'down') -> Board: \"\"\"Attempts to translate the current piece in the",
"function pass def lock(board_state: Board) -> Union[bool, Board]: \"\"\"Checks to see if the",
"# TODO: make sure to clear lines # TODO: update score # TODO:",
"0), (2, 0), (-1, 0), (2, 0), # 0 (-1, 0), (0, 0),",
"= board_state.copy() rotated_board_state['rotation'] = INT_ROTATE[new_rotate] k = 0 kicked_board_state = kick(board_state, rotated_board_state, k)",
"# 2 (0, 0), (-1, 0), (-1, -1), (0, 2), (-1, 2), #",
"KEYMAP[event]) display(board) if (time.perf_counter() - t_i) > TICK: t_i = time.perf_counter() board =",
"\"\"\"Attempt to store the current piece. Args: board_state: Returns: A new board state.",
"# L ] ROTATE_INT = {'0': 0, 'R': 1, '2': 2, 'L': 3}",
"rotated_board_state = board_state.copy() rotated_board_state['rotation'] = INT_ROTATE[new_rotate] k = 0 kicked_board_state = kick(board_state, rotated_board_state,",
"[ # T 0, 1, 0, 1, 1, 1, 0, 0, 0, ],",
"# 0 (0, 0), (1, 0), (1, -1), (0, 2), (1, 2), #",
"1, 1, 0, 0, 0, 0, ], [ # T 0, 1, 0,",
"kick(board_state, rotated_board_state, k): continue else: return board_state return kicked_board_state def translate(board_state: Board, direction:",
"iterations = (4 + new_rotation_idx - current_rotation_idx) % 4 assert(iterations != 2) dim",
"new_rotation: Returns: A list representation of the rotated tetromino Raises: AssertionError: \"\"\" #",
"clockwise and returns the rotated one. Args: board_state: new_rotation: Returns: A list representation",
"+= y_kick return kicked_board_state def rotate(board_state: Board, direction: str = 'clockwise') -> Board:",
"= '<EMAIL>' __status__ = 'Development' \"\"\" Docstring \"\"\" from typing import Dict, List,",
"new board state. \"\"\" rotate_offset = DIRECTION_INT[direction] current_rotate = ROTATE_INT[Board['rotation']] new_rotate = (current_rotate",
"(time.perf_counter() - t_i) > TICK: t_i = time.perf_counter() board = move(board) display(board) print('GAME",
"the given direction. Args: board_state: direction: Returns: A new board state. \"\"\" rotate_offset",
"'counterclockwise': -1} KEYMAP = { # TODO: change the keys to the correct",
"!= 2) dim = int(len(tetromino)**0.5) for _ in range(iterations): tetromino = [tetromino[rot(i, dim)]",
"# O 0, 1, 1, 0, 1, 1, 0, 0, 0, ], [",
"'stored': None, 'stack': [], 'queue': [], 'score': 0, 'store_flag': False, } # TODO:",
"kicked_board_state['x'] += x_kick kicked_board_state['y'] += y_kick return kicked_board_state def rotate(board_state: Board, direction: str",
"board results in a collision. Args: board_state: Returns: True if there is a",
"with keyboard.Events() as events: t_i = time.perf_counter() while ~game_over(board): event = events.get(TICK) if",
"(0, 0), (0, 0), (0, 1), (0, -2), # R (-1, 1), (1,",
"1, 0, 1, 1, 1, 0, 0, 0, ], [ # Z 1,",
"= {'I': 0, 'J': 1, 'L': 2, 'O': 3, 'S': 4, 'T': 5,",
"sure to clear lines # TODO: update score # TODO: write this function",
"<NAME>' __credits__ = ['<NAME>'] __license__ = 'Apache License 2.0' __version__ = '0.0.1' __maintainer__",
"[], 'queue': [], 'score': 0, 'store_flag': False, } # TODO: initialize stack #",
"Args: board_state: Dictionary containing the board state. key: A strign representation of the",
"AssertionError: \"\"\" # This nested function returns the new index for a given",
"Dict, List, Union, Optional import time from pynput import keyboard Board = Dict[",
"from pynput import keyboard Board = Dict[ Optional[str], str, int, int, Optional[str], List[int],",
"1, 0, 0, 0, ], ] OFFSETS = [ (0, 0), (0, 0),",
"index to use. Returns: \"\"\" i_rotate = ROTATE_INT[board_state['rotation']] f_rotate = ROTATE_INT[rotated_board_state['rotation']] if board_state['tetromino']",
"= OFFSETS[i_rotate*5 + k] f_offset = OFFSETS[f_rotate*5 + k] x_kick = f_offset[0] -",
"be locked. If the piece should not be locked, returns False. Otherwise, returns",
"} # TODO: initialize stack # TODO: initialize queue return board_state def game_over(board_state:",
"Args: board_state: Returns: True if there is a collision, False if there is",
"key) if locked_board_state := lock(translated_board_state): return locked_board_state return translate(board_state, key) elif key in",
"a collision, False if there is not. \"\"\" # TODO: write this function",
"'Apache License 2.0' __version__ = '0.0.1' __maintainer__ = '<NAME>' __email__ = '<EMAIL>' __status__",
"[ # I 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,",
"= move(board, KEYMAP[event]) display(board) if (time.perf_counter() - t_i) > TICK: t_i = time.perf_counter()",
"k: int, ) -> Union[bool, Board]: \"\"\"Translates the rotated board using the offset",
"the rotated board using the offset tables. Returns the kicked board if there",
"+ k] f_offset = I_OFFSETS[f_rotate*5 + k] else: i_offset = OFFSETS[i_rotate*5 + k]",
"= INT_ROTATE[new_rotate] k = 0 kicked_board_state = kick(board_state, rotated_board_state, k) while collision(kicked_board_state): k",
"'score': 0, 'store_flag': False, } # TODO: initialize stack # TODO: initialize queue",
"== 'O': if k != 0: return False i_offset = O_OFFSETS[i_rotate] f_offset =",
"TODO: write this function pass def store(board_state: Board) -> Board: \"\"\"Attempt to store",
"TODO: initialize queue return board_state def game_over(board_state: Board) -> bool: # TODO: write",
"= time.perf_counter() while ~game_over(board): event = events.get(TICK) if event is not None: board",
"board state. \"\"\" # TODO: write this function pass def lock(board_state: Board) ->",
"== '__main__': TICK = 0.5 board = initialize_board() with keyboard.Events() as events: t_i",
"1), (0, -1), (0, 2), # L ] O_OFFSETS = [ (0, 0),",
"2 (0, 0), (-1, 0), (-1, -1), (0, 2), (-1, 2), # L",
"'counterclockwise', 'store'. Args: board_state: Dictionary containing the board state. key: A strign representation",
"1, 1, 0, 0, 0, ], [ # Z 1, 1, 0, 0,",
"piece. Args: board_state: Returns: A new board state. \"\"\" # TODO: write this",
"reset the store flag # TODO: write this function pass def initialize_board() ->",
"f_offset[0] - i_offset[0] y_kick = f_offset[1] - i_offset[1] kicked_board_state = rotated_board_state.copy() kicked_board_state['x'] +=",
"in range(iterations): tetromino = [tetromino[rot(i, dim)] for i in tetromino] return tetromino def",
"if there is not. \"\"\" # TODO: write this function pass def kick(board_state:",
"\"\"\" \"\"\" board_state = { 'tetromino': None, 'rotation': '0', 'x': 0, 'y': 0,",
"dim: int) -> int: return (dim - 1 - (idx % dim))*dim +",
"using the offset tables. Returns the kicked board if there is a kick",
"1, 1, 1, 0, 0, 0, ], [ # O 0, 1, 1,",
"= ('0', 'R', '2', 'L') TETROMINO_INT = {'I': 0, 'J': 1, 'L': 2,",
"def move(board_state: Board, key: str = 'down') -> Board: \"\"\"Attempts to move the",
"the locked piece. Args: board_state: Returns: \"\"\" # TODO: make sure to clear",
"to console. update to use curses. Args: board_state: Dictionary containing the board state.",
"piece in the given direction. Args: board_state: direction: Returns: A new board state.",
"TICK = 0.5 board = initialize_board() with keyboard.Events() as events: t_i = time.perf_counter()",
"Board) -> bool: \"\"\"Checks if given board results in a collision. Args: board_state:",
"translate(board_state: Board, direction: str = 'down') -> Board: \"\"\"Attempts to translate the current",
"0, ], [ # J 1, 0, 0, 1, 1, 1, 0, 0,",
"List, Union, Optional import time from pynput import keyboard Board = Dict[ Optional[str],",
"= 'clockwise') -> Board: \"\"\"Attempts to rotate the current piece in the given",
"- (idx % dim))*dim + idx//dim tetromino_idx = TETROMINO_INT[board_state['tetromino']] tetromino = TETROMINOES[tetromino_idx] current_rotation_idx",
"0, 0, 0, ], [ # L 0, 0, 1, 1, 1, 1,",
"board_state['tetromino'] is None: return pop(board_state) translated_board_state = translate(board_state, key) if locked_board_state := lock(translated_board_state):",
"= O_OFFSETS[f_rotate] elif ~(0 <= k <= 4): return False elif board_state['tetromino'] ==",
"to reset the store flag # TODO: write this function pass def initialize_board()",
"[], 'score': 0, 'store_flag': False, } # TODO: initialize stack # TODO: initialize",
"'<NAME>' __email__ = '<EMAIL>' __status__ = 'Development' \"\"\" Docstring \"\"\" from typing import",
"tetromino_idx = TETROMINO_INT[board_state['tetromino']] tetromino = TETROMINOES[tetromino_idx] current_rotation_idx = ROTATE_INT[board_state['rotation']] new_rotation_idx = ROTATE_INT[new_rotation] iterations",
"Board]: \"\"\"Checks to see if the current piece should be locked. If the",
"\"\"\" # TODO: make sure to clear lines # TODO: update score #",
"returns False. Args: board_state: rotated_board_state: k: The offset index to use. Returns: \"\"\"",
"1, 1, 1, 1, 0, 0, 0, ], [ # O 0, 1,",
"0), (0, 1), (0, -2), # R (-1, 1), (1, 1), (-2, 1),",
"4 assert(iterations != 2) dim = int(len(tetromino)**0.5) for _ in range(iterations): tetromino =",
"= ROTATE_INT[board_state['rotation']] f_rotate = ROTATE_INT[rotated_board_state['rotation']] if board_state['tetromino'] == 'O': if k != 0:",
"range(iterations): tetromino = [tetromino[rot(i, dim)] for i in tetromino] return tetromino def collision(board_state:",
"update score # TODO: write this function pass def pop(board_state: Board) -> Board:",
"board state. TODO: currently simply printing to console. update to use curses. Args:",
"-> Board: # TODO: make sure to reset the store flag # TODO:",
"if (time.perf_counter() - t_i) > TICK: t_i = time.perf_counter() board = move(board) display(board)",
"to move the active piece based on the key. Key presses allowed: 'up',",
"'left': 'left', 'right': 'right', 'clockwise': 'clockwise', 'counterclockwise': 'counterclockwise', 'store': 'store', } def display(board_state:",
"= f_offset[1] - i_offset[1] kicked_board_state = rotated_board_state.copy() kicked_board_state['x'] += x_kick kicked_board_state['y'] += y_kick",
"(-1, 0), # L ] ROTATE_INT = {'0': 0, 'R': 1, '2': 2,",
"Returns: A list representation of the rotated tetromino Raises: AssertionError: \"\"\" # This",
"_ in range(iterations): tetromino = [tetromino[rot(i, dim)] for i in tetromino] return tetromino",
"in a collision. Args: board_state: Returns: True if there is a collision, False",
"+ k] x_kick = f_offset[0] - i_offset[0] y_kick = f_offset[1] - i_offset[1] kicked_board_state",
"y_kick = f_offset[1] - i_offset[1] kicked_board_state = rotated_board_state.copy() kicked_board_state['x'] += x_kick kicked_board_state['y'] +=",
"{ 'tetromino': None, 'rotation': '0', 'x': 0, 'y': 0, 'stored': None, 'stack': [],",
"1, 1, 0, 0, 1, 1, 0, 0, 0, ], ] OFFSETS =",
"TODO: initialize stack # TODO: initialize queue return board_state def game_over(board_state: Board) ->",
"if locked_board_state := lock(translated_board_state): return locked_board_state return translate(board_state, key) elif key in rotations:",
"1, 0, 0, 0, ], [ # L 0, 0, 1, 1, 1,",
"def pop(board_state: Board) -> Board: # TODO: make sure to reset the store",
"0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0,",
"List[int]: \"\"\"Rotates a given tetromino clockwise and returns the rotated one. Args: board_state:",
"-> bool: \"\"\"Checks if given board results in a collision. Args: board_state: Returns:",
"(1, 1), (-2, 1), (1, 0), (-2, 0), # 2 (0, 1), (0,",
"int, Optional[str], List[int], List[int], int, bool, ] TETROMINOES = [ [ # I",
"clockwise rotation. def rot(idx: int, dim: int) -> int: return (dim - 1",
"TETROMINOES = [ [ # I 0, 0, 0, 0, 0, 0, 0,",
"], [ # S 0, 1, 1, 1, 1, 0, 0, 0, 0,",
"collision, False if there is not. \"\"\" # TODO: write this function pass",
"R (-1, 1), (1, 1), (-2, 1), (1, 0), (-2, 0), # 2",
"= O_OFFSETS[i_rotate] f_offset = O_OFFSETS[f_rotate] elif ~(0 <= k <= 4): return False",
"translated_board_state = translate(board_state, key) if locked_board_state := lock(translated_board_state): return locked_board_state return translate(board_state, key)",
"O_OFFSETS = [ (0, 0), # 0 (0, -1), # R (-1, -1),",
"state with the locked piece. Args: board_state: Returns: \"\"\" # TODO: make sure",
"A strign representation of the key pressed. Returns: The new board state \"\"\"",
"board_state['tetromino'] == 'I': i_offset = I_OFFSETS[i_rotate*5 + k] f_offset = I_OFFSETS[f_rotate*5 + k]",
"(-2, 1), (1, 0), (-2, 0), # 2 (0, 1), (0, 1), (0,",
"bool, ] TETROMINOES = [ [ # I 0, 0, 0, 0, 0,",
"1, 1, 0, 0, 0, ], [ # O 0, 1, 1, 0,",
"(-1, 1), (1, 1), (-2, 1), (1, 0), (-2, 0), # 2 (0,",
"move(board, KEYMAP[event]) display(board) if (time.perf_counter() - t_i) > TICK: t_i = time.perf_counter() board",
"curses. Args: board_state: Dictionary containing the board state. \"\"\" # TODO: write this",
"Z 1, 1, 0, 0, 1, 1, 0, 0, 0, ], ] OFFSETS",
"'counterclockwise': 'counterclockwise', 'store': 'store', } def display(board_state: Board) -> None: \"\"\"Displays the current",
"store the current piece. Args: board_state: Returns: A new board state. \"\"\" #",
"__author__ = '<NAME>' __copyright__ = 'Copyright 2020 <NAME>' __credits__ = ['<NAME>'] __license__ =",
"0), (0, 0), (0, 0), (0, 1), (0, -2), # R (-1, 1),",
"= '<NAME>' __copyright__ = 'Copyright 2020 <NAME>' __credits__ = ['<NAME>'] __license__ = 'Apache",
"(0, 0), (0, 0), (0, 0), (0, 0), # 2 (0, 0), (-1,",
"kicked_board_state def rotate(board_state: Board, direction: str = 'clockwise') -> Board: \"\"\"Attempts to rotate",
"0), (0, 0), # 0 (0, 0), (1, 0), (1, -1), (0, 2),",
"(0, 1), (0, 1), (0, -1), (0, 2), # L ] O_OFFSETS =",
"str = '0') -> List[int]: \"\"\"Rotates a given tetromino clockwise and returns the",
"board = initialize_board() with keyboard.Events() as events: t_i = time.perf_counter() while ~game_over(board): event",
"tetromino def collision(board_state: Board) -> bool: \"\"\"Checks if given board results in a",
"pynput import keyboard Board = Dict[ Optional[str], str, int, int, Optional[str], List[int], List[int],",
"is a collision, False if there is not. \"\"\" # TODO: write this",
"# TODO: write this function pass def pop(board_state: Board) -> Board: # TODO:",
"0, 'y': 0, 'stored': None, 'stack': [], 'queue': [], 'score': 0, 'store_flag': False,",
"in rotations: return rotate(board_state, key) else: # elif key == 'store': return store(board_state)",
"sure to reset the store flag # TODO: write this function pass def",
"(2, 0), (-1, 0), (2, 0), # 0 (-1, 0), (0, 0), (0,",
"rotation. def rot(idx: int, dim: int) -> int: return (dim - 1 -",
"~(0 <= k <= 4): return False elif board_state['tetromino'] == 'I': i_offset =",
"('0', 'R', '2', 'L') TETROMINO_INT = {'I': 0, 'J': 1, 'L': 2, 'O':",
"{'I': 0, 'J': 1, 'L': 2, 'O': 3, 'S': 4, 'T': 5, 'Z':",
"given direction. Args: board_state: direction: Returns: A new board state. \"\"\" rotate_offset =",
"0), (0, 0), (0, 1), (0, -2), # R (-1, 1), (1, 1),",
"this function pass def pop(board_state: Board) -> Board: # TODO: make sure to",
"\"\"\"Attempts to rotate the current piece in the given direction. Args: board_state: direction:",
"the current piece should be locked. If the piece should not be locked,",
"elif key == 'store': return store(board_state) if __name__ == '__main__': TICK = 0.5",
"'2': 2, 'L': 3} INT_ROTATE = ('0', 'R', '2', 'L') TETROMINO_INT = {'I':",
"= time.perf_counter() board = move(board) display(board) print('GAME OVER') input(\"Press the <ENTER> key to",
"store flag # TODO: write this function pass def initialize_board() -> Board: \"\"\"",
"(-1, 0), (0, 0), (0, 0), (0, 1), (0, -2), # R (-1,",
"allowed: 'up', 'down', 'left', 'right', 'clockwise', 'counterclockwise', 'store'. Args: board_state: Dictionary containing the",
"k) while collision(kicked_board_state): k += 1 if kicked_board_state := kick(board_state, rotated_board_state, k): continue",
"0, 0, 0, 0, 0, 0, 0, 0, 0, ], [ # J",
"True if there is a collision, False if there is not. \"\"\" #",
"return (dim - 1 - (idx % dim))*dim + idx//dim tetromino_idx = TETROMINO_INT[board_state['tetromino']]",
"should be locked. If the piece should not be locked, returns False. Otherwise,",
"1), (-2, 1), (1, 0), (-2, 0), # 2 (0, 1), (0, 1),",
"None: return pop(board_state) translated_board_state = translate(board_state, key) if locked_board_state := lock(translated_board_state): return locked_board_state",
"(0, -1), (0, 2), # L ] O_OFFSETS = [ (0, 0), #",
"return kicked_board_state def rotate(board_state: Board, direction: str = 'clockwise') -> Board: \"\"\"Attempts to",
"__credits__ = ['<NAME>'] __license__ = 'Apache License 2.0' __version__ = '0.0.1' __maintainer__ =",
"(idx % dim))*dim + idx//dim tetromino_idx = TETROMINO_INT[board_state['tetromino']] tetromino = TETROMINOES[tetromino_idx] current_rotation_idx =",
"ROTATE_INT[board_state['rotation']] f_rotate = ROTATE_INT[rotated_board_state['rotation']] if board_state['tetromino'] == 'O': if k != 0: return",
"\"\"\" Docstring \"\"\" from typing import Dict, List, Union, Optional import time from",
"event is not None: board = move(board, KEYMAP[event]) display(board) if (time.perf_counter() - t_i)",
"Args: board_state: direction: Returns: A new board state. \"\"\" rotate_offset = DIRECTION_INT[direction] current_rotate",
"not None: board = move(board, KEYMAP[event]) display(board) if (time.perf_counter() - t_i) > TICK:",
"write this function pass def store(board_state: Board) -> Board: \"\"\"Attempt to store the",
"int, dim: int) -> int: return (dim - 1 - (idx % dim))*dim",
"stack # TODO: initialize queue return board_state def game_over(board_state: Board) -> bool: #",
"# 2 (0, 1), (0, 1), (0, 1), (0, -1), (0, 2), #",
"printing to console. update to use curses. Args: board_state: Dictionary containing the board",
"'store'. Args: board_state: Dictionary containing the board state. key: A strign representation of",
"pressed. Returns: The new board state \"\"\" translations = set('up', 'down', 'left', 'right')",
"0, 'store_flag': False, } # TODO: initialize stack # TODO: initialize queue return",
"[ # S 0, 1, 1, 1, 1, 0, 0, 0, 0, ],",
"move(board_state: Board, key: str = 'down') -> Board: \"\"\"Attempts to move the active",
"0), (0, 0), (0, 0), (0, 0), # 2 (0, 0), (-1, 0),",
"collision(kicked_board_state): k += 1 if kicked_board_state := kick(board_state, rotated_board_state, k): continue else: return",
"locked piece. Args: board_state: Returns: \"\"\" # TODO: make sure to clear lines",
"0 (-1, 0), (0, 0), (0, 0), (0, 1), (0, -2), # R",
"} def display(board_state: Board) -> None: \"\"\"Displays the current board state. TODO: currently",
"board state. \"\"\" rotate_offset = DIRECTION_INT[direction] current_rotate = ROTATE_INT[Board['rotation']] new_rotate = (current_rotate +",
"= [ (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), #",
"new_rotation_idx = ROTATE_INT[new_rotation] iterations = (4 + new_rotation_idx - current_rotation_idx) % 4 assert(iterations",
"i_offset = I_OFFSETS[i_rotate*5 + k] f_offset = I_OFFSETS[f_rotate*5 + k] else: i_offset =",
"0, 0, ], [ # J 1, 0, 0, 1, 1, 1, 0,",
"def true_rotate(board_state: Board, new_rotation: str = '0') -> List[int]: \"\"\"Rotates a given tetromino",
"Args: board_state: new_rotation: Returns: A list representation of the rotated tetromino Raises: AssertionError:",
"0), (-1, -1), (0, 2), (-1, 2), # L ] I_OFFSETS = [",
"INT_ROTATE = ('0', 'R', '2', 'L') TETROMINO_INT = {'I': 0, 'J': 1, 'L':",
"given index after a # clockwise rotation. def rot(idx: int, dim: int) ->",
"pass def move(board_state: Board, key: str = 'down') -> Board: \"\"\"Attempts to move",
"current board state. TODO: currently simply printing to console. update to use curses.",
"S 0, 1, 1, 1, 1, 0, 0, 0, 0, ], [ #",
"= (4 + new_rotation_idx - current_rotation_idx) % 4 assert(iterations != 2) dim =",
"['<NAME>'] __license__ = 'Apache License 2.0' __version__ = '0.0.1' __maintainer__ = '<NAME>' __email__",
"continue else: return board_state return kicked_board_state def translate(board_state: Board, direction: str = 'down')",
"# TODO: make sure to reset the store flag # TODO: write this",
"False if there is not. \"\"\" # TODO: write this function pass def",
"0, 1, 1, 1, 1, 0, 0, 0, 0, ], [ # T",
"representation of the key pressed. Returns: The new board state \"\"\" translations =",
"to clear lines # TODO: update score # TODO: write this function pass",
"[ # L 0, 0, 1, 1, 1, 1, 0, 0, 0, ],",
"(0, 0), (0, 0), (0, 0), (0, 0), # 0 (0, 0), (1,",
"(0, -2), # R (-1, 1), (1, 1), (-2, 1), (1, 0), (-2,",
"rotate(board_state: Board, direction: str = 'clockwise') -> Board: \"\"\"Attempts to rotate the current",
"# TODO: write this function pass def move(board_state: Board, key: str = 'down')",
"return locked_board_state return translate(board_state, key) elif key in rotations: return rotate(board_state, key) else:",
"0, 1, 1, 1, 1, 0, 0, 0, ], [ # O 0,",
"board_state: rotated_board_state: k: The offset index to use. Returns: \"\"\" i_rotate = ROTATE_INT[board_state['rotation']]",
"False elif board_state['tetromino'] == 'I': i_offset = I_OFFSETS[i_rotate*5 + k] f_offset = I_OFFSETS[f_rotate*5",
"-1), # R (-1, -1), # 2 (-1, 0), # L ] ROTATE_INT",
"if k != 0: return False i_offset = O_OFFSETS[i_rotate] f_offset = O_OFFSETS[f_rotate] elif",
"Union[bool, Board]: \"\"\"Checks to see if the current piece should be locked. If",
"# R (-1, 1), (1, 1), (-2, 1), (1, 0), (-2, 0), #",
"Board) -> bool: # TODO: write this function pass def move(board_state: Board, key:",
"key) else: # elif key == 'store': return store(board_state) if __name__ == '__main__':",
"L ] O_OFFSETS = [ (0, 0), # 0 (0, -1), # R",
"str = 'clockwise') -> Board: \"\"\"Attempts to rotate the current piece in the",
"4): return False elif board_state['tetromino'] == 'I': i_offset = I_OFFSETS[i_rotate*5 + k] f_offset",
"function pass def kick(board_state: Board, rotated_board_state: Board, k: int, ) -> Union[bool, Board]:",
"- i_offset[1] kicked_board_state = rotated_board_state.copy() kicked_board_state['x'] += x_kick kicked_board_state['y'] += y_kick return kicked_board_state",
"dim)] for i in tetromino] return tetromino def collision(board_state: Board) -> bool: \"\"\"Checks",
"0), (0, 0), (0, 0), (0, 0), (0, 0), # 0 (0, 0),",
"piece based on the key. Key presses allowed: 'up', 'down', 'left', 'right', 'clockwise',",
"this function pass def lock(board_state: Board) -> Union[bool, Board]: \"\"\"Checks to see if",
"0), (0, 0), (0, 0), # 2 (0, 0), (-1, 0), (-1, -1),",
"tetromino clockwise and returns the rotated one. Args: board_state: new_rotation: Returns: A list",
"# R (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), #",
"i_offset[1] kicked_board_state = rotated_board_state.copy() kicked_board_state['x'] += x_kick kicked_board_state['y'] += y_kick return kicked_board_state def",
"the current board state. TODO: currently simply printing to console. update to use",
"1, 1, 1, 0, 0, 0, ], [ # Z 1, 1, 0,",
"= I_OFFSETS[i_rotate*5 + k] f_offset = I_OFFSETS[f_rotate*5 + k] else: i_offset = OFFSETS[i_rotate*5",
"R (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), # 2",
"I_OFFSETS[f_rotate*5 + k] else: i_offset = OFFSETS[i_rotate*5 + k] f_offset = OFFSETS[f_rotate*5 +",
"= {'clockwise': 1, 'counterclockwise': -1} KEYMAP = { # TODO: change the keys",
"(-1, 2), # L ] I_OFFSETS = [ (0, 0), (-1, 0), (2,",
"for i in tetromino] return tetromino def collision(board_state: Board) -> bool: \"\"\"Checks if",
"return kicked_board_state def translate(board_state: Board, direction: str = 'down') -> Board: \"\"\"Attempts to",
"1, 0, 0, 1, 1, 0, 0, 0, ], ] OFFSETS = [",
"tetromino Raises: AssertionError: \"\"\" # This nested function returns the new index for",
"new index for a given index after a # clockwise rotation. def rot(idx:",
"Returns: True if there is a collision, False if there is not. \"\"\"",
"lines # TODO: update score # TODO: write this function pass def pop(board_state:",
"queue return board_state def game_over(board_state: Board) -> bool: # TODO: write this function",
"(0, 0), (0, 0), (0, 0), (0, 0), (0, 0), # 0 (0,",
"one. Args: board_state: new_rotation: Returns: A list representation of the rotated tetromino Raises:",
"Board: \"\"\"Attempt to store the current piece. Args: board_state: Returns: A new board",
"= TETROMINO_INT[board_state['tetromino']] tetromino = TETROMINOES[tetromino_idx] current_rotation_idx = ROTATE_INT[board_state['rotation']] new_rotation_idx = ROTATE_INT[new_rotation] iterations =",
"# L ] O_OFFSETS = [ (0, 0), # 0 (0, -1), #",
"1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ],",
"dim = int(len(tetromino)**0.5) for _ in range(iterations): tetromino = [tetromino[rot(i, dim)] for i",
"], [ # O 0, 1, 1, 0, 1, 1, 0, 0, 0,",
"# 2 (-1, 0), # L ] ROTATE_INT = {'0': 0, 'R': 1,",
"board_state: Dictionary containing the board state. key: A strign representation of the key",
"initialize queue return board_state def game_over(board_state: Board) -> bool: # TODO: write this",
"Otherwise, returns the new board state with the locked piece. Args: board_state: Returns:",
"1, 1, 0, 0, 0, ], [ # S 0, 1, 1, 1,",
"\"\"\"Rotates a given tetromino clockwise and returns the rotated one. Args: board_state: new_rotation:",
"ROTATE_INT[new_rotation] iterations = (4 + new_rotation_idx - current_rotation_idx) % 4 assert(iterations != 2)",
"t_i = time.perf_counter() while ~game_over(board): event = events.get(TICK) if event is not None:",
"6} DIRECTION_INT = {'clockwise': 1, 'counterclockwise': -1} KEYMAP = { # TODO: change",
"0), # 2 (0, 1), (0, 1), (0, 1), (0, -1), (0, 2),",
"state. TODO: currently simply printing to console. update to use curses. Args: board_state:",
"rotated board using the offset tables. Returns the kicked board if there is",
"+= x_kick kicked_board_state['y'] += y_kick return kicked_board_state def rotate(board_state: Board, direction: str =",
"board_state return kicked_board_state def translate(board_state: Board, direction: str = 'down') -> Board: \"\"\"Attempts",
"== 'store': return store(board_state) if __name__ == '__main__': TICK = 0.5 board =",
"if there is a collision, False if there is not. \"\"\" # TODO:",
"function returns the new index for a given index after a # clockwise",
"False. Args: board_state: rotated_board_state: k: The offset index to use. Returns: \"\"\" i_rotate",
"+ idx//dim tetromino_idx = TETROMINO_INT[board_state['tetromino']] tetromino = TETROMINOES[tetromino_idx] current_rotation_idx = ROTATE_INT[board_state['rotation']] new_rotation_idx =",
"rotated_board_state: k: The offset index to use. Returns: \"\"\" i_rotate = ROTATE_INT[board_state['rotation']] f_rotate",
"1, 'L': 2, 'O': 3, 'S': 4, 'T': 5, 'Z': 6} DIRECTION_INT =",
"(0, 0), (-1, 0), (-1, -1), (0, 2), (-1, 2), # L ]",
"the board state. key: A strign representation of the key pressed. Returns: The",
"a given index after a # clockwise rotation. def rot(idx: int, dim: int)",
"kick(board_state: Board, rotated_board_state: Board, k: int, ) -> Union[bool, Board]: \"\"\"Translates the rotated",
"Board: \"\"\"Attempts to rotate the current piece in the given direction. Args: board_state:",
"rotations = set('clockwise', 'counterclockwise') if key in translations: if board_state['tetromino'] is None: return",
"# Z 1, 1, 0, 0, 1, 1, 0, 0, 0, ], ]",
"= OFFSETS[f_rotate*5 + k] x_kick = f_offset[0] - i_offset[0] y_kick = f_offset[1] -",
"0, 0, 0, 0, ], [ # J 1, 0, 0, 1, 1,",
"~game_over(board): event = events.get(TICK) if event is not None: board = move(board, KEYMAP[event])",
"= { 'tetromino': None, 'rotation': '0', 'x': 0, 'y': 0, 'stored': None, 'stack':",
"key. Key presses allowed: 'up', 'down', 'left', 'right', 'clockwise', 'counterclockwise', 'store'. Args: board_state:",
"set('up', 'down', 'left', 'right') rotations = set('clockwise', 'counterclockwise') if key in translations: if",
"0), (0, 0), (0, 0), (0, 0), (0, 0), # 2 (0, 0),",
"board_state: direction: Returns: A new board state. \"\"\" # TODO: write this function",
"'store': 'store', } def display(board_state: Board) -> None: \"\"\"Displays the current board state.",
"store(board_state: Board) -> Board: \"\"\"Attempt to store the current piece. Args: board_state: Returns:",
"Args: board_state: Returns: A new board state. \"\"\" # TODO: write this function",
"(-1, -1), (0, 2), (-1, 2), # L ] I_OFFSETS = [ (0,",
"if key in translations: if board_state['tetromino'] is None: return pop(board_state) translated_board_state = translate(board_state,",
"% 4 rotated_board_state = board_state.copy() rotated_board_state['rotation'] = INT_ROTATE[new_rotate] k = 0 kicked_board_state =",
"new_rotation_idx - current_rotation_idx) % 4 assert(iterations != 2) dim = int(len(tetromino)**0.5) for _",
"import Dict, List, Union, Optional import time from pynput import keyboard Board =",
"the kicked board if there is a kick available. Otherwise, returns False. Args:",
"f_rotate = ROTATE_INT[rotated_board_state['rotation']] if board_state['tetromino'] == 'O': if k != 0: return False",
"containing the board state. key: A strign representation of the key pressed. Returns:",
"'up': 'up', 'down': 'down', 'left': 'left', 'right': 'right', 'clockwise': 'clockwise', 'counterclockwise': 'counterclockwise', 'store':",
"(0, 2), (1, 2), # R (0, 0), (0, 0), (0, 0), (0,",
"function pass def initialize_board() -> Board: \"\"\" \"\"\" board_state = { 'tetromino': None,",
"this function pass def store(board_state: Board) -> Board: \"\"\"Attempt to store the current",
"1, 1, 0, 0, 0, ], [ # L 0, 0, 1, 1,",
"\"\"\" i_rotate = ROTATE_INT[board_state['rotation']] f_rotate = ROTATE_INT[rotated_board_state['rotation']] if board_state['tetromino'] == 'O': if k",
"with the locked piece. Args: board_state: Returns: \"\"\" # TODO: make sure to",
"'counterclockwise') if key in translations: if board_state['tetromino'] is None: return pop(board_state) translated_board_state =",
"], [ # Z 1, 1, 0, 0, 1, 1, 0, 0, 0,",
"{'clockwise': 1, 'counterclockwise': -1} KEYMAP = { # TODO: change the keys to",
"int: return (dim - 1 - (idx % dim))*dim + idx//dim tetromino_idx =",
"the key. Key presses allowed: 'up', 'down', 'left', 'right', 'clockwise', 'counterclockwise', 'store'. Args:",
"results in a collision. Args: board_state: Returns: True if there is a collision,",
"strign representation of the key pressed. Returns: The new board state \"\"\" translations",
"rotations: return rotate(board_state, key) else: # elif key == 'store': return store(board_state) if",
"], ] OFFSETS = [ (0, 0), (0, 0), (0, 0), (0, 0),",
"board_state.copy() rotated_board_state['rotation'] = INT_ROTATE[new_rotate] k = 0 kicked_board_state = kick(board_state, rotated_board_state, k) while",
"TODO: write this function pass def initialize_board() -> Board: \"\"\" \"\"\" board_state =",
"0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1,",
"(0, 0), (0, 1), (0, -2), # R (-1, 1), (1, 1), (-2,",
"to translate the current piece in the given direction. Args: board_state: direction: Returns:",
"0), # 0 (0, 0), (1, 0), (1, -1), (0, 2), (1, 2),",
"DIRECTION_INT[direction] current_rotate = ROTATE_INT[Board['rotation']] new_rotate = (current_rotate + rotate_offset) % 4 rotated_board_state =",
"board_state: Returns: A new board state. \"\"\" # TODO: write this function pass",
"0), # 0 (-1, 0), (0, 0), (0, 0), (0, 1), (0, -2),",
"x_kick kicked_board_state['y'] += y_kick return kicked_board_state def rotate(board_state: Board, direction: str = 'clockwise')",
"board state with the locked piece. Args: board_state: Returns: \"\"\" # TODO: make",
"this function pass def move(board_state: Board, key: str = 'down') -> Board: \"\"\"Attempts",
"import time from pynput import keyboard Board = Dict[ Optional[str], str, int, int,",
"The offset index to use. Returns: \"\"\" i_rotate = ROTATE_INT[board_state['rotation']] f_rotate = ROTATE_INT[rotated_board_state['rotation']]",
"O_OFFSETS[i_rotate] f_offset = O_OFFSETS[f_rotate] elif ~(0 <= k <= 4): return False elif",
"board_state: direction: Returns: A new board state. \"\"\" rotate_offset = DIRECTION_INT[direction] current_rotate =",
"\"\"\" # TODO: write this function pass def kick(board_state: Board, rotated_board_state: Board, k:",
"idx//dim tetromino_idx = TETROMINO_INT[board_state['tetromino']] tetromino = TETROMINOES[tetromino_idx] current_rotation_idx = ROTATE_INT[board_state['rotation']] new_rotation_idx = ROTATE_INT[new_rotation]",
"- i_offset[0] y_kick = f_offset[1] - i_offset[1] kicked_board_state = rotated_board_state.copy() kicked_board_state['x'] += x_kick",
"False, } # TODO: initialize stack # TODO: initialize queue return board_state def",
"use curses. Args: board_state: Dictionary containing the board state. \"\"\" # TODO: write",
"# TODO: initialize stack # TODO: initialize queue return board_state def game_over(board_state: Board)",
"Key presses allowed: 'up', 'down', 'left', 'right', 'clockwise', 'counterclockwise', 'store'. Args: board_state: Dictionary",
"Board, key: str = 'down') -> Board: \"\"\"Attempts to move the active piece",
"display(board) if (time.perf_counter() - t_i) > TICK: t_i = time.perf_counter() board = move(board)",
"'stack': [], 'queue': [], 'score': 0, 'store_flag': False, } # TODO: initialize stack",
"board state. key: A strign representation of the key pressed. Returns: The new",
"-> bool: # TODO: write this function pass def move(board_state: Board, key: str",
"'down', 'left': 'left', 'right': 'right', 'clockwise': 'clockwise', 'counterclockwise': 'counterclockwise', 'store': 'store', } def",
"1), (1, 1), (-2, 1), (1, 0), (-2, 0), # 2 (0, 1),",
"function pass def move(board_state: Board, key: str = 'down') -> Board: \"\"\"Attempts to",
"pass def store(board_state: Board) -> Board: \"\"\"Attempt to store the current piece. Args:",
"return board_state def game_over(board_state: Board) -> bool: # TODO: write this function pass",
"0: return False i_offset = O_OFFSETS[i_rotate] f_offset = O_OFFSETS[f_rotate] elif ~(0 <= k",
"Board: \"\"\"Attempts to translate the current piece in the given direction. Args: board_state:",
"to use curses. Args: board_state: Dictionary containing the board state. \"\"\" # TODO:",
"False. Otherwise, returns the new board state with the locked piece. Args: board_state:",
"not be locked, returns False. Otherwise, returns the new board state with the",
"the given direction. Args: board_state: direction: Returns: A new board state. \"\"\" #",
"0, 1, 1, 0, 0, 0, ], ] OFFSETS = [ (0, 0),",
"make sure to reset the store flag # TODO: write this function pass",
":= lock(translated_board_state): return locked_board_state return translate(board_state, key) elif key in rotations: return rotate(board_state,",
"# L 0, 0, 1, 1, 1, 1, 0, 0, 0, ], [",
"return store(board_state) if __name__ == '__main__': TICK = 0.5 board = initialize_board() with",
"use. Returns: \"\"\" i_rotate = ROTATE_INT[board_state['rotation']] f_rotate = ROTATE_INT[rotated_board_state['rotation']] if board_state['tetromino'] == 'O':",
"Docstring \"\"\" from typing import Dict, List, Union, Optional import time from pynput",
"1, 0, 0, 1, 1, 1, 0, 0, 0, ], [ # L",
"KEYMAP = { # TODO: change the keys to the correct strings 'up':",
"4, 'T': 5, 'Z': 6} DIRECTION_INT = {'clockwise': 1, 'counterclockwise': -1} KEYMAP =",
"1, '2': 2, 'L': 3} INT_ROTATE = ('0', 'R', '2', 'L') TETROMINO_INT =",
"Board) -> Union[bool, Board]: \"\"\"Checks to see if the current piece should be",
"return translate(board_state, key) elif key in rotations: return rotate(board_state, key) else: # elif",
"0, ], ] OFFSETS = [ (0, 0), (0, 0), (0, 0), (0,",
"False i_offset = O_OFFSETS[i_rotate] f_offset = O_OFFSETS[f_rotate] elif ~(0 <= k <= 4):",
"0), (-1, 0), (-1, -1), (0, 2), (-1, 2), # L ] I_OFFSETS",
"0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0,",
"A new board state. \"\"\" rotate_offset = DIRECTION_INT[direction] current_rotate = ROTATE_INT[Board['rotation']] new_rotate =",
"for _ in range(iterations): tetromino = [tetromino[rot(i, dim)] for i in tetromino] return",
"kicked_board_state = kick(board_state, rotated_board_state, k) while collision(kicked_board_state): k += 1 if kicked_board_state :=",
"0.5 board = initialize_board() with keyboard.Events() as events: t_i = time.perf_counter() while ~game_over(board):",
"'O': 3, 'S': 4, 'T': 5, 'Z': 6} DIRECTION_INT = {'clockwise': 1, 'counterclockwise':",
"\"\"\"Attempts to move the active piece based on the key. Key presses allowed:",
"3} INT_ROTATE = ('0', 'R', '2', 'L') TETROMINO_INT = {'I': 0, 'J': 1,",
"1 - (idx % dim))*dim + idx//dim tetromino_idx = TETROMINO_INT[board_state['tetromino']] tetromino = TETROMINOES[tetromino_idx]",
"] TETROMINOES = [ [ # I 0, 0, 0, 0, 0, 0,",
"0, 0, 0, ], ] OFFSETS = [ (0, 0), (0, 0), (0,",
"offset index to use. Returns: \"\"\" i_rotate = ROTATE_INT[board_state['rotation']] f_rotate = ROTATE_INT[rotated_board_state['rotation']] if",
"-> Board: \"\"\"Attempt to store the current piece. Args: board_state: Returns: A new",
"board_state['tetromino'] == 'O': if k != 0: return False i_offset = O_OFFSETS[i_rotate] f_offset",
"# L ] I_OFFSETS = [ (0, 0), (-1, 0), (2, 0), (-1,",
"new_rotation: str = '0') -> List[int]: \"\"\"Rotates a given tetromino clockwise and returns",
"0), (1, -1), (0, 2), (1, 2), # R (0, 0), (0, 0),",
"(0, 0), (-1, 0), (2, 0), (-1, 0), (2, 0), # 0 (-1,",
"= [ (0, 0), (-1, 0), (2, 0), (-1, 0), (2, 0), #",
"% 4 assert(iterations != 2) dim = int(len(tetromino)**0.5) for _ in range(iterations): tetromino",
"Otherwise, returns False. Args: board_state: rotated_board_state: k: The offset index to use. Returns:",
"k <= 4): return False elif board_state['tetromino'] == 'I': i_offset = I_OFFSETS[i_rotate*5 +",
"0), # 0 (0, -1), # R (-1, -1), # 2 (-1, 0),",
"direction: Returns: A new board state. \"\"\" rotate_offset = DIRECTION_INT[direction] current_rotate = ROTATE_INT[Board['rotation']]",
"= DIRECTION_INT[direction] current_rotate = ROTATE_INT[Board['rotation']] new_rotate = (current_rotate + rotate_offset) % 4 rotated_board_state",
"# J 1, 0, 0, 1, 1, 1, 0, 0, 0, ], [",
"# TODO: change the keys to the correct strings 'up': 'up', 'down': 'down',",
"k: The offset index to use. Returns: \"\"\" i_rotate = ROTATE_INT[board_state['rotation']] f_rotate =",
"write this function pass def move(board_state: Board, key: str = 'down') -> Board:",
"def game_over(board_state: Board) -> bool: # TODO: write this function pass def move(board_state:",
"index for a given index after a # clockwise rotation. def rot(idx: int,",
"TODO: currently simply printing to console. update to use curses. Args: board_state: Dictionary",
"'counterclockwise', 'store': 'store', } def display(board_state: Board) -> None: \"\"\"Displays the current board",
"= int(len(tetromino)**0.5) for _ in range(iterations): tetromino = [tetromino[rot(i, dim)] for i in",
"'clockwise', 'counterclockwise': 'counterclockwise', 'store': 'store', } def display(board_state: Board) -> None: \"\"\"Displays the",
"- current_rotation_idx) % 4 assert(iterations != 2) dim = int(len(tetromino)**0.5) for _ in",
"while ~game_over(board): event = events.get(TICK) if event is not None: board = move(board,",
"'L') TETROMINO_INT = {'I': 0, 'J': 1, 'L': 2, 'O': 3, 'S': 4,",
"event = events.get(TICK) if event is not None: board = move(board, KEYMAP[event]) display(board)",
"return False elif board_state['tetromino'] == 'I': i_offset = I_OFFSETS[i_rotate*5 + k] f_offset =",
"(0, 2), # L ] O_OFFSETS = [ (0, 0), # 0 (0,",
"the rotated tetromino Raises: AssertionError: \"\"\" # This nested function returns the new",
"is a kick available. Otherwise, returns False. Args: board_state: rotated_board_state: k: The offset",
"in the given direction. Args: board_state: direction: Returns: A new board state. \"\"\"",
"\"\"\" # TODO: write this function pass def store(board_state: Board) -> Board: \"\"\"Attempt",
"board_state def game_over(board_state: Board) -> bool: # TODO: write this function pass def",
"- t_i) > TICK: t_i = time.perf_counter() board = move(board) display(board) print('GAME OVER')",
"'clockwise', 'counterclockwise', 'store'. Args: board_state: Dictionary containing the board state. key: A strign",
"__name__ == '__main__': TICK = 0.5 board = initialize_board() with keyboard.Events() as events:",
"This nested function returns the new index for a given index after a",
"\"\"\"Checks if given board results in a collision. Args: board_state: Returns: True if",
"The new board state \"\"\" translations = set('up', 'down', 'left', 'right') rotations =",
"(0, 1), (0, -2), # R (-1, 1), (1, 1), (-2, 1), (1,",
"'Z': 6} DIRECTION_INT = {'clockwise': 1, 'counterclockwise': -1} KEYMAP = { # TODO:",
"'store', } def display(board_state: Board) -> None: \"\"\"Displays the current board state. TODO:",
"# TODO: write this function pass def lock(board_state: Board) -> Union[bool, Board]: \"\"\"Checks",
"def translate(board_state: Board, direction: str = 'down') -> Board: \"\"\"Attempts to translate the",
"A new board state. \"\"\" # TODO: write this function pass def lock(board_state:",
"= 0 kicked_board_state = kick(board_state, rotated_board_state, k) while collision(kicked_board_state): k += 1 if",
"= 'Development' \"\"\" Docstring \"\"\" from typing import Dict, List, Union, Optional import",
"while collision(kicked_board_state): k += 1 if kicked_board_state := kick(board_state, rotated_board_state, k): continue else:",
"= events.get(TICK) if event is not None: board = move(board, KEYMAP[event]) display(board) if",
"0 kicked_board_state = kick(board_state, rotated_board_state, k) while collision(kicked_board_state): k += 1 if kicked_board_state",
"if event is not None: board = move(board, KEYMAP[event]) display(board) if (time.perf_counter() -",
"kick(board_state, rotated_board_state, k) while collision(kicked_board_state): k += 1 if kicked_board_state := kick(board_state, rotated_board_state,",
"OFFSETS[f_rotate*5 + k] x_kick = f_offset[0] - i_offset[0] y_kick = f_offset[1] - i_offset[1]",
"0, ], [ # O 0, 1, 1, 0, 1, 1, 0, 0,",
"f_offset = OFFSETS[f_rotate*5 + k] x_kick = f_offset[0] - i_offset[0] y_kick = f_offset[1]",
"int, int, Optional[str], List[int], List[int], int, bool, ] TETROMINOES = [ [ #",
"__maintainer__ = '<NAME>' __email__ = '<EMAIL>' __status__ = 'Development' \"\"\" Docstring \"\"\" from",
"] OFFSETS = [ (0, 0), (0, 0), (0, 0), (0, 0), (0,",
"(1, 0), (-2, 0), # 2 (0, 1), (0, 1), (0, 1), (0,",
"tetromino = [tetromino[rot(i, dim)] for i in tetromino] return tetromino def collision(board_state: Board)",
"-1), (0, 2), # L ] O_OFFSETS = [ (0, 0), # 0"
] |
[
"only published posts, and order by descending date \"\"\" return Post.objects.filter( published_at__lte=timezone.now(), status=\"P\"",
"PostDetailView(generic.DetailView): model = Post queryset = Post.objects.exclude(status='D') template_name = 'blog/detail.html' class PostView(generic.ListView): template_name",
"item.title def item_pubdate(self, item): return datetime.datetime.combine(item.published_at, datetime.time()) def item_description(self, item): return item.render() def",
"description = \"Blog posts from utf9k\" def items(self): return Post.objects.order_by('-published_at') def item_title(self, item):",
"django.contrib.syndication.views import Feed from django.utils import timezone from django.urls import reverse from django.views",
"class PostView(generic.ListView): template_name = 'blog/list.html' context_object_name = 'posts' def get_queryset(self): \"\"\" Fetch only",
"context_object_name = 'posts' def get_queryset(self): \"\"\" Fetch only published posts, and order by",
"get_queryset(self): \"\"\" Fetch only published posts, and order by descending date \"\"\" return",
"by descending date \"\"\" return Post.objects.filter( published_at__lte=timezone.now(), status=\"P\" ).order_by('-published_at') class RSSFeed(Feed): title =",
"from django.contrib.syndication.views import Feed from django.utils import timezone from django.urls import reverse from",
"= Post queryset = Post.objects.exclude(status='D') template_name = 'blog/detail.html' class PostView(generic.ListView): template_name = 'blog/list.html'",
"from django.views import generic from .models import Post class PostDetailView(generic.DetailView): model = Post",
"and order by descending date \"\"\" return Post.objects.filter( published_at__lte=timezone.now(), status=\"P\" ).order_by('-published_at') class RSSFeed(Feed):",
"def get_queryset(self): \"\"\" Fetch only published posts, and order by descending date \"\"\"",
"class RSSFeed(Feed): title = \"utf9k\" link = \"/blog/\" description = \"Blog posts from",
"return Post.objects.order_by('-published_at') def item_title(self, item): return item.title def item_pubdate(self, item): return datetime.datetime.combine(item.published_at, datetime.time())",
"published_at__lte=timezone.now(), status=\"P\" ).order_by('-published_at') class RSSFeed(Feed): title = \"utf9k\" link = \"/blog/\" description =",
"timezone from django.urls import reverse from django.views import generic from .models import Post",
"\"/blog/\" description = \"Blog posts from utf9k\" def items(self): return Post.objects.order_by('-published_at') def item_title(self,",
"Post.objects.filter( published_at__lte=timezone.now(), status=\"P\" ).order_by('-published_at') class RSSFeed(Feed): title = \"utf9k\" link = \"/blog/\" description",
"import datetime from django.contrib.syndication.views import Feed from django.utils import timezone from django.urls import",
"datetime from django.contrib.syndication.views import Feed from django.utils import timezone from django.urls import reverse",
".models import Post class PostDetailView(generic.DetailView): model = Post queryset = Post.objects.exclude(status='D') template_name =",
"= \"Blog posts from utf9k\" def items(self): return Post.objects.order_by('-published_at') def item_title(self, item): return",
"import reverse from django.views import generic from .models import Post class PostDetailView(generic.DetailView): model",
"'blog/list.html' context_object_name = 'posts' def get_queryset(self): \"\"\" Fetch only published posts, and order",
"= 'blog/list.html' context_object_name = 'posts' def get_queryset(self): \"\"\" Fetch only published posts, and",
"items(self): return Post.objects.order_by('-published_at') def item_title(self, item): return item.title def item_pubdate(self, item): return datetime.datetime.combine(item.published_at,",
"from django.utils import timezone from django.urls import reverse from django.views import generic from",
"PostView(generic.ListView): template_name = 'blog/list.html' context_object_name = 'posts' def get_queryset(self): \"\"\" Fetch only published",
"order by descending date \"\"\" return Post.objects.filter( published_at__lte=timezone.now(), status=\"P\" ).order_by('-published_at') class RSSFeed(Feed): title",
"django.utils import timezone from django.urls import reverse from django.views import generic from .models",
"published posts, and order by descending date \"\"\" return Post.objects.filter( published_at__lte=timezone.now(), status=\"P\" ).order_by('-published_at')",
"from .models import Post class PostDetailView(generic.DetailView): model = Post queryset = Post.objects.exclude(status='D') template_name",
").order_by('-published_at') class RSSFeed(Feed): title = \"utf9k\" link = \"/blog/\" description = \"Blog posts",
"return Post.objects.filter( published_at__lte=timezone.now(), status=\"P\" ).order_by('-published_at') class RSSFeed(Feed): title = \"utf9k\" link = \"/blog/\"",
"from django.urls import reverse from django.views import generic from .models import Post class",
"reverse from django.views import generic from .models import Post class PostDetailView(generic.DetailView): model =",
"Post queryset = Post.objects.exclude(status='D') template_name = 'blog/detail.html' class PostView(generic.ListView): template_name = 'blog/list.html' context_object_name",
"descending date \"\"\" return Post.objects.filter( published_at__lte=timezone.now(), status=\"P\" ).order_by('-published_at') class RSSFeed(Feed): title = \"utf9k\"",
"django.views import generic from .models import Post class PostDetailView(generic.DetailView): model = Post queryset",
"item): return datetime.datetime.combine(item.published_at, datetime.time()) def item_description(self, item): return item.render() def item_link(self, item): return",
"= \"utf9k\" link = \"/blog/\" description = \"Blog posts from utf9k\" def items(self):",
"generic from .models import Post class PostDetailView(generic.DetailView): model = Post queryset = Post.objects.exclude(status='D')",
"import generic from .models import Post class PostDetailView(generic.DetailView): model = Post queryset =",
"= 'posts' def get_queryset(self): \"\"\" Fetch only published posts, and order by descending",
"Fetch only published posts, and order by descending date \"\"\" return Post.objects.filter( published_at__lte=timezone.now(),",
"template_name = 'blog/detail.html' class PostView(generic.ListView): template_name = 'blog/list.html' context_object_name = 'posts' def get_queryset(self):",
"posts, and order by descending date \"\"\" return Post.objects.filter( published_at__lte=timezone.now(), status=\"P\" ).order_by('-published_at') class",
"import timezone from django.urls import reverse from django.views import generic from .models import",
"Post.objects.exclude(status='D') template_name = 'blog/detail.html' class PostView(generic.ListView): template_name = 'blog/list.html' context_object_name = 'posts' def",
"= 'blog/detail.html' class PostView(generic.ListView): template_name = 'blog/list.html' context_object_name = 'posts' def get_queryset(self): \"\"\"",
"def item_title(self, item): return item.title def item_pubdate(self, item): return datetime.datetime.combine(item.published_at, datetime.time()) def item_description(self,",
"'posts' def get_queryset(self): \"\"\" Fetch only published posts, and order by descending date",
"\"\"\" Fetch only published posts, and order by descending date \"\"\" return Post.objects.filter(",
"RSSFeed(Feed): title = \"utf9k\" link = \"/blog/\" description = \"Blog posts from utf9k\"",
"import Feed from django.utils import timezone from django.urls import reverse from django.views import",
"Post class PostDetailView(generic.DetailView): model = Post queryset = Post.objects.exclude(status='D') template_name = 'blog/detail.html' class",
"def item_pubdate(self, item): return datetime.datetime.combine(item.published_at, datetime.time()) def item_description(self, item): return item.render() def item_link(self,",
"template_name = 'blog/list.html' context_object_name = 'posts' def get_queryset(self): \"\"\" Fetch only published posts,",
"from utf9k\" def items(self): return Post.objects.order_by('-published_at') def item_title(self, item): return item.title def item_pubdate(self,",
"link = \"/blog/\" description = \"Blog posts from utf9k\" def items(self): return Post.objects.order_by('-published_at')",
"\"\"\" return Post.objects.filter( published_at__lte=timezone.now(), status=\"P\" ).order_by('-published_at') class RSSFeed(Feed): title = \"utf9k\" link =",
"return item.title def item_pubdate(self, item): return datetime.datetime.combine(item.published_at, datetime.time()) def item_description(self, item): return item.render()",
"return datetime.datetime.combine(item.published_at, datetime.time()) def item_description(self, item): return item.render() def item_link(self, item): return reverse('blog:detail',",
"status=\"P\" ).order_by('-published_at') class RSSFeed(Feed): title = \"utf9k\" link = \"/blog/\" description = \"Blog",
"model = Post queryset = Post.objects.exclude(status='D') template_name = 'blog/detail.html' class PostView(generic.ListView): template_name =",
"date \"\"\" return Post.objects.filter( published_at__lte=timezone.now(), status=\"P\" ).order_by('-published_at') class RSSFeed(Feed): title = \"utf9k\" link",
"\"utf9k\" link = \"/blog/\" description = \"Blog posts from utf9k\" def items(self): return",
"import Post class PostDetailView(generic.DetailView): model = Post queryset = Post.objects.exclude(status='D') template_name = 'blog/detail.html'",
"def items(self): return Post.objects.order_by('-published_at') def item_title(self, item): return item.title def item_pubdate(self, item): return",
"= Post.objects.exclude(status='D') template_name = 'blog/detail.html' class PostView(generic.ListView): template_name = 'blog/list.html' context_object_name = 'posts'",
"datetime.datetime.combine(item.published_at, datetime.time()) def item_description(self, item): return item.render() def item_link(self, item): return reverse('blog:detail', args=[item.slug])",
"item_pubdate(self, item): return datetime.datetime.combine(item.published_at, datetime.time()) def item_description(self, item): return item.render() def item_link(self, item):",
"Feed from django.utils import timezone from django.urls import reverse from django.views import generic",
"'blog/detail.html' class PostView(generic.ListView): template_name = 'blog/list.html' context_object_name = 'posts' def get_queryset(self): \"\"\" Fetch",
"title = \"utf9k\" link = \"/blog/\" description = \"Blog posts from utf9k\" def",
"Post.objects.order_by('-published_at') def item_title(self, item): return item.title def item_pubdate(self, item): return datetime.datetime.combine(item.published_at, datetime.time()) def",
"item_title(self, item): return item.title def item_pubdate(self, item): return datetime.datetime.combine(item.published_at, datetime.time()) def item_description(self, item):",
"queryset = Post.objects.exclude(status='D') template_name = 'blog/detail.html' class PostView(generic.ListView): template_name = 'blog/list.html' context_object_name =",
"\"Blog posts from utf9k\" def items(self): return Post.objects.order_by('-published_at') def item_title(self, item): return item.title",
"= \"/blog/\" description = \"Blog posts from utf9k\" def items(self): return Post.objects.order_by('-published_at') def",
"posts from utf9k\" def items(self): return Post.objects.order_by('-published_at') def item_title(self, item): return item.title def",
"utf9k\" def items(self): return Post.objects.order_by('-published_at') def item_title(self, item): return item.title def item_pubdate(self, item):",
"class PostDetailView(generic.DetailView): model = Post queryset = Post.objects.exclude(status='D') template_name = 'blog/detail.html' class PostView(generic.ListView):",
"django.urls import reverse from django.views import generic from .models import Post class PostDetailView(generic.DetailView):",
"item): return item.title def item_pubdate(self, item): return datetime.datetime.combine(item.published_at, datetime.time()) def item_description(self, item): return"
] |