content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
''' LeetCode LinkedList Q.876 Middle of the Linked List Recusion and Slow/Fast Pointer Solution ''' def middleNode(self, head: ListNode) -> ListNode: def rec(slow, fast): if not fast: return slow elif not fast.next: return slow return rec(slow.next, fast.next.next) return rec(head, head)
""" LeetCode LinkedList Q.876 Middle of the Linked List Recusion and Slow/Fast Pointer Solution """ def middle_node(self, head: ListNode) -> ListNode: def rec(slow, fast): if not fast: return slow elif not fast.next: return slow return rec(slow.next, fast.next.next) return rec(head, head)
class ParameterDefinition(object): def __init__(self, name, param_type=None, value=None): self.name = name self.param_type = param_type self.value = value class Parameter(object): def __init__(self, definition): self.definition = definition self.value = definition.value self.binding = None
class Parameterdefinition(object): def __init__(self, name, param_type=None, value=None): self.name = name self.param_type = param_type self.value = value class Parameter(object): def __init__(self, definition): self.definition = definition self.value = definition.value self.binding = None
def check_kwargs(input_kwargs, allowed_kwargs, raise_error=True): """Tests if the input `**kwargs` are allowed. Parameters ---------- input_kwargs : `dict`, `list` Dictionary or list with the input values. allowed_kwargs : `list` List with the allowed keys. raise_error : `bool` Raises error if ``True``. If ``False``, it will raise the error listing the not allowed keys. """ not_allowed = [i for i in input_kwargs if i not in allowed_kwargs] if raise_error: if len(not_allowed) > 0: allowed_kwargs.sort() raise TypeError("function got an unexpected keyword argument {}\n" "Available kwargs are: {}".format(not_allowed, allowed_kwargs)) else: return not_allowed def test_attr(attr, typ, name): """Tests attribute. This function tests if the attribute ``attr`` belongs to the type ``typ``, if not it gives an error message informing the name of the variable. """ try: return typ(attr) except: raise TypeError('"{}" keyword must be a {} object'.format(name, typ))
def check_kwargs(input_kwargs, allowed_kwargs, raise_error=True): """Tests if the input `**kwargs` are allowed. Parameters ---------- input_kwargs : `dict`, `list` Dictionary or list with the input values. allowed_kwargs : `list` List with the allowed keys. raise_error : `bool` Raises error if ``True``. If ``False``, it will raise the error listing the not allowed keys. """ not_allowed = [i for i in input_kwargs if i not in allowed_kwargs] if raise_error: if len(not_allowed) > 0: allowed_kwargs.sort() raise type_error('function got an unexpected keyword argument {}\nAvailable kwargs are: {}'.format(not_allowed, allowed_kwargs)) else: return not_allowed def test_attr(attr, typ, name): """Tests attribute. This function tests if the attribute ``attr`` belongs to the type ``typ``, if not it gives an error message informing the name of the variable. """ try: return typ(attr) except: raise type_error('"{}" keyword must be a {} object'.format(name, typ))
load(":import_external.bzl", import_external = "import_external") def dependencies(): import_external( name = "org_apache_httpcomponents_client5_httpclient5", artifact = "org.apache.httpcomponents.client5:httpclient5:5.1", artifact_sha256 = "b7a30296763a4d5dbf840f0b79df7439cf3d2341c8990aee4111591b61b50935", srcjar_sha256 = "d7351329b7720b482766aca78d1c040225a1b4bbd723034c6f686bec538edddd", deps = [ "@commons_codec_commons_codec", "@org_apache_httpcomponents_core5_httpcore5", "@org_apache_httpcomponents_core5_httpcore5_h2", "@org_slf4j_slf4j_api", ], )
load(':import_external.bzl', import_external='import_external') def dependencies(): import_external(name='org_apache_httpcomponents_client5_httpclient5', artifact='org.apache.httpcomponents.client5:httpclient5:5.1', artifact_sha256='b7a30296763a4d5dbf840f0b79df7439cf3d2341c8990aee4111591b61b50935', srcjar_sha256='d7351329b7720b482766aca78d1c040225a1b4bbd723034c6f686bec538edddd', deps=['@commons_codec_commons_codec', '@org_apache_httpcomponents_core5_httpcore5', '@org_apache_httpcomponents_core5_httpcore5_h2', '@org_slf4j_slf4j_api'])
class Solution: def imageSmoother(self, M: list) -> list: l = len(M) if l == 0: return M m = len(M[0]) res = [] for i in range(l): res.append([0] * m) # print(res) for x in range(l): for y in range(m): summ = 0 count = 0 for i in range(x-1, x+2): for j in range(y-1, y+2): if 0 <= i < l and 0 <= j < m: summ += M[i][j] count += 1 res[x][y] = int(summ / count) return res M = [[1,1,1], [1,0,1], [1,1,1]] s = Solution() print(s.imageSmoother(M))
class Solution: def image_smoother(self, M: list) -> list: l = len(M) if l == 0: return M m = len(M[0]) res = [] for i in range(l): res.append([0] * m) for x in range(l): for y in range(m): summ = 0 count = 0 for i in range(x - 1, x + 2): for j in range(y - 1, y + 2): if 0 <= i < l and 0 <= j < m: summ += M[i][j] count += 1 res[x][y] = int(summ / count) return res m = [[1, 1, 1], [1, 0, 1], [1, 1, 1]] s = solution() print(s.imageSmoother(M))
#!/usr/bin/env python3 # pylint: disable=invalid-name,missing-docstring def test_get_arns(oa, shared_datadir): with open("%s/saml_assertion.txt" % shared_datadir) as fh: assertion = fh.read() arns = oa.get_arns(assertion) # Principal assert arns[0] == 'arn:aws:iam::012345678901:saml-provider/OKTA' # Role assert arns[1] == 'arn:aws:iam::012345678901:role/Okta_AdministratorAccess'
def test_get_arns(oa, shared_datadir): with open('%s/saml_assertion.txt' % shared_datadir) as fh: assertion = fh.read() arns = oa.get_arns(assertion) assert arns[0] == 'arn:aws:iam::012345678901:saml-provider/OKTA' assert arns[1] == 'arn:aws:iam::012345678901:role/Okta_AdministratorAccess'
__all__ = [ "cart_factory", "cart", "environment", "job_factory", "job", "location", "trace", ]
__all__ = ['cart_factory', 'cart', 'environment', 'job_factory', 'job', 'location', 'trace']
TITLE = "The World of Light and Shadow" ALPHABET = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] ALPHABET += ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] MISC = [",", "!", "#", "$", "%", "&", "*", "(", ")", "-", "_", "+", "=", "`", "~", ".", ";", ":", " ", "?", "@", "[", "]", "{", "}"] NUMBERS = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] CLEAN_CHARS = ALPHABET + MISC + NUMBERS ZONE_NAMES = ["harbor"] # --------------------------------------------- TILESIZE = 120 TILES_WIDE = 4 TILES_HIGH = 4 WINDOW_WIDTH = TILESIZE * TILES_WIDE WINDOW_HEIGHT = TILESIZE * TILES_HIGH # --------------------------------------------- WHITE = (255, 255, 255) BLACK = (0, 0, 0) DARKGREY = (40, 40, 40) LIGHTGREY = (200, 200, 200) DARK_GREEN = ( 0, 153, 0) GREEN = (0, 255, 0) DARK_RED = (204, 0, 0) RED = (255, 0, 0) ORANGE = (255, 128, 0) YELLOW = (255, 255, 0) BROWN = (106, 55, 5) AQUA = ( 0, 255, 255) BLUE = ( 0, 0, 255) FUCHIA = (255, 0, 255) GRAY = (128, 128, 128) LIME = ( 0, 255, 0) MAROON = (128, 0, 0) NAVY_BLUE = ( 0, 0, 128) OLIVE = (128, 128, 0) PURPLE = (128, 0, 128) LIGHT_PURBLE = (255, 153, 255) SILVER = (192, 192, 192) TEAL = ( 0, 128, 128) BACKGROUND_COLOR = WHITE
title = 'The World of Light and Shadow' alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] alphabet += ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] misc = [',', '!', '#', '$', '%', '&', '*', '(', ')', '-', '_', '+', '=', '`', '~', '.', ';', ':', ' ', '?', '@', '[', ']', '{', '}'] numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] clean_chars = ALPHABET + MISC + NUMBERS zone_names = ['harbor'] tilesize = 120 tiles_wide = 4 tiles_high = 4 window_width = TILESIZE * TILES_WIDE window_height = TILESIZE * TILES_HIGH white = (255, 255, 255) black = (0, 0, 0) darkgrey = (40, 40, 40) lightgrey = (200, 200, 200) dark_green = (0, 153, 0) green = (0, 255, 0) dark_red = (204, 0, 0) red = (255, 0, 0) orange = (255, 128, 0) yellow = (255, 255, 0) brown = (106, 55, 5) aqua = (0, 255, 255) blue = (0, 0, 255) fuchia = (255, 0, 255) gray = (128, 128, 128) lime = (0, 255, 0) maroon = (128, 0, 0) navy_blue = (0, 0, 128) olive = (128, 128, 0) purple = (128, 0, 128) light_purble = (255, 153, 255) silver = (192, 192, 192) teal = (0, 128, 128) background_color = WHITE
class Solution: def closedIsland(self, grid: List[List[int]]) -> int: def dfs(r, c, val): grid[r][c] = val for nr, nc in (r-1, c), (r+1, c), (r, c-1), (r, c+1): if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] != val: dfs(nr, nc, val) for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == 0 and (i == 0 or i == len(grid) - 1 or j == 0 or j == len(grid[i]) - 1): dfs(i, j, 1) count = 0 for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == 0: count += 1 dfs(i, j, 1) return count
class Solution: def closed_island(self, grid: List[List[int]]) -> int: def dfs(r, c, val): grid[r][c] = val for (nr, nc) in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)): if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and (grid[nr][nc] != val): dfs(nr, nc, val) for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == 0 and (i == 0 or i == len(grid) - 1 or j == 0 or (j == len(grid[i]) - 1)): dfs(i, j, 1) count = 0 for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == 0: count += 1 dfs(i, j, 1) return count
# you can use print for debugging purposes, e.g. # print "this is a debug message" def solution(A): # write your code in Python 2.7 N = len(A) counter = [] leader = -1 leader_count = 0 left_leader_count = 0 equi_count = 0 for i in xrange(N): if not counter: counter.append((A[i], 1)) elif counter[0][0] == A[i]: counter[0] = (counter[0][0], counter[0][1]+1) elif counter[0][1] > 1: counter[0] = (counter[0][0], counter[0][1]-1) else: counter.pop() if counter: for i in xrange(N): if A[i] == counter[0][0]: leader_count += 1 if leader_count > N/2: leader = counter[0][0] else: return 0 else: return 0 for i in xrange(N): if leader == A[i]: left_leader_count += 1 if left_leader_count > (i+1)/2: if leader_count - left_leader_count > (N-(i+1))/2: equi_count += 1 return equi_count
def solution(A): n = len(A) counter = [] leader = -1 leader_count = 0 left_leader_count = 0 equi_count = 0 for i in xrange(N): if not counter: counter.append((A[i], 1)) elif counter[0][0] == A[i]: counter[0] = (counter[0][0], counter[0][1] + 1) elif counter[0][1] > 1: counter[0] = (counter[0][0], counter[0][1] - 1) else: counter.pop() if counter: for i in xrange(N): if A[i] == counter[0][0]: leader_count += 1 if leader_count > N / 2: leader = counter[0][0] else: return 0 else: return 0 for i in xrange(N): if leader == A[i]: left_leader_count += 1 if left_leader_count > (i + 1) / 2: if leader_count - left_leader_count > (N - (i + 1)) / 2: equi_count += 1 return equi_count
# this py file will be strictly dedicated to "Boolean Logic" # Boolean Logic is best defined as the combination of phrases that can result in printing different values # define two variables a = True b = False # if-statement... output: True # the if condition prints, if the "if statement" evaluates to True if a: print("True") else: print("False") if b: # output: False print("True") else: print("False") ''' and: both clauses must be True or: one of the clauses must be True ''' # and-statements... output: Neither if a and b: print("Both") else: print("Neither") # or-statement... output: Both if a or b: print("Both") else: print("Neither") # define new variables to demonstrate truth table x = True y = True # output: True if x and y: print("True") else: print("False") # output: True if (x and y) or x: print("True") else: print("False") # new reassignment # x still equals True y = False # output: False if x and y: print("True") else: print("False") # output: True if x or y: print("True") else: print("False") # output: True if (x or y) and x: print("True") else: print("False") # output: True if (x and y) or x: print("True") else: print("False") # output: False if not x and not y: print("True") else: print("False")
a = True b = False if a: print('True') else: print('False') if b: print('True') else: print('False') ' \nand: both clauses must be True \nor: one of the clauses must be True\n' if a and b: print('Both') else: print('Neither') if a or b: print('Both') else: print('Neither') x = True y = True if x and y: print('True') else: print('False') if x and y or x: print('True') else: print('False') y = False if x and y: print('True') else: print('False') if x or y: print('True') else: print('False') if (x or y) and x: print('True') else: print('False') if x and y or x: print('True') else: print('False') if not x and (not y): print('True') else: print('False')
class Solution(object): def robot(self, command, obstacles, x, y): """ :type command: str :type obstacles: List[List[int]] :type x: int :type y: int :rtype: bool """ # zb = [0, 0] # ind = 0 # while True: # if command[ind] == 'U': # zb = [zb[0], zb[1]+1] # elif command[ind] == 'R': # zb = [zb[0]+1, zb[1]] # # print(zb) # if zb == [x, y]: # return True # if zb in obstacles: # return False # if zb[0] > x or zb[1] > y: # return False # if ind < len(command)-1: # ind += 1 # elif ind == len(command)-1: # ind = 0 # return False xi = 0 yi = 0 zb = [0, 0] for c in command: if c == 'R': xi += 1 if c == 'U': yi += 1 epoch = min(x//xi, y//yi) x_ = x-epoch*xi y_ = y-epoch*yi zb = [0, 0] is_reach = False for i in command: if zb == [x_, y_]: is_reach = True if i == 'R': zb = [zb[0]+1, zb[1]] if i == 'U': zb = [zb[0], zb[1]+1] obstacles_ = [] for item in obstacles: if item[0]<=x and item[1]<=y: obstacles_.append(item) for ob in obstacles_: cur_epo = min(ob[0]//xi, ob[1]//yi) cur_x = ob[0]-cur_epo*xi cur_y = ob[1]-cur_epo*yi cur_zb = [0, 0] for cm in command: print(cur_zb) if cur_zb == [cur_x, cur_y]: return False if cm == 'R': cur_zb = [cur_zb[0]+1, cur_zb[1]] if cm == 'U': cur_zb = [cur_zb[0], cur_zb[1]+1] return is_reach
class Solution(object): def robot(self, command, obstacles, x, y): """ :type command: str :type obstacles: List[List[int]] :type x: int :type y: int :rtype: bool """ xi = 0 yi = 0 zb = [0, 0] for c in command: if c == 'R': xi += 1 if c == 'U': yi += 1 epoch = min(x // xi, y // yi) x_ = x - epoch * xi y_ = y - epoch * yi zb = [0, 0] is_reach = False for i in command: if zb == [x_, y_]: is_reach = True if i == 'R': zb = [zb[0] + 1, zb[1]] if i == 'U': zb = [zb[0], zb[1] + 1] obstacles_ = [] for item in obstacles: if item[0] <= x and item[1] <= y: obstacles_.append(item) for ob in obstacles_: cur_epo = min(ob[0] // xi, ob[1] // yi) cur_x = ob[0] - cur_epo * xi cur_y = ob[1] - cur_epo * yi cur_zb = [0, 0] for cm in command: print(cur_zb) if cur_zb == [cur_x, cur_y]: return False if cm == 'R': cur_zb = [cur_zb[0] + 1, cur_zb[1]] if cm == 'U': cur_zb = [cur_zb[0], cur_zb[1] + 1] return is_reach
"""Contains the ItemManager class, used to manage items.txt""" class ItemManager: """A class to manage items.txt.""" def __init__(self): self.items_file = 'txt_files/items.txt' def clear_items(self): with open(self.items_file, 'w') as File: File.write("Items:\n") print("Items Cleared!") def recover_items(self): try: with open(self.items_file, 'r') as file: # Try to read the file read_data = file.readlines() except FileNotFoundError: # If the file doesn't exist with open(self.items_file, 'w') as file: # Create the file file.write("Items:\n") # Write this line at the start with open(self.items_file, 'r') as file: read_data = file.readlines() read_data = read_data[1:] # Remove first line of file, which is # "Items:" if not read_data: print("No Data Found.") return None else: new_read_data = [] # New read data gets set to the old read # data, but # without the newlines at the end of each line. for line in read_data: new_read_data.append(line.rstrip("\n")) read_data = new_read_data print("Data Found!") item_data = [] for line in read_data: # Save the old data to this program item_data.append((str(line[4:]), int(line[:3]))) print("Item data saved!") return item_data def add_item(self, item, position): position = str(position) for _ in range(0, 3 - len(position)): position = f"0{position}" # Make positions 3-digit numbers. # E.g. 12 becomes 012 position += " " # Add a space at the end of position text = position + item + "\n" try: with open(self.items_file, 'a') as file: file.write(text) except FileNotFoundError: with open(self.items_file, 'w') as file: file.write("Items:\n{text}") def remove_item(self, item): newlines = "" try: with open(self.items_file, 'r') as file: old_lines = file.readlines() except FileNotFoundError: with open(self.items_file, 'w') as file: file.write("Items:\n") print("File Not Found.") return for line in old_lines[1:]: if item not in line: newlines += line newlines += "\n" with open(self.items_file, 'w') as file: file.write("Items:\n") with open(self.items_file, 'a') as file: file.write(newlines)
"""Contains the ItemManager class, used to manage items.txt""" class Itemmanager: """A class to manage items.txt.""" def __init__(self): self.items_file = 'txt_files/items.txt' def clear_items(self): with open(self.items_file, 'w') as file: File.write('Items:\n') print('Items Cleared!') def recover_items(self): try: with open(self.items_file, 'r') as file: read_data = file.readlines() except FileNotFoundError: with open(self.items_file, 'w') as file: file.write('Items:\n') with open(self.items_file, 'r') as file: read_data = file.readlines() read_data = read_data[1:] if not read_data: print('No Data Found.') return None else: new_read_data = [] for line in read_data: new_read_data.append(line.rstrip('\n')) read_data = new_read_data print('Data Found!') item_data = [] for line in read_data: item_data.append((str(line[4:]), int(line[:3]))) print('Item data saved!') return item_data def add_item(self, item, position): position = str(position) for _ in range(0, 3 - len(position)): position = f'0{position}' position += ' ' text = position + item + '\n' try: with open(self.items_file, 'a') as file: file.write(text) except FileNotFoundError: with open(self.items_file, 'w') as file: file.write('Items:\n{text}') def remove_item(self, item): newlines = '' try: with open(self.items_file, 'r') as file: old_lines = file.readlines() except FileNotFoundError: with open(self.items_file, 'w') as file: file.write('Items:\n') print('File Not Found.') return for line in old_lines[1:]: if item not in line: newlines += line newlines += '\n' with open(self.items_file, 'w') as file: file.write('Items:\n') with open(self.items_file, 'a') as file: file.write(newlines)
words = set( ( "scipy", "Combinatorics", "rhs", "lhs", "df", "AttributeError", "Cymru", "FiniteSet", "Jupyter", "LaTeX", "Modularisation", "NameError", "PyCons", "allclose", "ax", "bc", "boolean", "docstring", "dtype", "dx", "dy", "expr", "frisbee", "inv", "ipynb", "isclose", "itertools", "jupyter", "len", "nbs", "nd", "np", "numpy", "solveset", "sqrt", "sym", "sympy", "th", ) ) prose_exceptions = { "assets/nbs/assessment/mock/main.ipynb": set( ( r"The matrix \\(D\\) is given by \\(D = \begin{pmatrix} a & 2 & 0\\ 3 & 1 & 2\\ 0 & -1 & 1\end{pmatrix}\\) where \\(a\ne 2\\).", ), ), "assets/nbs/assessment/mock/assignment.ipynb": set( ( r"The matrix \\(D\\) is given by \\(D = \begin{pmatrix} a & 2 & 0\\ 3 & 1 & 2\\ 0 & -1 & 1\end{pmatrix}\\) where \\(a\ne 2\\).", ) ), "assets/nbs/assessment/mock/solution.ipynb": set( ( r"The matrix \\(D\\) is given by \\(D = \begin{pmatrix} a & 2 & 0\\ 3 & 1 & 2\\ 0 & -1 & 1\end{pmatrix}\\) where \\(a\ne 2\\).", ) ), } prose_suggestions_to_ignore = { "assets/nbs/assessment/2020/main.ipynb": set( ("typography.symbols.curly_quotes", "garner.preferred_forms") ), "assets/nbs/assessment/2020/solution.ipynb": set( ("typography.symbols.curly_quotes", "garner.preferred_forms") ), "assets/nbs/assessment/mock/main.ipynb": set( ("typography.symbols.curly_quotes", "garner.preferred_forms") ), "assets/nbs/assessment/mock/assignment.ipynb": set( ("typography.symbols.curly_quotes", "garner.preferred_forms") ), "assets/nbs/assessment/mock/solution.ipynb": set( ("typography.symbols.curly_quotes", "garner.preferred_forms") ), "assets/nbs/assessment/example/main.ipynb": set( ( "typography.symbols.curly_quotes", "typography.symbols.ellipsis", "garner.preferred_forms", ) ), }
words = set(('scipy', 'Combinatorics', 'rhs', 'lhs', 'df', 'AttributeError', 'Cymru', 'FiniteSet', 'Jupyter', 'LaTeX', 'Modularisation', 'NameError', 'PyCons', 'allclose', 'ax', 'bc', 'boolean', 'docstring', 'dtype', 'dx', 'dy', 'expr', 'frisbee', 'inv', 'ipynb', 'isclose', 'itertools', 'jupyter', 'len', 'nbs', 'nd', 'np', 'numpy', 'solveset', 'sqrt', 'sym', 'sympy', 'th')) prose_exceptions = {'assets/nbs/assessment/mock/main.ipynb': set(('The matrix \\\\(D\\\\) is given by \\\\(D = \\begin{pmatrix} a & 2 & 0\\\\ 3 & 1 & 2\\\\ 0 & -1 & 1\\end{pmatrix}\\\\) where \\\\(a\\ne 2\\\\).',)), 'assets/nbs/assessment/mock/assignment.ipynb': set(('The matrix \\\\(D\\\\) is given by \\\\(D = \\begin{pmatrix} a & 2 & 0\\\\ 3 & 1 & 2\\\\ 0 & -1 & 1\\end{pmatrix}\\\\) where \\\\(a\\ne 2\\\\).',)), 'assets/nbs/assessment/mock/solution.ipynb': set(('The matrix \\\\(D\\\\) is given by \\\\(D = \\begin{pmatrix} a & 2 & 0\\\\ 3 & 1 & 2\\\\ 0 & -1 & 1\\end{pmatrix}\\\\) where \\\\(a\\ne 2\\\\).',))} prose_suggestions_to_ignore = {'assets/nbs/assessment/2020/main.ipynb': set(('typography.symbols.curly_quotes', 'garner.preferred_forms')), 'assets/nbs/assessment/2020/solution.ipynb': set(('typography.symbols.curly_quotes', 'garner.preferred_forms')), 'assets/nbs/assessment/mock/main.ipynb': set(('typography.symbols.curly_quotes', 'garner.preferred_forms')), 'assets/nbs/assessment/mock/assignment.ipynb': set(('typography.symbols.curly_quotes', 'garner.preferred_forms')), 'assets/nbs/assessment/mock/solution.ipynb': set(('typography.symbols.curly_quotes', 'garner.preferred_forms')), 'assets/nbs/assessment/example/main.ipynb': set(('typography.symbols.curly_quotes', 'typography.symbols.ellipsis', 'garner.preferred_forms'))}
#Booleans are operators that allow you to convey True or False statements print(True) print(False) type(False) print(1>2) print(1==1) b= None #None is used as a placeholder for an object that has not been assigned , so that object unassigned errors can be avoided type(b) print(b) type(True)
print(True) print(False) type(False) print(1 > 2) print(1 == 1) b = None type(b) print(b) type(True)
class ServerState: """Class for server state""" def __init__(self): self.history = set() self.requests = 0 def register(self, pickup_line): self.requests += 1 self.history.add(pickup_line) def get_status(self): return "<table> " + \ wrap_in_row("<b>Pickup lines delivered: </b>", str(self.requests)) + \ wrap_in_row("<b>Unique pickup lines delivered: </b>", str(len(self.history))) + \ "</table>" + \ "<h3>Generated pickup lines:</h3>" + \ ("<br/>".join(self.history)) def wrap_in_row(input1, input2): return "<tr>" \ "<td>" + input1 + "</td>" + \ "<td>" + input2 + "</td>" + \ "</tr>"
class Serverstate: """Class for server state""" def __init__(self): self.history = set() self.requests = 0 def register(self, pickup_line): self.requests += 1 self.history.add(pickup_line) def get_status(self): return '<table> ' + wrap_in_row('<b>Pickup lines delivered: </b>', str(self.requests)) + wrap_in_row('<b>Unique pickup lines delivered: </b>', str(len(self.history))) + '</table>' + '<h3>Generated pickup lines:</h3>' + '<br/>'.join(self.history) def wrap_in_row(input1, input2): return '<tr><td>' + input1 + '</td>' + '<td>' + input2 + '</td>' + '</tr>'
def for_g(): for row in range(6): for col in range(3): if row-col==2 or col-row==1 or row+col==4 or col==2 and row>0 or row==5 and col==1 or row==1 and col==0: print("*",end=" ") else: print(" ",end=" ") print() def while_g(): row=0 while row<6: col=0 while col<3: if row-col==2 or col-row==1 or row+col==4 or col==2 and row>0 or row==5 and col==1 or row==1 and col==0: print("*",end=" ") else: print(" ",end=" ") col+=1 row+=1 print()
def for_g(): for row in range(6): for col in range(3): if row - col == 2 or col - row == 1 or row + col == 4 or (col == 2 and row > 0) or (row == 5 and col == 1) or (row == 1 and col == 0): print('*', end=' ') else: print(' ', end=' ') print() def while_g(): row = 0 while row < 6: col = 0 while col < 3: if row - col == 2 or col - row == 1 or row + col == 4 or (col == 2 and row > 0) or (row == 5 and col == 1) or (row == 1 and col == 0): print('*', end=' ') else: print(' ', end=' ') col += 1 row += 1 print()
ERR_SVR_NOT_FOUND = 1 ERR_CLSTR_NOT_FOUND = 2 ERR_IMG_NOT_FOUND = 3 ERR_SVR_EXISTS = 4 ERR_CLSTR_EXISTS = 5 ERR_IMG_EXISTS = 6 ERR_IMG_TYPE_INVALID = 7 ERR_OPR_ERROR = 8 ERR_GENERAL_ERROR = 9 ERR_MATCH_KEY_NOT_PRESENT = 10 ERR_MATCH_VALUE_NOT_PRESENT = 11 ERR_INVALID_MATCH_KEY = 12
err_svr_not_found = 1 err_clstr_not_found = 2 err_img_not_found = 3 err_svr_exists = 4 err_clstr_exists = 5 err_img_exists = 6 err_img_type_invalid = 7 err_opr_error = 8 err_general_error = 9 err_match_key_not_present = 10 err_match_value_not_present = 11 err_invalid_match_key = 12
def swap_case(s): # sWAP cASE in Python - HackerRank Solution START Output = '' for char in s: if(char.isupper()==True): Output += (char.lower()) elif(char.islower()==True): Output += (char.upper()) else: Output += char return Output
def swap_case(s): output = '' for char in s: if char.isupper() == True: output += char.lower() elif char.islower() == True: output += char.upper() else: output += char return Output
a=10 b=1.5 c= 'Arpan' print (c,"is of type",type(c) )
a = 10 b = 1.5 c = 'Arpan' print(c, 'is of type', type(c))
KNOWN_BINARIES = [ "*.avi", # video "*.bin", # binary "*.bmp", # image "*.docx", # ms-word "*.eot", # font "*.exe", # binary "*.gif", # image "*.gz", # compressed "*.heic", # image "*.heif", # image "*.ico", # image "*.jpeg", # image "*.jpg", # image "*.m1v", # video "*.m2a", # audio "*.mov", # video "*.mp2", # audio "*.mp3", # audio "*.mp4", # video "*.mpa", # video "*.mpe", # video "*.mpeg", # video "*.mpg", # video "*.opus", # audio "*.otf", # font "*.pdf", # pdf "*.png", # image "*.pptx", # ms-powerpoint "*.qt", # video "*.rar", # compressed "*.tar", # compressed "*.tif", # image "*.tiff", # image "*.ttf", # font "*.wasm", # wasm "*.wav", # audio "*.webm", # video "*.wma", # video "*.wmv", # video "*.woff", # font "*.woff2", # font "*.xlsx", # ms-excel "*.zip", # compressed ]
known_binaries = ['*.avi', '*.bin', '*.bmp', '*.docx', '*.eot', '*.exe', '*.gif', '*.gz', '*.heic', '*.heif', '*.ico', '*.jpeg', '*.jpg', '*.m1v', '*.m2a', '*.mov', '*.mp2', '*.mp3', '*.mp4', '*.mpa', '*.mpe', '*.mpeg', '*.mpg', '*.opus', '*.otf', '*.pdf', '*.png', '*.pptx', '*.qt', '*.rar', '*.tar', '*.tif', '*.tiff', '*.ttf', '*.wasm', '*.wav', '*.webm', '*.wma', '*.wmv', '*.woff', '*.woff2', '*.xlsx', '*.zip']
ecc_fpga_constants_v128 = [ [ # Parameter name "p192", # base word size 16, # extended word size 128, # number of bits added 9, # number of words 2, # prime 6277101735386680763835789423207666416083908700390324961279, # prime size in bits 192, # prime+1 6277101735386680763835789423207666416083908700390324961280, # prime' = -1/prime mod r 340282366920938463444927863358058659841, # prime plus one number of zeroes 0, # 2*prime 12554203470773361527671578846415332832167817400780649922558, # r mod prime 340282366920938463481821351505477763072, # r^2 mod prime 680564733841876926982089447084665077762, # value 1 1, # ECC curve order 6277101735386680763835789423176059013767194773182842284081, # ECC curve order bit length 192, # ECC curve constant a in Montgomery domain (*r mod prime) 6277101735386680762814942322444851025638444645873891672063, # ECC curve constant a^2 in Montgomery domain (*r mod prime) 3062541302288446171336392163549299867648, # ECC curve constant 3*b in Montgomery domain (*r mod prime) 2146011979814483024655457172515544228634458728892725334932, # ECC curve constant a original 6277101735386680763835789423207666416083908700390324961276, # ECC curve constant a^2 original 9, # ECC curve constant 3*b original 1088364902640150689385092322384688938223415474093248752916, # ECC curve generator point x original 602046282375688656758213480587526111916698976636884684818, # ECC curve generator point y original 174050332293622031404857552280219410364023488927386650641, # ECC curve generator point z original 1, # ECC stack starting address 1792, ], [ # Parameter name "p224", # base word size 16, # extended word size 128, # number of bits added 9, # number of words 2, # prime 26959946667150639794667015087019630673557916260026308143510066298881, # prime size in bits 224, # prime+1 26959946667150639794667015087019630673557916260026308143510066298882, # prime' = -1/prime mod r 26959946660873538059280334323183841250350249843923952699046031785983, # prime plus one number of zeroes 0, # 2*prime 53919893334301279589334030174039261347115832520052616287020132597762, # r mod prime 340282366920938463463374607427473244160, # r^2 mod prime 26959946667150639791744011812698107204071485058075563455699384008705, # value 1 1, # ECC curve order 26959946667150639794667015087019625940457807714424391721682722368061, # ECC curve order bit length 224, # ECC curve constant a in Montgomery domain (*r mod prime) 26959946667150639794667015085998783572795100869636184321227646566401, # ECC curve constant a^2 in Montgomery domain (*r mod prime) 3062541302288446171170371466847259197440, # ECC curve constant 3*b in Montgomery domain (*r mod prime) 13401218465836556856847955134146467949031625748186257869499969637734, # ECC curve constant a original 26959946667150639794667015087019630673557916260026308143510066298878, # ECC curve constant a^2 original 9, # ECC curve constant 3*b original 2954965522398544411891975459442517899398210385985346940341571419930, # ECC curve generator point x original 19277929113566293071110308034699488026831934219452440156649784352033, # ECC curve generator point y original 19926808758034470970197974370888749184205991990603949537637343198772, # ECC curve generator point z original 1, # ECC stack starting address 1792, ], [ # Parameter name "p256", # base word size 16, # extended word size 128, # number of bits added 9, # number of words 3, # prime 115792089210356248762697446949407573530086143415290314195533631308867097853951, # prime size in bits 256, # prime+1 115792089210356248762697446949407573530086143415290314195533631308867097853952, # prime' = -1/prime mod r 18347988923648598022536716706971804129709918677350277014173567881887264878223328924289981802626012577529857, # prime plus one number of zeroes 0, # 2*prime 231584178420712497525394893898815147060172286830580628391067262617734195707902, # r mod prime 115792089183396302095546807154740558443747077475653503024948336717809816961022, # r^2 mod prime 647038720017892456816164052675271495997532319237579337257304618696714, # value 1 1, # ECC curve order 115792089210356248762697446949407573529996955224135760342422259061068512044369, # ECC curve order bit length 256, # ECC curve constant a in Montgomery domain (*r mod prime) 80879840001451919384001045259017197818910433511755883773171842678787, # ECC curve constant a^2 in Montgomery domain (*r mod prime) 115792088967716728758341688797404437753034549958559013660265979989351569817590, # ECC curve constant 3*b in Montgomery domain (*r mod prime) 33495354891368907141352085619905772971337155559618643861777243941875987635246, # ECC curve constant a original 115792089210356248762697446949407573530086143415290314195533631308867097853948, # ECC curve constant a^2 original 9, # ECC curve constant 3*b original 7383001965100177625280942390734231697257179632690862468972137633251304349922, # ECC curve generator point x original 48439561293906451759052585252797914202762949526041747995844080717082404635286, # ECC curve generator point y original 36134250956749795798585127919587881956611106672985015071877198253568414405109, # ECC curve generator point z original 1, # ECC stack starting address 1792, ], [ # Parameter name "p384", # base word size 16, # extended word size 128, # number of bits added 9, # number of words 4, # prime 39402006196394479212279040100143613805079739270465446667948293404245721771496870329047266088258938001861606973112319, # prime size in bits 384, # prime+1 39402006196394479212279040100143613805079739270465446667948293404245721771496870329047266088258938001861606973112320, # prime' = -1/prime mod r 13407807648985227524617045814712496250916495602455859132428975829761605269743128573023706335482896061566913845096358773683926276119763782985192138296262657, # prime plus one number of zeroes 0, # 2*prime 78804012392788958424558080200287227610159478540930893335896586808491443542993740658094532176517876003723213946224638, # r mod prime 115792089264276142090721624801893421303298994787994962092745248076792575557632, # r^2 mod prime 18347988930056559127812830772223728126786819762522737026661065083431152758333894840256060847379628934823936, # value 1 1, # ECC curve order 39402006196394479212279040100143613805079739270465446667946905279627659399113263569398956308152294913554433653942643, # ECC curve order bit length 384, # ECC curve constant a in Montgomery domain (*r mod prime) 39402006196394479212279040100143613804732363002672618241676128529840041507586973344683281201980702257631229246439423, # ECC curve constant a^2 in Montgomery domain (*r mod prime) 1042128803378485278816494623217040791729690953091954658834707232691133180018688, # ECC curve constant 3*b in Montgomery domain (*r mod prime) 26111218080071188457686646591327611440845506966732540570282325137754995868870791235070305575251358638402738321777086, # ECC curve constant a original 39402006196394479212279040100143613805079739270465446667948293404245721771496870329047266088258938001861606973112316, # ECC curve constant a^2 original 9, # ECC curve constant 3*b original 3936568287090159208988955320879916669011239028153812228389535097474624180935841937314250118133359319573105337467087, # ECC curve generator point x original 26247035095799689268623156744566981891852923491109213387815615900925518854738050089022388053975719786650872476732087, # ECC curve generator point y original 8325710961489029985546751289520108179287853048861315594709205902480503199884419224438643760392947333078086511627871, # ECC curve generator point z original 1, # ECC stack starting address 1792, ], [ # Parameter name "p521", # base word size 16, # extended word size 128, # number of bits added 9, # number of words 5, # prime 6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151, # prime size in bits 521, # prime+1 6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057152, # prime' = -1/prime mod r 6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057153, # prime plus one number of zeroes 3, # 2*prime 13729595320261219429963801598162786434538870600286610818788926918371086366795312104245119281322909109954592622782961716074243975999433287625148056582230114302, # r mod prime 664613997892457936451903530140172288, # r^2 mod prime 441711766194596082395824375185729628956870974218904739530401550323154944, # value 1 1, # ECC curve order 6864797660130609714981900799081393217269435300143305409394463459185543183397655394245057746333217197532963996371363321113864768612440380340372808892707005449, # ECC curve order bit length 521, # ECC curve constant a in Montgomery domain (*r mod prime) 6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858035128146006039270003218317700694540287, # ECC curve constant a^2 in Montgomery domain (*r mod prime) 5981525981032121428067131771261550592, # ECC curve constant 3*b in Montgomery domain (*r mod prime) 6454495390007915947061041987725961162904274121557891147018847125712493623674470779573474404800029704056764955388514936956769162135843165244571821404023458019, # ECC curve constant a original 6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057148, # ECC curve constant a^2 original 9, # ECC curve constant 3*b original 3281547114221202823533337172300416709808622796855051246983759183487859348452205048041126212721278869745776396890118939928315357594773038736426982465436957952, # ECC curve generator point x original 2661740802050217063228768716723360960729859168756973147706671368418802944996427808491545080627771902352094241225065558662157113545570916814161637315895999846, # ECC curve generator point y original 3757180025770020463545507224491183603594455134769762486694567779615544477440556316691234405012945539562144444537289428522585666729196580810124344277578376784, # ECC curve generator point z original 1, # ECC stack starting address 1792, ], ]
ecc_fpga_constants_v128 = [['p192', 16, 128, 9, 2, 6277101735386680763835789423207666416083908700390324961279, 192, 6277101735386680763835789423207666416083908700390324961280, 340282366920938463444927863358058659841, 0, 12554203470773361527671578846415332832167817400780649922558, 340282366920938463481821351505477763072, 680564733841876926982089447084665077762, 1, 6277101735386680763835789423176059013767194773182842284081, 192, 6277101735386680762814942322444851025638444645873891672063, 3062541302288446171336392163549299867648, 2146011979814483024655457172515544228634458728892725334932, 6277101735386680763835789423207666416083908700390324961276, 9, 1088364902640150689385092322384688938223415474093248752916, 602046282375688656758213480587526111916698976636884684818, 174050332293622031404857552280219410364023488927386650641, 1, 1792], ['p224', 16, 128, 9, 2, 26959946667150639794667015087019630673557916260026308143510066298881, 224, 26959946667150639794667015087019630673557916260026308143510066298882, 26959946660873538059280334323183841250350249843923952699046031785983, 0, 53919893334301279589334030174039261347115832520052616287020132597762, 340282366920938463463374607427473244160, 26959946667150639791744011812698107204071485058075563455699384008705, 1, 26959946667150639794667015087019625940457807714424391721682722368061, 224, 26959946667150639794667015085998783572795100869636184321227646566401, 3062541302288446171170371466847259197440, 13401218465836556856847955134146467949031625748186257869499969637734, 26959946667150639794667015087019630673557916260026308143510066298878, 9, 2954965522398544411891975459442517899398210385985346940341571419930, 19277929113566293071110308034699488026831934219452440156649784352033, 19926808758034470970197974370888749184205991990603949537637343198772, 1, 1792], ['p256', 16, 128, 9, 3, 115792089210356248762697446949407573530086143415290314195533631308867097853951, 256, 115792089210356248762697446949407573530086143415290314195533631308867097853952, 18347988923648598022536716706971804129709918677350277014173567881887264878223328924289981802626012577529857, 0, 231584178420712497525394893898815147060172286830580628391067262617734195707902, 115792089183396302095546807154740558443747077475653503024948336717809816961022, 647038720017892456816164052675271495997532319237579337257304618696714, 1, 115792089210356248762697446949407573529996955224135760342422259061068512044369, 256, 80879840001451919384001045259017197818910433511755883773171842678787, 115792088967716728758341688797404437753034549958559013660265979989351569817590, 33495354891368907141352085619905772971337155559618643861777243941875987635246, 115792089210356248762697446949407573530086143415290314195533631308867097853948, 9, 7383001965100177625280942390734231697257179632690862468972137633251304349922, 48439561293906451759052585252797914202762949526041747995844080717082404635286, 36134250956749795798585127919587881956611106672985015071877198253568414405109, 1, 1792], ['p384', 16, 128, 9, 4, 39402006196394479212279040100143613805079739270465446667948293404245721771496870329047266088258938001861606973112319, 384, 39402006196394479212279040100143613805079739270465446667948293404245721771496870329047266088258938001861606973112320, 13407807648985227524617045814712496250916495602455859132428975829761605269743128573023706335482896061566913845096358773683926276119763782985192138296262657, 0, 78804012392788958424558080200287227610159478540930893335896586808491443542993740658094532176517876003723213946224638, 115792089264276142090721624801893421303298994787994962092745248076792575557632, 18347988930056559127812830772223728126786819762522737026661065083431152758333894840256060847379628934823936, 1, 39402006196394479212279040100143613805079739270465446667946905279627659399113263569398956308152294913554433653942643, 384, 39402006196394479212279040100143613804732363002672618241676128529840041507586973344683281201980702257631229246439423, 1042128803378485278816494623217040791729690953091954658834707232691133180018688, 26111218080071188457686646591327611440845506966732540570282325137754995868870791235070305575251358638402738321777086, 39402006196394479212279040100143613805079739270465446667948293404245721771496870329047266088258938001861606973112316, 9, 3936568287090159208988955320879916669011239028153812228389535097474624180935841937314250118133359319573105337467087, 26247035095799689268623156744566981891852923491109213387815615900925518854738050089022388053975719786650872476732087, 8325710961489029985546751289520108179287853048861315594709205902480503199884419224438643760392947333078086511627871, 1, 1792], ['p521', 16, 128, 9, 5, 6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151, 521, 6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057152, 6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057153, 3, 13729595320261219429963801598162786434538870600286610818788926918371086366795312104245119281322909109954592622782961716074243975999433287625148056582230114302, 664613997892457936451903530140172288, 441711766194596082395824375185729628956870974218904739530401550323154944, 1, 6864797660130609714981900799081393217269435300143305409394463459185543183397655394245057746333217197532963996371363321113864768612440380340372808892707005449, 521, 6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858035128146006039270003218317700694540287, 5981525981032121428067131771261550592, 6454495390007915947061041987725961162904274121557891147018847125712493623674470779573474404800029704056764955388514936956769162135843165244571821404023458019, 6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057148, 9, 3281547114221202823533337172300416709808622796855051246983759183487859348452205048041126212721278869745776396890118939928315357594773038736426982465436957952, 2661740802050217063228768716723360960729859168756973147706671368418802944996427808491545080627771902352094241225065558662157113545570916814161637315895999846, 3757180025770020463545507224491183603594455134769762486694567779615544477440556316691234405012945539562144444537289428522585666729196580810124344277578376784, 1, 1792]]
OpenVZ_EXIT_STATUS = { 'vzctl': {0: 'Command executed successfully', 1: 'Failed to set a UBC parameter', 2: 'Failed to set a fair scheduler parameter', 3: 'Generic system error', 5: 'The running kernel is not an OpenVZ kernel (or some OpenVZ modules are not loaded)', 6: 'Not enough system resources', 7: 'ENV_CREATE ioctl failed', 8: 'Command executed by vzctl exec returned non-zero exit code', 9: 'Container is locked by another vzctl invocation', 10: 'Global OpenVZ configuration file vz.conf(5) not found', 11: 'A vzctl helper script file not found', 12: 'Permission denied', 13: 'Capability setting failed', 14: 'Container configuration file ctid.conf(5) not found', 15: 'Timeout on vzctl exec', 16: 'Error during vzctl chkpnt', 17: 'Error during vzctl restore', 18: 'Error from setluid() syscall', 20: 'Invalid command line parameter', 21: 'Invalid value for command line parameter', 22: 'Container root directory (VE_ROOT) not set', 23: 'Container private directory (VE_PRIVATE) not set', 24: 'Container template directory (TEMPLATE) not set', 28: 'Not all required UBC parameters are set, unable to start container', 29: 'OS template is not specified, unable to create container', 31: 'Container not running', 32: 'Container already running', 33: 'Unable to stop container', 34: 'Unable to add IP address to container', 40: 'Container not mounted', 41: 'Container already mounted', 43: 'Container private area not found', 44: 'Container private area already exists', 46: 'Not enough disk space', 47: 'Bad/broken container (/sbin/init or /bin/sh not found)', 48: 'Unable to create a new container private area', 49: 'Unable to create a new container root area', 50: 'Unable to mount container', 51: 'Unable to unmount container', 52: 'Unable to delete a container', 53: 'Container private area not exist', 60: 'vzquota on failed', 61: 'vzquota init failed', 62: 'vzquota setlimit failed', 63: 'Parameter DISKSPACE not set (or set too high)', 64: 'Parameter DISKINODES not set', 65: 'Error setting in-container disk quotas', 66: 'vzquota off failed', 67: 'ugid quota not initialized', 71: 'Incorrect IP address format', 74: 'Error changing password', 78: 'IP address already in use', 79: 'Container action script returned an error', 82: 'Config file copying error', 86: 'Error setting devices (--devices or --devnodes)', 89: 'IP address not available', 91: 'OS template not found', 99: 'Ploop is not supported by either the running kernel or vzctl.', 100: 'Unable to find container IP address', 104: 'VE_NETDEV ioctl error', 105: 'Container start disabled', 106: 'Unable to set iptables on a running container', 107: 'Distribution-specific configuration file not found', 109: 'Unable to apply a config', 129: 'Unable to set meminfo parameter', 130: 'Error setting veth interface', 131: 'Error setting container name', 133: 'Waiting for container start failed', 139: 'Error saving container configuration file', 148: 'Error setting container IO parameters (ioprio)', 150: 'Ploop image file not found', 151: 'Error creating ploop image', 152: 'Error mounting ploop image', 153: 'Error unmounting ploop image', 154: 'Error resizing ploop image', 155: 'Error converting container to ploop layout', 156: 'Error creating ploop snapshot', 157: 'Error merging ploop snapshot', 158: 'Error deleting ploop snapshot', 159: 'Error switching ploop snapshot', 161: 'Error compacting ploop image'}, 'vzquoata': {0: 'Command executed successfully', 1: 'System error', 2: 'Usage error', 3: 'Virtuozzo syscall error', 4: 'Quota file error', 5: 'Quota is already running', 6: 'Quota is not running', 7: 'Can not get lock on this quota id', 8: 'Directory tree crosses mount points', 9: '(Info) Quota is running but user/group quota is inactive', 10: '(Info) Quota is marked as dirty in file', 11: 'Quota file does not exist', 12: 'Internal error', 13: "Can't obtain mount point"}, 'ndsend': {0: 'Command executed successfully', 1: 'Usage error', 2: 'System error'}, 'arpsend': {0: 'Command executed successfully', 1: 'Usage error', 2: 'System error', 3: 'ARP reply was received'}, 'vzmigrate': {0: 'Command executed successfully', 1: 'Bad command line options.', 2: 'Container is stopped.', 4: "Can't connect to destination (source) HN.", 6: 'Container private area copying/moving failed.', 7: "Can't start or restore destination CT.", 8: "Can't stop or checkpoint source CT.", 9: 'Container already exists on destination HN.', 10: 'Container does not exists on source HN.', 12: 'You attempt to migrate CT which IP address(es) are already in use on the destination node.', 13: 'Operation with CT quota failed.', 14: 'OpenVZ is not running, or some required kernel modules are not loaded.', 15: 'Unable to set CT name on destination node.', 16: 'Ploop is not supported by destination node.'}, 'vzcfgvalidate': {0: 'Command executed successfully', 1: 'On program execution error.', 2: 'Validation failed.'} }
open_vz_exit_status = {'vzctl': {0: 'Command executed successfully', 1: 'Failed to set a UBC parameter', 2: 'Failed to set a fair scheduler parameter', 3: 'Generic system error', 5: 'The running kernel is not an OpenVZ kernel (or some OpenVZ modules are not loaded)', 6: 'Not enough system resources', 7: 'ENV_CREATE ioctl failed', 8: 'Command executed by vzctl exec returned non-zero exit code', 9: 'Container is locked by another vzctl invocation', 10: 'Global OpenVZ configuration file vz.conf(5) not found', 11: 'A vzctl helper script file not found', 12: 'Permission denied', 13: 'Capability setting failed', 14: 'Container configuration file ctid.conf(5) not found', 15: 'Timeout on vzctl exec', 16: 'Error during vzctl chkpnt', 17: 'Error during vzctl restore', 18: 'Error from setluid() syscall', 20: 'Invalid command line parameter', 21: 'Invalid value for command line parameter', 22: 'Container root directory (VE_ROOT) not set', 23: 'Container private directory (VE_PRIVATE) not set', 24: 'Container template directory (TEMPLATE) not set', 28: 'Not all required UBC parameters are set, unable to start container', 29: 'OS template is not specified, unable to create container', 31: 'Container not running', 32: 'Container already running', 33: 'Unable to stop container', 34: 'Unable to add IP address to container', 40: 'Container not mounted', 41: 'Container already mounted', 43: 'Container private area not found', 44: 'Container private area already exists', 46: 'Not enough disk space', 47: 'Bad/broken container (/sbin/init or /bin/sh not found)', 48: 'Unable to create a new container private area', 49: 'Unable to create a new container root area', 50: 'Unable to mount container', 51: 'Unable to unmount container', 52: 'Unable to delete a container', 53: 'Container private area not exist', 60: 'vzquota on failed', 61: 'vzquota init failed', 62: 'vzquota setlimit failed', 63: 'Parameter DISKSPACE not set (or set too high)', 64: 'Parameter DISKINODES not set', 65: 'Error setting in-container disk quotas', 66: 'vzquota off failed', 67: 'ugid quota not initialized', 71: 'Incorrect IP address format', 74: 'Error changing password', 78: 'IP address already in use', 79: 'Container action script returned an error', 82: 'Config file copying error', 86: 'Error setting devices (--devices or --devnodes)', 89: 'IP address not available', 91: 'OS template not found', 99: 'Ploop is not supported by either the running kernel or vzctl.', 100: 'Unable to find container IP address', 104: 'VE_NETDEV ioctl error', 105: 'Container start disabled', 106: 'Unable to set iptables on a running container', 107: 'Distribution-specific configuration file not found', 109: 'Unable to apply a config', 129: 'Unable to set meminfo parameter', 130: 'Error setting veth interface', 131: 'Error setting container name', 133: 'Waiting for container start failed', 139: 'Error saving container configuration file', 148: 'Error setting container IO parameters (ioprio)', 150: 'Ploop image file not found', 151: 'Error creating ploop image', 152: 'Error mounting ploop image', 153: 'Error unmounting ploop image', 154: 'Error resizing ploop image', 155: 'Error converting container to ploop layout', 156: 'Error creating ploop snapshot', 157: 'Error merging ploop snapshot', 158: 'Error deleting ploop snapshot', 159: 'Error switching ploop snapshot', 161: 'Error compacting ploop image'}, 'vzquoata': {0: 'Command executed successfully', 1: 'System error', 2: 'Usage error', 3: 'Virtuozzo syscall error', 4: 'Quota file error', 5: 'Quota is already running', 6: 'Quota is not running', 7: 'Can not get lock on this quota id', 8: 'Directory tree crosses mount points', 9: '(Info) Quota is running but user/group quota is inactive', 10: '(Info) Quota is marked as dirty in file', 11: 'Quota file does not exist', 12: 'Internal error', 13: "Can't obtain mount point"}, 'ndsend': {0: 'Command executed successfully', 1: 'Usage error', 2: 'System error'}, 'arpsend': {0: 'Command executed successfully', 1: 'Usage error', 2: 'System error', 3: 'ARP reply was received'}, 'vzmigrate': {0: 'Command executed successfully', 1: 'Bad command line options.', 2: 'Container is stopped.', 4: "Can't connect to destination (source) HN.", 6: 'Container private area copying/moving failed.', 7: "Can't start or restore destination CT.", 8: "Can't stop or checkpoint source CT.", 9: 'Container already exists on destination HN.', 10: 'Container does not exists on source HN.', 12: 'You attempt to migrate CT which IP address(es) are already in use on the destination node.', 13: 'Operation with CT quota failed.', 14: 'OpenVZ is not running, or some required kernel modules are not loaded.', 15: 'Unable to set CT name on destination node.', 16: 'Ploop is not supported by destination node.'}, 'vzcfgvalidate': {0: 'Command executed successfully', 1: 'On program execution error.', 2: 'Validation failed.'}}
# -*- coding: utf-8 -*- """ Parameters """ """ Annotated transcript filtering Setting TSL threshold to 1 excludes some Uniprot canonical transcripts, e.g., DDP8_HUMAN with the first 18 amino acids. """ tsl_threshold = 2 # the transcript levels below which (lower is better) to consider """ Stop codon forced translation This threshold may be set to allow some stop codon transcripts to be translated to Tier 4 """ ptc_threshold = 0.33 # the PTC slice should be at least this portion of the long slice to be included """ Canonical transcript recognition Canonical can be chosen from the GTF (longest protein coding sequence) alone which speeds up the analysis or through an API call to Uniprot. This has the advantage of allowing splice graphs to determine which junctions map to which transcripts. However, note that Uniprot has manual annotation on what is the canonical sequence through prevalence and homology to other species that are not apparent in the GTF file without calling to other resources like APPRIS (e.g. see DET1_HUMAN). Because of the prominence of Uniprot in proteomics work we have chosen to use Uniprot for now. """ use_gtf_only = False # use GTF but not Uniprot to get canonical transcripts uniprot_max_retries = 10 # max number of retries if retrieving sequences from Uniprot aa_stitch_length = 10 # amino acid joint to stitch to canonical when using aa for joining
""" Parameters """ '\nAnnotated transcript filtering\n\nSetting TSL threshold to 1 excludes some Uniprot canonical transcripts, e.g.,\nDDP8_HUMAN with the first 18 amino acids.\n\n' tsl_threshold = 2 '\nStop codon forced translation\n\nThis threshold may be set to allow some stop codon transcripts to be translated to Tier 4\n\n' ptc_threshold = 0.33 '\nCanonical transcript recognition\n\nCanonical can be chosen from the GTF (longest protein coding sequence) alone \nwhich speeds up the analysis or through an API call to Uniprot. \nThis has the advantage of allowing splice graphs to determine which junctions\nmap to which transcripts.\nHowever, note that Uniprot has manual annotation on what is the canonical sequence\nthrough prevalence and homology to other species that are not apparent in the GTF file without\ncalling to other resources like APPRIS (e.g. see DET1_HUMAN). \nBecause of the prominence of Uniprot in proteomics work\nwe have chosen to use Uniprot for now.\n\n' use_gtf_only = False uniprot_max_retries = 10 aa_stitch_length = 10
""" Provide help messages for command line interface's receipt commands. """ RECEIPT_TRANSACTION_IDENTIFIERS_ARGUMENT_HELP_MESSAGE = 'Identifiers to get a list of transaction\'s receipts by.'
""" Provide help messages for command line interface's receipt commands. """ receipt_transaction_identifiers_argument_help_message = "Identifiers to get a list of transaction's receipts by."
# !/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/4/16 13:02 # @Author : Yunhao Cao # @File : exceptions.py __author__ = 'Yunhao Cao' __all__ = [ 'CrawlerBaseException', 'RuleManyMatchedError', ] class CrawlerBaseException(Exception): pass class RuleManyMatchedError(CrawlerBaseException): pass
__author__ = 'Yunhao Cao' __all__ = ['CrawlerBaseException', 'RuleManyMatchedError'] class Crawlerbaseexception(Exception): pass class Rulemanymatchederror(CrawlerBaseException): pass
""" Permutation where the order the way the elements are arranged matters Using a back tracking we print all the permutations E.g. abc There are total 3! permutations abc acb acb bac bca cab cba """ def calculate_permutations(element_list, result_list, pos, r=None): n = len(element_list) if pos == n: if r: result_list.append(element_list[:r][:]) else: result_list.append(element_list[:]) return index = pos while pos < n: element_list[pos], element_list[index] = element_list[index], element_list[pos] calculate_permutations(element_list, result_list, index+1, r) # back tracking the element in the list element_list[pos], element_list[index] = element_list[index], element_list[pos] pos += 1 def permutations(element_list, r=None): result_list = [] calculate_permutations(list(element_list), result_list, 0) return result_list def main(): for da in permutations("abc", 2): print(da) if __name__ == '__main__': main()
""" Permutation where the order the way the elements are arranged matters Using a back tracking we print all the permutations E.g. abc There are total 3! permutations abc acb acb bac bca cab cba """ def calculate_permutations(element_list, result_list, pos, r=None): n = len(element_list) if pos == n: if r: result_list.append(element_list[:r][:]) else: result_list.append(element_list[:]) return index = pos while pos < n: (element_list[pos], element_list[index]) = (element_list[index], element_list[pos]) calculate_permutations(element_list, result_list, index + 1, r) (element_list[pos], element_list[index]) = (element_list[index], element_list[pos]) pos += 1 def permutations(element_list, r=None): result_list = [] calculate_permutations(list(element_list), result_list, 0) return result_list def main(): for da in permutations('abc', 2): print(da) if __name__ == '__main__': main()
class Cat: name = '' age = 0 color = '' def __init__(self, name, age=0, color ='White'): self.name = name self.age = age self.color = color def meow(self): print(f'{self.name} meow') def sleep(self): print(f' {self.name} zzz') def hungry(self): for x in range(5): self.meow() def description(self): print(f'{self.name} is a {self.color} color Cat, who is {self.age} years old')
class Cat: name = '' age = 0 color = '' def __init__(self, name, age=0, color='White'): self.name = name self.age = age self.color = color def meow(self): print(f'{self.name} meow') def sleep(self): print(f' {self.name} zzz') def hungry(self): for x in range(5): self.meow() def description(self): print(f'{self.name} is a {self.color} color Cat, who is {self.age} years old')
""" Creating a custom error by extending the TypeError class """ class MyCustomError(TypeError): """ Raising a custom error by extending the TypeError class """ def __init__(self, error_message, error_code): super().__init__(f'Error code: {error_code}, Error Message: {error_message}') self.message = error_message self.code = error_code raise MyCustomError('This is a custom error', 403)
""" Creating a custom error by extending the TypeError class """ class Mycustomerror(TypeError): """ Raising a custom error by extending the TypeError class """ def __init__(self, error_message, error_code): super().__init__(f'Error code: {error_code}, Error Message: {error_message}') self.message = error_message self.code = error_code raise my_custom_error('This is a custom error', 403)
###################################################################### # # File: b2/sync/file.py # # Copyright 2018 Backblaze Inc. All Rights Reserved. # # License https://www.backblaze.com/using_b2_code.html # ###################################################################### class File(object): """ Holds information about one file in a folder. The name is relative to the folder in all cases. Files that have multiple versions (which only happens in B2, not in local folders) include information about all of the versions, most recent first. """ def __init__(self, name, versions): self.name = name self.versions = versions def latest_version(self): return self.versions[0] def __repr__(self): return 'File(%s, [%s])' % (self.name, ', '.join(repr(v) for v in self.versions)) class FileVersion(object): """ Holds information about one version of a file: id - The B2 file id, or the local full path name mod_time - modification time, in milliseconds, to avoid rounding issues with millisecond times from B2 action - "hide" or "upload" (never "start") """ def __init__(self, id_, file_name, mod_time, action, size): self.id_ = id_ self.name = file_name self.mod_time = mod_time self.action = action self.size = size def __repr__(self): return 'FileVersion(%s, %s, %s, %s)' % ( repr(self.id_), repr(self.name), repr(self.mod_time), repr(self.action) )
class File(object): """ Holds information about one file in a folder. The name is relative to the folder in all cases. Files that have multiple versions (which only happens in B2, not in local folders) include information about all of the versions, most recent first. """ def __init__(self, name, versions): self.name = name self.versions = versions def latest_version(self): return self.versions[0] def __repr__(self): return 'File(%s, [%s])' % (self.name, ', '.join((repr(v) for v in self.versions))) class Fileversion(object): """ Holds information about one version of a file: id - The B2 file id, or the local full path name mod_time - modification time, in milliseconds, to avoid rounding issues with millisecond times from B2 action - "hide" or "upload" (never "start") """ def __init__(self, id_, file_name, mod_time, action, size): self.id_ = id_ self.name = file_name self.mod_time = mod_time self.action = action self.size = size def __repr__(self): return 'FileVersion(%s, %s, %s, %s)' % (repr(self.id_), repr(self.name), repr(self.mod_time), repr(self.action))
def ascending_order(arr): if(len(arr) == 1): return 0 else: count = 0 for i in range(0, len(arr)-1): if(arr[i+1]<arr[i]): diff = arr[i] - arr[i+1] arr[i+1]+=diff count+=diff return count if __name__=="__main__": n = int(input()) arr = [int(i) for i in input().split(" ")][:n] print(ascending_order(arr))
def ascending_order(arr): if len(arr) == 1: return 0 else: count = 0 for i in range(0, len(arr) - 1): if arr[i + 1] < arr[i]: diff = arr[i] - arr[i + 1] arr[i + 1] += diff count += diff return count if __name__ == '__main__': n = int(input()) arr = [int(i) for i in input().split(' ')][:n] print(ascending_order(arr))
class Products: # Surface Reflectance 8-day 500m modisRefl = 'MODIS/006/MOD09A1' # => NDDI # Surface Temperature 8-day 1000m */ modisTemp = 'MODIS/006/MOD11A2' # => T/NDVI # fAPAR 8-day 500m modisFpar = 'MODIS/006/MOD15A2H' # => fAPAR #Evapotranspiration 8-day 500m modisEt = 'MODIS/006/MOD16A2' # => ET # EVI 16-day 500m modisEvi = 'MODIS/006/MOD13A1' # => EVI
class Products: modis_refl = 'MODIS/006/MOD09A1' modis_temp = 'MODIS/006/MOD11A2' modis_fpar = 'MODIS/006/MOD15A2H' modis_et = 'MODIS/006/MOD16A2' modis_evi = 'MODIS/006/MOD13A1'
# 3. Longest Substring Without Repeating Characters # Runtime: 60 ms, faster than 74.37% of Python3 online submissions for Longest Substring Without Repeating Characters. # Memory Usage: 14.4 MB, less than 53.07% of Python3 online submissions for Longest Substring Without Repeating Characters. class Solution: # Two Pointers def lengthOfLongestSubstring(self, s: str) -> int: # Define a mapping of the characters to its index. idx = {} max_len = 0 left = 0 for right in range(len(s)): char = s[right] if char in idx: # Skip the characters immediately when finding a repeated character. left = max(left, idx[char]) max_len = max(max_len, right - left + 1) idx[char] = right + 1 return max_len
class Solution: def length_of_longest_substring(self, s: str) -> int: idx = {} max_len = 0 left = 0 for right in range(len(s)): char = s[right] if char in idx: left = max(left, idx[char]) max_len = max(max_len, right - left + 1) idx[char] = right + 1 return max_len
class MXWarmSpareSettings(object): def __init__(self, session): super(MXWarmSpareSettings, self).__init__() self._session = session def swapNetworkWarmSpare(self, networkId: str): """ **Swap MX primary and warm spare appliances** https://developer.cisco.com/meraki/api/#!swap-network-warm-spare - networkId (string) """ metadata = { 'tags': ['MX warm spare settings'], 'operation': 'swapNetworkWarmSpare', } resource = f'/networks/{networkId}/swapWarmSpare' return self._session.post(metadata, resource) def getNetworkWarmSpareSettings(self, networkId: str): """ **Return MX warm spare settings** https://developer.cisco.com/meraki/api/#!get-network-warm-spare-settings - networkId (string) """ metadata = { 'tags': ['MX warm spare settings'], 'operation': 'getNetworkWarmSpareSettings', } resource = f'/networks/{networkId}/warmSpareSettings' return self._session.get(metadata, resource) def updateNetworkWarmSpareSettings(self, networkId: str, enabled: bool, **kwargs): """ **Update MX warm spare settings** https://developer.cisco.com/meraki/api/#!update-network-warm-spare-settings - networkId (string) - enabled (boolean): Enable warm spare - spareSerial (string): Serial number of the warm spare appliance - uplinkMode (string): Uplink mode, either virtual or public - virtualIp1 (string): The WAN 1 shared IP - virtualIp2 (string): The WAN 2 shared IP """ kwargs.update(locals()) metadata = { 'tags': ['MX warm spare settings'], 'operation': 'updateNetworkWarmSpareSettings', } resource = f'/networks/{networkId}/warmSpareSettings' body_params = ['enabled', 'spareSerial', 'uplinkMode', 'virtualIp1', 'virtualIp2'] payload = {k: v for (k, v) in kwargs.items() if k in body_params} return self._session.put(metadata, resource, payload)
class Mxwarmsparesettings(object): def __init__(self, session): super(MXWarmSpareSettings, self).__init__() self._session = session def swap_network_warm_spare(self, networkId: str): """ **Swap MX primary and warm spare appliances** https://developer.cisco.com/meraki/api/#!swap-network-warm-spare - networkId (string) """ metadata = {'tags': ['MX warm spare settings'], 'operation': 'swapNetworkWarmSpare'} resource = f'/networks/{networkId}/swapWarmSpare' return self._session.post(metadata, resource) def get_network_warm_spare_settings(self, networkId: str): """ **Return MX warm spare settings** https://developer.cisco.com/meraki/api/#!get-network-warm-spare-settings - networkId (string) """ metadata = {'tags': ['MX warm spare settings'], 'operation': 'getNetworkWarmSpareSettings'} resource = f'/networks/{networkId}/warmSpareSettings' return self._session.get(metadata, resource) def update_network_warm_spare_settings(self, networkId: str, enabled: bool, **kwargs): """ **Update MX warm spare settings** https://developer.cisco.com/meraki/api/#!update-network-warm-spare-settings - networkId (string) - enabled (boolean): Enable warm spare - spareSerial (string): Serial number of the warm spare appliance - uplinkMode (string): Uplink mode, either virtual or public - virtualIp1 (string): The WAN 1 shared IP - virtualIp2 (string): The WAN 2 shared IP """ kwargs.update(locals()) metadata = {'tags': ['MX warm spare settings'], 'operation': 'updateNetworkWarmSpareSettings'} resource = f'/networks/{networkId}/warmSpareSettings' body_params = ['enabled', 'spareSerial', 'uplinkMode', 'virtualIp1', 'virtualIp2'] payload = {k: v for (k, v) in kwargs.items() if k in body_params} return self._session.put(metadata, resource, payload)
# Party member and chosen four names CHOSEN_FOUR = ( 'NESS', 'PAULA', 'JEFF', 'POO', ) PARTY_MEMBERS = ( 'NESS', 'PAULA', 'JEFF', 'POO', 'POKEY', 'PICKY', 'KING', 'TONY', 'BUBBLE_MONKEY', 'DUNGEON_MAN', 'FLYING_MAN_1', 'FLYING_MAN_2', 'FLYING_MAN_3', 'FLYING_MAN_4', 'FLYING_MAN_5', 'TEDDY_BEAR', 'SUPER_PLUSH_BEAR', )
chosen_four = ('NESS', 'PAULA', 'JEFF', 'POO') party_members = ('NESS', 'PAULA', 'JEFF', 'POO', 'POKEY', 'PICKY', 'KING', 'TONY', 'BUBBLE_MONKEY', 'DUNGEON_MAN', 'FLYING_MAN_1', 'FLYING_MAN_2', 'FLYING_MAN_3', 'FLYING_MAN_4', 'FLYING_MAN_5', 'TEDDY_BEAR', 'SUPER_PLUSH_BEAR')
# -*- coding: utf-8 -*- def test_receiving_events(vim): vim.command('call rpcnotify(%d, "test-event", 1, 2, 3)' % vim.channel_id) event = vim.next_message() assert event[1] == 'test-event' assert event[2] == [1, 2, 3] vim.command('au FileType python call rpcnotify(%d, "py!", bufnr("$"))' % vim.channel_id) vim.command('set filetype=python') event = vim.next_message() assert event[1] == 'py!' assert event[2] == [vim.current.buffer.number] def test_sending_notify(vim): # notify after notify vim.command("let g:test = 3", async_=True) cmd = 'call rpcnotify(%d, "test-event", g:test)' % vim.channel_id vim.command(cmd, async_=True) event = vim.next_message() assert event[1] == 'test-event' assert event[2] == [3] # request after notify vim.command("let g:data = 'xyz'", async_=True) assert vim.eval('g:data') == 'xyz' def test_broadcast(vim): vim.subscribe('event2') vim.command('call rpcnotify(0, "event1", 1, 2, 3)') vim.command('call rpcnotify(0, "event2", 4, 5, 6)') vim.command('call rpcnotify(0, "event2", 7, 8, 9)') event = vim.next_message() assert event[1] == 'event2' assert event[2] == [4, 5, 6] event = vim.next_message() assert event[1] == 'event2' assert event[2] == [7, 8, 9] vim.unsubscribe('event2') vim.subscribe('event1') vim.command('call rpcnotify(0, "event2", 10, 11, 12)') vim.command('call rpcnotify(0, "event1", 13, 14, 15)') msg = vim.next_message() assert msg[1] == 'event1' assert msg[2] == [13, 14, 15]
def test_receiving_events(vim): vim.command('call rpcnotify(%d, "test-event", 1, 2, 3)' % vim.channel_id) event = vim.next_message() assert event[1] == 'test-event' assert event[2] == [1, 2, 3] vim.command('au FileType python call rpcnotify(%d, "py!", bufnr("$"))' % vim.channel_id) vim.command('set filetype=python') event = vim.next_message() assert event[1] == 'py!' assert event[2] == [vim.current.buffer.number] def test_sending_notify(vim): vim.command('let g:test = 3', async_=True) cmd = 'call rpcnotify(%d, "test-event", g:test)' % vim.channel_id vim.command(cmd, async_=True) event = vim.next_message() assert event[1] == 'test-event' assert event[2] == [3] vim.command("let g:data = 'xyz'", async_=True) assert vim.eval('g:data') == 'xyz' def test_broadcast(vim): vim.subscribe('event2') vim.command('call rpcnotify(0, "event1", 1, 2, 3)') vim.command('call rpcnotify(0, "event2", 4, 5, 6)') vim.command('call rpcnotify(0, "event2", 7, 8, 9)') event = vim.next_message() assert event[1] == 'event2' assert event[2] == [4, 5, 6] event = vim.next_message() assert event[1] == 'event2' assert event[2] == [7, 8, 9] vim.unsubscribe('event2') vim.subscribe('event1') vim.command('call rpcnotify(0, "event2", 10, 11, 12)') vim.command('call rpcnotify(0, "event1", 13, 14, 15)') msg = vim.next_message() assert msg[1] == 'event1' assert msg[2] == [13, 14, 15]
""" Constants for common property names =================================== In order for different parts of the code to have got a common convention for the names of properties of importance of data points, here in this module, constants are defined for these names to facilitate the interoperability of different parts of codes. Also, by using constants in this module, another advantage is that typos in the property names are able to be captured by the python interpreter. Properties for the input of computations ---------------------------------------- .. py:data:: CONFIGURATION The configuration of the structure being computed. Normally given as a string for the name of the configuration. .. py:data:: METHOD The computational methodology. Usually can be given as a string for the computational method of the computation. But it can also be more complicated structure if finer recording of method is what is concentrated. Properties for the output of computations ----------------------------------------- .. py:data:: COORDINATES The atomic coordinates. Usually given as a list of lists of atomic element symbol followed by three floating point numbers for the coordinate of the atoms, in Angstrom. .. py:data:: ELECTRON_ENERGY The electronic energy of the system. .. py:data:: ZERO_POINT_CORRECTION The zero-point correction to the base energy. .. py:data:: GIBBS_THERMAL_CORRECTION The thermal correction to the Gibbs free energy. .. py:data:: COUNTERPOISE_CORRECTION The counterpoise correction fot the basis set superposition error. By convention the units for the energies is Hartree. """ CONFIGURATION = 'configuration' METHOD = 'method' COORDINATES = 'coordinates' ELECTRON_ENERGY = 'electron_energy' ZERO_POINT_CORRECTION = 'zero_point_correction' GIIBS_THERMAL_CORRECTION = 'gibbs_thermal_correction' COUNTERPOISE_CORRECTION = 'counterpoise_correction'
""" Constants for common property names =================================== In order for different parts of the code to have got a common convention for the names of properties of importance of data points, here in this module, constants are defined for these names to facilitate the interoperability of different parts of codes. Also, by using constants in this module, another advantage is that typos in the property names are able to be captured by the python interpreter. Properties for the input of computations ---------------------------------------- .. py:data:: CONFIGURATION The configuration of the structure being computed. Normally given as a string for the name of the configuration. .. py:data:: METHOD The computational methodology. Usually can be given as a string for the computational method of the computation. But it can also be more complicated structure if finer recording of method is what is concentrated. Properties for the output of computations ----------------------------------------- .. py:data:: COORDINATES The atomic coordinates. Usually given as a list of lists of atomic element symbol followed by three floating point numbers for the coordinate of the atoms, in Angstrom. .. py:data:: ELECTRON_ENERGY The electronic energy of the system. .. py:data:: ZERO_POINT_CORRECTION The zero-point correction to the base energy. .. py:data:: GIBBS_THERMAL_CORRECTION The thermal correction to the Gibbs free energy. .. py:data:: COUNTERPOISE_CORRECTION The counterpoise correction fot the basis set superposition error. By convention the units for the energies is Hartree. """ configuration = 'configuration' method = 'method' coordinates = 'coordinates' electron_energy = 'electron_energy' zero_point_correction = 'zero_point_correction' giibs_thermal_correction = 'gibbs_thermal_correction' counterpoise_correction = 'counterpoise_correction'
#%% Imports and function declaration class Node: """LinkedListNode class to be used for this problem""" def __init__(self, data): self.data = data self.next = None # helper functions for testing purpose def create_linked_list(arr): if len(arr)==0: return None head = Node(arr[0]) tail = head for data in arr[1:]: tail.next = Node(data) tail = tail.next return head def print_linked_list(head): while head: print(head.data, end=" ") head = head.next print() # Personal Implementation def swap_nodes(head, left_index, right_index): """ :param: head- head of input linked list :param: left_index - indicates position :param: right_index - indicates position return: head of updated linked list with nodes swapped Do not create a new linked list """ # Values to swap node = head position = 0 while position <= right_index: if position == left_index: left_data = node.data if position == right_index: right_data = node.data position += 1 node = node.next # Swapping values node = head position = 0 while position <= right_index: if position == left_index: node.data = right_data if position == right_index: node.data = left_data position += 1 node = node.next return head #%% Testing # Case 1 arr = [3, 4, 5, 2, 6, 1, 9] left_index = 3 right_index = 4 head = create_linked_list(arr) print_linked_list(swap_nodes(head=head, left_index=left_index, right_index=right_index)) # Case 2 arr = [3, 4, 5, 2, 6, 1, 9] left_index = 2 right_index = 4 head = create_linked_list(arr) print_linked_list(swap_nodes(head=head, left_index=left_index, right_index=right_index)) # Case 3 arr = [3, 4, 5, 2, 6, 1, 9] left_index = 0 right_index = 1 head = create_linked_list(arr) print_linked_list(swap_nodes(head=head, left_index=left_index, right_index=right_index))
class Node: """LinkedListNode class to be used for this problem""" def __init__(self, data): self.data = data self.next = None def create_linked_list(arr): if len(arr) == 0: return None head = node(arr[0]) tail = head for data in arr[1:]: tail.next = node(data) tail = tail.next return head def print_linked_list(head): while head: print(head.data, end=' ') head = head.next print() def swap_nodes(head, left_index, right_index): """ :param: head- head of input linked list :param: left_index - indicates position :param: right_index - indicates position return: head of updated linked list with nodes swapped Do not create a new linked list """ node = head position = 0 while position <= right_index: if position == left_index: left_data = node.data if position == right_index: right_data = node.data position += 1 node = node.next node = head position = 0 while position <= right_index: if position == left_index: node.data = right_data if position == right_index: node.data = left_data position += 1 node = node.next return head arr = [3, 4, 5, 2, 6, 1, 9] left_index = 3 right_index = 4 head = create_linked_list(arr) print_linked_list(swap_nodes(head=head, left_index=left_index, right_index=right_index)) arr = [3, 4, 5, 2, 6, 1, 9] left_index = 2 right_index = 4 head = create_linked_list(arr) print_linked_list(swap_nodes(head=head, left_index=left_index, right_index=right_index)) arr = [3, 4, 5, 2, 6, 1, 9] left_index = 0 right_index = 1 head = create_linked_list(arr) print_linked_list(swap_nodes(head=head, left_index=left_index, right_index=right_index))
class PlotmanError(Exception): """An exception type for all plotman errors to inherit from. This is never to be raised. """ pass class UnableToIdentifyPlotterFromLogError(PlotmanError): def __init__(self) -> None: super().__init__("Failed to identify the plotter definition for parsing log")
class Plotmanerror(Exception): """An exception type for all plotman errors to inherit from. This is never to be raised. """ pass class Unabletoidentifyplotterfromlogerror(PlotmanError): def __init__(self) -> None: super().__init__('Failed to identify the plotter definition for parsing log')
class TreeError: TYPE_ERROR = 'ERROR' TYPE_ANOMALY = 'ANOMALY' ON_INDI = 'INDIVIDUAL' ON_FAM = 'FAMILY' def __init__(self, err_type, err_on, err_us, err_on_id, err_msg): self.err_type = err_type self.err_on = err_on self.err_us = err_us self.err_on_id = err_on_id self.err_msg = err_msg def __str__(self): return f'{self.err_type}: {self.err_on}: {self.err_us}: {self.err_on_id}: {self.err_msg}'
class Treeerror: type_error = 'ERROR' type_anomaly = 'ANOMALY' on_indi = 'INDIVIDUAL' on_fam = 'FAMILY' def __init__(self, err_type, err_on, err_us, err_on_id, err_msg): self.err_type = err_type self.err_on = err_on self.err_us = err_us self.err_on_id = err_on_id self.err_msg = err_msg def __str__(self): return f'{self.err_type}: {self.err_on}: {self.err_us}: {self.err_on_id}: {self.err_msg}'
budget_header = 'Budget' forecast_total_header = 'Forecast outturn' variance_header = 'Variance -overspend/underspend' variance_percentage_header = 'Variance %' year_to_date_header = 'Year to Date Actuals' budget_spent_percentage_header = '% of budget spent to date' variance_outturn_header = "Forecast movement"
budget_header = 'Budget' forecast_total_header = 'Forecast outturn' variance_header = 'Variance -overspend/underspend' variance_percentage_header = 'Variance %' year_to_date_header = 'Year to Date Actuals' budget_spent_percentage_header = '% of budget spent to date' variance_outturn_header = 'Forecast movement'
''' Commands: Basic module to handle all commands. Commands for mops are driven by one-line exec statements; these exec statements are held in a dictionary. Model Operations Processing System. Copyright Brian Fairbairn 2009-2010. Licenced under the EUPL. You may not use this work except in compliance with the Licence. You may obtain a copy of the Licence at http://ec.europa.eu/idabc/eupl or as attached with this application (see Licence file). Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an 'AS IS' basis WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either expressed or implied. See the Licence governing permissions and limitations under the Licence. Changes: Rev 1 Added Params as a parameter to CXSCHD for triMOPS Added Params as a parameter to ADROUT for default direction Added Params to LINEUP for passenger car checking Added Params to LICONS for passenger car checking ''' def load_commands(commands): """This contains a list of commands to be exec'd in the main loop. The key is the input command and the value is the line to be executed (generally a class method). Command structure: verb data where verb is (almost always) a 6-figure word which translates to a class method and data is a set of parameters for the class method delimited by semi-colons Verb structure special verbs are available which equate to specific commands and these are described in the user manual or can be see below. general verbs are constructed on the following basis: chars 1 + 2 AD - Add a new item CH - Change existing item (addittional changes will be C*) DX - Delete item LI - List items (to screen) (additional list verions will be LA, LB etc) LX - unformatted list versions PA - Print items (to file) (additional print version will be PA, PB etx) PX - unformatted print versions (for .csv files) XX - Supervisor command functions chars 3-6 type of data being updated (can also use char 6) AREA - Maintain Areas USER - Maintain users TYPE - Maintain Stax Types STAX - Maintain Stax PARM - Parameter values """ #areas commands['ADAREA'] = 'Area.adarea(input_data)\n' commands['CHAREA'] = 'Area.charea(input_data)\n' commands['DXAREA'] = 'Area.dxarea(input_data)\n' commands['LIAREA'] = 'Area.liarea(input_data)\n' commands['LXAREA'] = 'Area.dump_to_screen()\n' commands['PRAREA'] = 'Area.prarea(input_data, Params)\n' commands['PXAREA'] = 'Area.extract_to_file(Params)\n' #calendar commands['HOLIDX'] = 'Calendar.holidx(input_data)\n' commands['LICALX'] = 'Calendar.licalx(input_data)\n' #car commands['ADCARX'] = 'Car.adcarx(input_data)\n' commands['ACARXB'] = 'Car.acarxb(input_data)\n' commands['ACARXS'] = 'Car.acarxs(input_data)\n' commands['CARXAT'] = 'Car.carxat(input_data)\n' commands['CHCARX'] = 'Car.chcarx(input_data)\n' commands['CLEANX'] = 'Car.cleanx(input_data)\n' commands['MAINTC'] = 'Car.maintc(input_data)\n' commands['CXCARS'] = 'Car.cxcars(input_data)\n' commands['DXCARX'] = 'Car.dxcarx(input_data)\n' commands['LACARS'] = 'Car.lacars(input_data)\n' commands['LICARS'] = 'Car.licars(input_data)\n' commands['LMTCAR'] = 'Car.lmtcar(input_data)\n' commands['LONWAY'] = 'Car.lonway(input_data)\n' commands['LXCARS'] = 'Car.dump_to_screen()\n' commands['MTYORD'] = 'Car.mtyord(input_data)\n' commands['PRCARS'] = 'Car.prcars(input_data, Params)\n' commands['PXCARS'] = 'Car.extract_to_file(Params)\n' commands['CARXSP'] = 'Car.carxsp(input_data)\n' commands['XCARXB'] = 'Car.xcarxb(input_data)\n' commands['XCARXS'] = 'Car.xcarxs(input_data)\n' #carclass commands['ADCLAS'] = 'CarClass.adclas(input_data)\n' commands['CHCLAS'] = 'CarClass.chclas(input_data)\n' commands['DXCLAS'] = 'CarClass.dxclas(input_data)\n' commands['LICLAS'] = 'CarClass.liclas(input_data)\n' commands['LXCLAS'] = 'CarClass.dump_to_screen()\n' commands['PRCLAS'] = 'CarClass.prclas(input_data, Params)\n' commands['PXCLAS'] = 'CarClass.extract_to_file(Params)\n' #cartype commands['ADCART'] = 'CarType.adcart(input_data)\n' commands['CHCART'] = 'CarType.chcart(input_data)\n' commands['DXCART'] = 'CarType.dxcart(input_data)\n' commands['LICART'] = 'CarType.licart(input_data)\n' commands['LXCART'] = 'CarType.dump_to_screen()\n' commands['PRCART'] = 'CarType.prcart(input_data, Params,)\n' commands['PXCART'] = 'CarType.extract_to_file(Params)\n' #commodities commands['ADCOMM'] = 'Commodity.adcomm(input_data)\n' commands['CHCOMM'] = 'Commodity.chcomm(input_data)\n' commands['DXCOMM'] = 'Commodity.dxcomm(input_data)\n' commands['LICOMM'] = 'Commodity.licomm(input_data)\n' commands['LXCOMM'] = 'Commodity.dump_to_screen()\n' commands['PRCOMM'] = 'Commodity.prcomm(input_data, Params)\n' commands['PXCOMM'] = 'Commodity.extract_to_file(Params)\n' #flash commands['FLASHX'] = 'Flash.flashx(input_data, Params)\n' #help commands['ABOUT'] = 'MOPS_Help.about()\n' commands['HELP'] = 'MOPS_Help.help()\n' commands['ASSIST'] = 'MOPS_Commands.assist()\n' #instruction commands['ADINST'] = 'Instruction.adinst(input_data)\n' commands['DXINST'] = 'Instruction.dxinst(input_data)\n' #loading commands['ADLOAD'] = 'Loading.adload(input_data)\n' commands['CHLOAD'] = 'Loading.chload(input_data)\n' commands['DXLOAD'] = 'Loading.dxload(input_data)\n' commands['LILOAD'] = 'Loading.liload(input_data)\n' commands['LXLOAD'] = 'Loading.dump_to_screen()\n' commands['PRLOAD'] = 'Loading.prload(input_data, Params)\n' commands['PXLOAD'] = 'Loading.extract_to_file(Params)\n' #loco commands['ADLOCO'] = 'Loco.adloco(input_data)\n' commands['FUELXX'] = 'Loco.fuelxx(input_data)\n' commands['CHLOCO'] = 'Loco.chloco(input_data)\n' commands['MAINTL'] = 'Loco.maintl(input_data)\n' commands['POWERX'] = 'Loco.powerx(input_data)\n' commands['DXLOCO'] = 'Loco.dxloco(input_data)\n' commands['LOCOAT'] = 'Loco.locoat(input_data)\n' commands['LOCOSP'] = 'Loco.locosp(input_data)\n' commands['LILOCO'] = 'Loco.liloco(input_data)\n' commands['LSLOCO'] = 'Loco.lsloco(input_data)\n' commands['LXLOCO'] = 'Loco.dump_to_screen()\n' commands['PRLOCO'] = 'Loco.prloco(input_data, Params)\n' commands['PSLOCO'] = 'Loco.psloco(input_data, Params)\n' commands['PXLOCO'] = 'Loco.extract_to_file(Params)\n' #loco type commands['ADLOCT'] = 'LocoType.adloct(input_data)\n' commands['CHLOCT'] = 'LocoType.chloct(input_data)\n' commands['DXLOCT'] = 'LocoType.dxloct(input_data)\n' commands['LILOCT'] = 'LocoType.liloct(input_data)' commands['LXLOCT'] = 'LocoType.dump_to_screen()\n' commands['PRLOCT'] = 'LocoType.prloct(input_data, Params)\n' commands['PXLOCT'] = 'LocoType.extract_to_file(Params)\n' #order commands['LEMPTY'] = 'Order.lempty(input_data)' commands['LORDER'] = 'Order.lorder(input_data)' commands['LXORDR'] = 'Order.dump_to_screen()\n' commands['DEMPTY'] = 'Order.dempty(input_data)' commands['PEMPTY'] = 'Order.pempty(input_data, Params)\n' commands['PXORDR'] = 'Order.extract_to_file(Params)\n' #parameter commands['CHPARM'] = 'Params.chparm(input_data)\n' commands['CSPEED'] = 'Params.cspeed(input_data)\n' commands['LIPARM'] = 'Params.liparm(input_data)\n' commands['PRPARM'] = 'Params.prparm(input_data, Params)\n' commands['LXPARM'] = 'Params.dump_to_screen()\n' commands['PXPARM'] = 'Params.extract_to_file(Params)\n' commands['SETTIM'] = 'Params.settim(input_data)\n' commands['XXSTOP'] = 'Params.xxstop()\n' #place commands['ADPLAX'] = 'Place.adplax(input_data)\n' commands['ADINDY'] = 'Place.adindy(input_data)\n' commands['CHPLAX'] = 'Place.chplax(input_data)\n' commands['CHINDY'] = 'Place.chindy(input_data)\n' commands['DXPLAX'] = 'Place.dxplax(input_data)\n' commands['DXINDY'] = 'Place.dxindy(input_data)\n' commands['LIPLAX'] = 'Place.liplax(input_data)\n' commands['LIGEOG'] = 'Place.ligeog(input_data)\n' commands['LXPLAX'] = 'Place.dump_to_screen()\n' commands['PRPLAX'] = 'Place.prplax(input_data, Params)\n' commands['PRGEOG'] = 'Place.prgeog(input_data, Params)\n' commands['PXPLAX'] = 'Place.extract_to_file(Params)\n' #railroad commands['ADRAIL'] = 'Railroad.adrail(input_data)\n' commands['CHRAIL'] = 'Railroad.chrail(input_data)\n' commands['DXRAIL'] = 'Railroad.dxrail(input_data)\n' commands['LIRAIL'] = 'Railroad.lirail(input_data)\n' commands['LXRAIL'] = 'Railroad.dump_to_screen()\n' commands['PRRAIL'] = 'Railroad.prrail(input_data, Params)\n' commands['PXRAIL'] = 'Railroad.extract_to_file(Params)\n' #route commands['ADROUT'] = 'Route.adrout(input_data, Params)\n' #Rev 1 commands['CHROUT'] = 'Route.chrout(input_data)\n' commands['DXROUT'] = 'Route.dxrout(input_data)\n' commands['LIROUT'] = 'Route.lirout(input_data)\n' commands['LXROUT'] = 'Route.dump_to_screen()\n' commands['PRROUT'] = 'Route.prrout(input_data, Params)\n' commands['UNPUBL'] = 'Route.unpubl(input_data)\n' commands['PUBLSH'] = 'Route.publsh(input_data)\n' commands['PXROUT'] = 'Route.extract_to_file(Params)\n' commands['VALIDR'] = 'Route.validr(input_data)\n' #routing code commands['ADCURO'] = 'Routing.adcuro(input_data)\n' commands['CHCURO'] = 'Routing.chcuro(input_data)\n' commands['DXCURO'] = 'Routing.dxcuro(input_data)\n' commands['LICURO'] = 'Routing.licuro(input_data)\n' commands['LXCURO'] = 'Routing.dump_to_screen()\n' commands['PRCURO'] = 'Routing.prcuro(input_data, Params)\n' commands['PXCURO'] = 'Routing.extract_to_file(Params)\n' #schedule commands['ADSCHD'] = 'Schedule.adschd(input_data)\n' commands['CHSCHD'] = 'Schedule.chschd(input_data)\n' commands['CPSCHD'] = 'Schedule.cpschd(input_data)\n' commands['DXSCHD'] = 'Schedule.dxschd(input_data)\n' commands['CXSCHD'] = 'Schedule.cxschd(input_data, Params)\n' commands['XCTIVE'] = 'Schedule.xctive(input_data)\n' commands['LISCHD'] = 'Schedule.lischd(input_data)\n' commands['LSSCHD'] = 'Schedule.lsschd(input_data)\n' commands['LXSCHD'] = 'Schedule.dump_to_screen()\n' commands['ACTIVE'] = 'Schedule.active(input_data)\n' commands['PRSCHD'] = 'Schedule.prschd(input_data, Params)\n' commands['PXSCHD'] = 'Schedule.extract_to_file(Params)\n' commands['PRTABL'] = 'Schedule.prtabl(input_data, user_type, user_id)\n' commands['PXTABL'] = 'Schedule.pxtabl(input_data, user_type, user_id)\n' #section commands['ADSECT'] = 'Section.adsect(input_data)\n' commands['DXSECT'] = 'Section.dxsect(input_data)\n' commands['LXSECT'] = 'Section.dump_to_screen()\n' commands['LSROUT'] = 'Section.lsrout(input_data)\n' commands['LDROUT'] = 'Section.ldrout(input_data)\n' commands['PDROUT'] = 'Section.pdrout(input_data, Params)\n' commands['PXSECT'] = 'Section.extract_to_file(Params)\n' #stations commands['ADSTAX'] = 'Station.adstax(input_data, Params)\n' commands['CHSTAX'] = 'Station.chstax(input_data, Params)\n' commands['DXSTAX'] = 'Station.dxstax(input_data)\n' commands['LISTAX'] = 'Station.listax(input_data)\n' commands['LXSTAX'] = 'Station.dump_to_screen()\n' commands['PRSTAX'] = 'Station.prstax(input_data, Params)\n' commands['PXSTAX'] = 'Station.extract_to_file(Params)\n' #station types commands['ADSTAT'] = 'StationType.adstat(input_data)\n' commands['CHSTAT'] = 'StationType.chstat(input_data)\n' commands['DXSTAT'] = 'StationType.dxstat(input_data)\n' commands['LISTAT'] = 'StationType.listat(input_data)\n' commands['LXSTAT'] = 'StationType.dump_to_screen()\n' commands['PRSTAT'] = 'StationType.prstat(input_data, Params)\n' commands['PXSTAT'] = 'StationType.extract_to_file(Params)\n' #timings commands['ADTIMS'] = 'Timings.adtims(input_data)\n' commands['CHTIMS'] = 'Timings.chtims(input_data)\n' commands['TIMING'] = 'Timings.timing(input_data)\n' commands['LDTIMS'] = 'Timings.ldtims(input_data)\n' commands['PRTIMS'] = 'Timings.prtims(input_data, Params)\n' commands['PXTIMS'] = 'Timings.extract_to_file(Params)\n' #train commands['UTRAIN'] = 'Train.utrain(input_data, Params)\n' commands['STRAIN'] = 'Train.strain(input_data, Params)\n' commands['ETRAIN'] = 'Train.etrain(input_data, Params)\n' commands['ALOCOT'] = 'Train.alocot(input_data)\n' commands['ACARXT'] = 'Train.acarxt(input_data)\n' commands['LTRAIN'] = 'Train.ltrain(input_data, Flash, Params)\n' commands['LINEUP'] = 'Train.lineup(input_data, Params)\n' #Rev 1 commands['REPORT'] = 'Train.report(input_data, Params)\n' commands['TTRAIN'] = 'Train.ttrain(input_data, Flash, Params)\n' commands['XLOCOT'] = 'Train.xlocot(input_data)\n' commands['XCARXT'] = 'Train.xcarxt(input_data)\n' commands['TRAINS'] = 'Train.trains(input_data)\n' commands['LICONS'] = 'Train.licons(input_data, Params)\n' #Rev 1 commands['PRCONS'] = 'Train.prcons(input_data, Params)\n' #users commands['ADUSER'] = 'User.aduser(input_data)\n' commands['CHPASS'] = 'User.chpass(uid)\n' commands['CHUSER'] = 'User.chuser(input_data)\n' commands['DXUSER'] = 'User.dxuser(input_data)\n' commands['EDUSER'] = 'User.eduser(input_data)\n' commands['LIUSER'] = 'User.liuser(input_data)\n' commands['LXUSER'] = 'User.dump_to_screen()\n' commands['PRUSER'] = 'User.pruser(input_data, Params)\n' commands['PXUSER'] = 'User.extract_to_file(Params)\n' commands['RESETP'] = 'User.resetp(input_data)\n' #warehouses commands['ADWARE'] = 'Warehouse.adware(input_data)\n' commands['CHWARE'] = 'Warehouse.chware(input_data)\n' commands['CPWARE'] = 'Warehouse.cpware(input_data)\n' commands['DXWARE'] = 'Warehouse.dxware(input_data)\n' commands['LIWARE'] = 'Warehouse.liware(input_data)\n' commands['LDWARE'] = 'Warehouse.ldware(input_data)\n' commands['LSWARE'] = 'Warehouse.lsware(input_data)\n' commands['LXWARE'] = 'Warehouse.dump_to_screen()\n' commands['PRWARE'] = 'Warehouse.prware(input_data, Params)\n' commands['PXWARE'] = 'Warehouse.extract_to_file(Params)\n' return commands def load_helper(helper): """Loads short descriptions about commands into an array """ #areas helper['ADAREA'] = 'ADD AREA' helper['CHAREA'] = 'CHANGE AREA' helper['DXAREA'] = 'DELETE AREA' helper['LIAREA'] = 'LIST AREAS' helper['LXAREA'] = 'SHOW AREAS FILE' helper['PRAREA'] = 'PRINT AREAS' helper['PXAREA'] = 'EXPORT AREAS' #calendar helper['HOLIDX'] = 'SET HOLIDAY' helper['LICALX'] = 'LIST NEXT 10 DAYS' #car helper['ADCARX'] = 'ADD CAR DETAIL' helper['ACARXB'] = 'ALLOCATE CAR TO BLOCK' helper['ACARXS'] = 'ALLOCATE CAR TO SET' helper['CARXAT'] = 'LOCATE CAR AT STATION' helper['CHCARX'] = 'CHANGE CAR DETAILS' helper['CLEANX'] = 'SET CAR TO EMPTY/CLEAN' helper['MAINTC'] = 'CHANGE CAR MAINTENANCE STATE' helper['CXCARS'] = 'CHANGE CAR LOCATION' helper['DXCARX'] = 'DELETE CAR' helper['LICARS'] = 'LIST CARS' helper['LACARS'] = 'REPORT CARS BY STATUS' helper['LMTCAR'] = 'REPORT UNALLOCATED EMPTY CARS' helper['LONWAY'] = 'REPORT EMPTIES EN ROUTE' helper['LXCARS'] = 'SHOW CARS FILE' helper['MTYORD'] = 'ALLOCATE EMPTY TO ORDER' helper['PRCARS'] = 'PRINT CARS' helper['PXCARS'] = 'EXPORT CARS' helper['CARXSP'] = 'SPOT CAR' helper['XCARXB'] = 'REMOVE CAR FROM BLOCK' helper['XCARXS'] = 'REMOVE CAR FROM SET' #carclass helper['ADCLAS'] = 'ADD CAR CLASSIFICATION' helper['CHCLAS'] = 'CHANGE CAR CLASSSIFICATION' helper['DXCLAS'] = 'DELETE CAR CLASSIFICATION' helper['LICLAS'] = 'LIST CAR CLASSIFICATIONS' helper['LXCLAS'] = 'SHOW CAR CLASSIFICATIONS FILE' helper['PRCLAS'] = 'PRINT CAR CLASSIFICATIONS' helper['PXCLAS'] = 'EXPORT CAR CLASSIFICATIONS' #carbuild helper['ADCART'] = 'ADD CAR TYPE' helper['CHCART'] = 'CHANGE CAR TYPE' helper['DXCART'] = 'DELETE CAR TYPE' helper['LICART'] = 'LIST CAR TYPES' helper['LXCART'] = 'SHOW CAR TYPES FILE' helper['PRCART'] = 'PRINT CAR TYPES' helper['PXCART'] = 'EXPORT CAR TYPES' #commodities helper['ADCOMM'] = 'ADD COMMODITY' helper['CHCOMM'] = 'CHANGE COMMODITY' helper['DXCOMM'] = 'DELETE COMMODITY' helper['LICOMM'] = 'LIST COMMODITIES' helper['LXCOMM'] = 'SHOW COMMODITIES FILE' helper['PRCOMM'] = 'PRINT COMMODITIES' helper['PXCOMM'] = 'EXPORT COMMODITIES' #flash helper['FLASHX'] = 'FLASH MESSAGE' #help helper['HELP'] = 'GENERAL HELP' helper['ABOUT'] = 'ABOUT MOPS' helper['ASSIST'] = 'LIST AVAILABLE COMMANDS' #instruction helper['ADINST'] = 'ADD INSTRUCTION' helper['DXINST'] = 'DELETE INSTRUCTION' #loading helper['ADLOAD'] = 'ADD LOADING DEFINITIONS' helper['CHLOAD'] = 'CHANGE LOADING DEFINITIONS' helper['DXLOAD'] = 'DELETE LOADING DEFINITION' helper['LILOAD'] = 'LIST LOADING DEFINITIONS' helper['LXLOAD'] = 'SHOW LOADING DEFINITIONS' helper['PRLOAD'] = 'PRINT LOADING DEFINITIONS' helper['PXLOAD'] = 'EXPORT LOADING DEFINITIONS' #loco helper['ADLOCO'] = 'ADD LOCOMOTIVE' helper['FUELXX'] = 'CHANGE LOCO FUEL STATE' helper['CHLOCO'] = 'CHANGE LOCOMOTIVE' helper['MAINTL'] = 'CHANGE LOCO MAINTENANCE STATE' helper['POWERX'] = 'CHANGE LOCO POWER STATE' helper['DXLOCO'] = 'DELETE LOCOMOTIVE' helper['LILOCO'] = 'LIST LOCOMOTIVES' helper['LOCOAT'] = 'LOCATE LOCO AT STATION' helper['LXLOCO'] = 'SHOW LOCOMOTIVE FILE' helper['PRLOCO'] = 'PRINT LOCOMOTIVES' helper['PXLOCO'] = 'EXPORT LOCOMOTIVES' helper['LOCOSP'] = 'SPOT LOCO' helper['LSLOCO'] = 'LIST LOCOMOTIVE DETAILS' helper['PSLOCO'] = 'PRINT LOCOMOTIVE DETAILS' #loco type helper['ADLOCT'] = 'ADD LOCOMOTIVE TYPE' helper['CHLOCT'] = 'CHANGE LOCOMOTIVE TYPE' helper['DXLOCT'] = 'DELETE LOCOMOTVE TYPE' helper['LILOCT'] = 'LIST LOCOMOTIVE TYPES' helper['LXLOCT'] = 'SHOW LOCOMOTIVE TYPES' helper['PRLOCT'] = 'PRINT LOCOMOTIVE TYPES' helper['PXLOCT'] = 'EXPORT LOCOMOTIVE TYPES' #order helper['LEMPTY'] = 'LIST EMPTY CAR REQUESTS' helper['LORDER'] = 'LIST EMPTY AND WAYBILL REQUESTS' helper['DEMPTY'] = 'DETAIL EMPTY CAR REQUESTS' helper['LXORDR'] = 'SHOW ORDERS FILE' helper['PEMPTY'] = 'REPORT EMPTY CAR REQUESTS' helper['PXORDR'] = 'EXPORT ORDERS FILE' #parameter helper['CHPARM'] = 'CHANGE PARAMETER' helper['CSPEED'] = 'SET MOPS CLOCK SPEED' helper['LIPARM'] = 'LIST PARAMETERS' helper['PRPARM'] = 'REPORT PARAMETERS' helper['LXPARM'] = 'SHOW PARAMETERS' helper['PXPARM'] = 'EXPORT PARAMETERS' helper['SETTIM'] = 'SET MOPS DATE AND TIME' helper['XXSTOP'] = 'STOP MOPS' #place helper['ADPLAX'] = 'ADD PLACE' helper['CHPLAX'] = 'CHANGE PLACE' helper['DXPLAX'] = 'DELETE PLACE' helper['ADINDY'] = 'ADD INDUSTRY' helper['CHINDY'] = 'CHANGE INDUSTRY' helper['DXINDY'] = 'DELETE INDUSTRY' helper['LIPLAX'] = 'LIST PLACES' helper['LXPLAX'] = 'SHOW PLACES FILE' helper['PRPLAX'] = 'PRINT PLACES' helper['PRGEOG'] = 'PRINT GEOGRAPHY' helper['LIGEOG'] = 'PRINT GEOGRAPHY' helper['PXPLAX'] = 'EXPORT PLACES' #railroad helper['ADRAIL'] = 'ADD RAILROAD' helper['CHRAIL'] = 'CHANGE RAILROAD' helper['DXRAIL'] = 'DELETE RAILROAD' helper['LIRAIL'] = 'LIST RAILROADS' helper['LXRAIL'] = 'SHOW RAILROAD FILE' helper['PRRAIL'] = 'PRINT RAILROADS' helper['PXRAIL'] = 'EXPORT RAILROADS' #route helper['ADROUT'] = 'ADD ROUTE' helper['CHROUT'] = 'CHANGE ROUTE NAME' helper['DXROUT'] = 'DELETE ROUTE' helper['LIROUT'] = 'LIST ALL ROUTES' helper['LXROUT'] = 'SHOW ROUTES FILE' helper['PRROUT'] = 'PRINT ALL ROUTES' helper['UNPUBL'] = 'SET PUBLISHED ROUTE TO DRAFT' helper['PUBLSH'] = 'PUBLISH ROUTE' helper['PXROUT'] = 'EXPORT ALL ROUTES' helper['VALIDR'] = 'VALIDATE ROUTE' #routing code helper['ADCURO'] = 'ADD CUSTOMER ROUTING INFORMATION' helper['CHCURO'] = 'CHANGE CUSTOMER ROUTING INFORMATION' helper['DXCURO'] = 'DELETE CUSTOMER ROUTING INFORMATION' helper['LICURO'] = 'LIST CUSTOMER ROUTING INFORMATION' helper['LXCURO'] = 'SHOW CUSTOMER ROUTINGS FILE' helper['PRCURO'] = 'PRINT CUSTOMER ROUTING INFORMATION' helper['PXCURO'] = 'EXPORT ROUTINGS' #schedule helper['ADSCHD'] = 'ADD SCHEDULE' helper['CHSCHD'] = 'CHANGE SCHEDULE' helper['CPSCHD'] = 'COPY SCHEDULE' helper['DXSCHD'] = 'DELETE SCHEDULE' helper['CXSCHD'] = 'CANCEL SCHEDULE' helper['ACTIVE'] = 'ACTIVATE SCHEDULE' helper['XCTIVE'] = 'SET SCHEDULE INACTIVE' helper['LISCHD'] = 'LIST ALL SCHEDULES' helper['LSSCHD'] = 'LIST ACTIVE/RUNNING SCHEDULES' helper['LXSCHD'] = 'SHOW SCHEDULES FILE' helper['PRSCHD'] = 'PRINT ALL SCHEDULES' helper['PRTABL'] = 'PRINT TIMETABLE' helper['PUBLIS'] = 'PUBLISH SCHEDULE' helper['PXSCHD'] = 'EXPORT ALL SCHEDULES' helper['PXTABL'] = 'EXPORT TIMETABLE' #section helper['ADSECT'] = 'ADD ROUTE SECTION' helper['DXSECT'] = 'DELETE ROUTE SECTION' helper['LDROUT'] = 'LIST DETAIL FOR SELECTED ROUTE' helper['LSROUT'] = 'LIST SECTIONS FOR ROUTE' helper['LXSECT'] = 'SHOW ALL SECTIONS' helper['PDROUT'] = 'PRINT DETAIL FOR SELECTED ROUTE' helper['PXSECT'] = 'EXPORT SECTIONS FOR ALL ROUTES' #stations helper['ADSTAX'] = 'ADD STATION' helper['CHSTAX'] = 'CHANGE STATION' helper['DXSTAX'] = 'DELETE STATION' helper['LISTAX'] = 'LIST STATIONS' helper['LXSTAX'] = 'SHOW STATIONS DATA' helper['PRSTAX'] = 'PRINT STATIONS' helper['PXSTAX'] = 'EXPORT STATIONS' #station types helper['ADSTAT'] = 'ADD STATION TYPE' helper['CHSTAT'] = 'CHANGE STATION TYPE' helper['DXSTAT'] = 'DELETE STATION TYPE' helper['LISTAT'] = 'LIST STATION TYPES' helper['PXSTAT'] = 'EXPORT STATION TYPES' helper['LXSTAT'] = 'SHOW STATION TYPE DATA' helper['PRSTAT'] = 'PRINT STATION TYPES' #timings helper['ADTIMS'] = 'ADD SCHEDULE TIMINGS' helper['CHTIMS'] = 'CHANGE SCHEDULE TIMINGS' helper['TIMING'] = 'LIST TIMINGS FOR SELECTED SCHEDULE' helper['LDTIMS'] = 'LIST TIMING RECORD DETAILS FOR SELECTED SCHEDULE' helper['PRTIMS'] = 'PRINT TIMINGS FOR SELECTED SCHEDULE' helper['PXTIMS'] = 'EXPORT TIMINGS FOR ALL SCHEDULES' #train helper['UTRAIN'] = 'SET UNSCHEDULED TRAIN' helper['STRAIN'] = 'SET SCHEDULED TRAIN' helper['ETRAIN'] = 'SET EXTRA TRAIN' helper['ACARXT'] = 'ALLOCATE CAR TO TRAIN' helper['ALOCOT'] = 'ALLOCATE LOCO TO TRAIN' helper['LTRAIN'] = 'START TRAIN AT LATER ORIGIN' helper['LINEUP'] = 'REPORT LINE-UP' helper['REPORT'] = 'REPORT TRAIN' helper['TTRAIN'] = 'TERMINATE TRAIN' helper['XLOCOT'] = 'REMOVE LOCO FROM TRAIN' helper['XCARXT'] = 'REMOVE CAR FROM TRAIN' helper['TRAINS'] = 'LIST RUNNING TRAINS' helper['LICONS'] = 'REPORT CONSIST' helper['PRCONS'] = 'PRINT CONSIST' #users helper['ADUSER'] = 'ADD USER' helper['CHPASS'] = 'CHANGE PASSWORD' helper['CHUSER'] = 'CHANGE USER' helper['DXUSER'] = 'DELETE USER' helper['EDUSER'] = 'ENABLE/DISABLE USER' helper['LIUSER'] = 'LIST USERS' helper['LXUSER'] = 'SHOW USER DATA' helper['PRUSER'] = 'PRINT USERS' helper['PXUSER'] = 'EXPORT USER DATA' helper['RESETP'] = 'RESET PASSWORD' #warehouses helper['ADWARE'] = 'ADD WAREHOUSE' helper['CHWARE'] = 'CHANGE WAREHOUSE DETAILS' helper['CPWARE'] = 'CHANGE PRODUCTION AT WAREHOUSE' helper['DXWARE'] = 'DELETE WAREHOUSE' helper['LIWARE'] = 'LIST WAREHOUSES' helper['LDWARE'] = 'LIST WAREHOUSE DETAILS' helper['LSWARE'] = 'WAREHOUSES AT STATIONS' helper['LXWARE'] = 'SHOW WAREHOUSE DATA' helper['PRWARE'] = 'PRINT WAREHOUSES' helper['PXWARE'] = 'EXPORT WAREHOUSES' #action helper['QUIT'] = 'EXIT MOPS' helper['EXIT'] = 'EXIT MOPS' return helper def assist(): """Provides a sorted list (by command name) of all the commands on the system with a short description of what the command does """ i = 0 commands = {} helpers = {} commands = load_commands(commands) helpers = load_helper(helpers) listed = list(commands.keys()) listed.sort() for entry in listed: i = i + 1 if i > 23: dummy = raw_input(' ... HIT ENTER TO CONTINUE') i = 0 try: print(entry + ' ' + helpers[entry]) except: print(entry) print(' ... END OF LIST ...') def get_helper(command): """Gets the helper (short description) information for a given command """ desc = '' helpers = {} helpers = load_helper(helpers) try: desc = helpers[command] except: desc = 'NOT FOUND' return desc
""" Commands: Basic module to handle all commands. Commands for mops are driven by one-line exec statements; these exec statements are held in a dictionary. Model Operations Processing System. Copyright Brian Fairbairn 2009-2010. Licenced under the EUPL. You may not use this work except in compliance with the Licence. You may obtain a copy of the Licence at http://ec.europa.eu/idabc/eupl or as attached with this application (see Licence file). Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an 'AS IS' basis WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either expressed or implied. See the Licence governing permissions and limitations under the Licence. Changes: Rev 1 Added Params as a parameter to CXSCHD for triMOPS Added Params as a parameter to ADROUT for default direction Added Params to LINEUP for passenger car checking Added Params to LICONS for passenger car checking """ def load_commands(commands): """This contains a list of commands to be exec'd in the main loop. The key is the input command and the value is the line to be executed (generally a class method). Command structure: verb data where verb is (almost always) a 6-figure word which translates to a class method and data is a set of parameters for the class method delimited by semi-colons Verb structure special verbs are available which equate to specific commands and these are described in the user manual or can be see below. general verbs are constructed on the following basis: chars 1 + 2 AD - Add a new item CH - Change existing item (addittional changes will be C*) DX - Delete item LI - List items (to screen) (additional list verions will be LA, LB etc) LX - unformatted list versions PA - Print items (to file) (additional print version will be PA, PB etx) PX - unformatted print versions (for .csv files) XX - Supervisor command functions chars 3-6 type of data being updated (can also use char 6) AREA - Maintain Areas USER - Maintain users TYPE - Maintain Stax Types STAX - Maintain Stax PARM - Parameter values """ commands['ADAREA'] = 'Area.adarea(input_data)\n' commands['CHAREA'] = 'Area.charea(input_data)\n' commands['DXAREA'] = 'Area.dxarea(input_data)\n' commands['LIAREA'] = 'Area.liarea(input_data)\n' commands['LXAREA'] = 'Area.dump_to_screen()\n' commands['PRAREA'] = 'Area.prarea(input_data, Params)\n' commands['PXAREA'] = 'Area.extract_to_file(Params)\n' commands['HOLIDX'] = 'Calendar.holidx(input_data)\n' commands['LICALX'] = 'Calendar.licalx(input_data)\n' commands['ADCARX'] = 'Car.adcarx(input_data)\n' commands['ACARXB'] = 'Car.acarxb(input_data)\n' commands['ACARXS'] = 'Car.acarxs(input_data)\n' commands['CARXAT'] = 'Car.carxat(input_data)\n' commands['CHCARX'] = 'Car.chcarx(input_data)\n' commands['CLEANX'] = 'Car.cleanx(input_data)\n' commands['MAINTC'] = 'Car.maintc(input_data)\n' commands['CXCARS'] = 'Car.cxcars(input_data)\n' commands['DXCARX'] = 'Car.dxcarx(input_data)\n' commands['LACARS'] = 'Car.lacars(input_data)\n' commands['LICARS'] = 'Car.licars(input_data)\n' commands['LMTCAR'] = 'Car.lmtcar(input_data)\n' commands['LONWAY'] = 'Car.lonway(input_data)\n' commands['LXCARS'] = 'Car.dump_to_screen()\n' commands['MTYORD'] = 'Car.mtyord(input_data)\n' commands['PRCARS'] = 'Car.prcars(input_data, Params)\n' commands['PXCARS'] = 'Car.extract_to_file(Params)\n' commands['CARXSP'] = 'Car.carxsp(input_data)\n' commands['XCARXB'] = 'Car.xcarxb(input_data)\n' commands['XCARXS'] = 'Car.xcarxs(input_data)\n' commands['ADCLAS'] = 'CarClass.adclas(input_data)\n' commands['CHCLAS'] = 'CarClass.chclas(input_data)\n' commands['DXCLAS'] = 'CarClass.dxclas(input_data)\n' commands['LICLAS'] = 'CarClass.liclas(input_data)\n' commands['LXCLAS'] = 'CarClass.dump_to_screen()\n' commands['PRCLAS'] = 'CarClass.prclas(input_data, Params)\n' commands['PXCLAS'] = 'CarClass.extract_to_file(Params)\n' commands['ADCART'] = 'CarType.adcart(input_data)\n' commands['CHCART'] = 'CarType.chcart(input_data)\n' commands['DXCART'] = 'CarType.dxcart(input_data)\n' commands['LICART'] = 'CarType.licart(input_data)\n' commands['LXCART'] = 'CarType.dump_to_screen()\n' commands['PRCART'] = 'CarType.prcart(input_data, Params,)\n' commands['PXCART'] = 'CarType.extract_to_file(Params)\n' commands['ADCOMM'] = 'Commodity.adcomm(input_data)\n' commands['CHCOMM'] = 'Commodity.chcomm(input_data)\n' commands['DXCOMM'] = 'Commodity.dxcomm(input_data)\n' commands['LICOMM'] = 'Commodity.licomm(input_data)\n' commands['LXCOMM'] = 'Commodity.dump_to_screen()\n' commands['PRCOMM'] = 'Commodity.prcomm(input_data, Params)\n' commands['PXCOMM'] = 'Commodity.extract_to_file(Params)\n' commands['FLASHX'] = 'Flash.flashx(input_data, Params)\n' commands['ABOUT'] = 'MOPS_Help.about()\n' commands['HELP'] = 'MOPS_Help.help()\n' commands['ASSIST'] = 'MOPS_Commands.assist()\n' commands['ADINST'] = 'Instruction.adinst(input_data)\n' commands['DXINST'] = 'Instruction.dxinst(input_data)\n' commands['ADLOAD'] = 'Loading.adload(input_data)\n' commands['CHLOAD'] = 'Loading.chload(input_data)\n' commands['DXLOAD'] = 'Loading.dxload(input_data)\n' commands['LILOAD'] = 'Loading.liload(input_data)\n' commands['LXLOAD'] = 'Loading.dump_to_screen()\n' commands['PRLOAD'] = 'Loading.prload(input_data, Params)\n' commands['PXLOAD'] = 'Loading.extract_to_file(Params)\n' commands['ADLOCO'] = 'Loco.adloco(input_data)\n' commands['FUELXX'] = 'Loco.fuelxx(input_data)\n' commands['CHLOCO'] = 'Loco.chloco(input_data)\n' commands['MAINTL'] = 'Loco.maintl(input_data)\n' commands['POWERX'] = 'Loco.powerx(input_data)\n' commands['DXLOCO'] = 'Loco.dxloco(input_data)\n' commands['LOCOAT'] = 'Loco.locoat(input_data)\n' commands['LOCOSP'] = 'Loco.locosp(input_data)\n' commands['LILOCO'] = 'Loco.liloco(input_data)\n' commands['LSLOCO'] = 'Loco.lsloco(input_data)\n' commands['LXLOCO'] = 'Loco.dump_to_screen()\n' commands['PRLOCO'] = 'Loco.prloco(input_data, Params)\n' commands['PSLOCO'] = 'Loco.psloco(input_data, Params)\n' commands['PXLOCO'] = 'Loco.extract_to_file(Params)\n' commands['ADLOCT'] = 'LocoType.adloct(input_data)\n' commands['CHLOCT'] = 'LocoType.chloct(input_data)\n' commands['DXLOCT'] = 'LocoType.dxloct(input_data)\n' commands['LILOCT'] = 'LocoType.liloct(input_data)' commands['LXLOCT'] = 'LocoType.dump_to_screen()\n' commands['PRLOCT'] = 'LocoType.prloct(input_data, Params)\n' commands['PXLOCT'] = 'LocoType.extract_to_file(Params)\n' commands['LEMPTY'] = 'Order.lempty(input_data)' commands['LORDER'] = 'Order.lorder(input_data)' commands['LXORDR'] = 'Order.dump_to_screen()\n' commands['DEMPTY'] = 'Order.dempty(input_data)' commands['PEMPTY'] = 'Order.pempty(input_data, Params)\n' commands['PXORDR'] = 'Order.extract_to_file(Params)\n' commands['CHPARM'] = 'Params.chparm(input_data)\n' commands['CSPEED'] = 'Params.cspeed(input_data)\n' commands['LIPARM'] = 'Params.liparm(input_data)\n' commands['PRPARM'] = 'Params.prparm(input_data, Params)\n' commands['LXPARM'] = 'Params.dump_to_screen()\n' commands['PXPARM'] = 'Params.extract_to_file(Params)\n' commands['SETTIM'] = 'Params.settim(input_data)\n' commands['XXSTOP'] = 'Params.xxstop()\n' commands['ADPLAX'] = 'Place.adplax(input_data)\n' commands['ADINDY'] = 'Place.adindy(input_data)\n' commands['CHPLAX'] = 'Place.chplax(input_data)\n' commands['CHINDY'] = 'Place.chindy(input_data)\n' commands['DXPLAX'] = 'Place.dxplax(input_data)\n' commands['DXINDY'] = 'Place.dxindy(input_data)\n' commands['LIPLAX'] = 'Place.liplax(input_data)\n' commands['LIGEOG'] = 'Place.ligeog(input_data)\n' commands['LXPLAX'] = 'Place.dump_to_screen()\n' commands['PRPLAX'] = 'Place.prplax(input_data, Params)\n' commands['PRGEOG'] = 'Place.prgeog(input_data, Params)\n' commands['PXPLAX'] = 'Place.extract_to_file(Params)\n' commands['ADRAIL'] = 'Railroad.adrail(input_data)\n' commands['CHRAIL'] = 'Railroad.chrail(input_data)\n' commands['DXRAIL'] = 'Railroad.dxrail(input_data)\n' commands['LIRAIL'] = 'Railroad.lirail(input_data)\n' commands['LXRAIL'] = 'Railroad.dump_to_screen()\n' commands['PRRAIL'] = 'Railroad.prrail(input_data, Params)\n' commands['PXRAIL'] = 'Railroad.extract_to_file(Params)\n' commands['ADROUT'] = 'Route.adrout(input_data, Params)\n' commands['CHROUT'] = 'Route.chrout(input_data)\n' commands['DXROUT'] = 'Route.dxrout(input_data)\n' commands['LIROUT'] = 'Route.lirout(input_data)\n' commands['LXROUT'] = 'Route.dump_to_screen()\n' commands['PRROUT'] = 'Route.prrout(input_data, Params)\n' commands['UNPUBL'] = 'Route.unpubl(input_data)\n' commands['PUBLSH'] = 'Route.publsh(input_data)\n' commands['PXROUT'] = 'Route.extract_to_file(Params)\n' commands['VALIDR'] = 'Route.validr(input_data)\n' commands['ADCURO'] = 'Routing.adcuro(input_data)\n' commands['CHCURO'] = 'Routing.chcuro(input_data)\n' commands['DXCURO'] = 'Routing.dxcuro(input_data)\n' commands['LICURO'] = 'Routing.licuro(input_data)\n' commands['LXCURO'] = 'Routing.dump_to_screen()\n' commands['PRCURO'] = 'Routing.prcuro(input_data, Params)\n' commands['PXCURO'] = 'Routing.extract_to_file(Params)\n' commands['ADSCHD'] = 'Schedule.adschd(input_data)\n' commands['CHSCHD'] = 'Schedule.chschd(input_data)\n' commands['CPSCHD'] = 'Schedule.cpschd(input_data)\n' commands['DXSCHD'] = 'Schedule.dxschd(input_data)\n' commands['CXSCHD'] = 'Schedule.cxschd(input_data, Params)\n' commands['XCTIVE'] = 'Schedule.xctive(input_data)\n' commands['LISCHD'] = 'Schedule.lischd(input_data)\n' commands['LSSCHD'] = 'Schedule.lsschd(input_data)\n' commands['LXSCHD'] = 'Schedule.dump_to_screen()\n' commands['ACTIVE'] = 'Schedule.active(input_data)\n' commands['PRSCHD'] = 'Schedule.prschd(input_data, Params)\n' commands['PXSCHD'] = 'Schedule.extract_to_file(Params)\n' commands['PRTABL'] = 'Schedule.prtabl(input_data, user_type, user_id)\n' commands['PXTABL'] = 'Schedule.pxtabl(input_data, user_type, user_id)\n' commands['ADSECT'] = 'Section.adsect(input_data)\n' commands['DXSECT'] = 'Section.dxsect(input_data)\n' commands['LXSECT'] = 'Section.dump_to_screen()\n' commands['LSROUT'] = 'Section.lsrout(input_data)\n' commands['LDROUT'] = 'Section.ldrout(input_data)\n' commands['PDROUT'] = 'Section.pdrout(input_data, Params)\n' commands['PXSECT'] = 'Section.extract_to_file(Params)\n' commands['ADSTAX'] = 'Station.adstax(input_data, Params)\n' commands['CHSTAX'] = 'Station.chstax(input_data, Params)\n' commands['DXSTAX'] = 'Station.dxstax(input_data)\n' commands['LISTAX'] = 'Station.listax(input_data)\n' commands['LXSTAX'] = 'Station.dump_to_screen()\n' commands['PRSTAX'] = 'Station.prstax(input_data, Params)\n' commands['PXSTAX'] = 'Station.extract_to_file(Params)\n' commands['ADSTAT'] = 'StationType.adstat(input_data)\n' commands['CHSTAT'] = 'StationType.chstat(input_data)\n' commands['DXSTAT'] = 'StationType.dxstat(input_data)\n' commands['LISTAT'] = 'StationType.listat(input_data)\n' commands['LXSTAT'] = 'StationType.dump_to_screen()\n' commands['PRSTAT'] = 'StationType.prstat(input_data, Params)\n' commands['PXSTAT'] = 'StationType.extract_to_file(Params)\n' commands['ADTIMS'] = 'Timings.adtims(input_data)\n' commands['CHTIMS'] = 'Timings.chtims(input_data)\n' commands['TIMING'] = 'Timings.timing(input_data)\n' commands['LDTIMS'] = 'Timings.ldtims(input_data)\n' commands['PRTIMS'] = 'Timings.prtims(input_data, Params)\n' commands['PXTIMS'] = 'Timings.extract_to_file(Params)\n' commands['UTRAIN'] = 'Train.utrain(input_data, Params)\n' commands['STRAIN'] = 'Train.strain(input_data, Params)\n' commands['ETRAIN'] = 'Train.etrain(input_data, Params)\n' commands['ALOCOT'] = 'Train.alocot(input_data)\n' commands['ACARXT'] = 'Train.acarxt(input_data)\n' commands['LTRAIN'] = 'Train.ltrain(input_data, Flash, Params)\n' commands['LINEUP'] = 'Train.lineup(input_data, Params)\n' commands['REPORT'] = 'Train.report(input_data, Params)\n' commands['TTRAIN'] = 'Train.ttrain(input_data, Flash, Params)\n' commands['XLOCOT'] = 'Train.xlocot(input_data)\n' commands['XCARXT'] = 'Train.xcarxt(input_data)\n' commands['TRAINS'] = 'Train.trains(input_data)\n' commands['LICONS'] = 'Train.licons(input_data, Params)\n' commands['PRCONS'] = 'Train.prcons(input_data, Params)\n' commands['ADUSER'] = 'User.aduser(input_data)\n' commands['CHPASS'] = 'User.chpass(uid)\n' commands['CHUSER'] = 'User.chuser(input_data)\n' commands['DXUSER'] = 'User.dxuser(input_data)\n' commands['EDUSER'] = 'User.eduser(input_data)\n' commands['LIUSER'] = 'User.liuser(input_data)\n' commands['LXUSER'] = 'User.dump_to_screen()\n' commands['PRUSER'] = 'User.pruser(input_data, Params)\n' commands['PXUSER'] = 'User.extract_to_file(Params)\n' commands['RESETP'] = 'User.resetp(input_data)\n' commands['ADWARE'] = 'Warehouse.adware(input_data)\n' commands['CHWARE'] = 'Warehouse.chware(input_data)\n' commands['CPWARE'] = 'Warehouse.cpware(input_data)\n' commands['DXWARE'] = 'Warehouse.dxware(input_data)\n' commands['LIWARE'] = 'Warehouse.liware(input_data)\n' commands['LDWARE'] = 'Warehouse.ldware(input_data)\n' commands['LSWARE'] = 'Warehouse.lsware(input_data)\n' commands['LXWARE'] = 'Warehouse.dump_to_screen()\n' commands['PRWARE'] = 'Warehouse.prware(input_data, Params)\n' commands['PXWARE'] = 'Warehouse.extract_to_file(Params)\n' return commands def load_helper(helper): """Loads short descriptions about commands into an array """ helper['ADAREA'] = 'ADD AREA' helper['CHAREA'] = 'CHANGE AREA' helper['DXAREA'] = 'DELETE AREA' helper['LIAREA'] = 'LIST AREAS' helper['LXAREA'] = 'SHOW AREAS FILE' helper['PRAREA'] = 'PRINT AREAS' helper['PXAREA'] = 'EXPORT AREAS' helper['HOLIDX'] = 'SET HOLIDAY' helper['LICALX'] = 'LIST NEXT 10 DAYS' helper['ADCARX'] = 'ADD CAR DETAIL' helper['ACARXB'] = 'ALLOCATE CAR TO BLOCK' helper['ACARXS'] = 'ALLOCATE CAR TO SET' helper['CARXAT'] = 'LOCATE CAR AT STATION' helper['CHCARX'] = 'CHANGE CAR DETAILS' helper['CLEANX'] = 'SET CAR TO EMPTY/CLEAN' helper['MAINTC'] = 'CHANGE CAR MAINTENANCE STATE' helper['CXCARS'] = 'CHANGE CAR LOCATION' helper['DXCARX'] = 'DELETE CAR' helper['LICARS'] = 'LIST CARS' helper['LACARS'] = 'REPORT CARS BY STATUS' helper['LMTCAR'] = 'REPORT UNALLOCATED EMPTY CARS' helper['LONWAY'] = 'REPORT EMPTIES EN ROUTE' helper['LXCARS'] = 'SHOW CARS FILE' helper['MTYORD'] = 'ALLOCATE EMPTY TO ORDER' helper['PRCARS'] = 'PRINT CARS' helper['PXCARS'] = 'EXPORT CARS' helper['CARXSP'] = 'SPOT CAR' helper['XCARXB'] = 'REMOVE CAR FROM BLOCK' helper['XCARXS'] = 'REMOVE CAR FROM SET' helper['ADCLAS'] = 'ADD CAR CLASSIFICATION' helper['CHCLAS'] = 'CHANGE CAR CLASSSIFICATION' helper['DXCLAS'] = 'DELETE CAR CLASSIFICATION' helper['LICLAS'] = 'LIST CAR CLASSIFICATIONS' helper['LXCLAS'] = 'SHOW CAR CLASSIFICATIONS FILE' helper['PRCLAS'] = 'PRINT CAR CLASSIFICATIONS' helper['PXCLAS'] = 'EXPORT CAR CLASSIFICATIONS' helper['ADCART'] = 'ADD CAR TYPE' helper['CHCART'] = 'CHANGE CAR TYPE' helper['DXCART'] = 'DELETE CAR TYPE' helper['LICART'] = 'LIST CAR TYPES' helper['LXCART'] = 'SHOW CAR TYPES FILE' helper['PRCART'] = 'PRINT CAR TYPES' helper['PXCART'] = 'EXPORT CAR TYPES' helper['ADCOMM'] = 'ADD COMMODITY' helper['CHCOMM'] = 'CHANGE COMMODITY' helper['DXCOMM'] = 'DELETE COMMODITY' helper['LICOMM'] = 'LIST COMMODITIES' helper['LXCOMM'] = 'SHOW COMMODITIES FILE' helper['PRCOMM'] = 'PRINT COMMODITIES' helper['PXCOMM'] = 'EXPORT COMMODITIES' helper['FLASHX'] = 'FLASH MESSAGE' helper['HELP'] = 'GENERAL HELP' helper['ABOUT'] = 'ABOUT MOPS' helper['ASSIST'] = 'LIST AVAILABLE COMMANDS' helper['ADINST'] = 'ADD INSTRUCTION' helper['DXINST'] = 'DELETE INSTRUCTION' helper['ADLOAD'] = 'ADD LOADING DEFINITIONS' helper['CHLOAD'] = 'CHANGE LOADING DEFINITIONS' helper['DXLOAD'] = 'DELETE LOADING DEFINITION' helper['LILOAD'] = 'LIST LOADING DEFINITIONS' helper['LXLOAD'] = 'SHOW LOADING DEFINITIONS' helper['PRLOAD'] = 'PRINT LOADING DEFINITIONS' helper['PXLOAD'] = 'EXPORT LOADING DEFINITIONS' helper['ADLOCO'] = 'ADD LOCOMOTIVE' helper['FUELXX'] = 'CHANGE LOCO FUEL STATE' helper['CHLOCO'] = 'CHANGE LOCOMOTIVE' helper['MAINTL'] = 'CHANGE LOCO MAINTENANCE STATE' helper['POWERX'] = 'CHANGE LOCO POWER STATE' helper['DXLOCO'] = 'DELETE LOCOMOTIVE' helper['LILOCO'] = 'LIST LOCOMOTIVES' helper['LOCOAT'] = 'LOCATE LOCO AT STATION' helper['LXLOCO'] = 'SHOW LOCOMOTIVE FILE' helper['PRLOCO'] = 'PRINT LOCOMOTIVES' helper['PXLOCO'] = 'EXPORT LOCOMOTIVES' helper['LOCOSP'] = 'SPOT LOCO' helper['LSLOCO'] = 'LIST LOCOMOTIVE DETAILS' helper['PSLOCO'] = 'PRINT LOCOMOTIVE DETAILS' helper['ADLOCT'] = 'ADD LOCOMOTIVE TYPE' helper['CHLOCT'] = 'CHANGE LOCOMOTIVE TYPE' helper['DXLOCT'] = 'DELETE LOCOMOTVE TYPE' helper['LILOCT'] = 'LIST LOCOMOTIVE TYPES' helper['LXLOCT'] = 'SHOW LOCOMOTIVE TYPES' helper['PRLOCT'] = 'PRINT LOCOMOTIVE TYPES' helper['PXLOCT'] = 'EXPORT LOCOMOTIVE TYPES' helper['LEMPTY'] = 'LIST EMPTY CAR REQUESTS' helper['LORDER'] = 'LIST EMPTY AND WAYBILL REQUESTS' helper['DEMPTY'] = 'DETAIL EMPTY CAR REQUESTS' helper['LXORDR'] = 'SHOW ORDERS FILE' helper['PEMPTY'] = 'REPORT EMPTY CAR REQUESTS' helper['PXORDR'] = 'EXPORT ORDERS FILE' helper['CHPARM'] = 'CHANGE PARAMETER' helper['CSPEED'] = 'SET MOPS CLOCK SPEED' helper['LIPARM'] = 'LIST PARAMETERS' helper['PRPARM'] = 'REPORT PARAMETERS' helper['LXPARM'] = 'SHOW PARAMETERS' helper['PXPARM'] = 'EXPORT PARAMETERS' helper['SETTIM'] = 'SET MOPS DATE AND TIME' helper['XXSTOP'] = 'STOP MOPS' helper['ADPLAX'] = 'ADD PLACE' helper['CHPLAX'] = 'CHANGE PLACE' helper['DXPLAX'] = 'DELETE PLACE' helper['ADINDY'] = 'ADD INDUSTRY' helper['CHINDY'] = 'CHANGE INDUSTRY' helper['DXINDY'] = 'DELETE INDUSTRY' helper['LIPLAX'] = 'LIST PLACES' helper['LXPLAX'] = 'SHOW PLACES FILE' helper['PRPLAX'] = 'PRINT PLACES' helper['PRGEOG'] = 'PRINT GEOGRAPHY' helper['LIGEOG'] = 'PRINT GEOGRAPHY' helper['PXPLAX'] = 'EXPORT PLACES' helper['ADRAIL'] = 'ADD RAILROAD' helper['CHRAIL'] = 'CHANGE RAILROAD' helper['DXRAIL'] = 'DELETE RAILROAD' helper['LIRAIL'] = 'LIST RAILROADS' helper['LXRAIL'] = 'SHOW RAILROAD FILE' helper['PRRAIL'] = 'PRINT RAILROADS' helper['PXRAIL'] = 'EXPORT RAILROADS' helper['ADROUT'] = 'ADD ROUTE' helper['CHROUT'] = 'CHANGE ROUTE NAME' helper['DXROUT'] = 'DELETE ROUTE' helper['LIROUT'] = 'LIST ALL ROUTES' helper['LXROUT'] = 'SHOW ROUTES FILE' helper['PRROUT'] = 'PRINT ALL ROUTES' helper['UNPUBL'] = 'SET PUBLISHED ROUTE TO DRAFT' helper['PUBLSH'] = 'PUBLISH ROUTE' helper['PXROUT'] = 'EXPORT ALL ROUTES' helper['VALIDR'] = 'VALIDATE ROUTE' helper['ADCURO'] = 'ADD CUSTOMER ROUTING INFORMATION' helper['CHCURO'] = 'CHANGE CUSTOMER ROUTING INFORMATION' helper['DXCURO'] = 'DELETE CUSTOMER ROUTING INFORMATION' helper['LICURO'] = 'LIST CUSTOMER ROUTING INFORMATION' helper['LXCURO'] = 'SHOW CUSTOMER ROUTINGS FILE' helper['PRCURO'] = 'PRINT CUSTOMER ROUTING INFORMATION' helper['PXCURO'] = 'EXPORT ROUTINGS' helper['ADSCHD'] = 'ADD SCHEDULE' helper['CHSCHD'] = 'CHANGE SCHEDULE' helper['CPSCHD'] = 'COPY SCHEDULE' helper['DXSCHD'] = 'DELETE SCHEDULE' helper['CXSCHD'] = 'CANCEL SCHEDULE' helper['ACTIVE'] = 'ACTIVATE SCHEDULE' helper['XCTIVE'] = 'SET SCHEDULE INACTIVE' helper['LISCHD'] = 'LIST ALL SCHEDULES' helper['LSSCHD'] = 'LIST ACTIVE/RUNNING SCHEDULES' helper['LXSCHD'] = 'SHOW SCHEDULES FILE' helper['PRSCHD'] = 'PRINT ALL SCHEDULES' helper['PRTABL'] = 'PRINT TIMETABLE' helper['PUBLIS'] = 'PUBLISH SCHEDULE' helper['PXSCHD'] = 'EXPORT ALL SCHEDULES' helper['PXTABL'] = 'EXPORT TIMETABLE' helper['ADSECT'] = 'ADD ROUTE SECTION' helper['DXSECT'] = 'DELETE ROUTE SECTION' helper['LDROUT'] = 'LIST DETAIL FOR SELECTED ROUTE' helper['LSROUT'] = 'LIST SECTIONS FOR ROUTE' helper['LXSECT'] = 'SHOW ALL SECTIONS' helper['PDROUT'] = 'PRINT DETAIL FOR SELECTED ROUTE' helper['PXSECT'] = 'EXPORT SECTIONS FOR ALL ROUTES' helper['ADSTAX'] = 'ADD STATION' helper['CHSTAX'] = 'CHANGE STATION' helper['DXSTAX'] = 'DELETE STATION' helper['LISTAX'] = 'LIST STATIONS' helper['LXSTAX'] = 'SHOW STATIONS DATA' helper['PRSTAX'] = 'PRINT STATIONS' helper['PXSTAX'] = 'EXPORT STATIONS' helper['ADSTAT'] = 'ADD STATION TYPE' helper['CHSTAT'] = 'CHANGE STATION TYPE' helper['DXSTAT'] = 'DELETE STATION TYPE' helper['LISTAT'] = 'LIST STATION TYPES' helper['PXSTAT'] = 'EXPORT STATION TYPES' helper['LXSTAT'] = 'SHOW STATION TYPE DATA' helper['PRSTAT'] = 'PRINT STATION TYPES' helper['ADTIMS'] = 'ADD SCHEDULE TIMINGS' helper['CHTIMS'] = 'CHANGE SCHEDULE TIMINGS' helper['TIMING'] = 'LIST TIMINGS FOR SELECTED SCHEDULE' helper['LDTIMS'] = 'LIST TIMING RECORD DETAILS FOR SELECTED SCHEDULE' helper['PRTIMS'] = 'PRINT TIMINGS FOR SELECTED SCHEDULE' helper['PXTIMS'] = 'EXPORT TIMINGS FOR ALL SCHEDULES' helper['UTRAIN'] = 'SET UNSCHEDULED TRAIN' helper['STRAIN'] = 'SET SCHEDULED TRAIN' helper['ETRAIN'] = 'SET EXTRA TRAIN' helper['ACARXT'] = 'ALLOCATE CAR TO TRAIN' helper['ALOCOT'] = 'ALLOCATE LOCO TO TRAIN' helper['LTRAIN'] = 'START TRAIN AT LATER ORIGIN' helper['LINEUP'] = 'REPORT LINE-UP' helper['REPORT'] = 'REPORT TRAIN' helper['TTRAIN'] = 'TERMINATE TRAIN' helper['XLOCOT'] = 'REMOVE LOCO FROM TRAIN' helper['XCARXT'] = 'REMOVE CAR FROM TRAIN' helper['TRAINS'] = 'LIST RUNNING TRAINS' helper['LICONS'] = 'REPORT CONSIST' helper['PRCONS'] = 'PRINT CONSIST' helper['ADUSER'] = 'ADD USER' helper['CHPASS'] = 'CHANGE PASSWORD' helper['CHUSER'] = 'CHANGE USER' helper['DXUSER'] = 'DELETE USER' helper['EDUSER'] = 'ENABLE/DISABLE USER' helper['LIUSER'] = 'LIST USERS' helper['LXUSER'] = 'SHOW USER DATA' helper['PRUSER'] = 'PRINT USERS' helper['PXUSER'] = 'EXPORT USER DATA' helper['RESETP'] = 'RESET PASSWORD' helper['ADWARE'] = 'ADD WAREHOUSE' helper['CHWARE'] = 'CHANGE WAREHOUSE DETAILS' helper['CPWARE'] = 'CHANGE PRODUCTION AT WAREHOUSE' helper['DXWARE'] = 'DELETE WAREHOUSE' helper['LIWARE'] = 'LIST WAREHOUSES' helper['LDWARE'] = 'LIST WAREHOUSE DETAILS' helper['LSWARE'] = 'WAREHOUSES AT STATIONS' helper['LXWARE'] = 'SHOW WAREHOUSE DATA' helper['PRWARE'] = 'PRINT WAREHOUSES' helper['PXWARE'] = 'EXPORT WAREHOUSES' helper['QUIT'] = 'EXIT MOPS' helper['EXIT'] = 'EXIT MOPS' return helper def assist(): """Provides a sorted list (by command name) of all the commands on the system with a short description of what the command does """ i = 0 commands = {} helpers = {} commands = load_commands(commands) helpers = load_helper(helpers) listed = list(commands.keys()) listed.sort() for entry in listed: i = i + 1 if i > 23: dummy = raw_input(' ... HIT ENTER TO CONTINUE') i = 0 try: print(entry + ' ' + helpers[entry]) except: print(entry) print(' ... END OF LIST ...') def get_helper(command): """Gets the helper (short description) information for a given command """ desc = '' helpers = {} helpers = load_helper(helpers) try: desc = helpers[command] except: desc = 'NOT FOUND' return desc
""" base.py: Base class for differentiable neural network layers.""" class Layer(object): """ Abstract base class for differentiable layer.""" def forward_pass(self, input_): """ Forward pass returning and storing outputs.""" raise NotImplementedError() def backward_pass(self, err): """ Backward pass returning and storing errors.""" raise NotImplementedError() def update_params(self, learning_rate): """ Update layer weights based on stored errors.""" raise NotImplementedError()
""" base.py: Base class for differentiable neural network layers.""" class Layer(object): """ Abstract base class for differentiable layer.""" def forward_pass(self, input_): """ Forward pass returning and storing outputs.""" raise not_implemented_error() def backward_pass(self, err): """ Backward pass returning and storing errors.""" raise not_implemented_error() def update_params(self, learning_rate): """ Update layer weights based on stored errors.""" raise not_implemented_error()
def get_distance_matrix(orig, edited): # initialize the matrix orig_len = len(orig) + 1 edit_len = len(edited) + 1 distance_matrix = [[0] * edit_len for _ in range(orig_len)] for i in range(orig_len): distance_matrix[i][0] = i for j in range(edit_len): distance_matrix[0][j] = j # calculate the edit distances for i in range(1, orig_len): for j in range(1, edit_len): deletion = distance_matrix[i - 1][j] + 1 insertion = distance_matrix[i][j - 1] + 1 substitution = distance_matrix[i - 1][j - 1] if orig[i - 1] != edited[j - 1]: substitution += 1 distance_matrix[i][j] = min(insertion, deletion, substitution) return distance_matrix class Compare: def __init__(self, original, edited): self.original = original self.edited = edited self.distance_matrix = get_distance_matrix(original, edited) i = len(self.distance_matrix) - 1 j = len(self.distance_matrix[i]) - 1 self.edit_distance = self.distance_matrix[i][j] self.num_orig_elements = i def __repr__(self): edited_str = str(self.edited) original_str = str(self.original) if len(edited_str) > 10: edited_str = edited_str[10:] + " ..." if len(original_str) > 10: original_str = original_str[10:] + " ..." return "Compare({}, {})".format(edited_str, original_str) def set_alignment_strings(self): original = self.original edited = self.edited num_orig_elements = self.num_orig_elements i = num_orig_elements j = len(self.edited) # edit_distance = self.edit_distance distance_matrix = self.distance_matrix num_deletions = 0 num_insertions = 0 num_substitutions = 0 align_orig_elements = [] align_edited_elements = [] align_label_str = [] # start at the cell containing the edit distance and analyze the # matrix to figure out what is a deletion, insertion, or # substitution. while i or j: # if deletion if distance_matrix[i][j] == distance_matrix[i - 1][j] + 1: num_deletions += 1 align_orig_elements.append(original[i - 1]) align_edited_elements.append(" ") align_label_str.append('D') i -= 1 # if insertion elif distance_matrix[i][j] == distance_matrix[i][j - 1] + 1: num_insertions += 1 align_orig_elements.append(" ") align_edited_elements.append(edited[j - 1]) align_label_str.append('I') j -= 1 # if match or substitution else: orig_element = original[i - 1] edited_element = edited[j - 1] if orig_element != edited_element: num_substitutions += 1 label = 'S' else: label = ' ' align_orig_elements.append(orig_element) align_edited_elements.append(edited_element) align_label_str.append(label) i -= 1 j -= 1 align_orig_elements.reverse() align_edited_elements.reverse() align_label_str.reverse() self.align_orig_elements = align_orig_elements self.align_edited_elements = align_edited_elements self.align_label_str = align_label_str def show_changes(self): if not hasattr(self, 'align_orig_elements'): self.set_alignment_strings() assert (len(self.align_orig_elements) == len(self.align_edited_elements) == len(self.align_label_str)) assert len(self.align_label_str) == len(self.align_edited_elements) == len( self.align_orig_elements), "different number of elements" # for each word in line, determine whether there's a change and append with the according format print_string = '' for index in range(len(self.align_label_str)): if self.align_label_str[index] == ' ': print_string += self.align_edited_elements[index] + ' ' elif self.align_label_str[index] == 'S' or self.align_label_str[index] == 'I': element = self.align_edited_elements[index] print_string += changed(element) + ' ' else: # a deletion - need to print what was in the original that got deleted element = self.align_orig_elements[index] print_string += changed(element) return print_string def changed(plain_text): return "<CORRECTION>" + plain_text + "</CORRECTION>"
def get_distance_matrix(orig, edited): orig_len = len(orig) + 1 edit_len = len(edited) + 1 distance_matrix = [[0] * edit_len for _ in range(orig_len)] for i in range(orig_len): distance_matrix[i][0] = i for j in range(edit_len): distance_matrix[0][j] = j for i in range(1, orig_len): for j in range(1, edit_len): deletion = distance_matrix[i - 1][j] + 1 insertion = distance_matrix[i][j - 1] + 1 substitution = distance_matrix[i - 1][j - 1] if orig[i - 1] != edited[j - 1]: substitution += 1 distance_matrix[i][j] = min(insertion, deletion, substitution) return distance_matrix class Compare: def __init__(self, original, edited): self.original = original self.edited = edited self.distance_matrix = get_distance_matrix(original, edited) i = len(self.distance_matrix) - 1 j = len(self.distance_matrix[i]) - 1 self.edit_distance = self.distance_matrix[i][j] self.num_orig_elements = i def __repr__(self): edited_str = str(self.edited) original_str = str(self.original) if len(edited_str) > 10: edited_str = edited_str[10:] + ' ...' if len(original_str) > 10: original_str = original_str[10:] + ' ...' return 'Compare({}, {})'.format(edited_str, original_str) def set_alignment_strings(self): original = self.original edited = self.edited num_orig_elements = self.num_orig_elements i = num_orig_elements j = len(self.edited) distance_matrix = self.distance_matrix num_deletions = 0 num_insertions = 0 num_substitutions = 0 align_orig_elements = [] align_edited_elements = [] align_label_str = [] while i or j: if distance_matrix[i][j] == distance_matrix[i - 1][j] + 1: num_deletions += 1 align_orig_elements.append(original[i - 1]) align_edited_elements.append(' ') align_label_str.append('D') i -= 1 elif distance_matrix[i][j] == distance_matrix[i][j - 1] + 1: num_insertions += 1 align_orig_elements.append(' ') align_edited_elements.append(edited[j - 1]) align_label_str.append('I') j -= 1 else: orig_element = original[i - 1] edited_element = edited[j - 1] if orig_element != edited_element: num_substitutions += 1 label = 'S' else: label = ' ' align_orig_elements.append(orig_element) align_edited_elements.append(edited_element) align_label_str.append(label) i -= 1 j -= 1 align_orig_elements.reverse() align_edited_elements.reverse() align_label_str.reverse() self.align_orig_elements = align_orig_elements self.align_edited_elements = align_edited_elements self.align_label_str = align_label_str def show_changes(self): if not hasattr(self, 'align_orig_elements'): self.set_alignment_strings() assert len(self.align_orig_elements) == len(self.align_edited_elements) == len(self.align_label_str) assert len(self.align_label_str) == len(self.align_edited_elements) == len(self.align_orig_elements), 'different number of elements' print_string = '' for index in range(len(self.align_label_str)): if self.align_label_str[index] == ' ': print_string += self.align_edited_elements[index] + ' ' elif self.align_label_str[index] == 'S' or self.align_label_str[index] == 'I': element = self.align_edited_elements[index] print_string += changed(element) + ' ' else: element = self.align_orig_elements[index] print_string += changed(element) return print_string def changed(plain_text): return '<CORRECTION>' + plain_text + '</CORRECTION>'
plural_suffixes = { 'ches': 'ch', 'shes': 'sh', 'ies': 'y', 'ves': 'fe', 'oes': 'o', 'zes': 'z', 's': '' } plural_words = { 'pieces': 'piece', 'bunches': 'bunch', 'haunches': 'haunch', 'flasks': 'flask', 'veins': 'vein', 'bowls': 'bowl' }
plural_suffixes = {'ches': 'ch', 'shes': 'sh', 'ies': 'y', 'ves': 'fe', 'oes': 'o', 'zes': 'z', 's': ''} plural_words = {'pieces': 'piece', 'bunches': 'bunch', 'haunches': 'haunch', 'flasks': 'flask', 'veins': 'vein', 'bowls': 'bowl'}
__author__ = 'jwely' __all__ = ["fetch_AVHRR"] def fetch_AVHRR(): """ fetches AVHRR-pathfinder data via ftp server: ftp://ftp.nodc.noaa.gov/pub/data.nodc/pathfinder/ """ print("this function is an unfinished stub!") return
__author__ = 'jwely' __all__ = ['fetch_AVHRR'] def fetch_avhrr(): """ fetches AVHRR-pathfinder data via ftp server: ftp://ftp.nodc.noaa.gov/pub/data.nodc/pathfinder/ """ print('this function is an unfinished stub!') return
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ============================================================================ # Erfr - One-time pad encryption tool # Substitution-box core module # Copyright (C) 2018 by Ralf Kilian # Distributed under the MIT License (https://opensource.org/licenses/MIT) # # Website: http://www.urbanware.org # GitHub: https://github.com/urbanware-org/erfr # ============================================================================ __version__ = "4.3.3" FSB_RIJNDAEL = [ 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16] ISB_RIJNDAEL = [ 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d] def get_version(): """ Return the version of this module. """ return __version__ # EOF
__version__ = '4.3.3' fsb_rijndael = [99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22] isb_rijndael = [82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251, 124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203, 84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78, 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37, 114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92, 204, 93, 101, 182, 146, 108, 112, 72, 80, 253, 237, 185, 218, 94, 21, 70, 87, 167, 141, 157, 132, 144, 216, 171, 0, 140, 188, 211, 10, 247, 228, 88, 5, 184, 179, 69, 6, 208, 44, 30, 143, 202, 63, 15, 2, 193, 175, 189, 3, 1, 19, 138, 107, 58, 145, 17, 65, 79, 103, 220, 234, 151, 242, 207, 206, 240, 180, 230, 115, 150, 172, 116, 34, 231, 173, 53, 133, 226, 249, 55, 232, 28, 117, 223, 110, 71, 241, 26, 113, 29, 41, 197, 137, 111, 183, 98, 14, 170, 24, 190, 27, 252, 86, 62, 75, 198, 210, 121, 32, 154, 219, 192, 254, 120, 205, 90, 244, 31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95, 96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239, 160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97, 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125] def get_version(): """ Return the version of this module. """ return __version__
def insert_space(msg, idx): msg = msg[:idx] + " " + msg[idx:] print(msg) return msg def reverse(msg, substring): if substring in msg: msg = msg.replace(substring, "", 1) msg += substring[::-1] print(msg) return msg else: print("error") return msg def change_all(msg, old_substring, new_substring): msg = msg.replace(old_substring, new_substring) print(msg) return msg concealed_msg = input() command = input() while not command == "Reveal": cmd = command.split(":|:") operation = cmd[0] if operation == "InsertSpace": curr_idx = int(cmd[1]) concealed_msg = insert_space(concealed_msg, curr_idx) elif operation == "Reverse": curr_substring = cmd[1] concealed_msg = reverse(concealed_msg, curr_substring) elif operation == "ChangeAll": curr_substring, replacement = cmd[1:] concealed_msg = change_all(concealed_msg, curr_substring, replacement) command = input() print(f"You have a new text message: {concealed_msg}")
def insert_space(msg, idx): msg = msg[:idx] + ' ' + msg[idx:] print(msg) return msg def reverse(msg, substring): if substring in msg: msg = msg.replace(substring, '', 1) msg += substring[::-1] print(msg) return msg else: print('error') return msg def change_all(msg, old_substring, new_substring): msg = msg.replace(old_substring, new_substring) print(msg) return msg concealed_msg = input() command = input() while not command == 'Reveal': cmd = command.split(':|:') operation = cmd[0] if operation == 'InsertSpace': curr_idx = int(cmd[1]) concealed_msg = insert_space(concealed_msg, curr_idx) elif operation == 'Reverse': curr_substring = cmd[1] concealed_msg = reverse(concealed_msg, curr_substring) elif operation == 'ChangeAll': (curr_substring, replacement) = cmd[1:] concealed_msg = change_all(concealed_msg, curr_substring, replacement) command = input() print(f'You have a new text message: {concealed_msg}')
class Evaluator(object): """ Evaluates a model on a Dataset, using metrics specific to the Dataset. """ def __init__(self, dataset_cls, model, embedding, data_loader, batch_size, device, keep_results=False): self.dataset_cls = dataset_cls self.model = model self.embedding = embedding self.data_loader = data_loader self.batch_size = batch_size self.device = device self.keep_results = keep_results def get_sentence_embeddings(self, batch): sent1 = self.embedding(batch.sentence_1).transpose(1, 2) sent2 = self.embedding(batch.sentence_2).transpose(1, 2) return sent1, sent2 def get_scores(self): """ Get the scores used to evaluate the model. Should return ([score1, score2, ..], [score1_name, score2_name, ...]). The first score is the primary score used to determine if the model has improved. """ raise NotImplementedError('Evaluator subclass needs to implement get_score')
class Evaluator(object): """ Evaluates a model on a Dataset, using metrics specific to the Dataset. """ def __init__(self, dataset_cls, model, embedding, data_loader, batch_size, device, keep_results=False): self.dataset_cls = dataset_cls self.model = model self.embedding = embedding self.data_loader = data_loader self.batch_size = batch_size self.device = device self.keep_results = keep_results def get_sentence_embeddings(self, batch): sent1 = self.embedding(batch.sentence_1).transpose(1, 2) sent2 = self.embedding(batch.sentence_2).transpose(1, 2) return (sent1, sent2) def get_scores(self): """ Get the scores used to evaluate the model. Should return ([score1, score2, ..], [score1_name, score2_name, ...]). The first score is the primary score used to determine if the model has improved. """ raise not_implemented_error('Evaluator subclass needs to implement get_score')
# Time: O(n) # Space: O(h) class Solution(object): def diameterOfBinaryTree(self, root): """ :type root: TreeNode :rtype: int """ return self.depth(root, 0)[1] def depth(self, root, diameter): if not root: return 0, diameter left, diameter = self.depth(root.left, diameter) right, diameter = self.depth(root.right, diameter) return 1 + max(left, right), max(diameter, left + right)
class Solution(object): def diameter_of_binary_tree(self, root): """ :type root: TreeNode :rtype: int """ return self.depth(root, 0)[1] def depth(self, root, diameter): if not root: return (0, diameter) (left, diameter) = self.depth(root.left, diameter) (right, diameter) = self.depth(root.right, diameter) return (1 + max(left, right), max(diameter, left + right))
# # Copyright (c) Members of the EGEE Collaboration. 2006-2009. # See http://www.eu-egee.org/partners/ for details on the copyright holders. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with 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 in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Authors: # Andrea Ceccanti (INFN) # commands_def="""<?xml version="1.0" encoding="UTF-8"?> <voms-commands> <command-group name="User management commands" shortname="user"> <command name="list-users"> <description>list-users</description> <help-string xml:space="preserve"> Lists the VO users.</help-string> </command> <command name="list-suspended-users"> <description>list-suspended-users</description> <help-string xml:space="preserve"> Lists the VO users that are currently suspended. (Requires VOMS Admin server >= 2.7.0)</help-string> </command> <command name="list-expired-users"> <description>list-expired-users</description> <help-string xml:space="preserve"> Lists the VO users that are currently expired. (Requires VOMS Admin server >= 2.7.0)</help-string> </command> <command name="count-expired-users"> <description>count-expired-users</description> <help-string xml:space="preserve"> Prints how many VO users are currently expired. (Requires VOMS Admin server >= 2.7.0)</help-string> </command> <command name="count-suspended-users"> <description>count-suspended-users</description> <help-string xml:space="preserve"> Counts how many VO users are currently suspended. (Requires VOMS Admin server >= 2.7.0)</help-string> </command> <command name="count-users"> <description>count-users</description> <help-string xml:space="preserve"> Counts how many users are in the VO. (Requires VOMS Admin server >= 2.7.0)</help-string> </command> <command name="list-user-stats"> <description>list-user-stats</description> <help-string xml:space="preserve"> List users statistics for this VO. (Requires VOMS Admin server >= 2.7.0)</help-string> </command> <command name="create-user"> <description>[options] create-user CERTIFICATE.PEM</description> <help-string xml:space="preserve"> Registers a new user in VOMS. Personal information can be specified with the following options: name, surname, address, institution, phone-number. (Personal info submission requires VOMS Admin server >= 2.7.0) All these options must be provided when registering a new user, or no option regarding personal information should be set. Besides the personal information, information about user certificate can be provided specifying a certificate file parameter. When using the --nousercert option, then four parameters are required (DN CA CN MAIL) to create the user. Examples: voms-admin --vo test --name Andrea --surname Ceccanti --institution IGI \\ --phoneNumber 243 --address "My Address" \\ create-user .globus/usercert.pem voms-admin --vo test_vo create-user .globus/usercert.pem voms-admin --nousercert --vo test_vo create-user \ 'My DN' 'My CA' 'My CN' 'My Email'</help-string> <arg type="X509v2" /> </command> <command name="suspend-user"> <description>suspend-user USER REASON</description> <help-string xml:space="preserve"> Supends a VOMS user. USER is either an X509 certificate file in PEM format, or a DN, CA couple when the --nousercert option is set. (Requires VOMS Admin server >= 2.7.0) </help-string> <arg type="User"/> <arg type="String"/> </command> <command name="restore-user"> <description>restore-user USER</description> <help-string xml:space="preserve"> Restores a VOMS user. USER is either an X509 certificate file in PEM format, or a DN, CA couple when the --nousercert option is set. (Requires VOMS Admin server >= 2.7.0) </help-string> <arg type="User"/> </command> <command name="restore-all-suspended-users"> <description>restore-all-suspended-users</description> <help-string xml:space="preserve"> Restores all the users currently suspended in the VOMS database. (Requires VOMS Admin server >= 2.7.0)</help-string> </command> <command name="delete-user"> <description>delete-user USER</description> <help-string xml:space="preserve"> Deletes a user from VOMS, including all their attributes and membership information. USER is either an X509 certificate file in PEM format, or a DN, CA couple when the --nousercert option is set. Examples: voms-admin --vo test_vo delete-user .globus/usercert.pem voms-admin --nousercert --vo test_vo delete-user \ 'My DN' 'MY CA'</help-string> <arg type="User" /> </command> </command-group> <command-group name="Role management commands" shortname="role"> <command name="list-roles"> <description>list-roles</description> <help-string xml:space="preserve"> Lists the roles defined in the VO.</help-string> </command> <command name="create-role"> <description>create-role ROLENAME</description> <help-string xml:space="preserve"> Creates a new role</help-string> <arg type="Role" /> </command> <command name="delete-role"> <description>delete-role ROLENAME</description> <help-string xml:space="preserve"> Deletes a role.</help-string> <arg type="Role" /> </command> </command-group> <command-group name="Group management commands" shortname="group"> <command name="list-groups"> <description>list-groups</description> <help-string xml:space="preserve"> Lists all the groups defined in the VO.</help-string> </command> <command name="list-sub-groups"> <description>list-sub-groups GROUPNAME</description> <help-string xml:space="preserve"> List the subgroups of GROUPNAME.</help-string> <arg type="Group" /> </command> <command name="create-group"> <description>[options] create-group GROUPNAME</description> <help-string xml:space="preserve"> Creates a new group named GROUPNAME. If the --description option is given, a description is registered for the group in the VOMS database (requires VOMS Admin server >= 2.7.0). Note that the vo root group part of the fully qualified group name can be omitted, i.e., if the group to be created is called /vo/ciccio, where /vo is the vo root group, this command accepts both the "ciccio" and "/vo/ciccio" syntaxes.</help-string> <arg type="NewGroup" /> </command> <command name="delete-group"> <description>delete-group GROUPNAME</description> <help-string xml:space="preserve"> Deletes a group.</help-string> <arg type="Group" /> </command> <command name="list-user-groups"> <description>list-user-groups USER</description> <help-string xml:space="preserve"> Lists the groups that USER is a member of. USER is either an X509 certificate file in PEM format, or a DN, CA couple when the --nousercert option is set.</help-string> <arg type="User" /> </command> </command-group> <command-group name="Group membership management commands" shortname="membership"> <command name="add-member"> <description>add-member GROUPNAME USER</description> <help-string xml:space="preserve"> Adds USER to the GROUPNAME group. USER is either an X509 certificate file in PEM format, or a DN, CA couple when the --nousercert option is set.</help-string> <arg type="Group" /> <arg type="User" /> </command> <command name="remove-member"> <description>remove-member GROUPNAME USER</description> <help-string xml:space="preserve"> Removes USER from the GROUPNAME group. USER is either an X509 certificate file in PEM format, or a DN, CA couple when the --nousercert option is set.</help-string> <arg type="Group" /> <arg type="User" /> </command> <command name="list-members"> <description>list-members GROUPNAME</description> <help-string xml:space="preserve"> Lists all members of a group.</help-string> <arg type="Group" /> </command> </command-group> <command-group name="Role assignment commands" shortname="role-assign"> <command name="assign-role"> <description>assign-role GROUPNAME ROLENAME USER</description> <help-string xml:space="preserve"> Assigns role ROLENAME to user USER in group GROUPNAME. USER is either an X509 certificate file in PEM format, or a DN, CA couple when the --nousercert option is set.</help-string> <arg type="Group" /> <arg type="Role" /> <arg type="User" /> </command> <command name="dismiss-role"> <description>dismiss-role GROUPNAME ROLENAME USER </description> <help-string xml:space="preserve"> Dismiss role ROLENAME from user USER in group GROUPNAME. USER is either an X509 certificate file in PEM format, or a DN, CA couple when the --nousercert option is set.</help-string> <arg type="Group" /> <arg type="Role" /> <arg type="User" /> </command> <command name="list-users-with-role"> <description>list-users-with-role GROUPNAME ROLENAME </description> <help-string xml:space="preserve"> Lists all users with ROLENAME in GROUPNAME.</help-string> <arg type="Group" /> <arg type="Role" /> </command> <command name="list-user-roles"> <description>list-user-roles USER</description> <help-string xml:space="preserve"> Lists the roles that USER is assigned. USER is either an X509 certificate file in PEM format, or a DN, CA couple when the --nousercert option is set.</help-string> <arg type="User" /> </command> </command-group> <command-group name="Attribute class management commands" shortname="attr-class"> <command name="create-attribute-class"> <description> create-attribute-class CLASSNAME DESCRIPTION UNIQUE </description> <help-string xml:space="preserve"> Creates a new generic attribute class named CLASSNAME, with description DESCRIPTION. UNIQUE is a boolean argument. If UNIQUE is true, attribute values assigned to users for this class are checked for uniqueness. Otherwise no checks are performed on user attribute values. </help-string> <arg type="String" /> <arg type="String" nillable="true" /> <arg type="Boolean" nillable="true" /> </command> <command name="delete-attribute-class"> <description>delete-attribute-class CLASSNAME </description> <help-string xml:space="preserve"> Removes the generic attribute class CLASSNAME. All the user, group and role attribute mappings will be deleted as well. </help-string> <arg type="String" /> </command> <command name="list-attribute-classes"> <description>list-attribute-classes</description> <help-string xml:space="preserve"> Lists the attribute classes defined for the VO.</help-string> </command> </command-group> <command-group name="Generic attribute assignment commands" shortname="attrs"> <command name="set-user-attribute"> <description> set-user-attribute USER ATTRIBUTE ATTRIBUTE_VALUE </description> <help-string xml:space="preserve"> Sets the generic attribute ATTRIBUTE value to ATTRIBUTE_VALUE for user USER. USER is either an X509 certificate file in PEM format, or a DN, CA couple when the --nousercert option is set. </help-string> <arg type="User" /> <arg type="String" /> <arg type="String" /> </command> <command name="delete-user-attribute"> <description>delete-user-attribute USER ATTRIBUTE </description> <help-string xml:space="preserve"> Deletes the generic attribute ATTRIBUTE value from user USER. USER is either an X509 certificate file in PEM format, or a DN, CA couple when the --nousercert option is set.</help-string> <arg type="User" /> <arg type="String" /> </command> <command name="list-user-attributes"> <description>list-user-attributes USER</description> <help-string xml:space="preserve"> Lists the generic attributes defined for user USER. USER is either an X509 certificate file in PEM format, or a DN, CA couple when the --nousercert option is set.</help-string> <arg type="User" /> </command> <command name="set-group-attribute"> <description> set-group-attribute GROUP ATTRIBUTE ATTRIBUTE_VALUE </description> <help-string xml:space="preserve"> Sets the generic attribute ATTRIBUTE value to ATTRIBUTE_VALUE for group GROUP.</help-string> <arg type="Group" /> <arg type="String" /> <arg type="String" /> </command> <command name="set-role-attribute"> <description> set-role-attribute GROUP ROLE ATTRIBUTE ATTRIBUTE_VALUE </description> <help-string xml:space="preserve"> Sets the generic attribute ATTRIBUTE value to ATTRIBUTE_VALUE for role ROLE in group GROUP.</help-string> <arg type="Group" /> <arg type="Role" /> <arg type="String" /> <arg type="String" /> </command> <command name="delete-group-attribute"> <description>delete-group-attribute GROUP ATTRIBUTE </description> <help-string xml:space="preserve"> Deletes the generic attribute ATTRIBUTE value from group GROUP.</help-string> <arg type="Group" /> <arg type="String" /> </command> <command name="list-group-attributes"> <description>list-group-attributes GROUP </description> <help-string xml:space="preserve"> Lists the generic attributes defined for group GROUP.</help-string> <arg type="Group" /> </command> <command name="list-role-attributes"> <description>list-role-attributes GROUP ROLE </description> <help-string xml:space="preserve"> Lists the generic attributes defined for role ROLE in group GROUP.</help-string> <arg type="Group" /> <arg type="Role" /> </command> <command name="delete-role-attribute"> <description> delete-role-attribute GROUP ROLE ATTRIBUTE</description> <help-string xml:space="preserve"> Deletes the generic attribute ATTRIBUTE value from role ROLE in group GROUP.</help-string> <arg type="Group" /> <arg type="Role" /> <arg type="String" /> </command> </command-group> <command-group name="ACL management commands" shortname="acl"> <command name="get-ACL"> <description>get-ACL CONTEXT</description> <help-string xml:space="preserve"> Gets the ACL defined for voms context CONTEXT. CONTEXT may be either a group (e.g. /groupname ) or a qualified role (e.g./groupname/Role=VO-Admin).</help-string> <arg type="String" /> </command> <command name="get-default-ACL"> <description>get-default-ACL GROUP</description> <help-string xml:space="preserve"> Gets the default ACL defined for group GROUP.</help-string> <arg type="Group" /> </command> <command name="add-ACL-entry"> <description> add-ACL-entry CONTEXT USER PERMISSION PROPAGATE </description> <help-string xml:space="preserve"> Adds an entry to the ACL for CONTEXT assigning PERMISSION to user/admin USER. If PROPAGATE is true, the entry is propagated to children contexts. CONTEXT may be either a group (e.g. /groupname ) or a qualified role (e.g./groupname/Role=VO-Admin). USER is either an X509 certificate file in PEM format, or a DN, CA couple when the --nousercert option is set. PERMISSION is a VOMS permission expressed using the VOMS-Admin 2.x format. Allowed permission values are: ALL CONTAINER_READ CONTAINER_WRITE MEMBERSHIP_READ MEMBERSHIP_WRITE ATTRIBUTES_READ ATTRIBUTES_WRITE ACL_READ ACL_WRITE ACL_DEFAULT REQUESTS_READ REQUESTS_WRITE PERSONAL_INFO_READ PERSONAL_INFO_WRITE SUSPEND Multiple permissions can be assigned by combining them in a comma separated list, e.g.: "CONTAINER_READ,MEMBERSHIP_READ" Special meaning DN,CA couples (to be used with the --nousercert option set) are listed hereafter: If DN is ANYONE and CA is VOMS_CA, an entry will be created that assigns the specified PERMISSION to to any authenticated user (i.e., any client that authenticates with a certificates signed by a trusted CA). if CA is GROUP_CA, DN is interpreted as a group and entry will be assigned to members of such group. if CA is ROLE_CA, DN is interpreted as a qualified role (i.e., /test_vo/Role=TestRole), the entry will be assigned to VO members that have the given role in the given group. Examples: voms-admin --vo test_vo add-ACL-entry /test_vo \\ .globus/usercert.pem ALL true (The above command grants full rights to the user identified by '.globus/usercert.pem' on the whole VO, since PROPAGATE is true) voms-admin --nousercert --vo test_vo add-ACL-entry /test_vo \\ 'ANYONE' 'VOMS_CA' 'CONTAINER_READ,MEMBERSHIP_READ' true (The above command grants READ rights on VO structure and membership to any authenticated user on the whole VO, since PROPAGATE is true) To get more detailed information about Voms admin AuthZ framework, either consult the voms-admin user's guide or type: voms-admin --help-acl</help-string> <arg type="String" /> <arg type="User" /> <arg type="Permission" /> <arg type="Boolean" /> </command> <command name="add-default-ACL-entry"> <description> add-default-ACL-entry GROUP USER PERMISSION</description> <help-string xml:space="preserve"> Adds an entry to the default ACL for GROUP assigning PERMISSION to user/admin USER. USER is either an X509 certificate file in PEM format, or a DN, CA couple when the --nousercert option is set. PERMISSION is a VOMS permission expressed using the VOMS-Admin 2.x format. Allowed permission values are: ALL CONTAINER_READ CONTAINER_WRITE MEMBERSHIP_READ MEMBERSHIP_WRITE ATTRIBUTES_READ ATTRIBUTES_WRITE ACL_READ ACL_WRITE ACL_DEFAULT REQUESTS_READ REQUESTS_WRITE PERSONAL_INFO_READ PERSONAL_INFO_WRITE SUSPEND Multiple permissions can be assigned by combining them in a comma separated list, e.g.: "CONTAINER_READ,MEMBERSHIP_READ" Special meaning DN,CA couples are listed hereafter: If DN is ANYONE and CA is VOMS_CA, an entry will be created that assigns the specified PERMISSION to to any authenticated user (i.e., any client that authenticates with a certificates signed by a trusted CA). if CA is GROUP_CA, DN is interpreted as a group and entry will be assigned to members of such group. if CA is ROLE_CA, DN is interpreted as a qualified role (i.e., /test_vo/Role=TestRole), the entry will be assigned to VO members that have the given role in the given group. To get more detailed information about Voms admin AuthZ framework, either consult the voms-admin user's guide or type: voms-admin --help-acl</help-string> <arg type="Group" /> <arg type="User" /> <arg type="Permission" /> </command> <command name="remove-ACL-entry"> <description>remove-ACL-entry CONTEXT USER PROPAGATE </description> <help-string xml:space="preserve"> Removes the entry from the ACL for CONTEXT for user/admin USER. If PROPAGATE is true, the entry is removed also from children contexts. CONTEXT may be either a group (e.g. /groupname ) or a qualified role (e.g./groupname/Role=VO-Admin). USER is either an X509 certificate file in PEM format, or a DN, CA couple when the --nousercert option is set. Special meaning DN,CA couples are listed hereafter: If DN is ANYONE and CA is VOMS_CA, an entry will be created that assigns the specified PERMISSION to to any authenticated user (i.e., any client that authenticates with a certificates signed by a trusted CA). if CA is GROUP_CA, DN is interpreted as a group and entry will be assigned to members of such group. if CA is ROLE_CA, DN is interpreted as a qualified role (i.e., /test_vo/Role=TestRole), the entry will be assigned to VO members that have the given role in the given group. Examples: voms-admin --nousercert --vo test_vo remove-ACL-entry \\ /test_vo 'ANYONE' 'VOMS_CA' true (The above command removes any right on the VO from any authenticated user) To get more detailed information about Voms admin AuthZ framework, either consult the voms-admin user's guide or type: voms-admin --help-acl</help-string> <arg type="String" /> <arg type="User" /> <arg type="Boolean" /> </command> <command name="remove-default-ACL-entry"> <description>remove-default-ACL-entry GROUP USER </description> <help-string xml:space="preserve"> Removes the entry for user/admin USER from the default ACL for GROUP. USER is either an X509 certificate file in PEM format, or a DN, CA couple when the --nousercert option is set. Special meaning DN,CA couples are listed hereafter: If DN is ANYONE and CA is VOMS_CA, an entry will be created that assigns the specified PERMISSION to to any authenticated user (i.e., any client that authenticates with a certificates signed by a trusted CA). if CA is GROUP_CA, DN is interpreted as a group and entry will be assigned to members of such group. if CA is ROLE_CA, DN is interpreted as a qualified role (i.e., /test_vo/Role=TestRole), the entry will be assigned to VO members that have the given role in the given group. To get more detailed information about Voms admin AuthZ framework, either consult the voms-admin user's guide or type: voms-admin --help-acl</help-string> <arg type="Group" /> <arg type="User" /> </command> </command-group> <command-group name="Other commands" shortname="other"> <command name="get-vo-name"> <description>get-vo-name</description> <help-string xml:space="preserve"> This command returns the name of the contacted vo.</help-string> </command> <command name="list-cas"> <description>list-cas</description> <help-string xml:space="preserve"> Lists the certificate authorities accepted by the VO.</help-string> </command> </command-group> <command-group name="Certificate management commands" shortname="Certificate" > <command name="add-certificate"> <description>add-certificate USER CERT</description> <help-string xml:space="preserve"> Binds a certificate to an existing VO user. This operation may take either two pem certficate files as argument, or, if the --nousercert option is set, two DN CA couples. Example: voms-admin --vo infngrid add-certificate my-cert.pem my-other-cert.pem voms-admin --vo infngrid --nousercert add-certificate \\ '/C=IT/O=INFN/OU=Personal Certificate/L=CNAF/CN=Andrea Ceccanti' '/C=IT/O=INFN/CN=INFN CA' \\ '/C=IT/ST=Test/CN=user0/Email=andrea.ceccanti@cnaf.infn.it' '/C=IT/ST=Test/L=Bologna/O=Voms-Admin/OU=Voms-Admin testing/CN=Test CA' </help-string> <arg type="User"/> <arg type="User"/> </command> <command name="remove-certificate"> <description>remove-certificate USER</description> <help-string xml:space="preserve"> Unbinds a certificate from an existing VO user. This operation takes either a pem certificate as argument, or, if the --nousercert option is set, a DN CA couple. Example: voms-admin --vo infngrid remove-certificate my-cert.pem voms-admin --vo infngrid --nousercert remove-certificate \\ '/C=IT/O=INFN/OU=Personal Certificate/L=CNAF/CN=Andrea Ceccanti' '/C=IT/O=INFN/CN=INFN CA' </help-string> <arg type="User"/> </command> <command name="suspend-certificate"> <description>suspend-certificate USER REASON</description> <help-string xml:space="preserve"> Suspends a user certificate, and specifies a reason for the suspension. This operation takes, for the first argument, either a pem certificate as argument, or, if the --nousercert option is set, a DN CA couple. Example: voms-admin --vo infngrid suspend-certificate usercert.pem 'Security incident!' voms-admin --vo infngrid --nousercert suspend-certificate \\ '/C=IT/O=INFN/OU=Personal Certificate/L=CNAF/CN=Andrea Ceccanti' '/C=IT/O=INFN/CN=INFN CA' \\ 'Security incident!' </help-string> <arg type="User"/> <arg type="String"/> </command> <command name="restore-certificate"> <description>restore-certificate USER</description> <help-string xml:space="preserve"> Restores a user certificate. This operation takes, for the first argument, either a pem certificate as argument, or, if the --nousercert option is set, a DN CA couple. Example: voms-admin --vo infngrid restore-certificate usercert.pem voms-admin --vo infngrid --nousercert restore-certificate \\ '/C=IT/O=INFN/OU=Personal Certificate/L=CNAF/CN=Andrea Ceccanti' '/C=IT/O=INFN/CN=INFN CA' </help-string> <arg type="User"/> </command> <command name="get-certificates"> <description>get-certificates USER</description> <help-string xml:space="preserve"> Lists the certificates associated to a user. This operation takes either a pem certificate as argument, or, if the --nousercert option is set, a DN CA couple. Example: voms-admin --vo infngrid get-certificates usercert.pem voms-admin --vo infngrid --nousercert get-certificates \\ '/C=IT/O=INFN/OU=Personal Certificate/L=CNAF/CN=Andrea Ceccanti' '/C=IT/O=INFN/CN=INFN CA' </help-string> <arg type="User"/> </command> </command-group> </voms-commands>"""
commands_def = '<?xml version="1.0" encoding="UTF-8"?>\n<voms-commands>\n <command-group\n name="User management commands"\n shortname="user">\n <command\n name="list-users">\n <description>list-users</description>\n <help-string\n xml:space="preserve">\n Lists the VO users.</help-string>\n </command>\n \n <command\n name="list-suspended-users">\n <description>list-suspended-users</description>\n <help-string\n xml:space="preserve">\n Lists the VO users that are currently suspended. (Requires VOMS Admin server >= 2.7.0)</help-string>\n </command>\n \n <command\n name="list-expired-users">\n <description>list-expired-users</description>\n <help-string\n xml:space="preserve">\n Lists the VO users that are currently expired. (Requires VOMS Admin server >= 2.7.0)</help-string>\n </command>\n \n <command\n name="count-expired-users">\n <description>count-expired-users</description>\n <help-string\n xml:space="preserve">\n Prints how many VO users are currently expired. (Requires VOMS Admin server >= 2.7.0)</help-string>\n </command>\n \n <command\n name="count-suspended-users">\n <description>count-suspended-users</description>\n <help-string\n xml:space="preserve">\n Counts how many VO users are currently suspended. (Requires VOMS Admin server >= 2.7.0)</help-string>\n </command>\n <command\n name="count-users">\n <description>count-users</description>\n <help-string\n xml:space="preserve">\n Counts how many users are in the VO. (Requires VOMS Admin server >= 2.7.0)</help-string>\n </command>\n \n <command\n name="list-user-stats">\n <description>list-user-stats</description>\n <help-string\n xml:space="preserve">\n List users statistics for this VO. (Requires VOMS Admin server >= 2.7.0)</help-string>\n </command>\n \n <command\n name="create-user">\n <description>[options] create-user CERTIFICATE.PEM</description>\n <help-string\n xml:space="preserve">\n Registers a new user in VOMS. \n \n Personal information can be specified with the following options:\n name, surname, address, institution, phone-number.\n (Personal info submission requires VOMS Admin server >= 2.7.0)\n \n All these options must be provided when registering a new user, \n or no option regarding personal information should be set.\n \n Besides the personal information, information about user certificate\n can be provided specifying a certificate file parameter.\n \n When using the --nousercert option, then four parameters are \n required (DN CA CN MAIL) to create the user. \n \n Examples: \n \n voms-admin --vo test --name Andrea --surname Ceccanti --institution IGI \\\n --phoneNumber 243 --address "My Address" \\\n create-user .globus/usercert.pem\n \n voms-admin --vo test_vo create-user .globus/usercert.pem \n \n voms-admin --nousercert --vo test_vo create-user \\ \n \'My DN\' \'My CA\' \'My CN\' \'My Email\'</help-string>\n <arg\n type="X509v2" />\n </command>\n\n <command\n name="suspend-user">\n <description>suspend-user USER REASON</description>\n <help-string\n xml:space="preserve">\n Supends a VOMS user.\n \n USER is either an X509 certificate file in PEM format, \n or a DN, CA couple when the --nousercert option is set.\n \n (Requires VOMS Admin server >= 2.7.0)\n </help-string>\n <arg type="User"/>\n <arg type="String"/>\n </command>\n \n <command\n name="restore-user">\n <description>restore-user USER</description>\n <help-string\n xml:space="preserve">\n Restores a VOMS user.\n \n USER is either an X509 certificate file in PEM format, \n or a DN, CA couple when the --nousercert option is set.\n \n (Requires VOMS Admin server >= 2.7.0)\n </help-string>\n <arg type="User"/>\n </command>\n \n <command\n name="restore-all-suspended-users">\n <description>restore-all-suspended-users</description>\n <help-string\n xml:space="preserve">\n Restores all the users currently suspended in the VOMS database. (Requires VOMS Admin server >= 2.7.0)</help-string>\n </command>\n\n <command\n name="delete-user">\n <description>delete-user USER</description>\n <help-string\n xml:space="preserve">\n Deletes a user from VOMS, including all their attributes\n and membership information. \n \n USER is either an X509 certificate file in PEM format, \n or a DN, CA couple when the --nousercert option is set.\n \n Examples: \n \n voms-admin --vo test_vo delete-user .globus/usercert.pem\n \n voms-admin --nousercert --vo test_vo delete-user \\ \n \'My DN\' \'MY CA\'</help-string>\n <arg\n type="User" />\n </command>\n </command-group>\n <command-group\n name="Role management commands"\n shortname="role">\n <command\n name="list-roles">\n <description>list-roles</description>\n <help-string\n xml:space="preserve">\n Lists the roles defined in the VO.</help-string>\n </command>\n <command\n name="create-role">\n <description>create-role ROLENAME</description>\n <help-string\n xml:space="preserve">\n Creates a new role</help-string>\n <arg\n type="Role" />\n </command>\n <command\n name="delete-role">\n <description>delete-role ROLENAME</description>\n <help-string\n xml:space="preserve">\n Deletes a role.</help-string>\n <arg\n type="Role" />\n </command>\n </command-group>\n <command-group\n name="Group management commands"\n shortname="group">\n <command\n name="list-groups">\n <description>list-groups</description>\n <help-string\n xml:space="preserve">\n Lists all the groups defined in the VO.</help-string>\n </command>\n <command\n name="list-sub-groups">\n <description>list-sub-groups GROUPNAME</description>\n <help-string\n xml:space="preserve">\n List the subgroups of GROUPNAME.</help-string>\n <arg\n type="Group" />\n </command>\n <command\n name="create-group">\n <description>[options] create-group GROUPNAME</description>\n <help-string xml:space="preserve">\n Creates a new group named GROUPNAME. \n \n If the --description option is given, a description is registered\n for the group in the VOMS database (requires VOMS Admin server >= 2.7.0).\n \n Note that the vo root group part of the fully qualified group name \n can be omitted, i.e., if the group to be created is called /vo/ciccio, \n where /vo is the vo root group, this command accepts both the "ciccio"\n and "/vo/ciccio" syntaxes.</help-string>\n <arg\n type="NewGroup" />\n </command>\n <command\n name="delete-group">\n <description>delete-group GROUPNAME</description>\n <help-string\n xml:space="preserve">\n Deletes a group.</help-string>\n <arg\n type="Group" />\n </command>\n <command\n name="list-user-groups">\n <description>list-user-groups USER</description>\n <help-string xml:space="preserve">\n Lists the groups that USER is a member of. USER is either\n an X509 certificate file in PEM format, or a DN, CA couple when the\n --nousercert option is set.</help-string>\n <arg\n type="User" />\n </command>\n </command-group>\n <command-group\n name="Group membership management commands"\n shortname="membership">\n <command\n name="add-member">\n <description>add-member GROUPNAME USER</description>\n <help-string xml:space="preserve">\n Adds USER to the GROUPNAME group. \n \n USER is either an X509 certificate file in PEM format,\n or a DN, CA couple when the --nousercert option is set.</help-string>\n <arg\n type="Group" />\n <arg\n type="User" />\n </command>\n <command\n name="remove-member">\n <description>remove-member GROUPNAME USER</description>\n <help-string xml:space="preserve">\n Removes USER from the GROUPNAME group. \n \n USER is either an X509 certificate file in PEM format, \n or a DN, CA couple when the --nousercert option is set.</help-string>\n <arg\n type="Group" />\n <arg\n type="User" />\n </command>\n <command\n name="list-members">\n <description>list-members GROUPNAME</description>\n <help-string\n xml:space="preserve">\n Lists all members of a group.</help-string>\n <arg\n type="Group" />\n </command>\n </command-group>\n <command-group\n name="Role assignment commands"\n shortname="role-assign">\n <command\n name="assign-role">\n <description>assign-role GROUPNAME ROLENAME USER</description>\n <help-string xml:space="preserve">\n Assigns role ROLENAME to user USER in group GROUPNAME. \n \n USER is either an X509 certificate file in PEM format, \n or a DN, CA couple when the --nousercert option is set.</help-string>\n <arg\n type="Group" />\n <arg\n type="Role" />\n <arg\n type="User" />\n </command>\n <command\n name="dismiss-role">\n <description>dismiss-role GROUPNAME ROLENAME USER\n </description>\n <help-string xml:space="preserve">\n Dismiss role ROLENAME from user USER in group GROUPNAME.\n \n USER is either an X509 certificate file in PEM format, \n or a DN, CA couple when the --nousercert option is set.</help-string>\n <arg\n type="Group" />\n <arg\n type="Role" />\n <arg\n type="User" />\n </command>\n <command\n name="list-users-with-role">\n <description>list-users-with-role GROUPNAME ROLENAME\n </description>\n <help-string xml:space="preserve">\n Lists all users with ROLENAME in GROUPNAME.</help-string>\n <arg\n type="Group" />\n <arg\n type="Role" />\n </command>\n <command\n name="list-user-roles">\n <description>list-user-roles USER</description>\n <help-string xml:space="preserve">\n Lists the roles that USER is assigned. \n \n USER is either an X509 certificate file in PEM format, \n or a DN, CA couple when the --nousercert option is set.</help-string>\n <arg\n type="User" />\n </command>\n </command-group>\n <command-group\n name="Attribute class management commands"\n shortname="attr-class">\n <command\n name="create-attribute-class">\n <description> create-attribute-class CLASSNAME DESCRIPTION UNIQUE\n </description>\n <help-string xml:space="preserve">\n Creates a new generic attribute class named CLASSNAME, with\n description DESCRIPTION. \n \n UNIQUE is a boolean argument. If UNIQUE is true, \n attribute values assigned to users for this class are checked for\n uniqueness. Otherwise no checks are performed on user attribute values.\n </help-string>\n <arg\n type="String" />\n <arg\n type="String"\n nillable="true" />\n <arg\n type="Boolean"\n nillable="true" />\n </command>\n <command\n name="delete-attribute-class">\n <description>delete-attribute-class CLASSNAME\n </description>\n <help-string xml:space="preserve">\n Removes the generic attribute class CLASSNAME. All the\n user, group and role attribute mappings will be deleted as well.\n </help-string>\n <arg\n type="String" />\n </command>\n <command\n name="list-attribute-classes">\n <description>list-attribute-classes</description>\n <help-string xml:space="preserve">\n Lists the attribute classes defined for the VO.</help-string>\n </command>\n </command-group>\n <command-group\n name="Generic attribute assignment commands"\n shortname="attrs">\n <command\n name="set-user-attribute">\n <description> set-user-attribute USER ATTRIBUTE ATTRIBUTE_VALUE\n </description>\n <help-string xml:space="preserve">\n Sets the generic attribute ATTRIBUTE value to\n ATTRIBUTE_VALUE for user USER. USER is either an X509 certificate file\n in PEM format, or a DN, CA couple when the --nousercert option is set.\n </help-string>\n <arg\n type="User" />\n <arg\n type="String" />\n <arg\n type="String" />\n </command>\n <command\n name="delete-user-attribute">\n <description>delete-user-attribute USER ATTRIBUTE\n </description>\n <help-string xml:space="preserve">\n Deletes the generic attribute ATTRIBUTE value from user\n USER. USER is either an X509 certificate file in PEM format, or a DN,\n CA couple when the --nousercert option is set.</help-string>\n <arg\n type="User" />\n <arg\n type="String" />\n </command>\n <command\n name="list-user-attributes">\n <description>list-user-attributes USER</description>\n <help-string xml:space="preserve">\n Lists the generic attributes defined for user USER. USER is\n either an X509 certificate file in PEM format, or a DN, CA couple when\n the --nousercert option is set.</help-string>\n <arg\n type="User" />\n </command>\n <command\n name="set-group-attribute">\n <description> set-group-attribute GROUP ATTRIBUTE ATTRIBUTE_VALUE\n </description>\n <help-string xml:space="preserve">\n Sets the generic attribute ATTRIBUTE value to\n ATTRIBUTE_VALUE for group GROUP.</help-string>\n <arg\n type="Group" />\n <arg\n type="String" />\n <arg\n type="String" />\n </command>\n <command\n name="set-role-attribute">\n <description> set-role-attribute GROUP ROLE ATTRIBUTE ATTRIBUTE_VALUE\n </description>\n <help-string xml:space="preserve">\n Sets the generic attribute ATTRIBUTE value to\n ATTRIBUTE_VALUE for role ROLE in group GROUP.</help-string>\n <arg\n type="Group" />\n <arg\n type="Role" />\n <arg\n type="String" />\n <arg\n type="String" />\n </command>\n <command\n name="delete-group-attribute">\n <description>delete-group-attribute GROUP ATTRIBUTE\n </description>\n <help-string xml:space="preserve"> \n Deletes the generic attribute ATTRIBUTE value from group\n GROUP.</help-string>\n <arg\n type="Group" />\n <arg\n type="String" />\n </command>\n <command\n name="list-group-attributes">\n <description>list-group-attributes GROUP\n </description>\n <help-string xml:space="preserve">\n Lists the generic attributes defined for group GROUP.</help-string>\n <arg\n type="Group" />\n </command>\n <command\n name="list-role-attributes">\n <description>list-role-attributes GROUP ROLE\n </description>\n <help-string xml:space="preserve">\n Lists the generic attributes defined for role ROLE in group\n GROUP.</help-string>\n <arg\n type="Group" />\n <arg\n type="Role" />\n </command>\n <command\n name="delete-role-attribute">\n <description> delete-role-attribute GROUP ROLE ATTRIBUTE</description>\n <help-string xml:space="preserve">\n Deletes the generic attribute ATTRIBUTE value from role\n ROLE in group GROUP.</help-string>\n <arg\n type="Group" />\n <arg\n type="Role" />\n <arg\n type="String" />\n </command>\n </command-group>\n <command-group\n name="ACL management commands"\n shortname="acl">\n <command\n name="get-ACL">\n <description>get-ACL CONTEXT</description>\n <help-string xml:space="preserve">\n Gets the ACL defined for voms context CONTEXT. CONTEXT may\n be either a group (e.g. /groupname ) or a qualified role\n (e.g./groupname/Role=VO-Admin).</help-string>\n <arg\n type="String" />\n </command>\n <command\n name="get-default-ACL">\n <description>get-default-ACL GROUP</description>\n <help-string xml:space="preserve">\n Gets the default ACL defined for group GROUP.</help-string>\n <arg\n type="Group" />\n </command>\n <command\n name="add-ACL-entry">\n <description> add-ACL-entry CONTEXT USER PERMISSION PROPAGATE\n </description>\n <help-string xml:space="preserve">\n Adds an entry to the ACL for CONTEXT assigning PERMISSION\n to user/admin USER. If PROPAGATE is true, the entry is\n propagated to children contexts. \n \n CONTEXT may be either a group (e.g. /groupname ) or \n a qualified role (e.g./groupname/Role=VO-Admin).\n \n USER is either an X509 certificate file in PEM format, \n or a DN, CA couple when the --nousercert option is set.\n \n PERMISSION is a VOMS permission expressed using the\n VOMS-Admin 2.x format. Allowed permission values are:\n \n ALL \n CONTAINER_READ CONTAINER_WRITE \n MEMBERSHIP_READ MEMBERSHIP_WRITE \n ATTRIBUTES_READ ATTRIBUTES_WRITE\n ACL_READ ACL_WRITE ACL_DEFAULT \n REQUESTS_READ REQUESTS_WRITE\n PERSONAL_INFO_READ PERSONAL_INFO_WRITE\n SUSPEND\n \n Multiple permissions can be assigned by combining them\n in a comma separated list, e.g.:\n "CONTAINER_READ,MEMBERSHIP_READ"\n \n Special meaning DN,CA couples (to be used with\n the --nousercert option set) are listed hereafter:\n\n If DN is ANYONE and CA is VOMS_CA, an entry will be created\n that assigns the specified PERMISSION to to any \n authenticated user (i.e., any client that authenticates\n with a certificates signed by a trusted CA).\n \n if CA is GROUP_CA, DN is interpreted as a group and entry\n will be assigned to members of such group.\n \n if CA is ROLE_CA, DN is interpreted as a qualified role \n (i.e., /test_vo/Role=TestRole), the entry will be assigned\n to VO members that have the given role in the given group.\n \n \n Examples:\n \n voms-admin --vo test_vo add-ACL-entry /test_vo \\\n .globus/usercert.pem ALL true\n \n (The above command grants full rights to the user identified by \n \'.globus/usercert.pem\' on the whole VO, since PROPAGATE is true)\n \n voms-admin --nousercert --vo test_vo add-ACL-entry /test_vo \\\n \'ANYONE\' \'VOMS_CA\' \'CONTAINER_READ,MEMBERSHIP_READ\' true\n \n (The above command grants READ rights on VO structure and membership \n to any authenticated user on the whole VO, since PROPAGATE is true)\n \n To get more detailed information about Voms admin AuthZ\n framework, either consult the voms-admin user\'s guide \n or type:\n \n voms-admin --help-acl</help-string>\n <arg\n type="String" />\n <arg\n type="User" />\n <arg\n type="Permission" />\n <arg\n type="Boolean" />\n </command>\n <command\n name="add-default-ACL-entry">\n <description> add-default-ACL-entry GROUP USER PERMISSION</description>\n <help-string xml:space="preserve"> \n Adds an entry to the default ACL for GROUP assigning\n PERMISSION to user/admin USER. \n \n USER is either an X509 certificate file\n in PEM format, or a DN, CA couple when the --nousercert option is set.\n \n PERMISSION is a VOMS permission expressed using the VOMS-Admin 2.x\n format. \n \n Allowed permission values are: \n ALL \n CONTAINER_READ CONTAINER_WRITE \n MEMBERSHIP_READ MEMBERSHIP_WRITE\n ATTRIBUTES_READ ATTRIBUTES_WRITE \n ACL_READ ACL_WRITE ACL_DEFAULT \n REQUESTS_READ REQUESTS_WRITE\n PERSONAL_INFO_READ PERSONAL_INFO_WRITE\n SUSPEND \n \n Multiple permissions can be assigned by combining them\n in a comma separated list, e.g.: \n "CONTAINER_READ,MEMBERSHIP_READ"\n \n Special meaning DN,CA couples are listed hereafter: \n \n If DN is ANYONE and CA is VOMS_CA, an entry will be created that \n assigns the specified PERMISSION to to any authenticated user (i.e., \n any client that authenticates with a certificates signed by \n a trusted CA). \n \n if CA is GROUP_CA, DN is interpreted as a group and entry will be \n assigned to members of such group. \n \n if CA is ROLE_CA, DN is interpreted as a qualified role \n (i.e., /test_vo/Role=TestRole), the entry will be assigned to VO \n members that have the given role in the given group. \n \n To get more detailed information about Voms admin AuthZ framework, \n either consult the voms-admin user\'s guide or type: \n \n voms-admin --help-acl</help-string>\n <arg\n type="Group" />\n <arg\n type="User" />\n <arg\n type="Permission" />\n </command>\n <command\n name="remove-ACL-entry">\n <description>remove-ACL-entry CONTEXT USER PROPAGATE\n </description>\n <help-string xml:space="preserve">\n Removes the entry from the ACL for CONTEXT for user/admin USER. \n \n If PROPAGATE is true, the entry is removed also from children\n contexts. \n \n CONTEXT may be either a group (e.g. /groupname ) or a\n qualified role (e.g./groupname/Role=VO-Admin). \n \n USER is either an X509 certificate file\n in PEM format, or a DN, CA couple when the --nousercert option is set.\n \n Special meaning DN,CA couples are listed hereafter: \n \n If DN is ANYONE and CA is VOMS_CA, an entry will be created that \n assigns the specified PERMISSION to to any authenticated user (i.e., \n any client that authenticates with a certificates signed by \n a trusted CA). \n \n if CA is GROUP_CA, DN is interpreted as a group and entry will be \n assigned to members of such group. \n \n if CA is ROLE_CA, DN is interpreted as a qualified role \n (i.e., /test_vo/Role=TestRole), the entry will be assigned to VO \n members that have the given role in the given group. \n \n Examples: \n \n voms-admin --nousercert --vo test_vo remove-ACL-entry \\ \n /test_vo \'ANYONE\' \'VOMS_CA\' true \n \n (The above command removes any right on the VO from any authenticated \n user) \n \n To get more detailed information about Voms admin AuthZ framework, \n either consult the voms-admin user\'s guide or type: \n \n voms-admin --help-acl</help-string>\n <arg\n type="String" />\n <arg\n type="User" />\n <arg\n type="Boolean" />\n </command>\n <command\n name="remove-default-ACL-entry">\n <description>remove-default-ACL-entry GROUP USER\n </description>\n <help-string xml:space="preserve"> \n Removes the entry for user/admin USER from the default ACL\n for GROUP. \n \n USER is either an X509 certificate file in PEM format, or a DN, \n CA couple when the --nousercert option is set.\n \n Special meaning DN,CA couples are listed hereafter: \n \n If DN is ANYONE and CA is VOMS_CA, an entry will be created that \n assigns the specified PERMISSION to to any authenticated user (i.e., \n any client that authenticates with a certificates signed by \n a trusted CA). \n \n if CA is GROUP_CA, DN is interpreted as a group and entry will be \n assigned to members of such group. \n \n if CA is ROLE_CA, DN is interpreted as a qualified role \n (i.e., /test_vo/Role=TestRole), the entry will be assigned to VO \n members that have the given role in the given group.\n \n To get more detailed information about Voms admin AuthZ framework, \n either consult the voms-admin user\'s guide or type: \n \n voms-admin --help-acl</help-string>\n <arg\n type="Group" />\n <arg\n type="User" />\n </command>\n </command-group>\n <command-group\n name="Other commands"\n shortname="other">\n <command\n name="get-vo-name">\n <description>get-vo-name</description>\n <help-string xml:space="preserve">\n This command returns the name of the contacted vo.</help-string>\n </command>\n <command\n name="list-cas">\n <description>list-cas</description>\n <help-string xml:space="preserve">\n Lists the certificate authorities accepted by the VO.</help-string>\n </command>\n </command-group>\n <command-group\n name="Certificate management commands"\n shortname="Certificate"\n >\n <command \n name="add-certificate">\n <description>add-certificate USER CERT</description>\n <help-string xml:space="preserve">\n Binds a certificate to an existing VO user. \n This operation may take either two pem certficate files as argument, or,\n if the --nousercert option is set, two DN CA couples.\n \n Example:\n voms-admin --vo infngrid add-certificate my-cert.pem my-other-cert.pem\n \n voms-admin --vo infngrid --nousercert add-certificate \\\n \'/C=IT/O=INFN/OU=Personal Certificate/L=CNAF/CN=Andrea Ceccanti\' \'/C=IT/O=INFN/CN=INFN CA\' \\\n \'/C=IT/ST=Test/CN=user0/Email=andrea.ceccanti@cnaf.infn.it\' \'/C=IT/ST=Test/L=Bologna/O=Voms-Admin/OU=Voms-Admin testing/CN=Test CA\'\n </help-string>\n <arg type="User"/>\n <arg type="User"/>\n </command>\n <command \n name="remove-certificate">\n <description>remove-certificate USER</description>\n <help-string xml:space="preserve">\n Unbinds a certificate from an existing VO user.\n This operation takes either a pem certificate as argument, or,\n if the --nousercert option is set, a DN CA couple.\n \n Example:\n \n voms-admin --vo infngrid remove-certificate my-cert.pem\n \n voms-admin --vo infngrid --nousercert remove-certificate \\\n \'/C=IT/O=INFN/OU=Personal Certificate/L=CNAF/CN=Andrea Ceccanti\' \'/C=IT/O=INFN/CN=INFN CA\'\n </help-string>\n <arg type="User"/>\n </command>\n <command \n name="suspend-certificate">\n <description>suspend-certificate USER REASON</description>\n <help-string xml:space="preserve">\n Suspends a user certificate, and specifies a reason for the suspension.\n This operation takes, for the first argument, either a pem certificate as argument, or,\n if the --nousercert option is set, a DN CA couple.\n \n Example:\n voms-admin --vo infngrid suspend-certificate usercert.pem \'Security incident!\'\n \n voms-admin --vo infngrid --nousercert suspend-certificate \\\n \'/C=IT/O=INFN/OU=Personal Certificate/L=CNAF/CN=Andrea Ceccanti\' \'/C=IT/O=INFN/CN=INFN CA\' \\\n \'Security incident!\'\n </help-string>\n <arg type="User"/>\n <arg type="String"/>\n </command>\n <command \n name="restore-certificate">\n <description>restore-certificate USER</description>\n <help-string xml:space="preserve">\n Restores a user certificate.\n This operation takes, for the first argument, either a pem certificate as argument, or,\n if the --nousercert option is set, a DN CA couple.\n \n Example:\n voms-admin --vo infngrid restore-certificate usercert.pem\n \n voms-admin --vo infngrid --nousercert restore-certificate \\\n \'/C=IT/O=INFN/OU=Personal Certificate/L=CNAF/CN=Andrea Ceccanti\' \'/C=IT/O=INFN/CN=INFN CA\'\n </help-string>\n <arg type="User"/>\n </command>\n <command\n name="get-certificates">\n <description>get-certificates USER</description>\n <help-string xml:space="preserve">\n Lists the certificates associated to a user.\n This operation takes either a pem certificate as argument, or, if the --nousercert option is set, a DN CA couple.\n \n Example:\n voms-admin --vo infngrid get-certificates usercert.pem\n \n voms-admin --vo infngrid --nousercert get-certificates \\\n \'/C=IT/O=INFN/OU=Personal Certificate/L=CNAF/CN=Andrea Ceccanti\' \'/C=IT/O=INFN/CN=INFN CA\'\n </help-string>\n <arg\n type="User"/>\n </command>\n </command-group>\n</voms-commands>'
#!/usr/bin/env python # coding: utf-8 # # Calculating protein mass, from [Rosalind.info](https://www.rosalind.info) # # (Specific exercise can be found at: http://rosalind.info/problems/prtm/) # # ## My personal interpretation # # 1. The exercise is about calculating the molecular weight of a protein # # 2. The protein is represented as an amino acid sequence (a string of letters) # # 3. Molecular weights per amino acid are given in a table of monoisotopic masses # # 4. The practical side of the exercise comes down to reading the table with masses and then translating the letters from a given sequence into numbers using the table and adding the numbers up. # # I think I can do this in three functions: # # 1. Read the monoisotopic mass table and convert to a dictionary # # 2. Read the text file with the amino acid sequence # # 3. Take the amino acid sequence and mass table to calculate the mass # In[5]: def read_monoisotopic_mass_table(input_file): """ Given a tab-separatedd input file with amino acids (as capital letters) in the first column, and molecular weights (as floating point numbers) in the second column - create a dictionary with the amino acids as keys and their respective weights as values. """ mass_dict = {} with open(input_file, "r") as read_file: for line in read_file: elements = line.split() amino_acid = str(elements[0]) weight = float(elements[1]) mass_dict[amino_acid] = weight return mass_dict # In[6]: mass_dict = read_monoisotopic_mass_table("data/monoisotopic_mass_table.tsv") print(mass_dict) # So far so good, now make the second function: # In[13]: def read_amino_acid_sequence(input_file): """ Read a text file with an amino acid sequence and return the sequence as string. """ with open(input_file, "r") as read_file: for line in read_file: amino_acids = str(line.strip()) #Note: the .strip() is required to remove the # newline, which otherwise would be interpreted # as amino acid! return amino_acids # In[14]: example_protein = read_amino_acid_sequence("data/Example_calculating_protein_mass.txt") print(example_protein) # Now that works as well, time to make the final function: the one that converts the amino acid sequence to its weight. # In[15]: def calculate_protein_weight(protein, mass_table): """ Given a protein sequence as string and a mass table as dictionary (with amino acids as keys and their respective weights as values), calculate the molecular weight of the protein by summing up the weight of each amino acid in the protein. """ total_weight = 0 for amino_acid in protein: weight = mass_table[amino_acid] total_weight += weight return total_weight # In[16]: calculate_protein_weight(example_protein, mass_dict) # Now this answer looks good, except the rounding of the decimals is slightly different from the example on rosalind.info... Perhaps I should just round the answer to 3 decimals? # In[17]: round(calculate_protein_weight(example_protein, mass_dict), 3) # Perfect! Now let me just overwrite the function to incorporate the rounding: # In[18]: def calculate_protein_weight(protein, mass_table): """ Given a protein sequence as string and a mass table as dictionary (with amino acids as keys and their respective weights as values), calculate the molecular weight of the protein by summing up the weight of each amino acid in the protein. """ total_weight = 0 for amino_acid in protein: weight = mass_table[amino_acid] total_weight += weight return round(total_weight, 3) # And let's give the actual exercise a shot with this! # In[19]: test_protein = read_amino_acid_sequence("data/rosalind_prtm.txt") molecular_weight = calculate_protein_weight(test_protein, mass_dict) print(molecular_weight)
def read_monoisotopic_mass_table(input_file): """ Given a tab-separatedd input file with amino acids (as capital letters) in the first column, and molecular weights (as floating point numbers) in the second column - create a dictionary with the amino acids as keys and their respective weights as values. """ mass_dict = {} with open(input_file, 'r') as read_file: for line in read_file: elements = line.split() amino_acid = str(elements[0]) weight = float(elements[1]) mass_dict[amino_acid] = weight return mass_dict mass_dict = read_monoisotopic_mass_table('data/monoisotopic_mass_table.tsv') print(mass_dict) def read_amino_acid_sequence(input_file): """ Read a text file with an amino acid sequence and return the sequence as string. """ with open(input_file, 'r') as read_file: for line in read_file: amino_acids = str(line.strip()) return amino_acids example_protein = read_amino_acid_sequence('data/Example_calculating_protein_mass.txt') print(example_protein) def calculate_protein_weight(protein, mass_table): """ Given a protein sequence as string and a mass table as dictionary (with amino acids as keys and their respective weights as values), calculate the molecular weight of the protein by summing up the weight of each amino acid in the protein. """ total_weight = 0 for amino_acid in protein: weight = mass_table[amino_acid] total_weight += weight return total_weight calculate_protein_weight(example_protein, mass_dict) round(calculate_protein_weight(example_protein, mass_dict), 3) def calculate_protein_weight(protein, mass_table): """ Given a protein sequence as string and a mass table as dictionary (with amino acids as keys and their respective weights as values), calculate the molecular weight of the protein by summing up the weight of each amino acid in the protein. """ total_weight = 0 for amino_acid in protein: weight = mass_table[amino_acid] total_weight += weight return round(total_weight, 3) test_protein = read_amino_acid_sequence('data/rosalind_prtm.txt') molecular_weight = calculate_protein_weight(test_protein, mass_dict) print(molecular_weight)
class PokepayResponse(object): def __init__(self, response, response_body): self.body = response_body self.elapsed = response.elapsed self.status_code = response.status_code self.ok = response.ok self.headers = response.headers self.url = response.url def body(self): return self.body def elapsed(self): return self.elapsed def status_code(self): return self.status_code def ok(self): return self.ok def headers(self): return self.headers def url(self): return self.url
class Pokepayresponse(object): def __init__(self, response, response_body): self.body = response_body self.elapsed = response.elapsed self.status_code = response.status_code self.ok = response.ok self.headers = response.headers self.url = response.url def body(self): return self.body def elapsed(self): return self.elapsed def status_code(self): return self.status_code def ok(self): return self.ok def headers(self): return self.headers def url(self): return self.url
str1=input("enter first string:") str2=input("enter second string:") new_a = str2[:2] + str1[2:] new_b = str1[:2] + str2[2:] print("the new string after swapping first two charaters of both string:",(new_a+' ' +new_b))
str1 = input('enter first string:') str2 = input('enter second string:') new_a = str2[:2] + str1[2:] new_b = str1[:2] + str2[2:] print('the new string after swapping first two charaters of both string:', new_a + ' ' + new_b)
a = int(input()) b = int(input()) if a > b: print(1) elif a == b: print(0) else: print(2)
a = int(input()) b = int(input()) if a > b: print(1) elif a == b: print(0) else: print(2)
keys = ['a', 'b', 'c'] values = [1, 2, 3] hash = dict(list(zip(keys, values))) # Lazily, Python 2.3+, not 3.x: hash = dict(zip(keys, values))
keys = ['a', 'b', 'c'] values = [1, 2, 3] hash = dict(list(zip(keys, values))) hash = dict(zip(keys, values))
class Space(): """ Common definitions for observations and actions. """ def sample(self, size=None, null=False): """ Uniformly randomly sample a random element(s) of this space. """ raise NotImplementedError
class Space: """ Common definitions for observations and actions. """ def sample(self, size=None, null=False): """ Uniformly randomly sample a random element(s) of this space. """ raise NotImplementedError
def main(request, response): """Send a response with the Origin-Policy header given in the query string. """ header = request.GET.first(b"header") response.headers.set(b"Origin-Policy", header) response.headers.set(b"Content-Type", b"text/html") return u""" <!DOCTYPE html> <meta charset="utf-8"> <title>Origin policy bad header subframe</title> """
def main(request, response): """Send a response with the Origin-Policy header given in the query string. """ header = request.GET.first(b'header') response.headers.set(b'Origin-Policy', header) response.headers.set(b'Content-Type', b'text/html') return u'\n <!DOCTYPE html>\n <meta charset="utf-8">\n <title>Origin policy bad header subframe</title>\n '
description = 'Refsans 4 analog 1 GPIO on Raspberry' group = 'optional' tango_base = 'tango://%s:10000/test/ads/' % setupname lowlevel = () devices = { '%s_ch1' % setupname : device('nicos.devices.entangle.Sensor', description = 'ADin0', tangodevice = tango_base + 'ch1', unit = 'V', fmtstr = '%.4f', visibility = lowlevel, ), '%s_ch2' % setupname : device('nicos.devices.entangle.Sensor', description = 'ADin1', tangodevice = tango_base + 'ch2', unit = 'V', fmtstr = '%.4f', visibility = lowlevel, ), '%s_ch3' % setupname : device('nicos.devices.entangle.Sensor', description = 'ADin2', tangodevice = tango_base + 'ch3', unit = 'V', fmtstr = '%.4f', visibility = lowlevel, ), '%s_ch4' % setupname : device('nicos.devices.entangle.Sensor', description = 'ADin3', tangodevice = tango_base + 'ch4', unit = 'V', fmtstr = '%.4f', visibility = lowlevel, ), }
description = 'Refsans 4 analog 1 GPIO on Raspberry' group = 'optional' tango_base = 'tango://%s:10000/test/ads/' % setupname lowlevel = () devices = {'%s_ch1' % setupname: device('nicos.devices.entangle.Sensor', description='ADin0', tangodevice=tango_base + 'ch1', unit='V', fmtstr='%.4f', visibility=lowlevel), '%s_ch2' % setupname: device('nicos.devices.entangle.Sensor', description='ADin1', tangodevice=tango_base + 'ch2', unit='V', fmtstr='%.4f', visibility=lowlevel), '%s_ch3' % setupname: device('nicos.devices.entangle.Sensor', description='ADin2', tangodevice=tango_base + 'ch3', unit='V', fmtstr='%.4f', visibility=lowlevel), '%s_ch4' % setupname: device('nicos.devices.entangle.Sensor', description='ADin3', tangodevice=tango_base + 'ch4', unit='V', fmtstr='%.4f', visibility=lowlevel)}
class Solution: """ @param s: a string @return: the number of segments in a string """ def countSegments(self, s): # write yout code here return len(s.split())
class Solution: """ @param s: a string @return: the number of segments in a string """ def count_segments(self, s): return len(s.split())
file = open('JacobiMatrix.java', 'w') for i in range(10): for j in range(10): file.write('jacobiMatrix.setEntry(' + str(i) + ', ' + str(j) + ', Allfunc.cg' + str(i) + str(j) + '(currentApprox));\n') file.close()
file = open('JacobiMatrix.java', 'w') for i in range(10): for j in range(10): file.write('jacobiMatrix.setEntry(' + str(i) + ', ' + str(j) + ', Allfunc.cg' + str(i) + str(j) + '(currentApprox));\n') file.close()
#!/usr/bin/python2 lst = [] with open('lst.txt', 'r') as f: lst = f.read().split('\n') i=1 for img in lst: if 'resized' in img: with open(img, 'r') as rd: with open("combined/%05d.%s.png" % (i, img.split('.')[1]), 'w') as wr: wr.write(rd.read()) i+=1
lst = [] with open('lst.txt', 'r') as f: lst = f.read().split('\n') i = 1 for img in lst: if 'resized' in img: with open(img, 'r') as rd: with open('combined/%05d.%s.png' % (i, img.split('.')[1]), 'w') as wr: wr.write(rd.read()) i += 1
class Task: def __init__(self): self.name = ""; self.active = False; def activate(self): pass def update(self, dt): pass def is_complete(self): pass def close(self): pass
class Task: def __init__(self): self.name = '' self.active = False def activate(self): pass def update(self, dt): pass def is_complete(self): pass def close(self): pass
"""Generate AXT release artifacts.""" load("//build_extensions:remove_from_jar.bzl", "remove_from_jar") load("//build_extensions:add_or_update_file_in_zip.bzl", "add_or_update_file_in_zip") def axt_release_lib( name, deps, custom_package = None, proguard_specs = None, proguard_library = None, multidex = "off", jarjar_rules = "//build_extensions:noJarJarRules.txt", keep_spec = None, remove_spec = None, overlapping_jars = [], resource_files = None): """Generates release artifacts for a AXT library. Resulting output will be two files: name_no_deps.jar and name.aar Args: name: The target name deps: The dependencies that make up the library custom_package: Option custom android package to use proguard_specs: Proguard to apply when building the jar proguard_library: Proguard to bundle with the jar jarjar_rules: Optional file containing jarjar rules to be applied keep_spec: A regex to match items to retain in the jar. This is typically the root java namespace of the library. remove_spec: A regex to match items to remove from the jar. overlapping_jars: jars containing entries to be removed from the main jar. This is useful when the library has dependencies whose java package namespaces overlap with this jar. See remove_from_jar docs for more details. resource_files: res files to include in library """ # The rules here produce a final .aar artifact and jar for external release. # It is a 5 stage pipeline: # 1. Produce a placeholder .aar # 2. Produce a .jar including all classes and all its dependencies, and optionally proguard it via # proguard_specs # 3. Rename classes if necessary via jarjar # 4. Strip out external dependencies from .jar # 5. Optionally, add in the proguard_library files to be bundled in the .aar # 6. Update the classes.jar inside the .aar from step 1 with the .jar from step 3 # Step 1. Generate initial shell aar. The generated classes.jar will be empty. # See # https://bazel.build/versions/master/docs/be/android.html#android_library, # name.aar native.android_library( name = "%s_initial" % name, manifest = "AndroidManifest.xml", resource_files = resource_files, visibility = ["//visibility:private"], custom_package = custom_package, testonly = 1, exports = deps, ) # Step 2. Generate jar containing all classes including dependencies. native.android_binary( name = "%s_all" % name, testonly = 1, manifest = "AndroidManifest.xml", multidex = multidex, custom_package = custom_package, proguard_specs = proguard_specs, deps = [ ":%s_initial" % name, ], ) expected_output = ":%s_all_deploy.jar" % name if proguard_specs: expected_output = ":%s_all_proguard.jar" % name # Step 3. Rename classes via jarjar native.java_binary( name = "jarjar_bin", main_class = "org.pantsbuild.jarjar.Main", runtime_deps = ["@maven//:org_pantsbuild_jarjar"], ) native.genrule( name = "%s_jarjared" % name, srcs = [expected_output], outs = ["%s_jarjared.jar" % name], cmd = ("$(location :jarjar_bin) process " + "$(location %s) '$<' '$@'") % jarjar_rules, tools = [ jarjar_rules, ":jarjar_bin", ], ) # Step 4. Strip out external dependencies. This produces the final name_no_deps.jar. remove_from_jar( name = "%s_no_deps" % name, jar = ":%s_jarjared.jar" % name, keep_spec = keep_spec, remove_spec = remove_spec, overlapping_jars = overlapping_jars, ) expected_output = ":%s_initial.aar" % name if proguard_library: expected_output = "%s_with_proguard.aar" % name # Step 5. Add the proguard library file to the aar from the first step add_or_update_file_in_zip( name = "%s_add_proguard" % name, src = ":%s_initial.aar" % name, out = expected_output, update_path = "proguard.txt", update_src = proguard_library, ) # Step 6. Update the .aar produced in the first step with the final .jar add_or_update_file_in_zip( name = name, src = expected_output, out = "%s.aar" % name, update_path = "classes.jar", update_src = ":%s_no_deps.jar" % name, )
"""Generate AXT release artifacts.""" load('//build_extensions:remove_from_jar.bzl', 'remove_from_jar') load('//build_extensions:add_or_update_file_in_zip.bzl', 'add_or_update_file_in_zip') def axt_release_lib(name, deps, custom_package=None, proguard_specs=None, proguard_library=None, multidex='off', jarjar_rules='//build_extensions:noJarJarRules.txt', keep_spec=None, remove_spec=None, overlapping_jars=[], resource_files=None): """Generates release artifacts for a AXT library. Resulting output will be two files: name_no_deps.jar and name.aar Args: name: The target name deps: The dependencies that make up the library custom_package: Option custom android package to use proguard_specs: Proguard to apply when building the jar proguard_library: Proguard to bundle with the jar jarjar_rules: Optional file containing jarjar rules to be applied keep_spec: A regex to match items to retain in the jar. This is typically the root java namespace of the library. remove_spec: A regex to match items to remove from the jar. overlapping_jars: jars containing entries to be removed from the main jar. This is useful when the library has dependencies whose java package namespaces overlap with this jar. See remove_from_jar docs for more details. resource_files: res files to include in library """ native.android_library(name='%s_initial' % name, manifest='AndroidManifest.xml', resource_files=resource_files, visibility=['//visibility:private'], custom_package=custom_package, testonly=1, exports=deps) native.android_binary(name='%s_all' % name, testonly=1, manifest='AndroidManifest.xml', multidex=multidex, custom_package=custom_package, proguard_specs=proguard_specs, deps=[':%s_initial' % name]) expected_output = ':%s_all_deploy.jar' % name if proguard_specs: expected_output = ':%s_all_proguard.jar' % name native.java_binary(name='jarjar_bin', main_class='org.pantsbuild.jarjar.Main', runtime_deps=['@maven//:org_pantsbuild_jarjar']) native.genrule(name='%s_jarjared' % name, srcs=[expected_output], outs=['%s_jarjared.jar' % name], cmd=('$(location :jarjar_bin) process ' + "$(location %s) '$<' '$@'") % jarjar_rules, tools=[jarjar_rules, ':jarjar_bin']) remove_from_jar(name='%s_no_deps' % name, jar=':%s_jarjared.jar' % name, keep_spec=keep_spec, remove_spec=remove_spec, overlapping_jars=overlapping_jars) expected_output = ':%s_initial.aar' % name if proguard_library: expected_output = '%s_with_proguard.aar' % name add_or_update_file_in_zip(name='%s_add_proguard' % name, src=':%s_initial.aar' % name, out=expected_output, update_path='proguard.txt', update_src=proguard_library) add_or_update_file_in_zip(name=name, src=expected_output, out='%s.aar' % name, update_path='classes.jar', update_src=':%s_no_deps.jar' % name)
''' define some function to use. ''' def bytes_to_int(bytes_string, order_type): ''' the bind of the int.from_bytes function. ''' return int.from_bytes(bytes_string, byteorder=order_type) def bits_to_int(bit_string): ''' the bind of int(string, 2) function. ''' return int(bit_string, 2)
""" define some function to use. """ def bytes_to_int(bytes_string, order_type): """ the bind of the int.from_bytes function. """ return int.from_bytes(bytes_string, byteorder=order_type) def bits_to_int(bit_string): """ the bind of int(string, 2) function. """ return int(bit_string, 2)
"""dbcfg - Annon configuration This is mutable object. """ dbcfg = { "created_on": None ,"modified_on": None ,"timestamp": None ,"anndb_id": None ,"rel_id": None ,"dbname": None ,"dbid": None ,"allowed_file_type":['.txt','.csv','.yml','.json'] ,"allowed_image_type":['.pdf','.png','.jpg','.jpeg','.gif'] ,"allowed_video_type":['.mp4'] ,"dataset": {} ,"load_data_from_file": False ,"train":[] ,"evaluate": [] ,"predict": [] ,"publish": [] ,"report": [] ,"description": "AI Dataset" ,"files": {} ,"id": "hmd" ,"name": "hmd" ,"problem_id": "hmd" ,"annon_type": "hmd" ,"dataclass": "AnnonDataset" ,"classes": "" ,"classinfo": None ,"class_ids": None ,"class_map": None ,"num_classes": None ,"splits": None ,"stats": {} ,"summary": {} ,"metadata": {} # set to negative value to load all data, '0' loads no data at all ,"data_read_threshold": -1 ,"db_dir": None ,"return_hmd": None ,"train_mode": "training" ,"test_mode": "inference" # ,"dnnarch": None # ,"log_dir": "logs/<dnnarch>" # ,"framework_type": None # ,"annotations": { # "train": "" # ,"val": "" # ,"test": "" # } # ,"images": { # "train": "" # ,"val": "" # ,"test": "" # } # ,"labels":{ ` # "train": "" # ,"val": "" # ,"test": "" # } # ,"classinfo": { # "train": "" # ,"val": "" # ,"test": "" # } }
"""dbcfg - Annon configuration This is mutable object. """ dbcfg = {'created_on': None, 'modified_on': None, 'timestamp': None, 'anndb_id': None, 'rel_id': None, 'dbname': None, 'dbid': None, 'allowed_file_type': ['.txt', '.csv', '.yml', '.json'], 'allowed_image_type': ['.pdf', '.png', '.jpg', '.jpeg', '.gif'], 'allowed_video_type': ['.mp4'], 'dataset': {}, 'load_data_from_file': False, 'train': [], 'evaluate': [], 'predict': [], 'publish': [], 'report': [], 'description': 'AI Dataset', 'files': {}, 'id': 'hmd', 'name': 'hmd', 'problem_id': 'hmd', 'annon_type': 'hmd', 'dataclass': 'AnnonDataset', 'classes': '', 'classinfo': None, 'class_ids': None, 'class_map': None, 'num_classes': None, 'splits': None, 'stats': {}, 'summary': {}, 'metadata': {}, 'data_read_threshold': -1, 'db_dir': None, 'return_hmd': None, 'train_mode': 'training', 'test_mode': 'inference'}
def _calc_product(series, start_idx, end_idx): product = 1 for digit in series[start_idx:end_idx + 1]: product *= int(digit) return product def largest_product_in_series(num_digits, series): largest_product = 0 for i in range(num_digits, len(series) + 1): product = _calc_product(series, max(0, i - num_digits), i - 1) largest_product = max(largest_product, product) return largest_product
def _calc_product(series, start_idx, end_idx): product = 1 for digit in series[start_idx:end_idx + 1]: product *= int(digit) return product def largest_product_in_series(num_digits, series): largest_product = 0 for i in range(num_digits, len(series) + 1): product = _calc_product(series, max(0, i - num_digits), i - 1) largest_product = max(largest_product, product) return largest_product
class Solution: def countOfAtoms(self, formula: str) -> str: formula = "(" + formula + ")" l = len(formula) def mmerge(dst, src, xs): for k, v in src.items(): t = dst.get(k, 0) dst[k] = v * xs + t def aux(st): nonlocal formula, l res = {} st += 1 while st < l and formula[st] != ')': if formula[st].isupper(): j = st + 1 while j < l and formula[j].islower(): j += 1 rp = j while j < l and formula[j].isdigit(): j += 1 x = 1 if j == rp else int(formula[rp: j]) x += res.get(formula[st: rp], 0) res[formula[st: rp]] = x st = j elif formula[st] == '(': endp, rres = aux(st) j = endp + 1 while j < l and formula[j].isdigit(): j += 1 xs = 1 if j == endp + 1 else int(formula[endp + 1: j]) mmerge(res, rres, xs) st = j return st, res _, ans = aux(0) lis = sorted(ans.keys()) aans = [] for s in lis: aans.append(s) t = ans[s] if t > 1: aans.append(str(t)) return "".join(aans)
class Solution: def count_of_atoms(self, formula: str) -> str: formula = '(' + formula + ')' l = len(formula) def mmerge(dst, src, xs): for (k, v) in src.items(): t = dst.get(k, 0) dst[k] = v * xs + t def aux(st): nonlocal formula, l res = {} st += 1 while st < l and formula[st] != ')': if formula[st].isupper(): j = st + 1 while j < l and formula[j].islower(): j += 1 rp = j while j < l and formula[j].isdigit(): j += 1 x = 1 if j == rp else int(formula[rp:j]) x += res.get(formula[st:rp], 0) res[formula[st:rp]] = x st = j elif formula[st] == '(': (endp, rres) = aux(st) j = endp + 1 while j < l and formula[j].isdigit(): j += 1 xs = 1 if j == endp + 1 else int(formula[endp + 1:j]) mmerge(res, rres, xs) st = j return (st, res) (_, ans) = aux(0) lis = sorted(ans.keys()) aans = [] for s in lis: aans.append(s) t = ans[s] if t > 1: aans.append(str(t)) return ''.join(aans)
#Program to be tested def boarding(seat_number): if seat_number >= 1 and seat_number <= 25: batch_no = 1 elif seat_number >= 26 and seat_number <= 100: batch_no = 2 elif seat_number >= 101 and seat_number <= 200: batch_no = 3 else: batch_no = -1 return batch_no
def boarding(seat_number): if seat_number >= 1 and seat_number <= 25: batch_no = 1 elif seat_number >= 26 and seat_number <= 100: batch_no = 2 elif seat_number >= 101 and seat_number <= 200: batch_no = 3 else: batch_no = -1 return batch_no
# PRE PROCESSING def symmetric_NaN_replacement(dataset): np_dataset = dataset.to_numpy() for col in range(0,(np_dataset.shape[1])): ss_idx = 0 for row in range(1,(dataset.shape[0]-1)): if (np.isnan(np_dataset[row,col]) and (~np.isnan(np_dataset[row-1,col]))): # if a NaN is found, and it is the first one in the range -> start of a window ss_idx = row if ((ss_idx != 0) and (~np.isnan(np_dataset[row+1,col]))): # end of the window has just be found es_idx = row # perform symmetric interpolation for i in range(0,es_idx-ss_idx+1): np_dataset[ss_idx+i,col] = np_dataset[ss_idx-i-1,col] ss_idx = 0 dataset = pd.DataFrame(np_dataset, columns = dataset.columns) return dataset # inspect_dataframe(dataset, dataset.columns) # original # Dealing with flat zones boolidx = np.ones(dataset['Sponginess'].shape[0]) dataset_np = [] for i, col in enumerate(dataset.columns): diff_null = (dataset[col][0:dataset[col].shape[0]].diff() == 0)*1 for j in range(0,dataset[col].shape[0]): if (diff_null[j] >= 1): diff_null[j] = diff_null[j-1]+1 boolidx = np.logical_and(boolidx, diff_null < 5) dataset[~boolidx] = np.NaN symmetric_NaN_replacement(dataset) #Dealing with Meme creativity mean removal THRESHOLD = 1.3 real_value_idx = np.ones(dataset.shape[0]) real_value_idx = np.logical_and(real_value_idx, dataset['Meme creativity'] > THRESHOLD) print(np.mean(dataset['Meme creativity'])) print(np.mean(dataset['Meme creativity'][~real_value_idx])) print(np.mean(dataset['Meme creativity'][real_value_idx])) dataset['Meme creativity'][~real_value_idx] = dataset['Meme creativity'][~real_value_idx] + np.mean(dataset['Meme creativity'][real_value_idx]) inspect_dataframe(dataset, dataset.columns) #pre processed
def symmetric__na_n_replacement(dataset): np_dataset = dataset.to_numpy() for col in range(0, np_dataset.shape[1]): ss_idx = 0 for row in range(1, dataset.shape[0] - 1): if np.isnan(np_dataset[row, col]) and ~np.isnan(np_dataset[row - 1, col]): ss_idx = row if ss_idx != 0 and ~np.isnan(np_dataset[row + 1, col]): es_idx = row for i in range(0, es_idx - ss_idx + 1): np_dataset[ss_idx + i, col] = np_dataset[ss_idx - i - 1, col] ss_idx = 0 dataset = pd.DataFrame(np_dataset, columns=dataset.columns) return dataset boolidx = np.ones(dataset['Sponginess'].shape[0]) dataset_np = [] for (i, col) in enumerate(dataset.columns): diff_null = (dataset[col][0:dataset[col].shape[0]].diff() == 0) * 1 for j in range(0, dataset[col].shape[0]): if diff_null[j] >= 1: diff_null[j] = diff_null[j - 1] + 1 boolidx = np.logical_and(boolidx, diff_null < 5) dataset[~boolidx] = np.NaN symmetric__na_n_replacement(dataset) threshold = 1.3 real_value_idx = np.ones(dataset.shape[0]) real_value_idx = np.logical_and(real_value_idx, dataset['Meme creativity'] > THRESHOLD) print(np.mean(dataset['Meme creativity'])) print(np.mean(dataset['Meme creativity'][~real_value_idx])) print(np.mean(dataset['Meme creativity'][real_value_idx])) dataset['Meme creativity'][~real_value_idx] = dataset['Meme creativity'][~real_value_idx] + np.mean(dataset['Meme creativity'][real_value_idx]) inspect_dataframe(dataset, dataset.columns)
name0_0_1_0_0_2_0 = None name0_0_1_0_0_2_1 = None name0_0_1_0_0_2_2 = None name0_0_1_0_0_2_3 = None name0_0_1_0_0_2_4 = None
name0_0_1_0_0_2_0 = None name0_0_1_0_0_2_1 = None name0_0_1_0_0_2_2 = None name0_0_1_0_0_2_3 = None name0_0_1_0_0_2_4 = None
# -*- coding: utf-8 -*- __title__ = 'pyginx' __version__ = '0.1.13.7.7' __description__ = '' __author__ = 'wrmsr' __author_email__ = 'timwilloney@gmail.com' __url__ = 'https://github.com/wrmsr/pyginx'
__title__ = 'pyginx' __version__ = '0.1.13.7.7' __description__ = '' __author__ = 'wrmsr' __author_email__ = 'timwilloney@gmail.com' __url__ = 'https://github.com/wrmsr/pyginx'
""" Exceptions declaration. """ __all__ = [ "PyCozmoException", "PyCozmoConnectionError", "ConnectionTimeout", "Timeout", ] class PyCozmoException(Exception): """ Base class for all PyCozmo exceptions. """ class PyCozmoConnectionError(PyCozmoException): """ Base class for all PyCozmo connection exceptions. """ class ConnectionTimeout(PyCozmoConnectionError): """ Connection timeout. """ class Timeout(PyCozmoException): """ Timeout. """
""" Exceptions declaration. """ __all__ = ['PyCozmoException', 'PyCozmoConnectionError', 'ConnectionTimeout', 'Timeout'] class Pycozmoexception(Exception): """ Base class for all PyCozmo exceptions. """ class Pycozmoconnectionerror(PyCozmoException): """ Base class for all PyCozmo connection exceptions. """ class Connectiontimeout(PyCozmoConnectionError): """ Connection timeout. """ class Timeout(PyCozmoException): """ Timeout. """
class InvalidMeasurement(Exception): """ Raised when a specified measurement is invalid. """
class Invalidmeasurement(Exception): """ Raised when a specified measurement is invalid. """
path = r'c:\users\raibows\desktop\emma.txt' file = open(path, 'r') s = file.readlines() file.close() r = [i.swapcase() for i in s] file = open(path, 'w') file.writelines(r) file.close()
path = 'c:\\users\\raibows\\desktop\\emma.txt' file = open(path, 'r') s = file.readlines() file.close() r = [i.swapcase() for i in s] file = open(path, 'w') file.writelines(r) file.close()
class Config(object): def __init__(self): # directories self.save_dir = '' self.log_dir = '' self.train_data_file = '' self.val_data_file = '' # input self.patch_size = [42, 42, 1] self.N = self.patch_size[0]*self.patch_size[1] # no. of layers self.pre_n_layers = 3 self.pregconv_n_layers = 1 self.hpf_n_layers = 3 self.lpf_n_layers = 3 self.prox_n_layers = 4 # no. of features self.Nfeat = 132 # must be multiple of 3 self.pre_Nfeat = self.Nfeat/3 self.pre_fnet_Nfeat = self.pre_Nfeat self.prox_fnet_Nfeat = self.Nfeat self.hpf_fnet_Nfeat = self.Nfeat # gconv params self.rank_theta = 11 self.stride = self.Nfeat/3 self.stride_pregconv = self.Nfeat/3 self.min_nn = 16 +8 # learning self.batch_size = 12 self.grad_accum = 1 self.N_iter = 400000 self.starter_learning_rate = 1e-4 self.end_learning_rate = 1e-5 self.decay_step = 1000 self.decay_rate = (self.end_learning_rate / self.starter_learning_rate)**(float(self.decay_step) / self.N_iter) self.Ngpus = 2 # debugging self.save_every_iter = 250 self.summaries_every_iter = 5 self.validate_every_iter = 100 self.test_every_iter = 250 # testing self.minisize = 49*3 # must be integer multiple of search window self.search_window = [49,49] self.searchN = self.search_window[0]*self.search_window[1] # noise std self.sigma = 25
class Config(object): def __init__(self): self.save_dir = '' self.log_dir = '' self.train_data_file = '' self.val_data_file = '' self.patch_size = [42, 42, 1] self.N = self.patch_size[0] * self.patch_size[1] self.pre_n_layers = 3 self.pregconv_n_layers = 1 self.hpf_n_layers = 3 self.lpf_n_layers = 3 self.prox_n_layers = 4 self.Nfeat = 132 self.pre_Nfeat = self.Nfeat / 3 self.pre_fnet_Nfeat = self.pre_Nfeat self.prox_fnet_Nfeat = self.Nfeat self.hpf_fnet_Nfeat = self.Nfeat self.rank_theta = 11 self.stride = self.Nfeat / 3 self.stride_pregconv = self.Nfeat / 3 self.min_nn = 16 + 8 self.batch_size = 12 self.grad_accum = 1 self.N_iter = 400000 self.starter_learning_rate = 0.0001 self.end_learning_rate = 1e-05 self.decay_step = 1000 self.decay_rate = (self.end_learning_rate / self.starter_learning_rate) ** (float(self.decay_step) / self.N_iter) self.Ngpus = 2 self.save_every_iter = 250 self.summaries_every_iter = 5 self.validate_every_iter = 100 self.test_every_iter = 250 self.minisize = 49 * 3 self.search_window = [49, 49] self.searchN = self.search_window[0] * self.search_window[1] self.sigma = 25
CAS_HEADERS = ('Host', 'Port', 'ID', 'Operator', 'NMEA', 'Country', 'Latitude', 'Longitude', 'FallbackHost', 'FallbackPort', 'Site', 'Other Details', 'Distance') NET_HEADERS = ('ID', 'Operator', 'Authentication', 'Fee', 'Web-Net', 'Web-Str', 'Web-Reg', 'Other Details', 'Distance') STR_HEADERS = ('Mountpoint', 'ID', 'Format', 'Format-Details', 'Carrier', 'Nav-System', 'Network', 'Country', 'Latitude', 'Longitude', 'NMEA', 'Solution', 'Generator', 'Compr-Encryp', 'Authentication', 'Fee', 'Bitrate', 'Other Details', 'Distance') PYCURL_COULD_NOT_RESOLVE_HOST_ERRNO = 6 PYCURL_CONNECTION_FAILED_ERRNO = 7 PYCURL_TIMEOUT_ERRNO = 28 PYCURL_HANDSHAKE_ERRNO = 35 MULTICURL_SELECT_TIMEOUT = 0.5
cas_headers = ('Host', 'Port', 'ID', 'Operator', 'NMEA', 'Country', 'Latitude', 'Longitude', 'FallbackHost', 'FallbackPort', 'Site', 'Other Details', 'Distance') net_headers = ('ID', 'Operator', 'Authentication', 'Fee', 'Web-Net', 'Web-Str', 'Web-Reg', 'Other Details', 'Distance') str_headers = ('Mountpoint', 'ID', 'Format', 'Format-Details', 'Carrier', 'Nav-System', 'Network', 'Country', 'Latitude', 'Longitude', 'NMEA', 'Solution', 'Generator', 'Compr-Encryp', 'Authentication', 'Fee', 'Bitrate', 'Other Details', 'Distance') pycurl_could_not_resolve_host_errno = 6 pycurl_connection_failed_errno = 7 pycurl_timeout_errno = 28 pycurl_handshake_errno = 35 multicurl_select_timeout = 0.5
""" """ def _impl(repository_ctx): sdk_path = repository_ctx.os.environ.get("VULKAN_SDK", None) if sdk_path == None: print("VULKAN_SDK environment variable not found, using /usr") sdk_path = "/usr" repository_ctx.symlink(sdk_path, "vulkan_sdk_linux") glslc_path = repository_ctx.which("glslc") if glslc_path == None: fail("Unable to find glslc binary in the system") file_content = """ cc_library( name = "vulkan_cc_library", srcs = ["vulkan_sdk_linux/lib/x86_64-linux-gnu/libvulkan.so"], hdrs = glob([ "vulkan_sdk_linux/include/vulkan/**/*.h", "vulkan_sdk_linux/include/vulkan/**/*.hpp", ]), includes = ["vulkan"], visibility = ["//visibility:public"] ) # FIXME: I cannot actually run this one in _glsl_shader. There is an error # when running _glsl_shader rule filegroup( name = "glslc", srcs = ["vulkan_sdk_linux/bin/glslc"], visibility = ["//visibility:public"], ) """.format(str(glslc_path)[1:]) repository_ctx.file("BUILD.bazel", file_content) vulkan_linux = repository_rule( implementation = _impl, local = True, environ = ["VULKAN_SDK"] )
""" """ def _impl(repository_ctx): sdk_path = repository_ctx.os.environ.get('VULKAN_SDK', None) if sdk_path == None: print('VULKAN_SDK environment variable not found, using /usr') sdk_path = '/usr' repository_ctx.symlink(sdk_path, 'vulkan_sdk_linux') glslc_path = repository_ctx.which('glslc') if glslc_path == None: fail('Unable to find glslc binary in the system') file_content = '\n\ncc_library(\n name = "vulkan_cc_library",\n srcs = ["vulkan_sdk_linux/lib/x86_64-linux-gnu/libvulkan.so"],\n hdrs = glob([\n "vulkan_sdk_linux/include/vulkan/**/*.h",\n "vulkan_sdk_linux/include/vulkan/**/*.hpp",\n ]),\n includes = ["vulkan"],\n visibility = ["//visibility:public"]\n)\n\n# FIXME: I cannot actually run this one in _glsl_shader. There is an error\n# when running _glsl_shader rule\nfilegroup(\n name = "glslc",\n srcs = ["vulkan_sdk_linux/bin/glslc"],\n visibility = ["//visibility:public"],\n)\n'.format(str(glslc_path)[1:]) repository_ctx.file('BUILD.bazel', file_content) vulkan_linux = repository_rule(implementation=_impl, local=True, environ=['VULKAN_SDK'])
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jun 27 21:16:00 2020 @author: mints """ A_K = 0.306 BANDS = { 'AllWISE': ['W1mag', 'W2mag'], 'ATLAS': ['%sap3' % s for s in list('UGRIZ')], 'DES': ['mag_auto_%s' % s for s in list('grizy')], 'KIDS': ['%smag' % s for s in list('ugri')], 'LAS': ['p%smag' % s for s in ['y', 'j', 'h', 'k']], 'LS8': ['dered_mag_%s' % s for s in list('grz')], 'NSC': ['%smag' % s for s in list('ugrizy') + ['vr']], 'PS1': ['%skmag' % s for s in list('grizy')], 'SDSS': ['%smag' % s for s in list('ugriz')], 'unWISE': ['W1mag', 'W2mag'], 'VHS': ['%spmag' % s for s in list('YJH') + ['Ks']], 'VIKING': ['%spmag' % s for s in list('ZYJH') + ['Ks']], #--- Simulated: 'Happy': ['%smag' % s for s in list('ugriz')], 'Teddy': ['%smag' % s for s in list('ugriz')], } EXTINCTIONS = { 'AllWISE': [0, 0], 'ATLAS': [0, 0, 0, 0, 0], 'DES': [3.237, 2.176, 1.595, 1.217, 1.058], 'KIDS': [4.239, 3.303, 2.285, 1.698], 'LAS': [1.194957, 0.895497, 0.568943, 0.356779], 'LS8': [0, 0, 0], 'NSC': [5.10826797, 3.9170915, 2.73640523, 2.07503268, 1.51035948, 1.30611111, 2.816129032], 'PS1': [3.612, 2.691, 2.097, 1.604, 1.336], 'SDSS': [0, 0, 0, 0, 0], 'unWISE': [0, 0], 'VHS': [1.213, 0.891, 0.564, 0.373], 'VIKING': [1.578, 1.213, 0.891, 0.564, 0.373], # -- Simulated: 'Happy': [0, 0, 0, 0, 0], 'Teddy': [0, 0, 0, 0, 0], } LIMITS = { 'AllWISE': [17.1, 15.7], 'ATLAS': [21.78, 22.71, 22.17, 21.40, 20.23], 'DES': [24.33, 24.08, 23.44, 22.69, 21.44], 'KIDS': [24.3, 25.4, 25.2, 24.2], 'LAS': [20.5, 20.0, 18.8, 18.4], 'LS8': [24.5, 23.9, 22.9], 'NSC': [22.6, 23.6, 23.2, 22.8, 22.3, 21.0, 23.3], 'PS1': [23.3, 23.2, 23.1, 22.3, 21.3], 'SDSS': [22.0, 22.2, 22.2, 21.3, 20.5], 'unWISE': [17.93, 16.72], 'VHS': [23., 21.6, 21.0, 20.2], 'VIKING': [23.1, 22.3, 22.1, 21.5, 21.2], # -- Simulated: #'Happy': [22.0, 22.2, 22.2, 21.3, 20.5], 'Happy': [99, 99, 99, 99, 99], 'Teddy': [99, 99, 99, 99, 99], } def collect(names): columns = [] ecolumns = [] limits = [] for t in names: columns += ['%s_%s' % (t.lower(), b.lower()) for b in BANDS[t]] ecolumns += ['e_%s_%s' % (t.lower(), b.lower()) for b in BANDS[t]] limits.extend(LIMITS[t]) return columns, ecolumns, limits
""" Created on Sat Jun 27 21:16:00 2020 @author: mints """ a_k = 0.306 bands = {'AllWISE': ['W1mag', 'W2mag'], 'ATLAS': ['%sap3' % s for s in list('UGRIZ')], 'DES': ['mag_auto_%s' % s for s in list('grizy')], 'KIDS': ['%smag' % s for s in list('ugri')], 'LAS': ['p%smag' % s for s in ['y', 'j', 'h', 'k']], 'LS8': ['dered_mag_%s' % s for s in list('grz')], 'NSC': ['%smag' % s for s in list('ugrizy') + ['vr']], 'PS1': ['%skmag' % s for s in list('grizy')], 'SDSS': ['%smag' % s for s in list('ugriz')], 'unWISE': ['W1mag', 'W2mag'], 'VHS': ['%spmag' % s for s in list('YJH') + ['Ks']], 'VIKING': ['%spmag' % s for s in list('ZYJH') + ['Ks']], 'Happy': ['%smag' % s for s in list('ugriz')], 'Teddy': ['%smag' % s for s in list('ugriz')]} extinctions = {'AllWISE': [0, 0], 'ATLAS': [0, 0, 0, 0, 0], 'DES': [3.237, 2.176, 1.595, 1.217, 1.058], 'KIDS': [4.239, 3.303, 2.285, 1.698], 'LAS': [1.194957, 0.895497, 0.568943, 0.356779], 'LS8': [0, 0, 0], 'NSC': [5.10826797, 3.9170915, 2.73640523, 2.07503268, 1.51035948, 1.30611111, 2.816129032], 'PS1': [3.612, 2.691, 2.097, 1.604, 1.336], 'SDSS': [0, 0, 0, 0, 0], 'unWISE': [0, 0], 'VHS': [1.213, 0.891, 0.564, 0.373], 'VIKING': [1.578, 1.213, 0.891, 0.564, 0.373], 'Happy': [0, 0, 0, 0, 0], 'Teddy': [0, 0, 0, 0, 0]} limits = {'AllWISE': [17.1, 15.7], 'ATLAS': [21.78, 22.71, 22.17, 21.4, 20.23], 'DES': [24.33, 24.08, 23.44, 22.69, 21.44], 'KIDS': [24.3, 25.4, 25.2, 24.2], 'LAS': [20.5, 20.0, 18.8, 18.4], 'LS8': [24.5, 23.9, 22.9], 'NSC': [22.6, 23.6, 23.2, 22.8, 22.3, 21.0, 23.3], 'PS1': [23.3, 23.2, 23.1, 22.3, 21.3], 'SDSS': [22.0, 22.2, 22.2, 21.3, 20.5], 'unWISE': [17.93, 16.72], 'VHS': [23.0, 21.6, 21.0, 20.2], 'VIKING': [23.1, 22.3, 22.1, 21.5, 21.2], 'Happy': [99, 99, 99, 99, 99], 'Teddy': [99, 99, 99, 99, 99]} def collect(names): columns = [] ecolumns = [] limits = [] for t in names: columns += ['%s_%s' % (t.lower(), b.lower()) for b in BANDS[t]] ecolumns += ['e_%s_%s' % (t.lower(), b.lower()) for b in BANDS[t]] limits.extend(LIMITS[t]) return (columns, ecolumns, limits)
# -*- coding: UTF-8 -*- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with 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 in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # Copied from trac/utils.py, ticket-links-trunk branch def unique(seq): """Yield unique elements from sequence of hashables, preserving order. (New in 0.13) """ seen = set() return (x for x in seq if x not in seen and not seen.add(x))
def unique(seq): """Yield unique elements from sequence of hashables, preserving order. (New in 0.13) """ seen = set() return (x for x in seq if x not in seen and (not seen.add(x)))
__version__ = '0.1' supported_aln_types = ('blast', 'sam', 'xml') supported_db_types = ('nt', 'nr','cds', 'genome', 'none') consensus_aln_types = ('xml',)
__version__ = '0.1' supported_aln_types = ('blast', 'sam', 'xml') supported_db_types = ('nt', 'nr', 'cds', 'genome', 'none') consensus_aln_types = ('xml',)
def ordinal(n): """Translate a 0-based index into a 1-based ordinal, e.g. 0 -> 1st, 1 -> 2nd, etc. :param int n: the index to be translated. :return: (*str*) -- Ordinal. """ ord_dict = {1: "st", 2: "nd", 3: "rd"} return str(n + 1) + ord_dict.get((n + 1) if (n + 1) < 20 else (n + 1) % 10, "th")
def ordinal(n): """Translate a 0-based index into a 1-based ordinal, e.g. 0 -> 1st, 1 -> 2nd, etc. :param int n: the index to be translated. :return: (*str*) -- Ordinal. """ ord_dict = {1: 'st', 2: 'nd', 3: 'rd'} return str(n + 1) + ord_dict.get(n + 1 if n + 1 < 20 else (n + 1) % 10, 'th')
def for_G(): for row in range(7): for col in range(5): if (col==0 and (row!=0 and row!=6)) or ((row==0 or row==6) and (col>0)) or (row==3 and col>1) or (row>3 and col==4): print("*",end=" ") else: print(end=" ") print() def while_G(): i=0 while i<7: j=0 while j<5: if (j==0 and (i!=0 and i!=6)) or ((i==0 or i==6) and (j>0)) or (i==3 and j>1) or (i>3 and j==4): print("*",end=" ") else: print(end=" ") j+=1 i+=1 print()
def for_g(): for row in range(7): for col in range(5): if col == 0 and (row != 0 and row != 6) or ((row == 0 or row == 6) and col > 0) or (row == 3 and col > 1) or (row > 3 and col == 4): print('*', end=' ') else: print(end=' ') print() def while_g(): i = 0 while i < 7: j = 0 while j < 5: if j == 0 and (i != 0 and i != 6) or ((i == 0 or i == 6) and j > 0) or (i == 3 and j > 1) or (i > 3 and j == 4): print('*', end=' ') else: print(end=' ') j += 1 i += 1 print()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jan 26 00:07:09 2017 @author: Nadiar """ def iterPower(base, exp): ''' base: int or float. exp: int >= 0 returns: int or float, base^exp ''' # Your code here res = 1 for i in range(1,(exp + 1)): res *= base return res
""" Created on Thu Jan 26 00:07:09 2017 @author: Nadiar """ def iter_power(base, exp): """ base: int or float. exp: int >= 0 returns: int or float, base^exp """ res = 1 for i in range(1, exp + 1): res *= base return res
def solution(A, K): # if length is equal to K nothing changes if K == len(A): return A # if all elements are the same, nothing change if all([item == A[0] for item in A]): return A N = len(A) _A = [0] * N for ind in range(N): transf_ind = ind + K _A[transf_ind - (transf_ind // N)*N] = A[ind] return _A
def solution(A, K): if K == len(A): return A if all([item == A[0] for item in A]): return A n = len(A) _a = [0] * N for ind in range(N): transf_ind = ind + K _A[transf_ind - transf_ind // N * N] = A[ind] return _A
#!/usr/bin/env python # # Azure Linux extension # # Copyright (c) Microsoft Corporation # All rights reserved. # MIT License # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated # documentation files (the ""Software""), to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above # copyright notice and this permission notice shall be included in all copies or substantial portions of the # Software. THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT # LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF # CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # Get elements from DiagnosticsMonitorConfiguration in LadCfg based on element name def getDiagnosticsMonitorConfigurationElement(ladCfg, elementName): if ladCfg and 'diagnosticMonitorConfiguration' in ladCfg: if elementName in ladCfg['diagnosticMonitorConfiguration']: return ladCfg['diagnosticMonitorConfiguration'][elementName] return None # Get fileCfg form FileLogs in LadCfg def getFileCfgFromLadCfg(ladCfg): fileLogs = getDiagnosticsMonitorConfigurationElement(ladCfg, 'fileLogs') if fileLogs and 'fileLogConfiguration' in fileLogs: return fileLogs['fileLogConfiguration'] return None # Get resource Id from LadCfg def getResourceIdFromLadCfg(ladCfg): metricsConfiguration = getDiagnosticsMonitorConfigurationElement(ladCfg, 'metrics') if metricsConfiguration and 'resourceId' in metricsConfiguration: return metricsConfiguration['resourceId'] return None # Get event volume from LadCfg def getEventVolumeFromLadCfg(ladCfg): return getDiagnosticsMonitorConfigurationElement(ladCfg, 'eventVolume') # Get default sample rate from LadCfg def getDefaultSampleRateFromLadCfg(ladCfg): if ladCfg and 'sampleRateInSeconds' in ladCfg: return ladCfg['sampleRateInSeconds'] return None def getPerformanceCounterCfgFromLadCfg(ladCfg): """ Return the array of metric definitions :param ladCfg: :return: array of metric definitions """ performanceCounters = getDiagnosticsMonitorConfigurationElement(ladCfg, 'performanceCounters') if performanceCounters and 'performanceCounterConfiguration' in performanceCounters: return performanceCounters['performanceCounterConfiguration'] return None def getAggregationPeriodsFromLadCfg(ladCfg): """ Return an array of aggregation periods as specified. If nothing appears in the config, default PT1H :param ladCfg: :return: array of ISO 8601 intervals :rtype: List(str) """ results = [] metrics = getDiagnosticsMonitorConfigurationElement(ladCfg, 'metrics') if metrics and 'metricAggregation' in metrics: for item in metrics['metricAggregation']: if 'scheduledTransferPeriod' in item: # assert isinstance(item['scheduledTransferPeriod'], str) results.append(item['scheduledTransferPeriod']) else: results.append('PT1H') return results def getSinkList(feature_config): """ Returns the list of sink names to which all data should be forwarded, according to this config :param feature_config: The JSON config for a feature (e.g. the struct for "performanceCounters" or "syslogEvents") :return: the list of names; might be an empty list :rtype: [str] """ if feature_config and 'sinks' in feature_config and feature_config['sinks']: return [sink_name.strip() for sink_name in feature_config['sinks'].split(',')] return [] def getFeatureWideSinksFromLadCfg(ladCfg, feature_name): """ Returns the list of sink names to which all data for the given feature should be forwarded :param ladCfg: The ladCfg JSON config :param str feature_name: Name of the feature. Expected to be "performanceCounters" or "syslogEvents" :return: the list of names; might be an empty list :rtype: [str] """ return getSinkList(getDiagnosticsMonitorConfigurationElement(ladCfg, feature_name)) class SinkConfiguration: def __init__(self): self._sinks = {} def insert_from_config(self, json): """ Walk through the sinksConfig JSON object and add all sinks within it. Every accepted sink is guaranteed to have a 'name' and 'type' element. :param json: A hash holding the body of a sinksConfig object :return: A string containing warning messages, or an empty string """ msgs = [] if json and 'sink' in json: for sink in json['sink']: if 'name' in sink and 'type' in sink: self._sinks[sink['name']] = sink else: msgs.append('Ignoring invalid sink definition {0}'.format(sink)) return '\n'.join(msgs) def get_sink_by_name(self, sink_name): """ Return the JSON object defining a particular sink. :param sink_name: string name of sink :return: JSON object or None """ if sink_name in self._sinks: return self._sinks[sink_name] return None def get_all_sink_names(self): """ Return a list of all names of defined sinks. :return: list of names """ return self._sinks.keys() def get_sinks_by_type(self, sink_type): """ Return a list of all names of defined sinks. :return: list of names """ return [self._sinks[name] for name in self._sinks if self._sinks[name]['type'] == sink_type]
def get_diagnostics_monitor_configuration_element(ladCfg, elementName): if ladCfg and 'diagnosticMonitorConfiguration' in ladCfg: if elementName in ladCfg['diagnosticMonitorConfiguration']: return ladCfg['diagnosticMonitorConfiguration'][elementName] return None def get_file_cfg_from_lad_cfg(ladCfg): file_logs = get_diagnostics_monitor_configuration_element(ladCfg, 'fileLogs') if fileLogs and 'fileLogConfiguration' in fileLogs: return fileLogs['fileLogConfiguration'] return None def get_resource_id_from_lad_cfg(ladCfg): metrics_configuration = get_diagnostics_monitor_configuration_element(ladCfg, 'metrics') if metricsConfiguration and 'resourceId' in metricsConfiguration: return metricsConfiguration['resourceId'] return None def get_event_volume_from_lad_cfg(ladCfg): return get_diagnostics_monitor_configuration_element(ladCfg, 'eventVolume') def get_default_sample_rate_from_lad_cfg(ladCfg): if ladCfg and 'sampleRateInSeconds' in ladCfg: return ladCfg['sampleRateInSeconds'] return None def get_performance_counter_cfg_from_lad_cfg(ladCfg): """ Return the array of metric definitions :param ladCfg: :return: array of metric definitions """ performance_counters = get_diagnostics_monitor_configuration_element(ladCfg, 'performanceCounters') if performanceCounters and 'performanceCounterConfiguration' in performanceCounters: return performanceCounters['performanceCounterConfiguration'] return None def get_aggregation_periods_from_lad_cfg(ladCfg): """ Return an array of aggregation periods as specified. If nothing appears in the config, default PT1H :param ladCfg: :return: array of ISO 8601 intervals :rtype: List(str) """ results = [] metrics = get_diagnostics_monitor_configuration_element(ladCfg, 'metrics') if metrics and 'metricAggregation' in metrics: for item in metrics['metricAggregation']: if 'scheduledTransferPeriod' in item: results.append(item['scheduledTransferPeriod']) else: results.append('PT1H') return results def get_sink_list(feature_config): """ Returns the list of sink names to which all data should be forwarded, according to this config :param feature_config: The JSON config for a feature (e.g. the struct for "performanceCounters" or "syslogEvents") :return: the list of names; might be an empty list :rtype: [str] """ if feature_config and 'sinks' in feature_config and feature_config['sinks']: return [sink_name.strip() for sink_name in feature_config['sinks'].split(',')] return [] def get_feature_wide_sinks_from_lad_cfg(ladCfg, feature_name): """ Returns the list of sink names to which all data for the given feature should be forwarded :param ladCfg: The ladCfg JSON config :param str feature_name: Name of the feature. Expected to be "performanceCounters" or "syslogEvents" :return: the list of names; might be an empty list :rtype: [str] """ return get_sink_list(get_diagnostics_monitor_configuration_element(ladCfg, feature_name)) class Sinkconfiguration: def __init__(self): self._sinks = {} def insert_from_config(self, json): """ Walk through the sinksConfig JSON object and add all sinks within it. Every accepted sink is guaranteed to have a 'name' and 'type' element. :param json: A hash holding the body of a sinksConfig object :return: A string containing warning messages, or an empty string """ msgs = [] if json and 'sink' in json: for sink in json['sink']: if 'name' in sink and 'type' in sink: self._sinks[sink['name']] = sink else: msgs.append('Ignoring invalid sink definition {0}'.format(sink)) return '\n'.join(msgs) def get_sink_by_name(self, sink_name): """ Return the JSON object defining a particular sink. :param sink_name: string name of sink :return: JSON object or None """ if sink_name in self._sinks: return self._sinks[sink_name] return None def get_all_sink_names(self): """ Return a list of all names of defined sinks. :return: list of names """ return self._sinks.keys() def get_sinks_by_type(self, sink_type): """ Return a list of all names of defined sinks. :return: list of names """ return [self._sinks[name] for name in self._sinks if self._sinks[name]['type'] == sink_type]
# *################### # * SYMBOL TABLE # *################### class SymbolTable: def __init__(self, parent=None): self.symbols = {} self.parent = parent def get(self, name): value = self.symbols.get(name, None) if value is None and self.parent: return self.parent.get(name) return value def set(self, name, value): self.symbols[name] = value def remove(self, name): del self.symbols[name]
class Symboltable: def __init__(self, parent=None): self.symbols = {} self.parent = parent def get(self, name): value = self.symbols.get(name, None) if value is None and self.parent: return self.parent.get(name) return value def set(self, name, value): self.symbols[name] = value def remove(self, name): del self.symbols[name]
#!/usr/bin/env python3 try: print('If you provide a legal file name, this program will output the last two lines of the song to that file...') print('\nMary had a little lamb,') answersnow = input('With fleece as white as (enter your file name): ') answersnowobj = open(answersnow, 'w') except: print('Error with that file name!') else: print('and every where that mary went', file=answersnowobj) print('The lamb was sure to go', file=answersnowobj) answersnowobj.close() finally: print('Thanks for playing!') quit()
try: print('If you provide a legal file name, this program will output the last two lines of the song to that file...') print('\nMary had a little lamb,') answersnow = input('With fleece as white as (enter your file name): ') answersnowobj = open(answersnow, 'w') except: print('Error with that file name!') else: print('and every where that mary went', file=answersnowobj) print('The lamb was sure to go', file=answersnowobj) answersnowobj.close() finally: print('Thanks for playing!') quit()
def solve_knapsack(profits, weights, capacity): # basic checks n = len(profits) if capacity <= 0 or n == 0 or len(weights) != n: return 0 dp = [0 for x in range(capacity + 1)] # <<<<<<<<<< # if we have only one weight, we will take it if it is not more than the capacity for c in range(0, capacity + 1): if weights[0] <= c: dp[c] = profits[0] # process all sub-arrays for all the capacities for i in range(1, n): for c in range(capacity, -1, -1): # <<<<<<<< profit_by_including, profit_by_excluding = 0, 0 if weights[i] <= c: # include the item, if it is not more than the capacity profit_by_including = profits[i] + dp[c - weights[i]] profit_by_excluding = dp[c] # exclude the item dp[c] = max(profit_by_including, profit_by_excluding) # take maximum return dp[capacity] if __name__ == '__main__': print("Total knapsack profit: ", str(solve_knapsack([1, 6, 10, 16], [1, 2, 3, 5], 7))) print("Total knapsack profit: ", str(solve_knapsack([1, 6, 10, 16], [1, 2, 3, 5], 6)))
def solve_knapsack(profits, weights, capacity): n = len(profits) if capacity <= 0 or n == 0 or len(weights) != n: return 0 dp = [0 for x in range(capacity + 1)] for c in range(0, capacity + 1): if weights[0] <= c: dp[c] = profits[0] for i in range(1, n): for c in range(capacity, -1, -1): (profit_by_including, profit_by_excluding) = (0, 0) if weights[i] <= c: profit_by_including = profits[i] + dp[c - weights[i]] profit_by_excluding = dp[c] dp[c] = max(profit_by_including, profit_by_excluding) return dp[capacity] if __name__ == '__main__': print('Total knapsack profit: ', str(solve_knapsack([1, 6, 10, 16], [1, 2, 3, 5], 7))) print('Total knapsack profit: ', str(solve_knapsack([1, 6, 10, 16], [1, 2, 3, 5], 6)))
input1 = input("Insira a palavra #1") input2 = input("Insira a palavra #2") input3 = input("Insira a palavra #3") input3 = input3.upper().replace('A', '').replace('E', '').replace('I', '').replace('O', '').replace('U', '') print(input1.upper()) print(input2.lower()) print(input3)
input1 = input('Insira a palavra #1') input2 = input('Insira a palavra #2') input3 = input('Insira a palavra #3') input3 = input3.upper().replace('A', '').replace('E', '').replace('I', '').replace('O', '').replace('U', '') print(input1.upper()) print(input2.lower()) print(input3)
# Define a simple function that prints x def f(x): x += 1 print(x) # Set y y = 10 # Call the function f(y) # Print y to see if it changed print(y)
def f(x): x += 1 print(x) y = 10 f(y) print(y)
# # @lc app=leetcode id=922 lang=python3 # # [922] Sort Array By Parity II # # @lc code=start class Solution: def sortArrayByParityII(self, a: List[int]) -> List[int]: i = 0 # pointer for even misplaced j = 1 # pointer for odd misplaced sz = len(a) # invariant: for every misplaced odd there is misplaced even # since there is just enough space for odds and evens while i < sz and j < sz: if a[i] % 2 == 0: i += 2 elif a[j] % 2 == 1: j += 2 else: # a[i] % 2 == 1 AND a[j] % 2 == 0 a[i],a[j] = a[j],a[i] i += 2 j += 2 return a # @lc code=end
class Solution: def sort_array_by_parity_ii(self, a: List[int]) -> List[int]: i = 0 j = 1 sz = len(a) while i < sz and j < sz: if a[i] % 2 == 0: i += 2 elif a[j] % 2 == 1: j += 2 else: (a[i], a[j]) = (a[j], a[i]) i += 2 j += 2 return a
class StringUtil: @staticmethod def is_empty(string): if string is None or string.strip() == "": return True else: return False @staticmethod def is_not_empty(string): return not StringUtil.is_empty(string)
class Stringutil: @staticmethod def is_empty(string): if string is None or string.strip() == '': return True else: return False @staticmethod def is_not_empty(string): return not StringUtil.is_empty(string)
#!python3 #encoding:utf-8 class Json2Sqlite(object): def __init__(self): pass def BoolToInt(self, bool_value): if True == bool_value: return 1 else: return 0 def IntToBool(self, int_value): if 0 == int_value: return False else: return True def ArrayToString(self, array): if None is array or 0 == len(array): return None ret = "" for v in array: ret += v + ',' print(ret) print(ret[:-1]) return ret[:-1] def StringToArray(self, string): if None is string or 0 == len(string): return None array = [] for item in string.sprit(','): if 0 < len(item): array.append(item) return array
class Json2Sqlite(object): def __init__(self): pass def bool_to_int(self, bool_value): if True == bool_value: return 1 else: return 0 def int_to_bool(self, int_value): if 0 == int_value: return False else: return True def array_to_string(self, array): if None is array or 0 == len(array): return None ret = '' for v in array: ret += v + ',' print(ret) print(ret[:-1]) return ret[:-1] def string_to_array(self, string): if None is string or 0 == len(string): return None array = [] for item in string.sprit(','): if 0 < len(item): array.append(item) return array
INPUT = { "google": { "id_token": "" }, "github": { "code": "", "state": "" } }
input = {'google': {'id_token': ''}, 'github': {'code': '', 'state': ''}}
"""Constants for the Kuna component.""" ATTR_NOTIFICATIONS_ENABLED = "notifications_enabled" ATTR_SERIAL_NUMBER = "serial_number" ATTR_VOLUME = "volume" CONF_RECORDING_INTERVAL = "recording_interval" CONF_STREAM_INTERVAL = "stream_interval" CONF_UPDATE_INTERVAL = "update_interval" DEFAULT_RECORDING_INTERVAL = 7200 DEFAULT_STREAM_INTERVAL = 5 DEFAULT_UPDATE_INTERVAL = 15 DOMAIN = "kuna" MANUFACTURER = "Kuna Smart Home Security"
"""Constants for the Kuna component.""" attr_notifications_enabled = 'notifications_enabled' attr_serial_number = 'serial_number' attr_volume = 'volume' conf_recording_interval = 'recording_interval' conf_stream_interval = 'stream_interval' conf_update_interval = 'update_interval' default_recording_interval = 7200 default_stream_interval = 5 default_update_interval = 15 domain = 'kuna' manufacturer = 'Kuna Smart Home Security'
base=10 height=5 area=1/2*(base*height) print("Area of our triangle is : ", area) file = open("/Users/lipingzhang/Desktop/program/pycharm/seq2seq/MNIST_data/0622_train_features.csv","r") lines = [] with file as myFile: for line in file: feat = [] line = line.split(',') for i in range(0, len(line)): feat.append(float(line[i])) lines.append(feat.tolist())
base = 10 height = 5 area = 1 / 2 * (base * height) print('Area of our triangle is : ', area) file = open('/Users/lipingzhang/Desktop/program/pycharm/seq2seq/MNIST_data/0622_train_features.csv', 'r') lines = [] with file as my_file: for line in file: feat = [] line = line.split(',') for i in range(0, len(line)): feat.append(float(line[i])) lines.append(feat.tolist())
def main(): A=input("Enter the string") A1=A[0:2:1] A2=A[-2::1] print(A1) print(A2) A3=(A1+A2) print("The new string is " ,A3) if(__name__== '__main__'): main()
def main(): a = input('Enter the string') a1 = A[0:2:1] a2 = A[-2::1] print(A1) print(A2) a3 = A1 + A2 print('The new string is ', A3) if __name__ == '__main__': main()
''' Kattis - memorymatch Consider the 2 different corner cases and the rest is not too hard. Time: O(num_opens), Space: O(n) ''' n = int(input()) num_opens = int(input()) cards = {} turned_off = set() for i in range(num_opens): x, y, cx, cy = input().split() x, y = int(x), int(y) if not cx in cards: cards[cx] = set() if not cy in cards: cards[cy] = set() cards[cx].add(x) cards[cy].add(y) if cx == cy: turned_off.add(x) turned_off.add(y) # Corner case where u know at least 1 of every type of card if len(cards) == n//2: min_length = min(len(cards[c]) for c in cards) if min_length >= 1: print(n//2 - len(turned_off)//2) exit() ans = 0 for x in cards: if len(cards[x]) == 2: for e in cards[x]: if e in turned_off: break else: ans += 1 if ans + len(turned_off)//2 == n//2 - 1: print(ans + 1) # Corner case where u have n-1 pairs already exit() print(ans)
""" Kattis - memorymatch Consider the 2 different corner cases and the rest is not too hard. Time: O(num_opens), Space: O(n) """ n = int(input()) num_opens = int(input()) cards = {} turned_off = set() for i in range(num_opens): (x, y, cx, cy) = input().split() (x, y) = (int(x), int(y)) if not cx in cards: cards[cx] = set() if not cy in cards: cards[cy] = set() cards[cx].add(x) cards[cy].add(y) if cx == cy: turned_off.add(x) turned_off.add(y) if len(cards) == n // 2: min_length = min((len(cards[c]) for c in cards)) if min_length >= 1: print(n // 2 - len(turned_off) // 2) exit() ans = 0 for x in cards: if len(cards[x]) == 2: for e in cards[x]: if e in turned_off: break else: ans += 1 if ans + len(turned_off) // 2 == n // 2 - 1: print(ans + 1) exit() print(ans)
# Copyright 2020 Tensorforce Team. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with 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 in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== class TensorforceConfig(object): # modify dtype mappings def __init__( self, *, buffer_observe=False, create_debug_assertions=False, create_tf_assertions=True, device='CPU', eager_mode=False, enable_int_action_masking=True, name='agent', seed=None, tf_log_level=40 ): assert buffer_observe is False or buffer_observe == 'episode' or \ isinstance(buffer_observe, int) and buffer_observe >= 1 if buffer_observe is False: buffer_observe = 1 super().__setattr__('buffer_observe', buffer_observe) assert isinstance(create_debug_assertions, bool) super().__setattr__('create_debug_assertions', create_debug_assertions) assert isinstance(create_tf_assertions, bool) super().__setattr__('create_tf_assertions', create_tf_assertions) assert isinstance(eager_mode, bool) super().__setattr__('eager_mode', eager_mode) assert isinstance(enable_int_action_masking, bool) super().__setattr__('enable_int_action_masking', enable_int_action_masking) assert device is None or isinstance(device, str) # more specific? super().__setattr__('device', device) assert isinstance(name, str) super().__setattr__('name', name) assert seed is None or isinstance(seed, int) super().__setattr__('seed', seed) assert isinstance(tf_log_level, int) and tf_log_level >= 0 super().__setattr__('tf_log_level', tf_log_level) def __setattr__(self, name, value): raise NotImplementedError def __delattr__(self, name): raise NotImplementedError
class Tensorforceconfig(object): def __init__(self, *, buffer_observe=False, create_debug_assertions=False, create_tf_assertions=True, device='CPU', eager_mode=False, enable_int_action_masking=True, name='agent', seed=None, tf_log_level=40): assert buffer_observe is False or buffer_observe == 'episode' or (isinstance(buffer_observe, int) and buffer_observe >= 1) if buffer_observe is False: buffer_observe = 1 super().__setattr__('buffer_observe', buffer_observe) assert isinstance(create_debug_assertions, bool) super().__setattr__('create_debug_assertions', create_debug_assertions) assert isinstance(create_tf_assertions, bool) super().__setattr__('create_tf_assertions', create_tf_assertions) assert isinstance(eager_mode, bool) super().__setattr__('eager_mode', eager_mode) assert isinstance(enable_int_action_masking, bool) super().__setattr__('enable_int_action_masking', enable_int_action_masking) assert device is None or isinstance(device, str) super().__setattr__('device', device) assert isinstance(name, str) super().__setattr__('name', name) assert seed is None or isinstance(seed, int) super().__setattr__('seed', seed) assert isinstance(tf_log_level, int) and tf_log_level >= 0 super().__setattr__('tf_log_level', tf_log_level) def __setattr__(self, name, value): raise NotImplementedError def __delattr__(self, name): raise NotImplementedError