content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
def hypotenuse_triangle(side1, side2): hypotenuse = side1 ** 2 + side2 ** 2 return hypotenuse print(hypotenuse_triangle(2, 4))
def hypotenuse_triangle(side1, side2): hypotenuse = side1 ** 2 + side2 ** 2 return hypotenuse print(hypotenuse_triangle(2, 4))
# Tuplas sao imutaveis, nao se pode substituir um valor enquanto o programa estiver rodando # oq foi definido no inicio permanece ate o final lanche = ('hamburguer', 'pizza', 'suco', 'refri') print(lanche[1]) print(lanche[-1]) #-1 mostra o ultimo elemento print(sorted(lanche)) #para organizar a lista em ordem alfabetica porem nao vai mudar os iten for comida in lanche: print(f'comi bastante {comida}') # A variavel comida vai percorrer cada valor na lista lanche, vai pegar os nomes print('estou gordo') for cont in range(0, len(lanche)): print(cont) # vai pegar o endereco da lista (0,1,2...) por causa das () print('fim') for food in range(0, len(lanche)): print(lanche[food], f'na posicao {food}') # vai pegar na lista lanche o endereco food 0,1,2,3... print('end')
lanche = ('hamburguer', 'pizza', 'suco', 'refri') print(lanche[1]) print(lanche[-1]) print(sorted(lanche)) for comida in lanche: print(f'comi bastante {comida}') print('estou gordo') for cont in range(0, len(lanche)): print(cont) print('fim') for food in range(0, len(lanche)): print(lanche[food], f'na posicao {food}') print('end')
FULL_ACCESS_GMAIL_SCOPE = "https://mail.google.com/" LABELS_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.labels" SEND_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.send" READ_ONLY_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.readonly" COMPOSE_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.compose" INSERT_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.insert" MODIFY_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.modify" METADATA_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.metadata" SETTINGS_BASIC_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.settings.basic" SETTINGS_SHARING_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.settings.sharing"
full_access_gmail_scope = 'https://mail.google.com/' labels_gmail_scope = 'https://www.googleapis.com/auth/gmail.labels' send_gmail_scope = 'https://www.googleapis.com/auth/gmail.send' read_only_gmail_scope = 'https://www.googleapis.com/auth/gmail.readonly' compose_gmail_scope = 'https://www.googleapis.com/auth/gmail.compose' insert_gmail_scope = 'https://www.googleapis.com/auth/gmail.insert' modify_gmail_scope = 'https://www.googleapis.com/auth/gmail.modify' metadata_gmail_scope = 'https://www.googleapis.com/auth/gmail.metadata' settings_basic_gmail_scope = 'https://www.googleapis.com/auth/gmail.settings.basic' settings_sharing_gmail_scope = 'https://www.googleapis.com/auth/gmail.settings.sharing'
def read(): x = int(input()) return x a = read() b = read() c = read() d = read() if b == c and b + c == d and b + c + d == a: print("S") else: print("N")
def read(): x = int(input()) return x a = read() b = read() c = read() d = read() if b == c and b + c == d and (b + c + d == a): print('S') else: print('N')
def test_home(client): response = client.get('/') #import pdb;pdb.set_trace() assert response.status_code == 200 assert response.template_name == ['home.html']
def test_home(client): response = client.get('/') assert response.status_code == 200 assert response.template_name == ['home.html']
# MIT licensed # Copyright (c) 2013-2020 lilydjwg <[email protected]>, et al. HACKAGE_URL = 'https://hackage.haskell.org/package/%s/preferred.json' async def get_version(name, conf, *, cache, **kwargs): key = conf.get('hackage', name) data = await cache.get_json(HACKAGE_URL % key) return data['normal-version'][0]
hackage_url = 'https://hackage.haskell.org/package/%s/preferred.json' async def get_version(name, conf, *, cache, **kwargs): key = conf.get('hackage', name) data = await cache.get_json(HACKAGE_URL % key) return data['normal-version'][0]
load( "//scala:advanced_usage/providers.bzl", _ScalaRulePhase = "ScalaRulePhase", ) load( "//scala/private:phases/phases.bzl", _phase_bloop = "phase_bloop", ) ext_add_phase_bloop = { "attrs": { # "bloopDir": attr.label( # allow_single_file = True, # doc = "Bloop output folder", # ), "_bloop": attr.label( cfg = "host", default = "//scala/bloop", executable = True, ), # "_runner": attr.label( # allow_single_file = True, # default = "//scala/bloop:runner", # ), # "_testrunner": attr.label( # allow_single_file = True, # default = "//scala/bloop:testrunner", # ), # "format": attr.bool( # default = False, # ), }, "phase_providers": [ "//scala/bloop:add_phase_bloop", ], } def _add_phase_bloop_singleton_implementation(ctx): return [ _ScalaRulePhase( custom_phases = [ #TODO plan is to make it a phase at the end then replace it later. Use phases before compile. ("=", "compile", "compile", _phase_bloop), # ("$", "", "bloop", _phase_bloop) # ("after", "compile", "bloop", _phase_bloop) ], ), ] add_phase_bloop_singleton = rule( implementation = _add_phase_bloop_singleton_implementation, )
load('//scala:advanced_usage/providers.bzl', _ScalaRulePhase='ScalaRulePhase') load('//scala/private:phases/phases.bzl', _phase_bloop='phase_bloop') ext_add_phase_bloop = {'attrs': {'_bloop': attr.label(cfg='host', default='//scala/bloop', executable=True)}, 'phase_providers': ['//scala/bloop:add_phase_bloop']} def _add_phase_bloop_singleton_implementation(ctx): return [__scala_rule_phase(custom_phases=[('=', 'compile', 'compile', _phase_bloop)])] add_phase_bloop_singleton = rule(implementation=_add_phase_bloop_singleton_implementation)
angka = { 0: 'tepat', 1: 'satu', 2: 'dua', 3: 'tiga', 4: 'empat', 5: 'lima', 6: 'enam', 7: 'tujuh', 8: 'delapan', 9: 'sembilan', 10: 'sepuluh', 11: 'sebelas', 12: 'dua belas', } def eja(n): lut1 = ['nol', 'satu', 'dua', 'tiga', 'empat', 'lima', 'enam', 'tujuh', 'delapan', 'sembilan', 'sepuluh', 'sebelas', 'dua belas', 'tiga belas', 'empat belas', 'lima belas', 'enam belas', 'tujuh belas', 'delapan belas', 'sembilan belas'] lut20 = ['x', 'x', 'dua puluh', 'tiga puluh', 'empat puluh', 'lima puluh', 'enam puluh', 'tujuh puluh', 'delapan puluh', 'sembilan puluh'] triples = ['x', 'ribu', 'juta', 'miliar', 'biliar', 'quadrillion', 'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion', 'decillion'] words = [] shift = 0 hasNumber = False insertpos = -1 while n > 0: ones = n % 10 shiftmod = shift % 3 shiftdiv = shift / 3 if shiftdiv > 0 and shiftmod == 0: insertpos = len(words) hasNumber = False if shiftmod == 2 and ones > 0: words.append('ratus') words.append(lut1[ones]) hasNumber = True if shiftmod == 1 and ones > 0: words.append(lut20[ones]) hasNumber = True if shiftmod == 0: tens = n % 100 if 0 < tens < 20: words.append(lut1[tens]) shift += 1 n = n / 10 hasNumber = True elif ones > 0: words.append(lut1[ones]) hasNumber = True if hasNumber and insertpos >= 0: words.insert(insertpos, triples[shiftdiv]) insertpos = -1 hasNumber = False n = n / 10 shift += 1 # oldones = ones words.reverse() text = ' '.join(words) result = text.split(' ') return result # return words if words else ['nol'] def mid(n): "around `n` +/- 1" return [n-1, n, n+1] def ucapkan(h, m): # jam = angka.get(h) # menit = angka.get(m) jam = eja(h) menit = eja(m) waktu = [] if m in mid(0) + [59]: waktu = [jam, 'tepat'] elif m in mid(15): waktu = [jam, 'seperempat'] elif m in mid(30): jam = eja(h+1) waktu = ['setengah', jam] elif m in mid(45): jam = eja(h+1) waktu = [jam, 'kurang', 'seperempat'] elif m < 30: waktu = [jam, 'lebih', menit] else: # waktu = [jam, menit] jam = eja(h+1) menit = eja(abs(60-m)) waktu = [jam, 'kurang', menit] return flattened(waktu) def flattened(arr): words = [] for r in arr: if isinstance(r, list): words += r else: words.append(r) text = ' '.join(words) result = text.split(' ') return result
angka = {0: 'tepat', 1: 'satu', 2: 'dua', 3: 'tiga', 4: 'empat', 5: 'lima', 6: 'enam', 7: 'tujuh', 8: 'delapan', 9: 'sembilan', 10: 'sepuluh', 11: 'sebelas', 12: 'dua belas'} def eja(n): lut1 = ['nol', 'satu', 'dua', 'tiga', 'empat', 'lima', 'enam', 'tujuh', 'delapan', 'sembilan', 'sepuluh', 'sebelas', 'dua belas', 'tiga belas', 'empat belas', 'lima belas', 'enam belas', 'tujuh belas', 'delapan belas', 'sembilan belas'] lut20 = ['x', 'x', 'dua puluh', 'tiga puluh', 'empat puluh', 'lima puluh', 'enam puluh', 'tujuh puluh', 'delapan puluh', 'sembilan puluh'] triples = ['x', 'ribu', 'juta', 'miliar', 'biliar', 'quadrillion', 'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion', 'decillion'] words = [] shift = 0 has_number = False insertpos = -1 while n > 0: ones = n % 10 shiftmod = shift % 3 shiftdiv = shift / 3 if shiftdiv > 0 and shiftmod == 0: insertpos = len(words) has_number = False if shiftmod == 2 and ones > 0: words.append('ratus') words.append(lut1[ones]) has_number = True if shiftmod == 1 and ones > 0: words.append(lut20[ones]) has_number = True if shiftmod == 0: tens = n % 100 if 0 < tens < 20: words.append(lut1[tens]) shift += 1 n = n / 10 has_number = True elif ones > 0: words.append(lut1[ones]) has_number = True if hasNumber and insertpos >= 0: words.insert(insertpos, triples[shiftdiv]) insertpos = -1 has_number = False n = n / 10 shift += 1 words.reverse() text = ' '.join(words) result = text.split(' ') return result def mid(n): """around `n` +/- 1""" return [n - 1, n, n + 1] def ucapkan(h, m): jam = eja(h) menit = eja(m) waktu = [] if m in mid(0) + [59]: waktu = [jam, 'tepat'] elif m in mid(15): waktu = [jam, 'seperempat'] elif m in mid(30): jam = eja(h + 1) waktu = ['setengah', jam] elif m in mid(45): jam = eja(h + 1) waktu = [jam, 'kurang', 'seperempat'] elif m < 30: waktu = [jam, 'lebih', menit] else: jam = eja(h + 1) menit = eja(abs(60 - m)) waktu = [jam, 'kurang', menit] return flattened(waktu) def flattened(arr): words = [] for r in arr: if isinstance(r, list): words += r else: words.append(r) text = ' '.join(words) result = text.split(' ') return result
#!/usr/bin/env python # coding: utf-8 # In[99]: class TreeNode: def __init__(self, val = None, par = None): self.left = None self.right = None self.value = val self.parent = par def left_child(self): return self.left def right_child(self): return self.right def set_value(self, val): self.value = val def get_value(self): return self.value def set_left(self, node): self.left = node node.parent = self return node def set_right(self, node): self.right = node node.parent = self return node def get_parent(self): return self.parent def level(self): result = 0 temp = self while temp.parent is not None: temp = temp.parent result += 1 return result def add(self, item): if item < self.get_value() : if self.left_child() is None: self.set_left(TreeNode(item)) else: self.left_child().add(item) else: if self.right_child() is None: self.set_right(TreeNode(item)) else: self.right_child().add(item) def preOrder(self, resultList): resultList.append(self.value) if self.left_child() is not None: self.left_child().preOrder(resultList) if self.right_child() is not None: self.right_child().preOrder(resultList) def inOrder(self, resultList): if self.left_child() is not None: self.left_child().inOrder(resultList) resultList.append(self.value) if self.right_child() is not None: self.right_child().inOrder(resultList) def postOrder(self, resultList): if self.left_child() is not None: self.left_child().postOrder(resultList) if self.right_child() is not None: self.right_child().postOrder(resultList) resultList.append(self.value) def find(self, item): if self.value == item: return self.value elif item < self.value: if self.left_child() is not None: return self.left_child().find(item) else: raise ValueError() else: if self.right_child() is not None: return self.right_child().find(item) else: raise ValueError() def preOrderStr(self): if self.left_child() is not None: self.left_child().preOrderStr() if self.right_child() is not None: self.right_child().preOrderStr() print("".ljust(self.level()*2), str(self.value)) def __str__(self): return str(self.value) # In[107]: class Pair: ''' Encapsulate letter,count pair as a single entity. Realtional methods make this object comparable using built-in operators. ''' def __init__(self, letter, count = 1): self.letter = letter self.count = count def __eq__(self, other): return self.letter == other.letter def __hash__(self): return hash(self.letter) def __ne__(self, other): return self.letter != other.letter def __lt__(self, other): return self.letter < other.letter def __le__(self, other): return self.letter <= other.letter def __gt__(self, other): return self.letter > other.letter def __ge__(self, other): return self.letter >= other.letter def __repr__(self): return f'({self.letter}, {self.count})' def __str__(self): return f'({self.letter}, {self.count})' class BinarySearchTree: def __init__(self): self.root = None def is_empty(self): return self.root is None def size(self): return self.__size(self.root) def __size(self, node): if node is None: return 0 result = 1 result += self.__size(node.left) result += self.__size(node.right) return result def add(self, item): if self.root is None: self.root = TreeNode(item) else: self.root.add(item) return self.root def find(self, item): if self.root is not None: return self.root.find(item) raise ValueError() def remove(self, item): return self.__remove(self.root, item) def __remove(self, node, item): if node is None: return node if item < node.get_value(): node.set_left(self.__remove(node.left_child(), item)) elif item > node.get_value(): node.set_right(self.__remove(node.right_child(), item)) else: if node.left_child() is None: temp = node.right_child() if temp is not None: temp.parent = node.parent node = None return temp elif node.right_child() is None: temp = node.left_child() if temp is not None: temp.parent = node.parent node = None return temp else: minNode = self.__minValueNode(node.right_child()) node.set_value(minNode.get_value()) node.set_right(self.__remove(node.right_child(), minNode.get_value())) return node def __minValueNode(self, node): current = node while (current.left_child() is not None): current = current.left_child() return current def inOrder(self): result = [] if self.root is not None: self.root.inOrder(result) return result def preOrder(self): result = [] if self.root is not None: self.root.preOrder(result) return result def postOrder(self): result = [] if self.root is not None: self.root.postOrder(result) return result def rebalance(self): orderedList = self.inOrder() self.root = None self.__rebalance(orderedList, 0, len(orderedList) - 1) def __rebalance(self, orderedList, low, high): if (low <= high): mid = (high - low) // 2 + low self.add(orderedList[mid]) self.__rebalance(orderedList, low, mid - 1) self.__rebalance(orderedList, mid + 1, high) def height(self): return self.__recursiveHeight(self.root, 0) def __recursiveHeight(self, node, current): leftValue = current rightValue = current if node.left_child() is not None: leftValue = self.__recursiveHeight(node.left, current + 1) if node.right_child() is not None: rightValue = self.__recursiveHeight(node.right, current + 1) return max(leftValue, rightValue) def __strInsert(self, value, position, char): return str(value[:position] + char + value[position + 1:]) def __str__(self): # if self.root is not None: # self.root.preOrderStr() # return "" totalLayers = self.height() + 1 totalWidth = (2 ** totalLayers) * 2 nodePosition = [None] * (totalLayers) for i in range(totalLayers): nodePosition[i] = [None] * (2 ** i) for j in range(2 ** i): nodePosition[i][j] = [0] * 3 lastLayer = nodePosition[totalLayers - 1] gap = totalWidth // len(lastLayer) for i in range(len(lastLayer)): lastLayer[i][0] = i * gap lastLayer[i][1] = lastLayer[i][0] lastLayer[i][2] = lastLayer[i][0] for i in reversed(range(totalLayers - 1)): for j in range(len(nodePosition[i])): first = nodePosition[i + 1][j * 2][0] second = nodePosition[i + 1][j * 2 + 1][0] nodePosition[i][j][1] = first + 1 nodePosition[i][j][2] = second - 1 nodePosition[i][j][0] = ((second - first) // 2) + first result = [""] * (totalLayers * 2) for i in range(1, len(result), 2): for j in range(totalWidth): result[i] += " " self.__nodePrettyPrint(result, self.root, [0] * (totalLayers), nodePosition, ' ') return "\n".join(result) def __nodePrettyPrint(self, result, node, nodeList, nodePosition, char): level = node.level() startLine = nodePosition[level][nodeList[level]][1] endLine = nodePosition[level][nodeList[level]][2] position = nodePosition[level][nodeList[level]][0] resultLevel = level * 2 nodeList[level] += 1 currentLen = len(result[resultLevel]) for i in range(currentLen - 1, startLine): result[resultLevel] += " " for i in range(startLine, position): result[resultLevel] += "_" result[resultLevel] += str(node.get_value()) for i in range(position + len(str(node.get_value())), endLine): result[resultLevel] += "_" result[resultLevel + 1] = self.__strInsert(result[resultLevel + 1], startLine, '/') if (endLine == startLine): endLine += len(str(node.get_value())) result[resultLevel + 1] = self.__strInsert(result[resultLevel + 1], endLine + 1, '\\') if (node.left_child() is not None): self.__nodePrettyPrint(result, node.left_child(), nodeList, nodePosition, '/') elif (level + 1) < len(nodeList): nextLevel = level + 1 capacity = 1 while nextLevel < len(nodeList): nodeList[nextLevel] += capacity capacity *= 2 nextLevel += 1 if (node.right_child() is not None): self.__nodePrettyPrint(result, node.right_child(), nodeList, nodePosition, '\\') elif (level + 1) < len(nodeList): nextLevel = level + 1 capacity = 1 while nextLevel < len(nodeList): nodeList[nextLevel] += capacity capacity *= 2 nextLevel += 1 # In[109]: myTree = BinarySearchTree() myTree.add(12) myTree.add(7) myTree.add(20) myTree.add(99) myTree.add(32) myTree.add(46) print(myTree) myTree.rebalance() print(myTree) myTree.remove(46) print() print(myTree) myTree.remove(20) print() print(myTree) # "C:\\Users\\Tavish\\Documents\\School\\Teaching\\CS_2420\\Project5\\around-the-world-in-80-days-3.txt" myTree = BinarySearchTree() with open("D:\\UVU\\Code\\Fall2020\\Child-Stuff\\CS2420\\Mod5\\P5\\around-the-world-in-80-days-3.txt", "r") as f: while True: c = f.read(1) if not c: break if c.isalnum(): try: found = myTree.find(Pair(c)) found.count += 1 except ValueError: myTree.add(Pair(c)) # myTree.rebalance() # print(myTree) # In[ ]: # In[ ]:
class Treenode: def __init__(self, val=None, par=None): self.left = None self.right = None self.value = val self.parent = par def left_child(self): return self.left def right_child(self): return self.right def set_value(self, val): self.value = val def get_value(self): return self.value def set_left(self, node): self.left = node node.parent = self return node def set_right(self, node): self.right = node node.parent = self return node def get_parent(self): return self.parent def level(self): result = 0 temp = self while temp.parent is not None: temp = temp.parent result += 1 return result def add(self, item): if item < self.get_value(): if self.left_child() is None: self.set_left(tree_node(item)) else: self.left_child().add(item) elif self.right_child() is None: self.set_right(tree_node(item)) else: self.right_child().add(item) def pre_order(self, resultList): resultList.append(self.value) if self.left_child() is not None: self.left_child().preOrder(resultList) if self.right_child() is not None: self.right_child().preOrder(resultList) def in_order(self, resultList): if self.left_child() is not None: self.left_child().inOrder(resultList) resultList.append(self.value) if self.right_child() is not None: self.right_child().inOrder(resultList) def post_order(self, resultList): if self.left_child() is not None: self.left_child().postOrder(resultList) if self.right_child() is not None: self.right_child().postOrder(resultList) resultList.append(self.value) def find(self, item): if self.value == item: return self.value elif item < self.value: if self.left_child() is not None: return self.left_child().find(item) else: raise value_error() elif self.right_child() is not None: return self.right_child().find(item) else: raise value_error() def pre_order_str(self): if self.left_child() is not None: self.left_child().preOrderStr() if self.right_child() is not None: self.right_child().preOrderStr() print(''.ljust(self.level() * 2), str(self.value)) def __str__(self): return str(self.value) class Pair: """ Encapsulate letter,count pair as a single entity. Realtional methods make this object comparable using built-in operators. """ def __init__(self, letter, count=1): self.letter = letter self.count = count def __eq__(self, other): return self.letter == other.letter def __hash__(self): return hash(self.letter) def __ne__(self, other): return self.letter != other.letter def __lt__(self, other): return self.letter < other.letter def __le__(self, other): return self.letter <= other.letter def __gt__(self, other): return self.letter > other.letter def __ge__(self, other): return self.letter >= other.letter def __repr__(self): return f'({self.letter}, {self.count})' def __str__(self): return f'({self.letter}, {self.count})' class Binarysearchtree: def __init__(self): self.root = None def is_empty(self): return self.root is None def size(self): return self.__size(self.root) def __size(self, node): if node is None: return 0 result = 1 result += self.__size(node.left) result += self.__size(node.right) return result def add(self, item): if self.root is None: self.root = tree_node(item) else: self.root.add(item) return self.root def find(self, item): if self.root is not None: return self.root.find(item) raise value_error() def remove(self, item): return self.__remove(self.root, item) def __remove(self, node, item): if node is None: return node if item < node.get_value(): node.set_left(self.__remove(node.left_child(), item)) elif item > node.get_value(): node.set_right(self.__remove(node.right_child(), item)) elif node.left_child() is None: temp = node.right_child() if temp is not None: temp.parent = node.parent node = None return temp elif node.right_child() is None: temp = node.left_child() if temp is not None: temp.parent = node.parent node = None return temp else: min_node = self.__minValueNode(node.right_child()) node.set_value(minNode.get_value()) node.set_right(self.__remove(node.right_child(), minNode.get_value())) return node def __min_value_node(self, node): current = node while current.left_child() is not None: current = current.left_child() return current def in_order(self): result = [] if self.root is not None: self.root.inOrder(result) return result def pre_order(self): result = [] if self.root is not None: self.root.preOrder(result) return result def post_order(self): result = [] if self.root is not None: self.root.postOrder(result) return result def rebalance(self): ordered_list = self.inOrder() self.root = None self.__rebalance(orderedList, 0, len(orderedList) - 1) def __rebalance(self, orderedList, low, high): if low <= high: mid = (high - low) // 2 + low self.add(orderedList[mid]) self.__rebalance(orderedList, low, mid - 1) self.__rebalance(orderedList, mid + 1, high) def height(self): return self.__recursiveHeight(self.root, 0) def __recursive_height(self, node, current): left_value = current right_value = current if node.left_child() is not None: left_value = self.__recursiveHeight(node.left, current + 1) if node.right_child() is not None: right_value = self.__recursiveHeight(node.right, current + 1) return max(leftValue, rightValue) def __str_insert(self, value, position, char): return str(value[:position] + char + value[position + 1:]) def __str__(self): total_layers = self.height() + 1 total_width = 2 ** totalLayers * 2 node_position = [None] * totalLayers for i in range(totalLayers): nodePosition[i] = [None] * 2 ** i for j in range(2 ** i): nodePosition[i][j] = [0] * 3 last_layer = nodePosition[totalLayers - 1] gap = totalWidth // len(lastLayer) for i in range(len(lastLayer)): lastLayer[i][0] = i * gap lastLayer[i][1] = lastLayer[i][0] lastLayer[i][2] = lastLayer[i][0] for i in reversed(range(totalLayers - 1)): for j in range(len(nodePosition[i])): first = nodePosition[i + 1][j * 2][0] second = nodePosition[i + 1][j * 2 + 1][0] nodePosition[i][j][1] = first + 1 nodePosition[i][j][2] = second - 1 nodePosition[i][j][0] = (second - first) // 2 + first result = [''] * (totalLayers * 2) for i in range(1, len(result), 2): for j in range(totalWidth): result[i] += ' ' self.__nodePrettyPrint(result, self.root, [0] * totalLayers, nodePosition, ' ') return '\n'.join(result) def __node_pretty_print(self, result, node, nodeList, nodePosition, char): level = node.level() start_line = nodePosition[level][nodeList[level]][1] end_line = nodePosition[level][nodeList[level]][2] position = nodePosition[level][nodeList[level]][0] result_level = level * 2 nodeList[level] += 1 current_len = len(result[resultLevel]) for i in range(currentLen - 1, startLine): result[resultLevel] += ' ' for i in range(startLine, position): result[resultLevel] += '_' result[resultLevel] += str(node.get_value()) for i in range(position + len(str(node.get_value())), endLine): result[resultLevel] += '_' result[resultLevel + 1] = self.__strInsert(result[resultLevel + 1], startLine, '/') if endLine == startLine: end_line += len(str(node.get_value())) result[resultLevel + 1] = self.__strInsert(result[resultLevel + 1], endLine + 1, '\\') if node.left_child() is not None: self.__nodePrettyPrint(result, node.left_child(), nodeList, nodePosition, '/') elif level + 1 < len(nodeList): next_level = level + 1 capacity = 1 while nextLevel < len(nodeList): nodeList[nextLevel] += capacity capacity *= 2 next_level += 1 if node.right_child() is not None: self.__nodePrettyPrint(result, node.right_child(), nodeList, nodePosition, '\\') elif level + 1 < len(nodeList): next_level = level + 1 capacity = 1 while nextLevel < len(nodeList): nodeList[nextLevel] += capacity capacity *= 2 next_level += 1 my_tree = binary_search_tree() myTree.add(12) myTree.add(7) myTree.add(20) myTree.add(99) myTree.add(32) myTree.add(46) print(myTree) myTree.rebalance() print(myTree) myTree.remove(46) print() print(myTree) myTree.remove(20) print() print(myTree) my_tree = binary_search_tree() with open('D:\\UVU\\Code\\Fall2020\\Child-Stuff\\CS2420\\Mod5\\P5\\around-the-world-in-80-days-3.txt', 'r') as f: while True: c = f.read(1) if not c: break if c.isalnum(): try: found = myTree.find(pair(c)) found.count += 1 except ValueError: myTree.add(pair(c))
ColorNames = \ { u'aliceblue': (240, 248, 255), u'antiquewhite': (250, 235, 215), u'aqua': (0, 255, 255), u'aquamarine': (127, 255, 212), u'azure': (240, 255, 255), u'beige': (245, 245, 220), u'bisque': (255, 228, 196), u'black': (0, 0, 0), u'blanchedalmond': (255, 235, 205), u'blue': (0, 0, 255), u'blueviolet': (138, 43, 226), u'brown': (165, 42, 42), u'burlywood': (222, 184, 135), u'cadetblue': (95, 158, 160), u'chartreuse': (127, 255, 0), u'chocolate': (210, 105, 30), u'coral': (255, 127, 80), u'cornflowerblue': (100, 149, 237), u'cornsilk': (255, 248, 220), u'crimson': (220, 20, 60), u'cyan': (0, 255, 255), u'darkblue': (0, 0, 139), u'darkcyan': (0, 139, 139), u'darkgoldenrod': (184, 134, 11), u'darkgray': (169, 169, 169), u'darkgreen': (0, 100, 0), u'darkgrey': (169, 169, 169), u'darkkhaki': (189, 183, 107), u'darkmagenta': (139, 0, 139), u'darkolivegreen': (85, 107, 47), u'darkorange': (255, 140, 0), u'darkorchid': (153, 50, 204), u'darkred': (139, 0, 0), u'darksalmon': (233, 150, 122), u'darkseagreen': (143, 188, 143), u'darkslateblue': (72, 61, 139), u'darkslategray': (47, 79, 79), u'darkslategrey': (47, 79, 79), u'darkturquoise': (0, 206, 209), u'darkviolet': (148, 0, 211), u'deeppink': (255, 20, 147), u'deepskyblue': (0, 191, 255), u'dimgray': (105, 105, 105), u'dimgrey': (105, 105, 105), u'dodgerblue': (30, 144, 255), u'firebrick': (178, 34, 34), u'floralwhite': (255, 250, 240), u'forestgreen': (34, 139, 34), u'fuchsia': (255, 0, 255), u'gainsboro': (220, 220, 220), u'ghostwhite': (248, 248, 255), u'gold': (255, 215, 0), u'goldenrod': (218, 165, 32), u'gray': (128, 128, 128), u'green': (0, 128, 0), u'greenyellow': (173, 255, 47), u'grey': (128, 128, 128), u'honeydew': (240, 255, 240), u'hotpink': (255, 105, 180), u'indianred': (205, 92, 92), u'indigo': (75, 0, 130), u'ivory': (255, 255, 240), u'khaki': (240, 230, 140), u'lavender': (230, 230, 250), u'lavenderblush': (255, 240, 245), u'lawngreen': (124, 252, 0), u'lemonchiffon': (255, 250, 205), u'lightblue': (173, 216, 230), u'lightcoral': (240, 128, 128), u'lightcyan': (224, 255, 255), u'lightgoldenrodyellow': (250, 250, 210), u'lightgray': (211, 211, 211), u'lightgreen': (144, 238, 144), u'lightgrey': (211, 211, 211), u'lightpink': (255, 182, 193), u'lightsalmon': (255, 160, 122), u'lightseagreen': (32, 178, 170), u'lightskyblue': (135, 206, 250), u'lightslategray': (119, 136, 153), u'lightslategrey': (119, 136, 153), u'lightsteelblue': (176, 196, 222), u'lightyellow': (255, 255, 224), u'lime': (0, 255, 0), u'limegreen': (50, 205, 50), u'linen': (250, 240, 230), u'magenta': (255, 0, 255), u'maroon': (128, 0, 0), u'mediumaquamarine': (102, 205, 170), u'mediumblue': (0, 0, 205), u'mediumorchid': (186, 85, 211), u'mediumpurple': (147, 112, 219), u'mediumseagreen': (60, 179, 113), u'mediumslateblue': (123, 104, 238), u'mediumspringgreen': (0, 250, 154), u'mediumturquoise': (72, 209, 204), u'mediumvioletred': (199, 21, 133), u'midnightblue': (25, 25, 112), u'mintcream': (245, 255, 250), u'mistyrose': (255, 228, 225), u'moccasin': (255, 228, 181), u'navajowhite': (255, 222, 173), u'navy': (0, 0, 128), u'oldlace': (253, 245, 230), u'olive': (128, 128, 0), u'olivedrab': (107, 142, 35), u'orange': (255, 165, 0), u'orangered': (255, 69, 0), u'orchid': (218, 112, 214), u'palegoldenrod': (238, 232, 170), u'palegreen': (152, 251, 152), u'paleturquoise': (175, 238, 238), u'palevioletred': (219, 112, 147), u'papayawhip': (255, 239, 213), u'peachpuff': (255, 218, 185), u'peru': (205, 133, 63), u'pink': (255, 192, 203), u'plum': (221, 160, 221), u'powderblue': (176, 224, 230), u'purple': (128, 0, 128), u'red': (255, 0, 0), u'rosybrown': (188, 143, 143), u'royalblue': (65, 105, 225), u'saddlebrown': (139, 69, 19), u'salmon': (250, 128, 114), u'sandybrown': (244, 164, 96), u'seagreen': (46, 139, 87), u'seashell': (255, 245, 238), u'sienna': (160, 82, 45), u'silver': (192, 192, 192), u'skyblue': (135, 206, 235), u'slateblue': (106, 90, 205), u'slategray': (112, 128, 144), u'slategrey': (112, 128, 144), u'snow': (255, 250, 250), u'springgreen': (0, 255, 127), u'steelblue': (70, 130, 180), u'tan': (210, 180, 140), u'teal': (0, 128, 128), u'thistle': (216, 191, 216), u'tomato': (255, 99, 71), u'turquoise': (64, 224, 208), u'violet': (238, 130, 238), u'wheat': (245, 222, 179), u'white': (255, 255, 255), u'whitesmoke': (245, 245, 245), u'yellow': (255, 255, 0), u'yellowgreen': (154, 205, 50)}
color_names = {u'aliceblue': (240, 248, 255), u'antiquewhite': (250, 235, 215), u'aqua': (0, 255, 255), u'aquamarine': (127, 255, 212), u'azure': (240, 255, 255), u'beige': (245, 245, 220), u'bisque': (255, 228, 196), u'black': (0, 0, 0), u'blanchedalmond': (255, 235, 205), u'blue': (0, 0, 255), u'blueviolet': (138, 43, 226), u'brown': (165, 42, 42), u'burlywood': (222, 184, 135), u'cadetblue': (95, 158, 160), u'chartreuse': (127, 255, 0), u'chocolate': (210, 105, 30), u'coral': (255, 127, 80), u'cornflowerblue': (100, 149, 237), u'cornsilk': (255, 248, 220), u'crimson': (220, 20, 60), u'cyan': (0, 255, 255), u'darkblue': (0, 0, 139), u'darkcyan': (0, 139, 139), u'darkgoldenrod': (184, 134, 11), u'darkgray': (169, 169, 169), u'darkgreen': (0, 100, 0), u'darkgrey': (169, 169, 169), u'darkkhaki': (189, 183, 107), u'darkmagenta': (139, 0, 139), u'darkolivegreen': (85, 107, 47), u'darkorange': (255, 140, 0), u'darkorchid': (153, 50, 204), u'darkred': (139, 0, 0), u'darksalmon': (233, 150, 122), u'darkseagreen': (143, 188, 143), u'darkslateblue': (72, 61, 139), u'darkslategray': (47, 79, 79), u'darkslategrey': (47, 79, 79), u'darkturquoise': (0, 206, 209), u'darkviolet': (148, 0, 211), u'deeppink': (255, 20, 147), u'deepskyblue': (0, 191, 255), u'dimgray': (105, 105, 105), u'dimgrey': (105, 105, 105), u'dodgerblue': (30, 144, 255), u'firebrick': (178, 34, 34), u'floralwhite': (255, 250, 240), u'forestgreen': (34, 139, 34), u'fuchsia': (255, 0, 255), u'gainsboro': (220, 220, 220), u'ghostwhite': (248, 248, 255), u'gold': (255, 215, 0), u'goldenrod': (218, 165, 32), u'gray': (128, 128, 128), u'green': (0, 128, 0), u'greenyellow': (173, 255, 47), u'grey': (128, 128, 128), u'honeydew': (240, 255, 240), u'hotpink': (255, 105, 180), u'indianred': (205, 92, 92), u'indigo': (75, 0, 130), u'ivory': (255, 255, 240), u'khaki': (240, 230, 140), u'lavender': (230, 230, 250), u'lavenderblush': (255, 240, 245), u'lawngreen': (124, 252, 0), u'lemonchiffon': (255, 250, 205), u'lightblue': (173, 216, 230), u'lightcoral': (240, 128, 128), u'lightcyan': (224, 255, 255), u'lightgoldenrodyellow': (250, 250, 210), u'lightgray': (211, 211, 211), u'lightgreen': (144, 238, 144), u'lightgrey': (211, 211, 211), u'lightpink': (255, 182, 193), u'lightsalmon': (255, 160, 122), u'lightseagreen': (32, 178, 170), u'lightskyblue': (135, 206, 250), u'lightslategray': (119, 136, 153), u'lightslategrey': (119, 136, 153), u'lightsteelblue': (176, 196, 222), u'lightyellow': (255, 255, 224), u'lime': (0, 255, 0), u'limegreen': (50, 205, 50), u'linen': (250, 240, 230), u'magenta': (255, 0, 255), u'maroon': (128, 0, 0), u'mediumaquamarine': (102, 205, 170), u'mediumblue': (0, 0, 205), u'mediumorchid': (186, 85, 211), u'mediumpurple': (147, 112, 219), u'mediumseagreen': (60, 179, 113), u'mediumslateblue': (123, 104, 238), u'mediumspringgreen': (0, 250, 154), u'mediumturquoise': (72, 209, 204), u'mediumvioletred': (199, 21, 133), u'midnightblue': (25, 25, 112), u'mintcream': (245, 255, 250), u'mistyrose': (255, 228, 225), u'moccasin': (255, 228, 181), u'navajowhite': (255, 222, 173), u'navy': (0, 0, 128), u'oldlace': (253, 245, 230), u'olive': (128, 128, 0), u'olivedrab': (107, 142, 35), u'orange': (255, 165, 0), u'orangered': (255, 69, 0), u'orchid': (218, 112, 214), u'palegoldenrod': (238, 232, 170), u'palegreen': (152, 251, 152), u'paleturquoise': (175, 238, 238), u'palevioletred': (219, 112, 147), u'papayawhip': (255, 239, 213), u'peachpuff': (255, 218, 185), u'peru': (205, 133, 63), u'pink': (255, 192, 203), u'plum': (221, 160, 221), u'powderblue': (176, 224, 230), u'purple': (128, 0, 128), u'red': (255, 0, 0), u'rosybrown': (188, 143, 143), u'royalblue': (65, 105, 225), u'saddlebrown': (139, 69, 19), u'salmon': (250, 128, 114), u'sandybrown': (244, 164, 96), u'seagreen': (46, 139, 87), u'seashell': (255, 245, 238), u'sienna': (160, 82, 45), u'silver': (192, 192, 192), u'skyblue': (135, 206, 235), u'slateblue': (106, 90, 205), u'slategray': (112, 128, 144), u'slategrey': (112, 128, 144), u'snow': (255, 250, 250), u'springgreen': (0, 255, 127), u'steelblue': (70, 130, 180), u'tan': (210, 180, 140), u'teal': (0, 128, 128), u'thistle': (216, 191, 216), u'tomato': (255, 99, 71), u'turquoise': (64, 224, 208), u'violet': (238, 130, 238), u'wheat': (245, 222, 179), u'white': (255, 255, 255), u'whitesmoke': (245, 245, 245), u'yellow': (255, 255, 0), u'yellowgreen': (154, 205, 50)}
# https://stackoverflow.com/questions/63626389/how-to-sort-points-along-a-hilbert-curve-without-using-hilbert-indices N=9 # 9 points n=2 # 2 dimension m=3 # order of Hilbert curve def BitTest(x,od): result = x & (1 << od) return int(bool(result)) def BitFlip(b,pos): b ^= 1 << pos return b def partition(idx,A,st,en,od,ax,di): i = st j = en while True: while i < j and BitTest(A[i][ax],od) == di: i = i + 1 while i < j and BitTest(A[j][ax],od) != di: j = j - 1 if j <= i: return i A[i], A[j] = A[j], A[i] idx[i], idx[j] = idx[j], idx[i] def HSort(idx,A,st,en,od,c,e,d,di,cnt): if en<=st: return p = partition(idx,A,st,en,od,(d+c)%n,BitTest(e,(d+c)%n)) if c==n-1: if od==0: return d2= (d+n+n-(2 if di else cnt + 2)) % n e=BitFlip(e,d2) e=BitFlip(e,(d+c)%n) HSort(idx,A,st,p-1,od-1,0,e,d2,False,0) e=BitFlip(e,(d+c)%n) e=BitFlip(e,d2) d2= (d+n+n-(cnt + 2 if di else 2))%n HSort(idx,A,p,en,od-1,0,e,d2,False,0) else: HSort(idx,A,st,p-1,od,c+1,e,d,False,(1 if di else cnt+1)) e=BitFlip(e,(d+c)%n) e=BitFlip(e,(d+c+1)%n) HSort(idx,A,p,en,od,c+1,e,d,True,(cnt+1 if di else 1)) e=BitFlip(e,(d+c+1)%n) e=BitFlip(e,(d+c)%n) # array = [[2,2],[2,4],[3,4],[2,5],[3,5],[1,6],[3,6],[5,6],[3,7]] # HSort(array,st=0,en=N-1,od=m-1,c=0,e=0,d=0,di=False,cnt=0) # print(array) # if False: # idx = self.recursive_sort(pca_X, n_components) # pca_X = pca_X[idx] # pca_X = np.array(pca_X) * 100000000 # pca_X = pca_X.astype(int) # N=len(pca_X) # 9 points # n=2 # 2 dimension # m=10 # order of Hilbert curve # idx = list(range(N)) # HSort(idx, pca_X,st=0,en=N-1,od=m-1,c=0,e=0,d=0,di=False,cnt=0) # else:
n = 9 n = 2 m = 3 def bit_test(x, od): result = x & 1 << od return int(bool(result)) def bit_flip(b, pos): b ^= 1 << pos return b def partition(idx, A, st, en, od, ax, di): i = st j = en while True: while i < j and bit_test(A[i][ax], od) == di: i = i + 1 while i < j and bit_test(A[j][ax], od) != di: j = j - 1 if j <= i: return i (A[i], A[j]) = (A[j], A[i]) (idx[i], idx[j]) = (idx[j], idx[i]) def h_sort(idx, A, st, en, od, c, e, d, di, cnt): if en <= st: return p = partition(idx, A, st, en, od, (d + c) % n, bit_test(e, (d + c) % n)) if c == n - 1: if od == 0: return d2 = (d + n + n - (2 if di else cnt + 2)) % n e = bit_flip(e, d2) e = bit_flip(e, (d + c) % n) h_sort(idx, A, st, p - 1, od - 1, 0, e, d2, False, 0) e = bit_flip(e, (d + c) % n) e = bit_flip(e, d2) d2 = (d + n + n - (cnt + 2 if di else 2)) % n h_sort(idx, A, p, en, od - 1, 0, e, d2, False, 0) else: h_sort(idx, A, st, p - 1, od, c + 1, e, d, False, 1 if di else cnt + 1) e = bit_flip(e, (d + c) % n) e = bit_flip(e, (d + c + 1) % n) h_sort(idx, A, p, en, od, c + 1, e, d, True, cnt + 1 if di else 1) e = bit_flip(e, (d + c + 1) % n) e = bit_flip(e, (d + c) % n)
# Authorization data host = '*****' user = '*****' passwd = '*****' db = 'hr'
host = '*****' user = '*****' passwd = '*****' db = 'hr'
# # PySNMP MIB module ENTERASYS-VLAN-AUTHORIZATION-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ENTERASYS-VLAN-AUTHORIZATION-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:04:50 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "ConstraintsUnion", "ValueRangeConstraint", "SingleValueConstraint") dot1dBasePortEntry, = mibBuilder.importSymbols("BRIDGE-MIB", "dot1dBasePortEntry") etsysModules, = mibBuilder.importSymbols("ENTERASYS-MIB-NAMES", "etsysModules") EnabledStatus, = mibBuilder.importSymbols("P-BRIDGE-MIB", "EnabledStatus") NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup") MibIdentifier, Bits, NotificationType, IpAddress, TimeTicks, Counter64, iso, Integer32, Counter32, ObjectIdentity, Unsigned32, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "Bits", "NotificationType", "IpAddress", "TimeTicks", "Counter64", "iso", "Integer32", "Counter32", "ObjectIdentity", "Unsigned32", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") etsysVlanAuthorizationMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48)) etsysVlanAuthorizationMIB.setRevisions(('2004-06-02 19:22',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setRevisionsDescriptions(('The initial version of this MIB module',)) if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setLastUpdated('200406021922Z') if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setOrganization('Enterasys Networks, Inc') if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setContactInfo('Postal: Enterasys Networks, Inc. 50 Minuteman Rd. Andover, MA 01810-1008 USA Phone: +1 978 684 1000 E-mail: [email protected] WWW: http://www.enterasys.com') if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setDescription("This MIB module defines a portion of the SNMP MIB under Enterasys Networks' enterprise OID pertaining to proprietary extensions to the IETF Q-BRIDGE-MIB, as specified in RFC2674, pertaining to VLAN authorization, as specified in RFC3580. Specifically, the enabling and disabling of support for the VLAN Tunnel-Type attribute returned from a RADIUS authentication, and how that attribute is applied to the port which initiated the authentication.") class VlanAuthEgressStatus(TextualConvention, Integer32): description = 'The possible egress configurations which may be applied in response to a successful authentication. none(1) No egress manipulation will be made. tagged(2) The authenticating port will be added to the current egress for the VLAN-ID returned. untagged(3) The authenticating port will be added to the current untagged egress for the VLAN-ID returned. dynamic(4) The authenticating port will use information returned in the authentication response to modify the current egress lists.' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4)) namedValues = NamedValues(("none", 1), ("tagged", 2), ("untagged", 3), ("dynamic", 4)) etsysVlanAuthorizationObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1)) etsysVlanAuthorizationSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 1)) etsysVlanAuthorizationPorts = MibIdentifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2)) etsysVlanAuthorizationEnable = MibScalar((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 1, 1), EnabledStatus().clone('disabled')).setMaxAccess("readwrite") if mibBuilder.loadTexts: etsysVlanAuthorizationEnable.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationEnable.setDescription('The enable/disable state for the VLAN authorization feature. When disabled, no modifications to the VLAN attributes related to packet switching should be enforced.') etsysVlanAuthorizationTable = MibTable((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1), ) if mibBuilder.loadTexts: etsysVlanAuthorizationTable.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationTable.setDescription('Extensions to the table that contains information about every port that is associated with this transparent bridge.') etsysVlanAuthorizationEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1), ) dot1dBasePortEntry.registerAugmentions(("ENTERASYS-VLAN-AUTHORIZATION-MIB", "etsysVlanAuthorizationEntry")) etsysVlanAuthorizationEntry.setIndexNames(*dot1dBasePortEntry.getIndexNames()) if mibBuilder.loadTexts: etsysVlanAuthorizationEntry.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationEntry.setDescription('A list of extensions that support the management of proprietary features for each port of a transparent bridge. This is indexed by dot1dBasePort.') etsysVlanAuthorizationStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1, 1), EnabledStatus().clone('enabled')).setMaxAccess("readwrite") if mibBuilder.loadTexts: etsysVlanAuthorizationStatus.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationStatus.setDescription('The enabled/disabled status for the application of VLAN authorization on this port, if disabled, the information returned in the VLAN-Tunnel-Type from the authentication will not be applied to the port (although it should be represented in this table). If enabled, those results will be applied to the port.') etsysVlanAuthorizationAdminEgress = MibTableColumn((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1, 2), VlanAuthEgressStatus().clone('untagged')).setMaxAccess("readwrite") if mibBuilder.loadTexts: etsysVlanAuthorizationAdminEgress.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationAdminEgress.setDescription('Controls the modification of the current vlan egress list (of the vlan returned in the VLAN-Tunnel-Type, and reported by etsysVlanAuthorizationVlanID) upon successful authentication in the following manner: none(1) No egress manipulation will be made. tagged(2) The authenticating port will be added to the current egress for the VLAN-ID returned. untagged(3) The authenticating port will be added to the current untagged egress for the VLAN-ID returned. dynamic(4) The authenticating port will use information returned in the authentication response to modify the current egress lists. This value is supported only if the device supports a mechanism through which the egress status may be returned through the RADIUS response. Should etsysVlanAuthorizationEnable become disabled, etsysVlanAuthorizationStatus become disabled for a port, or should etsysVlanAuthorizationVlanID become 0 or 4095, all effect on the port egress MUST be removed.') etsysVlanAuthorizationOperEgress = MibTableColumn((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1, 3), VlanAuthEgressStatus().clone('none')).setMaxAccess("readonly") if mibBuilder.loadTexts: etsysVlanAuthorizationOperEgress.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationOperEgress.setDescription('Reports the current state of modification to the current vlan egress list (of the vlan returned in the VLAN-Tunnel-Type) upon successful authentication, if etsysVlanAuthorizationStatus is enabled, in the following manner: none(1) No egress manipulation will be made. tagged(2) The authenticating port will be added to the current egress for the VLAN-ID returned. untagged(3) The authenticating port will be added to the current untagged egress for the VLAN-ID returned. The purpose of this leaf is to report, specifically when etsysVlanAuthorizationAdminEgress has been set to dynamic(4), the currently enforced egress modification. If the port is unauthenticated, or no VLAN-ID has been applied, this leaf should return none(1).') etsysVlanAuthorizationVlanID = MibTableColumn((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 4094), ValueRangeConstraint(4095, 4095), ))).setMaxAccess("readonly") if mibBuilder.loadTexts: etsysVlanAuthorizationVlanID.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationVlanID.setDescription('The 12 bit VLAN identifier for a given port, used to override the PVID of the given port, obtained as a result of an authentication. A value of zero indicates that there is no authenticated VLAN ID for the given port. Should a port become unauthenticated this value MUST be returned to zero. A value of 4095 indicates that a the port has been authenticated, but that the VLAN returned could not be applied to the port (possibly because of resource constraints or misconfiguration). In this instance, the original PVID should still be applied. Should the feature become disabled or the session terminate, all effect on the Port VLAN ID MUST be removed.') etsysVlanAuthorizationConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2)) etsysVlanAuthorizationGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2, 1)) etsysVlanAuthorizationCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2, 2)) etsysVlanAuthorizationGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2, 1, 1)).setObjects(("ENTERASYS-VLAN-AUTHORIZATION-MIB", "etsysVlanAuthorizationEnable"), ("ENTERASYS-VLAN-AUTHORIZATION-MIB", "etsysVlanAuthorizationStatus"), ("ENTERASYS-VLAN-AUTHORIZATION-MIB", "etsysVlanAuthorizationAdminEgress"), ("ENTERASYS-VLAN-AUTHORIZATION-MIB", "etsysVlanAuthorizationOperEgress"), ("ENTERASYS-VLAN-AUTHORIZATION-MIB", "etsysVlanAuthorizationVlanID")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): etsysVlanAuthorizationGroup = etsysVlanAuthorizationGroup.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationGroup.setDescription('A collection of objects relating to VLAN Authorization.') etsysVlanAuthorizationCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2, 2, 1)).setObjects(("ENTERASYS-VLAN-AUTHORIZATION-MIB", "etsysVlanAuthorizationGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): etsysVlanAuthorizationCompliance = etsysVlanAuthorizationCompliance.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationCompliance.setDescription('The compliance statement for devices that support the Enterasys VLAN Authorization MIB.') mibBuilder.exportSymbols("ENTERASYS-VLAN-AUTHORIZATION-MIB", etsysVlanAuthorizationVlanID=etsysVlanAuthorizationVlanID, etsysVlanAuthorizationGroup=etsysVlanAuthorizationGroup, etsysVlanAuthorizationEnable=etsysVlanAuthorizationEnable, etsysVlanAuthorizationOperEgress=etsysVlanAuthorizationOperEgress, etsysVlanAuthorizationAdminEgress=etsysVlanAuthorizationAdminEgress, etsysVlanAuthorizationConformance=etsysVlanAuthorizationConformance, VlanAuthEgressStatus=VlanAuthEgressStatus, etsysVlanAuthorizationPorts=etsysVlanAuthorizationPorts, etsysVlanAuthorizationStatus=etsysVlanAuthorizationStatus, etsysVlanAuthorizationCompliance=etsysVlanAuthorizationCompliance, etsysVlanAuthorizationMIB=etsysVlanAuthorizationMIB, etsysVlanAuthorizationGroups=etsysVlanAuthorizationGroups, etsysVlanAuthorizationObjects=etsysVlanAuthorizationObjects, etsysVlanAuthorizationTable=etsysVlanAuthorizationTable, etsysVlanAuthorizationSystem=etsysVlanAuthorizationSystem, etsysVlanAuthorizationEntry=etsysVlanAuthorizationEntry, etsysVlanAuthorizationCompliances=etsysVlanAuthorizationCompliances, PYSNMP_MODULE_ID=etsysVlanAuthorizationMIB)
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_size_constraint, constraints_union, value_range_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ValueSizeConstraint', 'ConstraintsUnion', 'ValueRangeConstraint', 'SingleValueConstraint') (dot1d_base_port_entry,) = mibBuilder.importSymbols('BRIDGE-MIB', 'dot1dBasePortEntry') (etsys_modules,) = mibBuilder.importSymbols('ENTERASYS-MIB-NAMES', 'etsysModules') (enabled_status,) = mibBuilder.importSymbols('P-BRIDGE-MIB', 'EnabledStatus') (notification_group, module_compliance, object_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance', 'ObjectGroup') (mib_identifier, bits, notification_type, ip_address, time_ticks, counter64, iso, integer32, counter32, object_identity, unsigned32, gauge32, mib_scalar, mib_table, mib_table_row, mib_table_column, module_identity) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibIdentifier', 'Bits', 'NotificationType', 'IpAddress', 'TimeTicks', 'Counter64', 'iso', 'Integer32', 'Counter32', 'ObjectIdentity', 'Unsigned32', 'Gauge32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ModuleIdentity') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') etsys_vlan_authorization_mib = module_identity((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48)) etsysVlanAuthorizationMIB.setRevisions(('2004-06-02 19:22',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setRevisionsDescriptions(('The initial version of this MIB module',)) if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setLastUpdated('200406021922Z') if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setOrganization('Enterasys Networks, Inc') if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setContactInfo('Postal: Enterasys Networks, Inc. 50 Minuteman Rd. Andover, MA 01810-1008 USA Phone: +1 978 684 1000 E-mail: [email protected] WWW: http://www.enterasys.com') if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setDescription("This MIB module defines a portion of the SNMP MIB under Enterasys Networks' enterprise OID pertaining to proprietary extensions to the IETF Q-BRIDGE-MIB, as specified in RFC2674, pertaining to VLAN authorization, as specified in RFC3580. Specifically, the enabling and disabling of support for the VLAN Tunnel-Type attribute returned from a RADIUS authentication, and how that attribute is applied to the port which initiated the authentication.") class Vlanauthegressstatus(TextualConvention, Integer32): description = 'The possible egress configurations which may be applied in response to a successful authentication. none(1) No egress manipulation will be made. tagged(2) The authenticating port will be added to the current egress for the VLAN-ID returned. untagged(3) The authenticating port will be added to the current untagged egress for the VLAN-ID returned. dynamic(4) The authenticating port will use information returned in the authentication response to modify the current egress lists.' status = 'current' subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4)) named_values = named_values(('none', 1), ('tagged', 2), ('untagged', 3), ('dynamic', 4)) etsys_vlan_authorization_objects = mib_identifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1)) etsys_vlan_authorization_system = mib_identifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 1)) etsys_vlan_authorization_ports = mib_identifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2)) etsys_vlan_authorization_enable = mib_scalar((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 1, 1), enabled_status().clone('disabled')).setMaxAccess('readwrite') if mibBuilder.loadTexts: etsysVlanAuthorizationEnable.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationEnable.setDescription('The enable/disable state for the VLAN authorization feature. When disabled, no modifications to the VLAN attributes related to packet switching should be enforced.') etsys_vlan_authorization_table = mib_table((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1)) if mibBuilder.loadTexts: etsysVlanAuthorizationTable.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationTable.setDescription('Extensions to the table that contains information about every port that is associated with this transparent bridge.') etsys_vlan_authorization_entry = mib_table_row((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1)) dot1dBasePortEntry.registerAugmentions(('ENTERASYS-VLAN-AUTHORIZATION-MIB', 'etsysVlanAuthorizationEntry')) etsysVlanAuthorizationEntry.setIndexNames(*dot1dBasePortEntry.getIndexNames()) if mibBuilder.loadTexts: etsysVlanAuthorizationEntry.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationEntry.setDescription('A list of extensions that support the management of proprietary features for each port of a transparent bridge. This is indexed by dot1dBasePort.') etsys_vlan_authorization_status = mib_table_column((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1, 1), enabled_status().clone('enabled')).setMaxAccess('readwrite') if mibBuilder.loadTexts: etsysVlanAuthorizationStatus.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationStatus.setDescription('The enabled/disabled status for the application of VLAN authorization on this port, if disabled, the information returned in the VLAN-Tunnel-Type from the authentication will not be applied to the port (although it should be represented in this table). If enabled, those results will be applied to the port.') etsys_vlan_authorization_admin_egress = mib_table_column((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1, 2), vlan_auth_egress_status().clone('untagged')).setMaxAccess('readwrite') if mibBuilder.loadTexts: etsysVlanAuthorizationAdminEgress.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationAdminEgress.setDescription('Controls the modification of the current vlan egress list (of the vlan returned in the VLAN-Tunnel-Type, and reported by etsysVlanAuthorizationVlanID) upon successful authentication in the following manner: none(1) No egress manipulation will be made. tagged(2) The authenticating port will be added to the current egress for the VLAN-ID returned. untagged(3) The authenticating port will be added to the current untagged egress for the VLAN-ID returned. dynamic(4) The authenticating port will use information returned in the authentication response to modify the current egress lists. This value is supported only if the device supports a mechanism through which the egress status may be returned through the RADIUS response. Should etsysVlanAuthorizationEnable become disabled, etsysVlanAuthorizationStatus become disabled for a port, or should etsysVlanAuthorizationVlanID become 0 or 4095, all effect on the port egress MUST be removed.') etsys_vlan_authorization_oper_egress = mib_table_column((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1, 3), vlan_auth_egress_status().clone('none')).setMaxAccess('readonly') if mibBuilder.loadTexts: etsysVlanAuthorizationOperEgress.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationOperEgress.setDescription('Reports the current state of modification to the current vlan egress list (of the vlan returned in the VLAN-Tunnel-Type) upon successful authentication, if etsysVlanAuthorizationStatus is enabled, in the following manner: none(1) No egress manipulation will be made. tagged(2) The authenticating port will be added to the current egress for the VLAN-ID returned. untagged(3) The authenticating port will be added to the current untagged egress for the VLAN-ID returned. The purpose of this leaf is to report, specifically when etsysVlanAuthorizationAdminEgress has been set to dynamic(4), the currently enforced egress modification. If the port is unauthenticated, or no VLAN-ID has been applied, this leaf should return none(1).') etsys_vlan_authorization_vlan_id = mib_table_column((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1, 4), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(0, 0), value_range_constraint(1, 4094), value_range_constraint(4095, 4095)))).setMaxAccess('readonly') if mibBuilder.loadTexts: etsysVlanAuthorizationVlanID.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationVlanID.setDescription('The 12 bit VLAN identifier for a given port, used to override the PVID of the given port, obtained as a result of an authentication. A value of zero indicates that there is no authenticated VLAN ID for the given port. Should a port become unauthenticated this value MUST be returned to zero. A value of 4095 indicates that a the port has been authenticated, but that the VLAN returned could not be applied to the port (possibly because of resource constraints or misconfiguration). In this instance, the original PVID should still be applied. Should the feature become disabled or the session terminate, all effect on the Port VLAN ID MUST be removed.') etsys_vlan_authorization_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2)) etsys_vlan_authorization_groups = mib_identifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2, 1)) etsys_vlan_authorization_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2, 2)) etsys_vlan_authorization_group = object_group((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2, 1, 1)).setObjects(('ENTERASYS-VLAN-AUTHORIZATION-MIB', 'etsysVlanAuthorizationEnable'), ('ENTERASYS-VLAN-AUTHORIZATION-MIB', 'etsysVlanAuthorizationStatus'), ('ENTERASYS-VLAN-AUTHORIZATION-MIB', 'etsysVlanAuthorizationAdminEgress'), ('ENTERASYS-VLAN-AUTHORIZATION-MIB', 'etsysVlanAuthorizationOperEgress'), ('ENTERASYS-VLAN-AUTHORIZATION-MIB', 'etsysVlanAuthorizationVlanID')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): etsys_vlan_authorization_group = etsysVlanAuthorizationGroup.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationGroup.setDescription('A collection of objects relating to VLAN Authorization.') etsys_vlan_authorization_compliance = module_compliance((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2, 2, 1)).setObjects(('ENTERASYS-VLAN-AUTHORIZATION-MIB', 'etsysVlanAuthorizationGroup')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): etsys_vlan_authorization_compliance = etsysVlanAuthorizationCompliance.setStatus('current') if mibBuilder.loadTexts: etsysVlanAuthorizationCompliance.setDescription('The compliance statement for devices that support the Enterasys VLAN Authorization MIB.') mibBuilder.exportSymbols('ENTERASYS-VLAN-AUTHORIZATION-MIB', etsysVlanAuthorizationVlanID=etsysVlanAuthorizationVlanID, etsysVlanAuthorizationGroup=etsysVlanAuthorizationGroup, etsysVlanAuthorizationEnable=etsysVlanAuthorizationEnable, etsysVlanAuthorizationOperEgress=etsysVlanAuthorizationOperEgress, etsysVlanAuthorizationAdminEgress=etsysVlanAuthorizationAdminEgress, etsysVlanAuthorizationConformance=etsysVlanAuthorizationConformance, VlanAuthEgressStatus=VlanAuthEgressStatus, etsysVlanAuthorizationPorts=etsysVlanAuthorizationPorts, etsysVlanAuthorizationStatus=etsysVlanAuthorizationStatus, etsysVlanAuthorizationCompliance=etsysVlanAuthorizationCompliance, etsysVlanAuthorizationMIB=etsysVlanAuthorizationMIB, etsysVlanAuthorizationGroups=etsysVlanAuthorizationGroups, etsysVlanAuthorizationObjects=etsysVlanAuthorizationObjects, etsysVlanAuthorizationTable=etsysVlanAuthorizationTable, etsysVlanAuthorizationSystem=etsysVlanAuthorizationSystem, etsysVlanAuthorizationEntry=etsysVlanAuthorizationEntry, etsysVlanAuthorizationCompliances=etsysVlanAuthorizationCompliances, PYSNMP_MODULE_ID=etsysVlanAuthorizationMIB)
class BookStore: def __init__(self, book): self.booklst = book class Book: def __init__(self, title, author, chapter, price): self.title = title self.author = author self.chapter = list(chapter) self.price = int(price) book1 = Book("han kubrat", "Tangra", ['1', '3', '4', '2'], 1) book2 = Book("han Asparuh", "Vitosha", ['12', '123', '55', '22'], 2) book3 = Book("han Tervel", "StaraPlanina", ['155', '33', '41', '245'], 3) lst_book = [book1, book2, book3] bookstor = BookStore(lst_book)
class Bookstore: def __init__(self, book): self.booklst = book class Book: def __init__(self, title, author, chapter, price): self.title = title self.author = author self.chapter = list(chapter) self.price = int(price) book1 = book('han kubrat', 'Tangra', ['1', '3', '4', '2'], 1) book2 = book('han Asparuh', 'Vitosha', ['12', '123', '55', '22'], 2) book3 = book('han Tervel', 'StaraPlanina', ['155', '33', '41', '245'], 3) lst_book = [book1, book2, book3] bookstor = book_store(lst_book)
# Contains the objects found on our user greetings page. # Imports -------------------------------------------------------------------------------- # Page Objects --------------------------------------------------------------------------- class PatientGreetingPageObject(object): bio = 'This is a test bio.' def get_current_feeling_buttons(self): feeling1element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-0"]') feeling2element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-1"]') feeling3element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-2"]') feeling4element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-3"]') feeling5element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-4"]') feeling6element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-5"]') feeling7element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-6"]') feeling8element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-7"]') feeling9element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-8"]') feeling10element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-9"]') attributes = { 'feeling1 element': feeling1element, 'feeling2 element': feeling2element, 'feeling3 element': feeling3element, 'feeling4 element': feeling4element, 'feeling5 element': feeling5element, 'feeling6 element': feeling6element, 'feeling7 element': feeling7element, 'feeling8 element': feeling8element, 'feeling9 element': feeling9element, 'feeling10 element': feeling10element } return attributes def click_feeling1_button(self): self.get_current_feeling_buttons(self)['feeling1 element'].click() def click_feeling2_button(self): self.get_current_feeling_buttons(self)['feeling2 element'].click() def click_feeling3_button(self): self.get_current_feeling_buttons(self)['feeling3 element'].click() def click_feeling4_button(self): self.get_current_feeling_buttons(self)['feeling4 element'].click() def click_feeling5_button(self): self.get_current_feeling_buttons(self)['feeling5 element'].click() def click_feeling6_button(self): self.get_current_feeling_buttons(self)['feeling6 element'].click() def click_feeling7_button(self): self.get_current_feeling_buttons(self)['feeling7 element'].click() def click_feeling8_button(self): self.get_current_feeling_buttons(self)['feeling8 element'].click() def click_feeling9_button(self): self.get_current_feeling_buttons(self)['feeling9 element'].click() def click_feeling10_button(self): self.get_current_feeling_buttons(self)['feeling10 element'].click() def get_feeling_comparison_buttons(self): attributes = { 'worse element': self.client.find_element_by_xpath('//*[@id="feeling_comparison-0"]'), 'same element': self.client.find_element_by_xpath('//*[@id="feeling_comparison-1"]'), 'better element': self.client.find_element_by_xpath('//*[@id="feeling_comparison-2"]'), } return attributes def click_worse_button(self): self.get_feeling_comparison_buttons(self)['worse element'].click() def click_same_button(self): self.get_feeling_comparison_buttons(self)['same element'].click() def click_better_button(self): self.get_feeling_comparison_buttons(self)['better element'].click() def get_behaviour_buttons(self): attributes = { 'happy element': self.client.find_element_by_xpath('//*[@id="behaviours-0"]'), 'angry element': self.client.find_element_by_xpath('//*[@id="behaviours-1"]'), 'disappointed element': self.client.find_element_by_xpath('//*[@id="behaviours-2"]'), 'done with today element': self.client.find_element_by_xpath('//*[@id="behaviours-3"]'), 'persevering element': self.client.find_element_by_xpath('//*[@id="behaviours-4"]'), 'anxious element': self.client.find_element_by_xpath('//*[@id="behaviours-5"]'), 'confused element': self.client.find_element_by_xpath('//*[@id="behaviours-6"]'), 'worried element': self.client.find_element_by_xpath('//*[@id="behaviours-7"]'), 'ill element': self.client.find_element_by_xpath('//*[@id="behaviours-8"]'), 'exhausted element': self.client.find_element_by_xpath('//*[@id="behaviours-9"]'), 'accomplished element': self.client.find_element_by_xpath('//*[@id="behaviours-10"]'), 'star struck element': self.client.find_element_by_xpath('//*[@id="behaviours-11"]'), 'frightened element': self.client.find_element_by_xpath('//*[@id="behaviours-12"]'), } return attributes def click_happy_element(self): self.get_behaviour_buttons(self)['happy element'].click() def click_angry_element(self): self.get_behaviour_buttons(self)['angry element'].click() def click_disappointed_element(self): self.get_behaviour_buttons(self)['disappointed element'].click() def click_done_with_today_element(self): self.get_behaviour_buttons(self)['done with today element'].click() def click_persevering_element(self): self.get_behaviour_buttons(self)['persevering element'].click() def click_anxious_element(self): self.get_behaviour_buttons(self)['anxious element'].click() def click_confused_element(self): self.get_behaviour_buttons(self)['confused element'].click() def click_worried_element(self): self.get_behaviour_buttons(self)['worried element'].click() def click_ill_element(self): self.get_behaviour_buttons(self)['ill element'].click() def click_exhausted_element(self): self.get_behaviour_buttons(self)['exhausted element'].click() def click_accomplished_element(self): self.get_behaviour_buttons(self)['accomplished element'].click() def click_star_struck_element(self): self.get_behaviour_buttons(self)['star struck element'].click() def click_frightened_element(self): self.get_behaviour_buttons(self)['frightened element'].click() def get_bio_element(self): return self.client.find_element_by_xpath('//*[@id="patient_comment"]') def type_in_bio_form(self, input_to_type=bio): # A function to type text into our bio form box. # Retrieve our form attributes. get_field_element = self.get_bio_element() # After retrieving the field element, simulate typing into a form box. get_field_element.send_keys(input_to_type) print(f"Running Simulation: Currently typing '{input_to_type}' in the bio field.") def clear_password_form(self): # A function to clear the text from within our password form box. # Retrieve our form attributes. get_field_element = self.get_bio_element() get_field_element.clear() # Clears our form. print(f"Running Simulation: Currently clearing the bio field.") def get_submit_button(self): return self.client.find_element_by_xpath('//*[@id="submit"]') def click_submit_button(self): self.get_submit_button(self).click() def get_skip_evaluation_button(self): return self.client.find_element_by_xpath('/html/body/p/a') def click_skip_evaluation_button(self): return self.get_skip_evaluation_button(self).click()
class Patientgreetingpageobject(object): bio = 'This is a test bio.' def get_current_feeling_buttons(self): feeling1element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-0"]') feeling2element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-1"]') feeling3element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-2"]') feeling4element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-3"]') feeling5element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-4"]') feeling6element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-5"]') feeling7element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-6"]') feeling8element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-7"]') feeling9element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-8"]') feeling10element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-9"]') attributes = {'feeling1 element': feeling1element, 'feeling2 element': feeling2element, 'feeling3 element': feeling3element, 'feeling4 element': feeling4element, 'feeling5 element': feeling5element, 'feeling6 element': feeling6element, 'feeling7 element': feeling7element, 'feeling8 element': feeling8element, 'feeling9 element': feeling9element, 'feeling10 element': feeling10element} return attributes def click_feeling1_button(self): self.get_current_feeling_buttons(self)['feeling1 element'].click() def click_feeling2_button(self): self.get_current_feeling_buttons(self)['feeling2 element'].click() def click_feeling3_button(self): self.get_current_feeling_buttons(self)['feeling3 element'].click() def click_feeling4_button(self): self.get_current_feeling_buttons(self)['feeling4 element'].click() def click_feeling5_button(self): self.get_current_feeling_buttons(self)['feeling5 element'].click() def click_feeling6_button(self): self.get_current_feeling_buttons(self)['feeling6 element'].click() def click_feeling7_button(self): self.get_current_feeling_buttons(self)['feeling7 element'].click() def click_feeling8_button(self): self.get_current_feeling_buttons(self)['feeling8 element'].click() def click_feeling9_button(self): self.get_current_feeling_buttons(self)['feeling9 element'].click() def click_feeling10_button(self): self.get_current_feeling_buttons(self)['feeling10 element'].click() def get_feeling_comparison_buttons(self): attributes = {'worse element': self.client.find_element_by_xpath('//*[@id="feeling_comparison-0"]'), 'same element': self.client.find_element_by_xpath('//*[@id="feeling_comparison-1"]'), 'better element': self.client.find_element_by_xpath('//*[@id="feeling_comparison-2"]')} return attributes def click_worse_button(self): self.get_feeling_comparison_buttons(self)['worse element'].click() def click_same_button(self): self.get_feeling_comparison_buttons(self)['same element'].click() def click_better_button(self): self.get_feeling_comparison_buttons(self)['better element'].click() def get_behaviour_buttons(self): attributes = {'happy element': self.client.find_element_by_xpath('//*[@id="behaviours-0"]'), 'angry element': self.client.find_element_by_xpath('//*[@id="behaviours-1"]'), 'disappointed element': self.client.find_element_by_xpath('//*[@id="behaviours-2"]'), 'done with today element': self.client.find_element_by_xpath('//*[@id="behaviours-3"]'), 'persevering element': self.client.find_element_by_xpath('//*[@id="behaviours-4"]'), 'anxious element': self.client.find_element_by_xpath('//*[@id="behaviours-5"]'), 'confused element': self.client.find_element_by_xpath('//*[@id="behaviours-6"]'), 'worried element': self.client.find_element_by_xpath('//*[@id="behaviours-7"]'), 'ill element': self.client.find_element_by_xpath('//*[@id="behaviours-8"]'), 'exhausted element': self.client.find_element_by_xpath('//*[@id="behaviours-9"]'), 'accomplished element': self.client.find_element_by_xpath('//*[@id="behaviours-10"]'), 'star struck element': self.client.find_element_by_xpath('//*[@id="behaviours-11"]'), 'frightened element': self.client.find_element_by_xpath('//*[@id="behaviours-12"]')} return attributes def click_happy_element(self): self.get_behaviour_buttons(self)['happy element'].click() def click_angry_element(self): self.get_behaviour_buttons(self)['angry element'].click() def click_disappointed_element(self): self.get_behaviour_buttons(self)['disappointed element'].click() def click_done_with_today_element(self): self.get_behaviour_buttons(self)['done with today element'].click() def click_persevering_element(self): self.get_behaviour_buttons(self)['persevering element'].click() def click_anxious_element(self): self.get_behaviour_buttons(self)['anxious element'].click() def click_confused_element(self): self.get_behaviour_buttons(self)['confused element'].click() def click_worried_element(self): self.get_behaviour_buttons(self)['worried element'].click() def click_ill_element(self): self.get_behaviour_buttons(self)['ill element'].click() def click_exhausted_element(self): self.get_behaviour_buttons(self)['exhausted element'].click() def click_accomplished_element(self): self.get_behaviour_buttons(self)['accomplished element'].click() def click_star_struck_element(self): self.get_behaviour_buttons(self)['star struck element'].click() def click_frightened_element(self): self.get_behaviour_buttons(self)['frightened element'].click() def get_bio_element(self): return self.client.find_element_by_xpath('//*[@id="patient_comment"]') def type_in_bio_form(self, input_to_type=bio): get_field_element = self.get_bio_element() get_field_element.send_keys(input_to_type) print(f"Running Simulation: Currently typing '{input_to_type}' in the bio field.") def clear_password_form(self): get_field_element = self.get_bio_element() get_field_element.clear() print(f'Running Simulation: Currently clearing the bio field.') def get_submit_button(self): return self.client.find_element_by_xpath('//*[@id="submit"]') def click_submit_button(self): self.get_submit_button(self).click() def get_skip_evaluation_button(self): return self.client.find_element_by_xpath('/html/body/p/a') def click_skip_evaluation_button(self): return self.get_skip_evaluation_button(self).click()
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} Boys = {'Tim': 18,'Charlie':12,'Robert':25} Girls = {'Tiffany':22} studentX=Boys.copy() studentY=Girls.copy() print(studentX) print(studentY) students = list(Dict.keys()) students.sort() for s in students: print(":".join((s,str(Dict[s]))))
dict = {'Tim': 18, 'Charlie': 12, 'Tiffany': 22, 'Robert': 25} boys = {'Tim': 18, 'Charlie': 12, 'Robert': 25} girls = {'Tiffany': 22} student_x = Boys.copy() student_y = Girls.copy() print(studentX) print(studentY) students = list(Dict.keys()) students.sort() for s in students: print(':'.join((s, str(Dict[s]))))
class RaiseException: def __init__(self, exception: Exception): self.exception = exception
class Raiseexception: def __init__(self, exception: Exception): self.exception = exception
EVENT_ALGO_LOG = "eAlgoLog" EVENT_ALGO_SETTING = "eAlgoSetting" EVENT_ALGO_VARIABLES = "eAlgoVariables" EVENT_ALGO_PARAMETERS = "eAlgoParameters" APP_NAME = "AlgoTrading"
event_algo_log = 'eAlgoLog' event_algo_setting = 'eAlgoSetting' event_algo_variables = 'eAlgoVariables' event_algo_parameters = 'eAlgoParameters' app_name = 'AlgoTrading'
class AminoAcid: def __init__(self,name='AA'): self.name = name self.name3L = '' self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 0 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.ResWeight = 0 # residue weight (weight - 56) backbone weight is 56 self.ResVol = 0 # Residue volume from http://prowl.rockefeller.edu/aainfo/volume.htm self.SideChainVol = 0 # Side Chain volume is evaluated as ResVol - 0.9 Gly.ResVol self.Hydropathy = 0 # Hydropathy index self.n1 = 0 self.n2 = 0 # n values # -1 when the amino acid (AA) residue has an N donor, short residue. # -2 when the AA residue has an O acceptor, short residue. # -3 when the AA residue has an N donor, long residue that able to bond across two turns. # -5 when the AA residue has an O acceptor, long residue that able to bond across two turns. # -7 when it is a Cystine(C) # 0 when bond is not possible. # 1 when this N or O participating in a bond. # A residu can only participate in one side-chain bond. So when a bond is created # for example with n1, n1 get the bond value and n2 will be assigned 0 def __mul__ (self,other): # Evaluating side chain interaction Prod = self.donor * other.acceptor return Prod # ############ Non Polar, HydroPhobic ########### class Ala(AminoAcid): def __init__(self): AminoAcid.__init__(self,'A') # Alanine # ### # CH3-CH(NH2)-COOH # # # Molecular weight 89.09 Da # Non ploar # Acidity - Natural # Hydrophobicity 0.616 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index 1.8 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point (when protonation accure) pH 6.01 # pKa( alpha-COOH) 2.35 # pKa( alpha-NH2) 9.87 # CAS # 56-41-7 # PubChem ID 5950 # self.name3L = 'ALA' self.Hydrophobic = 1 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 0 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = 0 self.n2 = 0 self.Hydropathy = 1.8 self.ResWeight = 33 self.ResVol = 88.6 self.SideChainVol = 88.6-54.1 class Val(AminoAcid): def __init__(self): AminoAcid.__init__(self,'V') # Valine # ######### # (CH3)2-CH-CH(NH2)-COOH # # # Essential AA (cannot be synthesized by humans) # Molecular weight 117.15 Da # Non ploar # Acidity - Natural # Hydrophobicity 0.825 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index 4.2 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 6.00 # pKa( alpha-COOH) 2.39 # pKa( alpha-NH2) 9.74 # CAS # 72-18-4 # PubChem ID 1182 # self.name3L = 'VAL' self.Hydrophobic = 1 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 0 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = 0 self.n2 = 0 self.Hydropathy = 4.2 self.ResWeight = 61 self.ResVol = 140.0 self.SideChainVol = 140-54.1 class Leu(AminoAcid): def __init__(self): AminoAcid.__init__(self,'L') # Leucine # ############# # (CH3)2-CH-CH2-CH(NH2)-COOH # # # Essential AA # Molecular weight 131.18 Da # Non ploar # Acidity - Natural # Hydrophobicity 0.943 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index 3.8 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 6.01 # pKa( alpha-COOH) 2.33 # pKa( alpha-NH2) 9.74 # CAS # 61-90-5 # PubChem ID 6106 # self.name3L = 'LEU' self.Hydrophobic = 1 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 0 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = 0 self.n2 = 0 self.Hydropathy = 3.8 self.ResWeight = 75 self.ResVol = 166.7 self.SideChainVol = 166.7-54.1 class Ile(AminoAcid): def __init__(self): AminoAcid.__init__(self,'I') # Isoleucine # ############### # CH3-CH2-CH(CH3)-CH(NH2)-COOH # # # Essential AA # Molecular weight 131.18 Da # Non ploar # Acidity - Natural # Hydrophobicity 0.943 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index 4.5 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 6.05 # pKa( alpha-COOH) 2.33 # pKa( alpha-NH2) 9.74 # CAS # 61-90-5 # PubChem ID 6106 # self.Hydropathy = 4.5 self.ResWeight = 75 self.name3L = 'ILE' self.Hydrophobic = 1 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 0 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = 0 self.n2 = 0 self.ResVol = 166.7 self.SideChainVol = 166.7-54.1 class Phe(AminoAcid): def __init__(self): AminoAcid.__init__(self,'F') # Phenylalanine # ###### # Ph-CH2-CH(NH2)-COOH # The residue Ph-CH2 : C6H5-CH2 benzyl # # Essential AA # Molecular weight 165.19 Da # Non ploar # Acidity - Natural # Hydrophobicity 1 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index 2.8 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 5.49 # pKa( alpha-COOH) 2.20 # pKa( alpha-NH2) 9.31 # CAS # 63-91-2 # PubChem ID 994 # self.Hydropathy = 2.8 self.ResWeight = 109 self.name3L = 'PHE' self.Hydrophobic = 1 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 0 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = 0 self.n2 = 0 self.ResVol = 189.9 self.SideChainVol = 189.9-54.1 class Trp(AminoAcid): def __init__(self): AminoAcid.__init__(self,'W') # Tryptophan # ############## # Ph-NH-CH=C-CH2-CH(NH2)-COOH # |________| # # contains an indole functional group. # aromatic heterocyclic organic compound # It has a bicyclic structure, consisting of a six-membered benzene ring fused to # a five-membered nitrogen-containing pyrrole ring # # Essential AA # Molecular weight 204.23 Da # Non ploar # Acidity - Natural # Hydrophobicity 0.878 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index -0.9 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 5.89 # pKa( alpha-COOH) 2.46 # pKa( alpha-NH2) 9.41 # CAS # 73-22-3 # PubChem ID 6305 # self.Hydropathy = -0.9 self.ResWeight = 148 self.name3L = 'TRP' self.Hydrophobic = 1 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 0 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = 0 self.n2 = 0 self.ResVol = 227.8 self.SideChainVol = 227.8-54.1 class Met(AminoAcid): def __init__(self): AminoAcid.__init__(self,'M') # Methionine # ############ # CH3-S-(CH2)2-CH(NH2)-COOH # sulfur-containing residue # methyl donor R-CH3 # methionine is incorporated into the N-terminal position of all proteins # in eukaryotes and archaea during translation, although it is usually removed # by post-translational modification # # Essential AA # Molecular weight 149.21 Da # Non ploar # Acidity - Natural # Hydrophobicity 0.738 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index 1.9 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 5.74 # pKa( alpha-COOH) 2.13 # pKa( alpha-NH2) 9.28 # CAS # 63-68-3 # PubChem ID 876 # self.Hydropathy = 1.9 self.ResWeight = 93 self.name3L = 'MET' self.Hydrophobic = 1 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 0 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = 0 self.n2 = 0 self.ResVol = 162.9 self.SideChainVol = 162.9-54.1 class Pro(AminoAcid): def __init__(self): AminoAcid.__init__(self,'P') # Proline # ********** # NH-(CH2)3-CH-COOH # |_________| # Side chain bond to C alpha # exceptional conformational rigidity # usually solvent-exposed. # lacks a hydrogen on the amide group, it cannot act as a hydrogen bond donor, # only as a hydrogen bond acceptor. # # Molecular weight 115.13 Da # Non ploar # Acidity - Natural # Hydrophobicity 0.711 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index -1.6 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 6.30 # pKa( alpha-COOH) 1.95 # pKa( alpha-NH2) 10.64 # CAS # 147-85-3 # PubChem ID 614 # self.Hydropathy = -1.6 self.ResWeight = 59 self.name3L = 'PRO' self.Hydrophobic = 1 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 0 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0,3:-3,4:-3,5:-3,6:-2} # special value scores self.n1 = 0 self.n2 = 0 self.ResVol = 112.7 self.SideChainVol = 112.7-54.1 # ############ Non Polar Uncharged ########### class Gly(AminoAcid): def __init__(self): AminoAcid.__init__(self,'G') # # NH2-CH2-COOH # # Molecular weight 75.07 Da # Non ploar # Acidity - Natural # Hydrophobicity 0.501 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index -0.4 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 6.06 # pKa( alpha-COOH) 2.35 # pKa( alpha-NH2) 9.78 # CAS # 56-40-6 # PubChem ID 750 self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic self.Hydropathy = -0.4 self.ResWeight = 19 self.name3L = 'GLY' self.SpecialRes = {0:0,3:-3,5:-3} # special value scores self.ResVol = 60.1 self.SideChainVol = 60.1-54.1 # ############ Polar Uncharged ########### class Ser(AminoAcid): def __init__(self): AminoAcid.__init__(self,'S') # Serine # ###### # HO-CH2-CH(NH2)-COOH # # Molecular weight 105.09 Da # Ploar # Acidity - Natural # Hydrophobicity 0.359 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index -0.8 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 5.68 # pKa( alpha-COOH) 2.19 # pKa( alpha-NH2) 9.21 # CAS # 56-45-1 # PubChem ID 617 # self.Hydropathy = -0.8 self.ResWeight = 49 self.name3L = 'SER' self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 1 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = 0 self.n2 = 0 self.ResVol = 89.0 self.SideChainVol = 89-54.1 class Thr(AminoAcid): def __init__(self): AminoAcid.__init__(self,'T') # Threonine # ########## # CH3-CH(OH)-CH(NH2)-COOH # bearing an alcohol group # # Essential AA # Molecular weight 119.12 Da # Ploar # Acidity - Natural # Hydrophobicity 0.450 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index -0.7 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 5.60 # pKa( alpha-COOH) 2.09 # pKa( alpha-NH2) 9.10 # CAS # 72-19-5 # PubChem ID 6288 # self.Hydropathy = -0.7 self.ResWeight = 63 self.name3L = 'THR' self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 1 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = 0 self.n2 = 0 self.ResVol = 116.1 self.SideChainVol = 116.1-54.1 class Cys(AminoAcid): def __init__(self): AminoAcid.__init__(self,'C') # Cysteine # ###### # HS-CH2-CH(NH2)-COOH # thiol (R-S-H) side chain # Has Sulfur in side chain # # Molecular weight 121.16 Da # Ploar # Acidity - Natural # Hydrophobicity 0.680 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index 2.5 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 5.05 # pKa( alpha-COOH) 1.92 # pKa( alpha-NH2) 10.70 # CAS # 59-90-4 # PubChem ID 5862 # self.Hydropathy = 2.5 self.ResWeight = 65 self.name3L = 'CYS' self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 1 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.n1 = -7 self.n2 = 0 self.SpecialRes = {0:0} # special value scores self.ResVol = 108.5 self.SideChainVol = 108.5-54.1 class Tyr(AminoAcid): def __init__(self): AminoAcid.__init__(self,'Y') # Tyrosine # ########### # HO-p-Ph-CH2-CH(NH2)-COOH # # Molecular weight 181.19 Da # Non ploar # Acidity - Natural # Hydrophobicity 0.880 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index -1.3 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 5.64 # pKa( alpha-COOH) 2.20 # pKa( alpha-NH2) 9.21 # CAS # 60-18-4 # PubChem ID 1153 # self.Hydropathy = -1.3 self.ResWeight = 125 self.name3L = 'TYR' self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 1 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = 0 self.n2 = 0 self.ResVol = 193.6 self.SideChainVol = 193.6-54.1 class Asn(AminoAcid): def __init__(self): AminoAcid.__init__(self,'N') # Asparagine # ########## # H2N-CO-CH2-CH(NH2)-COOH # N Donor - NH2 # # has carboxamide as the side chain's functional group(R-CO-NH2) # side chain can form hydrogen bond interactions with the peptide backbone # often found near the beginning and the end of alpha-helices, # and in turn motifs in beta sheets. # # Molecular weight 132.12 Da # Ploar # Acidity - Natural # Hydrophobicity 0.236 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index -3.5 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 5.41 # pKa( alpha-COOH) 2.14 # pKa( alpha-NH2) 8.72 # CAS # 70-47-3 # PubChem ID 236 # self.Hydropathy = -3.5 self.ResWeight = 76 self.name3L = 'ASN' self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 1 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = -1 self.n2 = -2 self.ResVol = 114.1 self.SideChainVol = 114.1-54.1 class Gln(AminoAcid): def __init__(self): AminoAcid.__init__(self,'Q') # Glutamine # ############# # H2N-CO-(CH2)2-CH(NH2)-COOH # N Donor - NH2 # # Molecular weight 146.14 Da # Ploar # Acidity - Natural # Hydrophobicity 0.251 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index -3.5 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 5.65 # pKa( alpha-COOH) 2.17 # pKa( alpha-NH2) 9.13 # CAS # 56-85-9 # PubChem ID 5950 # self.Hydropathy = -3.5 self.ResWeight = 90 self.name3L = 'GLN' self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0 self.polar = 1 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.n1 = -1 self.n2 = -2 self.SpecialRes = {0:0} # special value scores self.ResVol = 143.8 self.SideChainVol = 143.8-54.1 # ########## Polar Acidic ########### class Asp(AminoAcid): def __init__(self): AminoAcid.__init__(self,'D') # Aspartic acid # ######## # HOOC-CH2-CH(NH2)-COOH # # Molecular weight 133.10 Da # Ploar # Acidity - Acidic # Hydrophobicity 0.028 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index -3.5 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 2.85 # pKa( alpha-COOH) 1.99 # pKa( alpha-NH2) 9.90 # CAS # 56-84-8 # PubChem ID 5960 # self.Hydropathy = -3.5 self.ResWeight = 77 self.name3L = 'ASP' self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic self.charge = 1 self.polar = 1 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.loop = 0 self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = -2 self.n2 = 0 self.ResVol = 111.1 self.SideChainVol = 111.1-54.1 class Glu(AminoAcid): def __init__(self): AminoAcid.__init__(self,'E') # ########### # HOOC-(CH2)2-CH(NH2)-COOH # # Molecular weight 147.13 Da # Ploar # Acidity - Acidic # Hydrophobicity 0.043 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index -3.5 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 3.15 # pKa( alpha-COOH) 2.10 # pKa( alpha-NH2) 9.47 # CAS # 56-86-0 # PubChem ID 611 # self.Hydropathy = -3.5 self.ResWeight = 91 self.name3L = 'GLU' self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic self.charge = 1 self.polar = 1 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.loop = 0 self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = -2 self.n2 = 0 self.ResVol = 138.4 self.SideChainVol = 138.4-54.1 # ############## Polar Basic ############# class Lys(AminoAcid): def __init__(self): AminoAcid.__init__(self,'K') # Lysine # ########## # H2N-(CH2)4-CH(NH2)-COOH # often participates in hydrogen bonding # N Donor - NH2 # # Essential AA # Molecular weight 146.19 Da # Ploar # Acidity - Basic # Hydrophobicity 0.283 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index -3.9 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 6.90 # pKa( alpha-COOH) 2.16 # pKa( alpha-NH2) 9.06 # CAS # 56-87-1 # PubChem ID 866 # self.Hydropathy = -3.9 self.ResWeight = 90 self.Hydropathy = -3.9 self.ResWeight = 90 self.name3L = 'LYS' self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic self.charge = 1 self.polar = 1 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.loop = 0 self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = -1 self.n2 = 0 self.ResVol = 168.6 self.SideChainVol = 168.6-54.1 class Arg(AminoAcid): def __init__(self): AminoAcid.__init__(self,'R') # Arginine # ################### # HN=C(NH2)-NH-(CH2)3-CH(NH2)-COOH # N Donor - NH2 # # Molecular weight 174.20 Da # Ploar # Acidity - Basic (strong) # Hydrophobicity 0.000 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index -4.5 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point (when protonation accure) pH 10.76 # pKa( alpha-COOH) 1.82 # pKa( alpha-NH2) 8.99 # CAS # 74-79-3 # PubChem ID 5950 # self.Hydropathy = -4.5 self.ResWeight = 118 self.name3L = 'ARG' self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic self.charge = 1 self.polar = 1 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.loop = 1 self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = -1 self.n2 = -3 self.ResVol = 173.4 self.SideChainVol = 173.4-54.1 class His(AminoAcid): def __init__(self): AminoAcid.__init__(self,'H') # Histidine # ################ # NH-CH=N-CH=C-CH2-CH(NH2)-COOH # |__________| # N Donor - NH # The imidazole side chain has two nitrogens with different properties # # Molecular weight 155.15 Da # Ploar # Acidity - Basic (week) # Hydrophobicity 0.165 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991) # Hydrophathy index -3.2 (J.Mol.Bio(1982) 157, 105-132) # Isoelectric point 7.60 # pKa( alpha-COOH) 1.80 # pKa( alpha-NH2) 9.33 # CAS # 71-00-1 # PubChem ID 773 # self.Hydropathy = -3.2 self.ResWeight = 99 self.name3L = 'HIS' self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic self.charge = 0.5 self.polar = 1 self.corner = 0 # Would prefer to be at a corner : give positive value self.loop = 0 # cost/benefit when on a loop self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue self.SpecialRes = {0:0} # Special characteristic of residue self.n1 = -1 self.n2 = 0 self.ResVol = 153.2 self.SideChainVol = 153.2-54.1
class Aminoacid: def __init__(self, name='AA'): self.name = name self.name3L = '' self.Hydrophobic = 0 self.charge = 0 self.polar = 0 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.ResWeight = 0 self.ResVol = 0 self.SideChainVol = 0 self.Hydropathy = 0 self.n1 = 0 self.n2 = 0 def __mul__(self, other): prod = self.donor * other.acceptor return Prod class Ala(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'A') self.name3L = 'ALA' self.Hydrophobic = 1 self.charge = 0 self.polar = 0 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = 0 self.n2 = 0 self.Hydropathy = 1.8 self.ResWeight = 33 self.ResVol = 88.6 self.SideChainVol = 88.6 - 54.1 class Val(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'V') self.name3L = 'VAL' self.Hydrophobic = 1 self.charge = 0 self.polar = 0 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = 0 self.n2 = 0 self.Hydropathy = 4.2 self.ResWeight = 61 self.ResVol = 140.0 self.SideChainVol = 140 - 54.1 class Leu(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'L') self.name3L = 'LEU' self.Hydrophobic = 1 self.charge = 0 self.polar = 0 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = 0 self.n2 = 0 self.Hydropathy = 3.8 self.ResWeight = 75 self.ResVol = 166.7 self.SideChainVol = 166.7 - 54.1 class Ile(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'I') self.Hydropathy = 4.5 self.ResWeight = 75 self.name3L = 'ILE' self.Hydrophobic = 1 self.charge = 0 self.polar = 0 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = 0 self.n2 = 0 self.ResVol = 166.7 self.SideChainVol = 166.7 - 54.1 class Phe(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'F') self.Hydropathy = 2.8 self.ResWeight = 109 self.name3L = 'PHE' self.Hydrophobic = 1 self.charge = 0 self.polar = 0 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = 0 self.n2 = 0 self.ResVol = 189.9 self.SideChainVol = 189.9 - 54.1 class Trp(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'W') self.Hydropathy = -0.9 self.ResWeight = 148 self.name3L = 'TRP' self.Hydrophobic = 1 self.charge = 0 self.polar = 0 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = 0 self.n2 = 0 self.ResVol = 227.8 self.SideChainVol = 227.8 - 54.1 class Met(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'M') self.Hydropathy = 1.9 self.ResWeight = 93 self.name3L = 'MET' self.Hydrophobic = 1 self.charge = 0 self.polar = 0 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = 0 self.n2 = 0 self.ResVol = 162.9 self.SideChainVol = 162.9 - 54.1 class Pro(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'P') self.Hydropathy = -1.6 self.ResWeight = 59 self.name3L = 'PRO' self.Hydrophobic = 1 self.charge = 0 self.polar = 0 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0, 3: -3, 4: -3, 5: -3, 6: -2} self.n1 = 0 self.n2 = 0 self.ResVol = 112.7 self.SideChainVol = 112.7 - 54.1 class Gly(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'G') self.Hydrophobic = 0 self.Hydropathy = -0.4 self.ResWeight = 19 self.name3L = 'GLY' self.SpecialRes = {0: 0, 3: -3, 5: -3} self.ResVol = 60.1 self.SideChainVol = 60.1 - 54.1 class Ser(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'S') self.Hydropathy = -0.8 self.ResWeight = 49 self.name3L = 'SER' self.Hydrophobic = 0 self.charge = 0 self.polar = 1 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = 0 self.n2 = 0 self.ResVol = 89.0 self.SideChainVol = 89 - 54.1 class Thr(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'T') self.Hydropathy = -0.7 self.ResWeight = 63 self.name3L = 'THR' self.Hydrophobic = 0 self.charge = 0 self.polar = 1 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = 0 self.n2 = 0 self.ResVol = 116.1 self.SideChainVol = 116.1 - 54.1 class Cys(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'C') self.Hydropathy = 2.5 self.ResWeight = 65 self.name3L = 'CYS' self.Hydrophobic = 0 self.charge = 0 self.polar = 1 self.corner = 0 self.loop = 0 self.size = 0 self.n1 = -7 self.n2 = 0 self.SpecialRes = {0: 0} self.ResVol = 108.5 self.SideChainVol = 108.5 - 54.1 class Tyr(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'Y') self.Hydropathy = -1.3 self.ResWeight = 125 self.name3L = 'TYR' self.Hydrophobic = 0 self.charge = 0 self.polar = 1 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = 0 self.n2 = 0 self.ResVol = 193.6 self.SideChainVol = 193.6 - 54.1 class Asn(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'N') self.Hydropathy = -3.5 self.ResWeight = 76 self.name3L = 'ASN' self.Hydrophobic = 0 self.charge = 0 self.polar = 1 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = -1 self.n2 = -2 self.ResVol = 114.1 self.SideChainVol = 114.1 - 54.1 class Gln(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'Q') self.Hydropathy = -3.5 self.ResWeight = 90 self.name3L = 'GLN' self.Hydrophobic = 0 self.charge = 0 self.polar = 1 self.corner = 0 self.loop = 0 self.size = 0 self.n1 = -1 self.n2 = -2 self.SpecialRes = {0: 0} self.ResVol = 143.8 self.SideChainVol = 143.8 - 54.1 class Asp(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'D') self.Hydropathy = -3.5 self.ResWeight = 77 self.name3L = 'ASP' self.Hydrophobic = 0 self.charge = 1 self.polar = 1 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = -2 self.n2 = 0 self.ResVol = 111.1 self.SideChainVol = 111.1 - 54.1 class Glu(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'E') self.Hydropathy = -3.5 self.ResWeight = 91 self.name3L = 'GLU' self.Hydrophobic = 0 self.charge = 1 self.polar = 1 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = -2 self.n2 = 0 self.ResVol = 138.4 self.SideChainVol = 138.4 - 54.1 class Lys(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'K') self.Hydropathy = -3.9 self.ResWeight = 90 self.Hydropathy = -3.9 self.ResWeight = 90 self.name3L = 'LYS' self.Hydrophobic = 0 self.charge = 1 self.polar = 1 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = -1 self.n2 = 0 self.ResVol = 168.6 self.SideChainVol = 168.6 - 54.1 class Arg(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'R') self.Hydropathy = -4.5 self.ResWeight = 118 self.name3L = 'ARG' self.Hydrophobic = 0 self.charge = 1 self.polar = 1 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = -1 self.n2 = -3 self.ResVol = 173.4 self.SideChainVol = 173.4 - 54.1 class His(AminoAcid): def __init__(self): AminoAcid.__init__(self, 'H') self.Hydropathy = -3.2 self.ResWeight = 99 self.name3L = 'HIS' self.Hydrophobic = 0 self.charge = 0.5 self.polar = 1 self.corner = 0 self.loop = 0 self.size = 0 self.SpecialRes = {0: 0} self.n1 = -1 self.n2 = 0 self.ResVol = 153.2 self.SideChainVol = 153.2 - 54.1
''' A collection of classes corresponding to fixed-income securities, to be fed into (and used with) other classes and methods available in this repository (eg trees.py, Monte Carlo, etc) ''' class SelfAmortizingMortgage: def __init__(self, dates=mats6, early=False, rate=5.5 / 100, T=6, N=100): ''' Inputs: *** early: whether you can prepay the security when it is more advantageous to do so *** T: when the mortgage expires (maturity, years) *** N: the face value (dollars) *** rate: the interest rate paid yearly *** dates: numpy nd array with the payment dates of the security ''' self.T = T self.early = early self.rate = rate self.dates = dates # coupon chosen to have value N at time 0, given the mortgage quoted rate self.coupon = N / sum([(1 / pow(1 + self.rate, i)) for i in range(1, self.T + 1)]) if early: self._compute_balance(N) def get_cf(self, t, r, *args, **kwargs): ''' Inputs: *** t: the current time *** r: the current interest rate (at that node in the tree) Outputs: *** the cash-flow of the security for that (time, interest rate) ''' return self.coupon def exercise_early(self, current_value, val_if_exercise_early, t, r): ''' Method to say whether you should exercise early or not Inputs: *** current_value: the value of the contract at that node, if you do not exercise early *** t: the current time *** r: the current interest rate Returns: TRUE if should exercise early, FALSE otherwise ''' if not self.early: print('WARNING: this should not be called when the security does not allow for early exercise') return False return current_value > val_if_exercise_early def _compute_balance(self, N): ''' Makes a list with the amount of principal left at every possible moment, and a list with the interests paid ''' bal_st = [N] interest = [] princ = [] for i in range(self.T + 1): # for each payment until maturity interest.append(bal_st[i] * self.rate) princ.append(self.coupon - interest[i]) if i < self.T: bal_st.append(bal_st[i] - self.coupon + interest[i]) self.balances = bal_st self.interest = interest self.princ = princ def cf_early_exercise(self, t, r): ''' Gives the payoff if the security is exercised early, at time t, with rate r ''' # When a borrower prepays a mortgage, the borrower pays back the remaining principal on # the loan, and does not make any of the remaining scheduled payments return self.balances[t] def get_raw_cf_mat(self, interest_rate_tree, *args, **kwargs): ''' Inputs: *** interest_rate_tree: a 2D numpy array with corresponding interest rates in each cell Returns: *** the payoff matrix corresponding to the security, a matrix of the same dimension ''' payoff_mat = np.zeros((interest_rate_tree.shape[0] + 1, interest_rate_tree.shape[0] + 1)) for time in reversed(range(1, payoff_mat.shape[0])): for node in range(time + 1): payoff_mat[node, time] = self.get_cf(time, interest_rate_tree[max(node - 1, 0), time - 1], *args, **kwargs) return payoff_mat
""" A collection of classes corresponding to fixed-income securities, to be fed into (and used with) other classes and methods available in this repository (eg trees.py, Monte Carlo, etc) """ class Selfamortizingmortgage: def __init__(self, dates=mats6, early=False, rate=5.5 / 100, T=6, N=100): """ Inputs: *** early: whether you can prepay the security when it is more advantageous to do so *** T: when the mortgage expires (maturity, years) *** N: the face value (dollars) *** rate: the interest rate paid yearly *** dates: numpy nd array with the payment dates of the security """ self.T = T self.early = early self.rate = rate self.dates = dates self.coupon = N / sum([1 / pow(1 + self.rate, i) for i in range(1, self.T + 1)]) if early: self._compute_balance(N) def get_cf(self, t, r, *args, **kwargs): """ Inputs: *** t: the current time *** r: the current interest rate (at that node in the tree) Outputs: *** the cash-flow of the security for that (time, interest rate) """ return self.coupon def exercise_early(self, current_value, val_if_exercise_early, t, r): """ Method to say whether you should exercise early or not Inputs: *** current_value: the value of the contract at that node, if you do not exercise early *** t: the current time *** r: the current interest rate Returns: TRUE if should exercise early, FALSE otherwise """ if not self.early: print('WARNING: this should not be called when the security does not allow for early exercise') return False return current_value > val_if_exercise_early def _compute_balance(self, N): """ Makes a list with the amount of principal left at every possible moment, and a list with the interests paid """ bal_st = [N] interest = [] princ = [] for i in range(self.T + 1): interest.append(bal_st[i] * self.rate) princ.append(self.coupon - interest[i]) if i < self.T: bal_st.append(bal_st[i] - self.coupon + interest[i]) self.balances = bal_st self.interest = interest self.princ = princ def cf_early_exercise(self, t, r): """ Gives the payoff if the security is exercised early, at time t, with rate r """ return self.balances[t] def get_raw_cf_mat(self, interest_rate_tree, *args, **kwargs): """ Inputs: *** interest_rate_tree: a 2D numpy array with corresponding interest rates in each cell Returns: *** the payoff matrix corresponding to the security, a matrix of the same dimension """ payoff_mat = np.zeros((interest_rate_tree.shape[0] + 1, interest_rate_tree.shape[0] + 1)) for time in reversed(range(1, payoff_mat.shape[0])): for node in range(time + 1): payoff_mat[node, time] = self.get_cf(time, interest_rate_tree[max(node - 1, 0), time - 1], *args, **kwargs) return payoff_mat
AVG = 70 FUNCTIONS = [ lambda geslacht: 0 if geslacht == 'man' else 4, lambda rookt: -5 if rookt else 5, lambda sport: -3 if not sport else sport, lambda alcohol: 2 if not alcohol else -((alcohol - 7) * 0.5) if alcohol > 7 else 0, lambda fastfood: 3 if not fastfood else 0, ] def levensverwachting(geslacht, roker, sport, alcohol, fastfood): return AVG + sum(func(variable) for (func, variable) in zip(FUNCTIONS, [geslacht, roker, sport, alcohol, fastfood]))
avg = 70 functions = [lambda geslacht: 0 if geslacht == 'man' else 4, lambda rookt: -5 if rookt else 5, lambda sport: -3 if not sport else sport, lambda alcohol: 2 if not alcohol else -((alcohol - 7) * 0.5) if alcohol > 7 else 0, lambda fastfood: 3 if not fastfood else 0] def levensverwachting(geslacht, roker, sport, alcohol, fastfood): return AVG + sum((func(variable) for (func, variable) in zip(FUNCTIONS, [geslacht, roker, sport, alcohol, fastfood])))
class CommentHandlers(object): def __init__(self): self.handlers = [] self.comments = {} def handler(self): def wrapped(func): self.register(func) return func return wrapped def register_handler(self, func): for handler in self.handlers: print(handler.__name__) self.handlers.append(func) def add(self, addr, key, value): if (addr, key) in self.comments: self.comments[(addr, key)].append(value) else: self.comments[(addr, key)] = [value] for handler in self.handlers: handler(addr, key, value)
class Commenthandlers(object): def __init__(self): self.handlers = [] self.comments = {} def handler(self): def wrapped(func): self.register(func) return func return wrapped def register_handler(self, func): for handler in self.handlers: print(handler.__name__) self.handlers.append(func) def add(self, addr, key, value): if (addr, key) in self.comments: self.comments[addr, key].append(value) else: self.comments[addr, key] = [value] for handler in self.handlers: handler(addr, key, value)
def incrementing_time(start=2000, increment=1): while True: yield start start += increment def monotonic_time(start=2000): return incrementing_time(start, increment=0.000001) def static_time(value): while True: yield value
def incrementing_time(start=2000, increment=1): while True: yield start start += increment def monotonic_time(start=2000): return incrementing_time(start, increment=1e-06) def static_time(value): while True: yield value
class Solution: def reverseBits(self, n: int) -> int: val = 0 for i in range(32): val <<= 1 val += n & 1 n >>= 1 return val
class Solution: def reverse_bits(self, n: int) -> int: val = 0 for i in range(32): val <<= 1 val += n & 1 n >>= 1 return val
stages = iter(['alpha','beta','gamma']) try: next(stages) next(stages) next(stages) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations'
stages = iter(['alpha', 'beta', 'gamma']) try: next(stages) next(stages) next(stages) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations'
class Payment: def __init__(self): pass def setPayment(self, payment): Payment.payment = payment def getPayment(self): print("Total yang harus dibayarkan Rp. ", Payment.payment)
class Payment: def __init__(self): pass def set_payment(self, payment): Payment.payment = payment def get_payment(self): print('Total yang harus dibayarkan Rp. ', Payment.payment)
class Solution: def hammingDistance(self, x: int, y: int) -> int: c = x^y r = 0 while c != 0: r += (c & 1) c = c>>1 return r
class Solution: def hamming_distance(self, x: int, y: int) -> int: c = x ^ y r = 0 while c != 0: r += c & 1 c = c >> 1 return r
v = "vvv" a = [f"aaa{vvv}" "bbb"] print(a)
v = 'vvv' a = [f'aaa{vvv}bbb'] print(a)
# worst case O(n^2) # good case O(n) def insertion_sort(array): for i in range(1, len(array)): key = array[i] j = i -1 while (j>=0 and array[j]>key): # scoot array[j+1] = array[j] j-=1 array[j+1] = key return array arr = [3,-9,5, 100,-2, 294,5,56] sarr = insertion_sort(arr) print(sarr, sorted(arr)) assert(sarr == sorted(arr))
def insertion_sort(array): for i in range(1, len(array)): key = array[i] j = i - 1 while j >= 0 and array[j] > key: array[j + 1] = array[j] j -= 1 array[j + 1] = key return array arr = [3, -9, 5, 100, -2, 294, 5, 56] sarr = insertion_sort(arr) print(sarr, sorted(arr)) assert sarr == sorted(arr)
x=int(input("Enter first number:\n")) y=int(input("Enter second number:\n")) print("Before swapping:\n",x,"\n",y,"\n") #Inputting two numbers from user x,y=y,x #Swapping two variables print("After swapping:\n",x,"\n",y,"\n")
x = int(input('Enter first number:\n')) y = int(input('Enter second number:\n')) print('Before swapping:\n', x, '\n', y, '\n') (x, y) = (y, x) print('After swapping:\n', x, '\n', y, '\n')
n = int(input()) for i in range(1, 10): if n % i != 0: continue for j in range(1, 10): if n % j != 0: continue for k in range(1, 10): if n % k != 0: continue for m in range(1, 10): if n % m != 0: continue for o in range(1, 10): if n % o != 0: continue for p in range(1, 10): if n % i != 0: continue if (i * j * k * m * o * p == n): print("{0}{1}{2}{3}{4}{5}".format(i, j, k, m, o, p), end=' ')
n = int(input()) for i in range(1, 10): if n % i != 0: continue for j in range(1, 10): if n % j != 0: continue for k in range(1, 10): if n % k != 0: continue for m in range(1, 10): if n % m != 0: continue for o in range(1, 10): if n % o != 0: continue for p in range(1, 10): if n % i != 0: continue if i * j * k * m * o * p == n: print('{0}{1}{2}{3}{4}{5}'.format(i, j, k, m, o, p), end=' ')
reserv_list = set() party_list = set() command = input() while command != 'PARTY': reserv_list.add(command) command = input() if command == 'PARTY': command = input() while command != 'END': party_list.add(command) command = input() diff = abs(len(reserv_list) - len(party_list)) print(diff) losers = (reserv_list-party_list) sort = sorted(losers) for el in sort: print(el)
reserv_list = set() party_list = set() command = input() while command != 'PARTY': reserv_list.add(command) command = input() if command == 'PARTY': command = input() while command != 'END': party_list.add(command) command = input() diff = abs(len(reserv_list) - len(party_list)) print(diff) losers = reserv_list - party_list sort = sorted(losers) for el in sort: print(el)
class Player(object): TEAM_GREEN = 0 TEAM_RED = 1 TEAM_BLUE = 2 def __init__(self, id, front_grey, front_red, front_blue, deck_grey, deck_red, deck_blue): self.id = id self.front_grey = front_grey self.front_red = front_red self.front_blue = front_blue self.deck_grey = deck_grey self.deck_red = deck_red self.deck_blue = deck_blue
class Player(object): team_green = 0 team_red = 1 team_blue = 2 def __init__(self, id, front_grey, front_red, front_blue, deck_grey, deck_red, deck_blue): self.id = id self.front_grey = front_grey self.front_red = front_red self.front_blue = front_blue self.deck_grey = deck_grey self.deck_red = deck_red self.deck_blue = deck_blue
# Advent of code 2021 : Day 1 | Part 2 # Source : https://adventofcode.com/2020/day/1 infile = "aoc/2020/Day 1/input.txt" inputs = list(map(int, open(infile).read().splitlines())) print([i*j*_ for i in inputs for j in inputs for _ in inputs if i + j + _ == 2020][0]) # Answer : 165080960
infile = 'aoc/2020/Day 1/input.txt' inputs = list(map(int, open(infile).read().splitlines())) print([i * j * _ for i in inputs for j in inputs for _ in inputs if i + j + _ == 2020][0])
#!/usr/bin/python class JustCounter: __secret_count = 0 def count(self): self.__secret_count += 1 print(self.__secret_count) counter = JustCounter() counter.count() counter.count() # can't access print(counter.__secret_count)
class Justcounter: __secret_count = 0 def count(self): self.__secret_count += 1 print(self.__secret_count) counter = just_counter() counter.count() counter.count() print(counter.__secret_count)
N = int(input()) A = [int(n) for n in input().split()] ans = [0] + [0]*N for i in range(N-1): ans[A[i]] += 1 for i in range(1, N+1): print(ans[i])
n = int(input()) a = [int(n) for n in input().split()] ans = [0] + [0] * N for i in range(N - 1): ans[A[i]] += 1 for i in range(1, N + 1): print(ans[i])
def count(start, end=None, step=None): if step == 0: raise IndexError if hasattr(step, "__iter__"): raise TypeError if (hasattr(start, "__iter__") or hasattr(end, "__iter__")): return __iter_count(start, end, step) else: return __num_count(start, end, step) def __iter_count(start,end=None, step=None): items = None if hasattr(start, "__iter__"): if step is not None: raise IndexError items = start count = 0 step = end if hasattr(end, "__iter__"): count = start items = end if step is None: step = 1 for item in items: yield count, item count += step def __num_count(start, end=None, step=None): if end is None: end = start start = 0 count = start if step is None: step = 1 if start > end: if step > 0: step *= -1 while count >= end: yield count count += step else: if step < 0: step *= -1 while count <= end: yield count count += step
def count(start, end=None, step=None): if step == 0: raise IndexError if hasattr(step, '__iter__'): raise TypeError if hasattr(start, '__iter__') or hasattr(end, '__iter__'): return __iter_count(start, end, step) else: return __num_count(start, end, step) def __iter_count(start, end=None, step=None): items = None if hasattr(start, '__iter__'): if step is not None: raise IndexError items = start count = 0 step = end if hasattr(end, '__iter__'): count = start items = end if step is None: step = 1 for item in items: yield (count, item) count += step def __num_count(start, end=None, step=None): if end is None: end = start start = 0 count = start if step is None: step = 1 if start > end: if step > 0: step *= -1 while count >= end: yield count count += step else: if step < 0: step *= -1 while count <= end: yield count count += step
def prime(n): i=2 while i<=n//2: if n%i==0: return 0 i=i+1 return 1 n=2 sum=0 while n<=2000000: if prime(n): sum=sum+n n=n+1
def prime(n): i = 2 while i <= n // 2: if n % i == 0: return 0 i = i + 1 return 1 n = 2 sum = 0 while n <= 2000000: if prime(n): sum = sum + n n = n + 1
# Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order. # For example, # Given n = 3, # You should return the following matrix: # [ # [ 1, 2, 3 ], # [ 8, 9, 4 ], # [ 7, 6, 5 ] # ] class Solution: # @param {integer} n # @return {integer[][]} def generateMatrix(self, n): matrix = [[0 for x in range(n)] for x in range(n)] boundaries = [n-1, n-1, 0, 1] #r, d, l, u bi = 0 directions = [[0, 1], [1, 0], [0, -1], [-1, 0]] #r, d, l, u di = 0 e = [0, 0] ei = 1 for i in xrange(n*n): matrix[e[0]][e[1]] = i+1 if e[ei] == boundaries[bi]: boundaries[bi] -= directions[di][ei] bi = (bi+1)%4 di = (di+1)%4 ei = (ei+1)%2 e[0] += directions[di][0] e[1] += directions[di][1] return matrix
class Solution: def generate_matrix(self, n): matrix = [[0 for x in range(n)] for x in range(n)] boundaries = [n - 1, n - 1, 0, 1] bi = 0 directions = [[0, 1], [1, 0], [0, -1], [-1, 0]] di = 0 e = [0, 0] ei = 1 for i in xrange(n * n): matrix[e[0]][e[1]] = i + 1 if e[ei] == boundaries[bi]: boundaries[bi] -= directions[di][ei] bi = (bi + 1) % 4 di = (di + 1) % 4 ei = (ei + 1) % 2 e[0] += directions[di][0] e[1] += directions[di][1] return matrix
# # This file contains the Python code from Program 4.20 of # "Data Structures and Algorithms # with Object-Oriented Design Patterns in Python" # by Bruno R. Preiss. # # Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved. # # http://www.brpreiss.com/books/opus7/programs/pgm04_20.txt # class LinkedList(object): class Element(object): def insertAfter(self, item): self._next = LinkedList.Element( self._list, item, self._next) if self._list._tail is self: self._list._tail = self._next def insertBefore(self, item): tmp = LinkedList.Element(self._list, item, self) if self is self._list._head: self._list._head = tmp else: prevPtr = self._list._head while prevPtr is not None \ and prevPtr._next is not self: prevPtr = prevPtr._next prevPtr._next = tmp # ...
class Linkedlist(object): class Element(object): def insert_after(self, item): self._next = LinkedList.Element(self._list, item, self._next) if self._list._tail is self: self._list._tail = self._next def insert_before(self, item): tmp = LinkedList.Element(self._list, item, self) if self is self._list._head: self._list._head = tmp else: prev_ptr = self._list._head while prevPtr is not None and prevPtr._next is not self: prev_ptr = prevPtr._next prevPtr._next = tmp
#file = open("data.csv", "r") #for line in file: # print(line) with open("output.csv", "a") as fileout: fileout.write("Hello World") fileout.close()
with open('output.csv', 'a') as fileout: fileout.write('Hello World') fileout.close()
# -*- coding: utf-8 -*- __title__ = 'atomos' __version_info__ = ('0', '3', '1') __version__ = '.'.join(__version_info__) __author__ = 'Max Countryman' __license__ = 'BSD' __copyright__ = 'Copyright 2014 Max Countryman'
__title__ = 'atomos' __version_info__ = ('0', '3', '1') __version__ = '.'.join(__version_info__) __author__ = 'Max Countryman' __license__ = 'BSD' __copyright__ = 'Copyright 2014 Max Countryman'
# Copyright (C) 2019 Intel Corporation # # SPDX-License-Identifier: MIT class Converter: def __init__(self, cmdline_args=None): pass def __call__(self, extractor, save_dir): raise NotImplementedError() def _parse_cmdline(self, cmdline): parser = self.build_cmdline_parser() if len(cmdline) != 0 and cmdline[0] == '--': cmdline = cmdline[1:] args = parser.parse_args(cmdline) return vars(args)
class Converter: def __init__(self, cmdline_args=None): pass def __call__(self, extractor, save_dir): raise not_implemented_error() def _parse_cmdline(self, cmdline): parser = self.build_cmdline_parser() if len(cmdline) != 0 and cmdline[0] == '--': cmdline = cmdline[1:] args = parser.parse_args(cmdline) return vars(args)
primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251 ] # len(primes) = 54 # symbol_size = 3 # for prime in primes: # column_size = prime * symbol_size # if 1048576 % (column_size) == 1 or \ # 1048576 % (column_size) == (column_size - 1): # print('1048576 % column_size(={}, 3 * prime={}) = {}'. # format(column_size, prime, 1048576 % column_size)) divisions = (17, 32, 41) symbol_size = 3 target_size = 1048576 for d in divisions: column_size = symbol_size * d remainder = target_size % column_size if remainder == 0: padding_size = 0 else: padding_size = column_size - remainder rate = (1048576 + padding_size) / d print('(1048576 + {:3d}) / {} = {}, column_size = {:3d}, division = {}'. format(padding_size, d, rate, column_size, d)) # (1048576 + 35) / 17 = 61683.0, column_size = 51, division = 17 # (1048576 + 32) / 32 = 32769.0, column_size = 96, division = 32 # (1048576 + 122) / 41 = 25578.0, column_size = 123, division = 41 # 1048576 % prime=17 = 16 # 1048576 % prime=32 = 0 # 1048576 % prime=41 = 1 # (1048576 + 1) / 17 = 61681.0 # (1048576 + 0) / 16 = 65536.0 # (1048576 + 40) / 41 = 25576.0 # 1048576 % column_size(= 15, 3 * prime= 5) = 1 # 1048576 % column_size(= 33, 3 * prime=11) = 1 # 1048576 % column_size(= 93, 3 * prime=31) = 1 # 1048576 % column_size(=123, 3 * prime=41) = 1
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251] divisions = (17, 32, 41) symbol_size = 3 target_size = 1048576 for d in divisions: column_size = symbol_size * d remainder = target_size % column_size if remainder == 0: padding_size = 0 else: padding_size = column_size - remainder rate = (1048576 + padding_size) / d print('(1048576 + {:3d}) / {} = {}, column_size = {:3d}, division = {}'.format(padding_size, d, rate, column_size, d))
# -*- coding: utf-8 -*- RADIX = 3 BYTE_RADIX = 256 MAX_TRIT_VALUE = (RADIX - 1) // 2 MIN_TRIT_VALUE = -MAX_TRIT_VALUE NUMBER_OF_TRITS_IN_A_BYTE = 5 NUMBER_OF_TRITS_IN_A_TRYTE = 3 HASH_LENGTH = 243 BYTE_TO_TRITS_MAPPINGS = [[]] * HASH_LENGTH TRYTE_TO_TRITS_MAPPINGS = [[]] * 27 HIGH_INTEGER_BITS = 0xFFFFFFFF HIGH_LONG_BITS = 0xFFFFFFFFFFFFFFFF TRYTE_ALPHABET = '9ABCDEFGHIJKLMNOPQRSTUVWXYZ' MIN_TRYTE_VALUE = -13 MAX_TRYTE_VALUE = 13 def increment(trits, length): for i in range(length): trits[i] += 1 if trits[i] > MAX_TRIT_VALUE: trits[i] = MIN_TRIT_VALUE else: break def init_converter(): global BYTE_TO_TRITS_MAPPINGS, TRYTE_TO_TRITS_MAPPINGS trits = [0] * NUMBER_OF_TRITS_IN_A_BYTE for i in range(HASH_LENGTH): BYTE_TO_TRITS_MAPPINGS[i] = trits[:NUMBER_OF_TRITS_IN_A_BYTE] increment(trits, NUMBER_OF_TRITS_IN_A_BYTE) for i in range(27): TRYTE_TO_TRITS_MAPPINGS[i] = trits[:NUMBER_OF_TRITS_IN_A_TRYTE] increment(trits, NUMBER_OF_TRITS_IN_A_TRYTE) def from_trits_to_binary(trits, offset=0, size=HASH_LENGTH): b = bytearray(b' ' * int((size + NUMBER_OF_TRITS_IN_A_BYTE - 1) / NUMBER_OF_TRITS_IN_A_BYTE)) for i in range(len(b)): value = 0 for j in range(size - i * NUMBER_OF_TRITS_IN_A_BYTE - 1 if (size - i * NUMBER_OF_TRITS_IN_A_BYTE) < NUMBER_OF_TRITS_IN_A_BYTE else 4, -1, -1): value = value * RADIX + trits[offset + i * NUMBER_OF_TRITS_IN_A_BYTE + j] b[i] = value % 256 return bytes(b) def from_binary_to_trits(bs, length): offset = 0 trits = [0] * length for i in range(min(len(bs), length)): # We must convert the binary data # because java using different range with Python index = bs[i] if bs[i] < 127 else bs[i] - 256 + HASH_LENGTH copy_len = length - offset if length - offset < NUMBER_OF_TRITS_IN_A_BYTE else NUMBER_OF_TRITS_IN_A_BYTE trits[offset: offset + copy_len] = BYTE_TO_TRITS_MAPPINGS[index][:copy_len] offset += NUMBER_OF_TRITS_IN_A_BYTE return trits init_converter()
radix = 3 byte_radix = 256 max_trit_value = (RADIX - 1) // 2 min_trit_value = -MAX_TRIT_VALUE number_of_trits_in_a_byte = 5 number_of_trits_in_a_tryte = 3 hash_length = 243 byte_to_trits_mappings = [[]] * HASH_LENGTH tryte_to_trits_mappings = [[]] * 27 high_integer_bits = 4294967295 high_long_bits = 18446744073709551615 tryte_alphabet = '9ABCDEFGHIJKLMNOPQRSTUVWXYZ' min_tryte_value = -13 max_tryte_value = 13 def increment(trits, length): for i in range(length): trits[i] += 1 if trits[i] > MAX_TRIT_VALUE: trits[i] = MIN_TRIT_VALUE else: break def init_converter(): global BYTE_TO_TRITS_MAPPINGS, TRYTE_TO_TRITS_MAPPINGS trits = [0] * NUMBER_OF_TRITS_IN_A_BYTE for i in range(HASH_LENGTH): BYTE_TO_TRITS_MAPPINGS[i] = trits[:NUMBER_OF_TRITS_IN_A_BYTE] increment(trits, NUMBER_OF_TRITS_IN_A_BYTE) for i in range(27): TRYTE_TO_TRITS_MAPPINGS[i] = trits[:NUMBER_OF_TRITS_IN_A_TRYTE] increment(trits, NUMBER_OF_TRITS_IN_A_TRYTE) def from_trits_to_binary(trits, offset=0, size=HASH_LENGTH): b = bytearray(b' ' * int((size + NUMBER_OF_TRITS_IN_A_BYTE - 1) / NUMBER_OF_TRITS_IN_A_BYTE)) for i in range(len(b)): value = 0 for j in range(size - i * NUMBER_OF_TRITS_IN_A_BYTE - 1 if size - i * NUMBER_OF_TRITS_IN_A_BYTE < NUMBER_OF_TRITS_IN_A_BYTE else 4, -1, -1): value = value * RADIX + trits[offset + i * NUMBER_OF_TRITS_IN_A_BYTE + j] b[i] = value % 256 return bytes(b) def from_binary_to_trits(bs, length): offset = 0 trits = [0] * length for i in range(min(len(bs), length)): index = bs[i] if bs[i] < 127 else bs[i] - 256 + HASH_LENGTH copy_len = length - offset if length - offset < NUMBER_OF_TRITS_IN_A_BYTE else NUMBER_OF_TRITS_IN_A_BYTE trits[offset:offset + copy_len] = BYTE_TO_TRITS_MAPPINGS[index][:copy_len] offset += NUMBER_OF_TRITS_IN_A_BYTE return trits init_converter()
#encoding:utf-8 subreddit = 'HQDesi' t_channel = '@r_HqDesi' def send_post(submission, r2t): return r2t.send_simple(submission)
subreddit = 'HQDesi' t_channel = '@r_HqDesi' def send_post(submission, r2t): return r2t.send_simple(submission)
class OrderElement: def __init__(self, product, quantity): self.product = product self.quantity = quantity def calculate_price(self): return self.product.unit_price * self.quantity def __str__(self): return f"{self.product} x {self.quantity}"
class Orderelement: def __init__(self, product, quantity): self.product = product self.quantity = quantity def calculate_price(self): return self.product.unit_price * self.quantity def __str__(self): return f'{self.product} x {self.quantity}'
#!/usr/bin/env python3 class Parser: def __init__(self): self.token = None self.remained_token = None '''from regex string to NFA class''' def parse(self, regex_str): if len(regex_str) == 0: print("The compiled content is empty. Stop parsing.") return None regex_str_list = [i for i in regex_str] + [None] self.token = regex_str_list[0] self.remained_token = regex_str_list[1:] result = self.re() return result def advance(self): self.token = self.remained_token[0] self.remained_token = self.remained_token[1:] '''<RE> ::= (<simple-RE> "|" RE>) | <simple-RE>''' def re(self): result = self.simple_re() while self.token == "|": result_head = self.token self.advance() rhs = self.simple_re() result = [result_head, result, rhs] rhs = result return result '''<simple-RE> ::= <basic-RE>+''' def simple_re(self): result = self.basic_re() # self.token != ")" and self.token != "|" is used to fix the bug while self.token != None and self.token != ")" and self.token != "|": result_head = "CONC" # concat rhs = self.basic_re() result = [result_head, result, rhs] rhs = result return result '''<basic-RE> ::= <elementary-RE> "*" | <elementary-RE> "?" | elementary-RE> "+" | <elementary-RE>''' def basic_re(self): result = self.elementary_re() if self.token == "*": self.advance() result = ["STAR", result] elif self.token == "?": self.advance() result = ["QUESTION", result] elif self.token == "+": self.advance() result = ["PLUS", result] return result '''<elementary-RE> ::= <group> | <any> | <char> | <char-set>''' '''<group> ::= "(" <RE> ")"''' def elementary_re(self): # <group> ::= "(" <RE> ")" if self.token == "(": self.advance() result = self.re() if self.token != ")": raise("Except \")\", found %s", self.token) self.advance() result = [result] elif self.token == ".": self.advance() result = "ANY" elif self.token == "[": result = self.char_set() else: result = self.char() return result '''<char> ::= any non metacharacter | "\" metacharacter''' '''metacharacter = set{ \ * + . \ [ ] ( ) | }''' def char(self): meta_char_list = ["*", "+", ".", "\\", "[", "]", "(", ")", "|", "?"] # \ + metacharacter if self.token == "\\": self.advance() if self.token in meta_char_list: result = self.token self.advance() return result else: # exception description exception_desc = "Expect" + ", ".join(meta_char_list) + " , found \"%s\"" % self.token raise(exception_desc) else: if self.token in meta_char_list: print("Caution: \"%s\" is not recommended to be singly used." % self.token) result = self.token self.advance() return result '''<char-set> ::= <positive-set> | <negative-set>''' def char_set(self): # token [ is checked in elementary_re. so advance() self.advance() '''<negative-set> ::= "[^" <set-items> "]"''' if self.token == "^": result_rhs = self.set_items() result = ["NOT", result_rhs] else: result = self.set_items() return result def set_items(self): result = ["SET"] if self.token != "]": result.append(self.set_item()) return result '''<set-item> ::= <range> | <char> <range> ::= <char> "-" <char>''' def set_item(self): result = self.char() # range = <char> "-" <char> if self.token == "-": result_lhs = result self.advance() result_rhs = self.char() result = ["RANGE", result_lhs, result_rhs] return result regex_parser = Parser() print(regex_parser.parse("(abc)")) print(regex_parser.parse("(a|bc)")) print(regex_parser.parse("a*bc")) print(regex_parser.parse("(a*|b)c")) print(regex_parser.parse("a+bc")) print(regex_parser.parse("(a+|b)c")) print(regex_parser.parse("a*+bc")) print(regex_parser.parse("a*+bc"))
class Parser: def __init__(self): self.token = None self.remained_token = None 'from regex string to NFA class' def parse(self, regex_str): if len(regex_str) == 0: print('The compiled content is empty. Stop parsing.') return None regex_str_list = [i for i in regex_str] + [None] self.token = regex_str_list[0] self.remained_token = regex_str_list[1:] result = self.re() return result def advance(self): self.token = self.remained_token[0] self.remained_token = self.remained_token[1:] '<RE> \t::= (<simple-RE> "|" RE>) | <simple-RE>' def re(self): result = self.simple_re() while self.token == '|': result_head = self.token self.advance() rhs = self.simple_re() result = [result_head, result, rhs] rhs = result return result '<simple-RE> \t::= <basic-RE>+' def simple_re(self): result = self.basic_re() while self.token != None and self.token != ')' and (self.token != '|'): result_head = 'CONC' rhs = self.basic_re() result = [result_head, result, rhs] rhs = result return result '<basic-RE> \t::=\t<elementary-RE> "*" | <elementary-RE> "?" | elementary-RE> "+" | <elementary-RE>' def basic_re(self): result = self.elementary_re() if self.token == '*': self.advance() result = ['STAR', result] elif self.token == '?': self.advance() result = ['QUESTION', result] elif self.token == '+': self.advance() result = ['PLUS', result] return result '<elementary-RE> \t::=\t<group> | <any> | <char> | <char-set>' '<group> \t::= \t"(" <RE> ")"' def elementary_re(self): if self.token == '(': self.advance() result = self.re() if self.token != ')': raise ('Except ")", found %s', self.token) self.advance() result = [result] elif self.token == '.': self.advance() result = 'ANY' elif self.token == '[': result = self.char_set() else: result = self.char() return result '<char> \t::= \tany non metacharacter | "" metacharacter' 'metacharacter = set{ \\ * + . \\ [ ] ( ) | }' def char(self): meta_char_list = ['*', '+', '.', '\\', '[', ']', '(', ')', '|', '?'] if self.token == '\\': self.advance() if self.token in meta_char_list: result = self.token self.advance() return result else: exception_desc = 'Expect' + ', '.join(meta_char_list) + ' , found "%s"' % self.token raise exception_desc else: if self.token in meta_char_list: print('Caution: "%s" is not recommended to be singly used.' % self.token) result = self.token self.advance() return result '<char-set> \t::= \t<positive-set> | <negative-set>' def char_set(self): self.advance() '<negative-set> \t::= \t"[^" <set-items> "]"' if self.token == '^': result_rhs = self.set_items() result = ['NOT', result_rhs] else: result = self.set_items() return result def set_items(self): result = ['SET'] if self.token != ']': result.append(self.set_item()) return result '<set-item> \t::= \t<range> | <char>\n <range> \t::= \t<char> "-" <char>' def set_item(self): result = self.char() if self.token == '-': result_lhs = result self.advance() result_rhs = self.char() result = ['RANGE', result_lhs, result_rhs] return result regex_parser = parser() print(regex_parser.parse('(abc)')) print(regex_parser.parse('(a|bc)')) print(regex_parser.parse('a*bc')) print(regex_parser.parse('(a*|b)c')) print(regex_parser.parse('a+bc')) print(regex_parser.parse('(a+|b)c')) print(regex_parser.parse('a*+bc')) print(regex_parser.parse('a*+bc'))
def isgreaterthan20(number1,number2): print(number1) print(number2) num=20 num1=10 isgreaterthan20(num,num1)
def isgreaterthan20(number1, number2): print(number1) print(number2) num = 20 num1 = 10 isgreaterthan20(num, num1)
class InvalidIdError(RuntimeError): def __init__(self, id_value): super(InvalidIdError, self).__init__() self.id = id_value
class Invalididerror(RuntimeError): def __init__(self, id_value): super(InvalidIdError, self).__init__() self.id = id_value
sku = [{"name": "id", "type": "varchar(256)"}, {"name": "object", "type": "varchar(256)"}, {"name": "active", "type": "boolean"}, {"name": "attributes", "type": "varchar(max)"}, {"name": "created", "type": "timestamp"}, {"name": "currency", "type": "varchar(256)"}, {"name": "image", "type": "varchar(256)"}, {"name": "inventory", "type": "varchar(512)"}, {"name": "livemode", "type": "boolean"}, {"name": "metadata", "type": "varchar(max)"}, {"name": "package_dimensions", "type": "varchar(512)"}, {"name": "price", "type": "integer"}, {"name": "product", "type": "varchar(256)"}, {"name": "updated", "type": "timestamp"}]
sku = [{'name': 'id', 'type': 'varchar(256)'}, {'name': 'object', 'type': 'varchar(256)'}, {'name': 'active', 'type': 'boolean'}, {'name': 'attributes', 'type': 'varchar(max)'}, {'name': 'created', 'type': 'timestamp'}, {'name': 'currency', 'type': 'varchar(256)'}, {'name': 'image', 'type': 'varchar(256)'}, {'name': 'inventory', 'type': 'varchar(512)'}, {'name': 'livemode', 'type': 'boolean'}, {'name': 'metadata', 'type': 'varchar(max)'}, {'name': 'package_dimensions', 'type': 'varchar(512)'}, {'name': 'price', 'type': 'integer'}, {'name': 'product', 'type': 'varchar(256)'}, {'name': 'updated', 'type': 'timestamp'}]
#no refactoring class hash_test: participant = ["leo","kiki","eden"] completion = ["leo","kiki"] p = 31 m = 0xfffff x = 0 hash_table = list([0 for i in range(m)]) unfinished = list() # polynomial rolling hash function. for i in participant: print(i) mod_value=0 for j in i: mod_value = mod_value + ord(j)*pow(p,x) x+=1 hash_table[mod_value % m] = 1 #hash for completion for k in completion: print(k) mod_value=0 for j in i: mod_value = mod_value + ord(j)*pow(p,x) x+=1 if hash_table[mod_value % m] != 1: unfinished.append(i) print("unfinished="+i)
class Hash_Test: participant = ['leo', 'kiki', 'eden'] completion = ['leo', 'kiki'] p = 31 m = 1048575 x = 0 hash_table = list([0 for i in range(m)]) unfinished = list() for i in participant: print(i) mod_value = 0 for j in i: mod_value = mod_value + ord(j) * pow(p, x) x += 1 hash_table[mod_value % m] = 1 for k in completion: print(k) mod_value = 0 for j in i: mod_value = mod_value + ord(j) * pow(p, x) x += 1 if hash_table[mod_value % m] != 1: unfinished.append(i) print('unfinished=' + i)
# -*- coding: utf-8 - # # This file is part of tproxy released under the MIT license. # See the NOTICE for more information. version_info = (0, 5, 4) __version__ = ".".join(map(str, version_info))
version_info = (0, 5, 4) __version__ = '.'.join(map(str, version_info))
def eh_primo(x): if (x==3) or (x==2): return True if (x<2) or (x%2==0): return False for i in range(3, int(x**0.5)+1, 2): if x%i==0: return False return True def sup_primo(num): while num >= 10: sup = num % 10 num = int(num / 10) if not eh_primo(sup): return 0 if((num == 2) or (num == 3) or (num == 5) or (num == 7)): return True else: return False while(True): try: # (Entrada) n = input() if len(n)==0: break else: n = int(n) if not eh_primo(n): print("Nada") else: if sup_primo(n): print("Super") else: print("Primo") except EOFError: break
def eh_primo(x): if x == 3 or x == 2: return True if x < 2 or x % 2 == 0: return False for i in range(3, int(x ** 0.5) + 1, 2): if x % i == 0: return False return True def sup_primo(num): while num >= 10: sup = num % 10 num = int(num / 10) if not eh_primo(sup): return 0 if num == 2 or num == 3 or num == 5 or (num == 7): return True else: return False while True: try: n = input() if len(n) == 0: break else: n = int(n) if not eh_primo(n): print('Nada') elif sup_primo(n): print('Super') else: print('Primo') except EOFError: break
#listing #representacion de grafos a,b,c,d,e,f,g,h = range(8) N = [{b:2,c:1,d:3,e:9,f:4}, #a {c:4,e:3}, #b {d:8}, #c {e:7}, #d {f:5}, #e {c:2,g:2,h:2}, #f {f:1,h:6}, #g {f:9,g:8}] #h print(b in N[a]) #neighborhood membership/es vecino b de a?? print(len(N[f])) #degree of f print(N[a][b]) #edge weight for (a,b) input() #matrix for graphs #matriz de adyacencia # a b c d e f g h M = [[0,1,1,1,1,1,0,0], #a [0,0,1,0,1,0,0,0], #b [0,0,0,1,0,0,0,0], #c [0,0,0,0,1,0,0,0], #d [0,0,0,0,0,1,0,0], #e [0,0,0,1,0,0,1,1], #f [0,0,0,0,0,1,0,1], #g [0,0,0,0,0,1,1,0]] #h print(sum(M[a])) input() #representacionde nodos con infinito a traves de matrices: #a weight matrix with infinite weighr for missing edges print("------------------------------") a,b,c,d,e,f,g,h = range(8) _ = float('inf') # a b c d e f g h G = [[0,2,1,3,9,4,_,_], #a [_,0,4,_,3,_,_,_], #b [_,_,0,8,_,_,_,_], #c [_,_,_,0,7,_,_,_], #d [_,_,_,_,0,5,_,_], #e [_,_,2,_,_,0,2,2], #f [_,_,_,_,_,1,0,6], #g [_,_,_,_,_,9,8,0]] #h print(G[a][b] < _) print(G[c][e] < _) print(sum(1 for g in G[a] if g < _)-1) #degree #note: 1 is substracted from G[a] because we dont want the o from the diagonal input()
(a, b, c, d, e, f, g, h) = range(8) n = [{b: 2, c: 1, d: 3, e: 9, f: 4}, {c: 4, e: 3}, {d: 8}, {e: 7}, {f: 5}, {c: 2, g: 2, h: 2}, {f: 1, h: 6}, {f: 9, g: 8}] print(b in N[a]) print(len(N[f])) print(N[a][b]) input() m = [[0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 0, 0, 1, 1], [0, 0, 0, 0, 0, 1, 0, 1], [0, 0, 0, 0, 0, 1, 1, 0]] print(sum(M[a])) input() print('------------------------------') (a, b, c, d, e, f, g, h) = range(8) _ = float('inf') g = [[0, 2, 1, 3, 9, 4, _, _], [_, 0, 4, _, 3, _, _, _], [_, _, 0, 8, _, _, _, _], [_, _, _, 0, 7, _, _, _], [_, _, _, _, 0, 5, _, _], [_, _, 2, _, _, 0, 2, 2], [_, _, _, _, _, 1, 0, 6], [_, _, _, _, _, 9, 8, 0]] print(G[a][b] < _) print(G[c][e] < _) print(sum((1 for g in G[a] if g < _)) - 1) input()
class Config(object): _instance = None def __new__(self): if not self._instance: self._instance = super(Config, self).__new__(self) return self._instance def setConfig(self, config): self.config = config def get(self, key): return self.config[key] def getAll(self): return self.config
class Config(object): _instance = None def __new__(self): if not self._instance: self._instance = super(Config, self).__new__(self) return self._instance def set_config(self, config): self.config = config def get(self, key): return self.config[key] def get_all(self): return self.config
# Faca um programa que tenha uma funcao # chamada area(), # que receba as dimensoes de um terreno # retangular(largura e comprimento) e mostre a # area do terreno def area(larg, comp): a = larg * comp print(f'A area de um terreno {larg} x {comp} eh de {a}m2.') print(' Controle de Terrenos') print('-' * 20) l = float(input('Largura (m): ')) c = float(input('Comprimento (m): ')) area(l, c)
def area(larg, comp): a = larg * comp print(f'A area de um terreno {larg} x {comp} eh de {a}m2.') print(' Controle de Terrenos') print('-' * 20) l = float(input('Largura (m): ')) c = float(input('Comprimento (m): ')) area(l, c)
class Solution: def findMinFibonacciNumbers(self, k: int) -> int: fib = [] fib.extend([1, 1]) j = 1 i = 2 # calculate fibonacci number greater than k while j < k: x = fib[i - 1] + fib[i - 2] fib.append(x) i += 1 j = x count = 0 for i in range(len(fib) - 1, -1, -1): print(fib[i], k) if fib[i] == k: count += 1 break elif fib[i] < k: k = k - fib[i] count += 1 return count
class Solution: def find_min_fibonacci_numbers(self, k: int) -> int: fib = [] fib.extend([1, 1]) j = 1 i = 2 while j < k: x = fib[i - 1] + fib[i - 2] fib.append(x) i += 1 j = x count = 0 for i in range(len(fib) - 1, -1, -1): print(fib[i], k) if fib[i] == k: count += 1 break elif fib[i] < k: k = k - fib[i] count += 1 return count
input() groups = sorted([ int(i) for i in input().split() ], reverse=True) cars = 0 i = 0 j = len(groups) - 1 while i <= j: g = groups[i] if g == 4: i += 1 cars += 1 continue cur_car = g while groups[j] <= 4 - cur_car and i < j: cur_car += groups[j] j -= 1 i += 1 cars += 1 print(cars)
input() groups = sorted([int(i) for i in input().split()], reverse=True) cars = 0 i = 0 j = len(groups) - 1 while i <= j: g = groups[i] if g == 4: i += 1 cars += 1 continue cur_car = g while groups[j] <= 4 - cur_car and i < j: cur_car += groups[j] j -= 1 i += 1 cars += 1 print(cars)
def auto_newline(text: str, max_line_length: int): def wrap_line_helper(line: str): words = line.split(" ") wrapped_line = [] current_line = "" for word in words: current_line += word if len(current_line) > max_line_length: current_line = " ".join(current_line.split(" ")[:-1]) wrapped_line.append(current_line) current_line = word current_line += " " wrapped_line.append(current_line[:-1]) return "\n".join(wrapped_line) lines = text.split("\n") wrapped_lines = [] for line1 in lines: wrapped_lines.append(wrap_line_helper(line1)) return "\n".join(wrapped_lines)
def auto_newline(text: str, max_line_length: int): def wrap_line_helper(line: str): words = line.split(' ') wrapped_line = [] current_line = '' for word in words: current_line += word if len(current_line) > max_line_length: current_line = ' '.join(current_line.split(' ')[:-1]) wrapped_line.append(current_line) current_line = word current_line += ' ' wrapped_line.append(current_line[:-1]) return '\n'.join(wrapped_line) lines = text.split('\n') wrapped_lines = [] for line1 in lines: wrapped_lines.append(wrap_line_helper(line1)) return '\n'.join(wrapped_lines)
def explore(lines): y = 0 x = lines[0].index('|') dx = 0 dy = 1 answer = '' steps = 0 while True: x += dx y += dy if lines[y][x] == '+': if x < (len(lines[y]) - 1) and lines[y][x+1].strip() and dx != -1: dx = 1 dy = 0 elif y < (len(lines) - 1) and x < len(lines[y+1]) and lines[y+1][x].strip() and dy != -1: dx = 0 dy = 1 elif y > 0 and x < len(lines[y-1]) and lines[y-1][x].strip() and dy != 1: dx = 0 dy = -1 elif x > 0 and lines[y][x-1].strip() and dx != 1: dx = -1 dy = 0 elif lines[y][x] == ' ': break elif lines[y][x] not in ('-', '|'): answer += lines[y][x] steps += 1 return answer, steps + 1 def test_explore(): assert ('ABCDEF', 38) == explore(open("input/dec19_test").readlines()) if __name__ == "__main__": print(explore(open("input/dec19").readlines()))
def explore(lines): y = 0 x = lines[0].index('|') dx = 0 dy = 1 answer = '' steps = 0 while True: x += dx y += dy if lines[y][x] == '+': if x < len(lines[y]) - 1 and lines[y][x + 1].strip() and (dx != -1): dx = 1 dy = 0 elif y < len(lines) - 1 and x < len(lines[y + 1]) and lines[y + 1][x].strip() and (dy != -1): dx = 0 dy = 1 elif y > 0 and x < len(lines[y - 1]) and lines[y - 1][x].strip() and (dy != 1): dx = 0 dy = -1 elif x > 0 and lines[y][x - 1].strip() and (dx != 1): dx = -1 dy = 0 elif lines[y][x] == ' ': break elif lines[y][x] not in ('-', '|'): answer += lines[y][x] steps += 1 return (answer, steps + 1) def test_explore(): assert ('ABCDEF', 38) == explore(open('input/dec19_test').readlines()) if __name__ == '__main__': print(explore(open('input/dec19').readlines()))
# Search in Rotated Sorted Array: https://leetcode.com/problems/search-in-rotated-sorted-array/ # There is an integer array nums sorted in ascending order (with distinct values). # Prior to being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. # Given the array nums after the rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. # You must write an algorithm with O(log n) runtime complexity. # This is a basic binary search the only difference is that we need to check if the values are sorted from high to mid so that we know wether to follow the traditional patern # or to traverse the other way as the shift occurs on the other side class Solution: def search(self, nums, target: int) -> int: lo, hi = 0, len(nums) - 1 while lo <= hi: mid = lo + (hi - lo) // 2 if nums[mid] == target: return mid else: # Is it properly sorted? if nums[mid] >= nums[lo]: # Now since we know where it is supposed to be we need to check if it can be here if target >= nums[lo] and target <= nums[mid]: hi = mid - 1 else: lo = mid + 1 else: if target <= nums[hi] and target > nums[mid]: lo = mid + 1 else: hi = mid - 1 return -1 # So this is pretty standard the only weird hiccup is finding whether or not you have a sorted segment or not # this runs in o(logn) and O(1) # Score Card # Did I need hints? N # Did you finish within 30 min? 10 # Was the solution optimal? This is optimal # Were there any bugs? No # 5 5 5 5 = 5
class Solution: def search(self, nums, target: int) -> int: (lo, hi) = (0, len(nums) - 1) while lo <= hi: mid = lo + (hi - lo) // 2 if nums[mid] == target: return mid elif nums[mid] >= nums[lo]: if target >= nums[lo] and target <= nums[mid]: hi = mid - 1 else: lo = mid + 1 elif target <= nums[hi] and target > nums[mid]: lo = mid + 1 else: hi = mid - 1 return -1
class Solution: def rotate(self, nums: List[int], k: int) -> None: k %= len(nums) if k > 0: for i, v in enumerate(nums[-k:] + nums[0:-k]): nums[i] = v
class Solution: def rotate(self, nums: List[int], k: int) -> None: k %= len(nums) if k > 0: for (i, v) in enumerate(nums[-k:] + nums[0:-k]): nums[i] = v
# sort given sequence given that the numbers go from 1 to n def cyclic_sort(seq): for i in range(len(seq)): num = seq[i] if num != seq[num-1]: # swap seq[num-1], seq[i] = seq[i], seq[num-1] def main(): seq = [5,4,1,2,3] cyclic_sort(seq) print(f'seq = {seq}') if __name__ == "__main__": main()
def cyclic_sort(seq): for i in range(len(seq)): num = seq[i] if num != seq[num - 1]: (seq[num - 1], seq[i]) = (seq[i], seq[num - 1]) def main(): seq = [5, 4, 1, 2, 3] cyclic_sort(seq) print(f'seq = {seq}') if __name__ == '__main__': main()
class Student: # Using a global base for all the available courses numReg = [] # We will initalise the student class def __init__(self, number, name, family, courses=None): if courses is None: courses = [] self.number = number self.numReg.append(self) self.name = name self.family = family self.courses = courses # This is used to display the student details def displayStudent(self): print('You are logged in as ' + self.name + ' ' + self.family) # This is used to display the number of courses a student takes up during his term/semester def displayStudentCourses(self, numStudent): if self.number == numStudent: if self.courses: print(self.courses) else: print('You have not selected any courses. Please choose a course.') # Using this, the selected course will be added to the student's portfolio/data def studentCourseAdding(self, wantedCourse, numStudent): if self.number == numStudent: self.courses.append(wantedCourse) print('You Added ' + wantedCourse + ' to your schedule, successfully!')
class Student: num_reg = [] def __init__(self, number, name, family, courses=None): if courses is None: courses = [] self.number = number self.numReg.append(self) self.name = name self.family = family self.courses = courses def display_student(self): print('You are logged in as ' + self.name + ' ' + self.family) def display_student_courses(self, numStudent): if self.number == numStudent: if self.courses: print(self.courses) else: print('You have not selected any courses. Please choose a course.') def student_course_adding(self, wantedCourse, numStudent): if self.number == numStudent: self.courses.append(wantedCourse) print('You Added ' + wantedCourse + ' to your schedule, successfully!')
############################################################################### ############################################################################### #Copyright (c) 2016, Andy Schroder #See the file README.md for licensing information. ############################################################################### ############################################################################### ################################################################################################# #Input parameters ################################################################################################# ########################### #cycle input parameters ########################### CycleInputParameters['MaximumTemperature']=650.0+273.0 CycleInputParameters['StartingProperties']['Temperature']=273.0+47 CycleInputParameters['FluidType']='Carbon Dioxide' CycleInputParameters['PowerOutput']=1.0*10**6 #1MW ########################### #common recuperator parameters DeltaPPerDeltaT=0 ########################### #piston related design assumptions and required pressure ratio ########################### CycleInputParameters['Piston']['MassFraction']=1.0 CycleInputParameters['Piston']['IsentropicEfficiency']=1.0 ########################### #heater related design assumptions ########################### CycleInputParameters['SecondPlusThirdHeating']['MaximumTemperature']=CycleInputParameters['MaximumTemperature'] CycleInputParameters['SecondPlusThirdHeating']['MassFraction']=1 CycleInputParameters['SecondPlusThirdHeating']['DeltaPPerDeltaT']=DeltaPPerDeltaT ########################### #cooler related design assumptions ########################### CycleInputParameters['TotalFractionCooler']['MinimumTemperature']=CycleInputParameters['StartingProperties']['Temperature'] CycleInputParameters['TotalFractionCooler']['MassFraction']=1 CycleInputParameters['TotalFractionCooler']['DeltaPPerDeltaT']=DeltaPPerDeltaT ########################### #recuperator related design assumptions ########################### CycleInputParameters['HTRecuperator']['NumberofTemperatures']=200 #keep in mind that the resolution of the data being interpolated is the real upper limit on the usefulness of this value CycleInputParameters['HTRecuperator']['LowPressure']['MassFraction']=1 CycleInputParameters['HTRecuperator']['HighPressure']['MassFraction']=1 CycleInputParameters['HTRecuperator']['HighPressure']['ConstantVolume']=True CycleInputParameters['HTRecuperator']['DeltaPPerDeltaT']=DeltaPPerDeltaT #maybe this should be different for high and low pressure sides? CycleInputParameters['HTRecuperator']['MinimumDeltaT']=0 ################################################################################################# #end Input parameters #################################################################################################
CycleInputParameters['MaximumTemperature'] = 650.0 + 273.0 CycleInputParameters['StartingProperties']['Temperature'] = 273.0 + 47 CycleInputParameters['FluidType'] = 'Carbon Dioxide' CycleInputParameters['PowerOutput'] = 1.0 * 10 ** 6 delta_p_per_delta_t = 0 CycleInputParameters['Piston']['MassFraction'] = 1.0 CycleInputParameters['Piston']['IsentropicEfficiency'] = 1.0 CycleInputParameters['SecondPlusThirdHeating']['MaximumTemperature'] = CycleInputParameters['MaximumTemperature'] CycleInputParameters['SecondPlusThirdHeating']['MassFraction'] = 1 CycleInputParameters['SecondPlusThirdHeating']['DeltaPPerDeltaT'] = DeltaPPerDeltaT CycleInputParameters['TotalFractionCooler']['MinimumTemperature'] = CycleInputParameters['StartingProperties']['Temperature'] CycleInputParameters['TotalFractionCooler']['MassFraction'] = 1 CycleInputParameters['TotalFractionCooler']['DeltaPPerDeltaT'] = DeltaPPerDeltaT CycleInputParameters['HTRecuperator']['NumberofTemperatures'] = 200 CycleInputParameters['HTRecuperator']['LowPressure']['MassFraction'] = 1 CycleInputParameters['HTRecuperator']['HighPressure']['MassFraction'] = 1 CycleInputParameters['HTRecuperator']['HighPressure']['ConstantVolume'] = True CycleInputParameters['HTRecuperator']['DeltaPPerDeltaT'] = DeltaPPerDeltaT CycleInputParameters['HTRecuperator']['MinimumDeltaT'] = 0
#D def fibonacci(N :int) -> int: if N == 1: return 1 elif N == 2: return 1 else: return fibonacci(N-2)+fibonacci(N-1) def main(): # input N = int(input()) # compute # output print(fibonacci(N)) if __name__ == '__main__': main()
def fibonacci(N: int) -> int: if N == 1: return 1 elif N == 2: return 1 else: return fibonacci(N - 2) + fibonacci(N - 1) def main(): n = int(input()) print(fibonacci(N)) if __name__ == '__main__': main()
class Solution: def countVowelStrings(self, n: int) -> int: d = ['a', 'e', 'i', 'o', 'u'] path = [] count = 0 def backtracking(n, start): nonlocal count if n == 0: count += 1 return for i in range(start, 5): path.append(d[i]) backtracking(n-1, i) path.pop() return backtracking(n, 0) return count
class Solution: def count_vowel_strings(self, n: int) -> int: d = ['a', 'e', 'i', 'o', 'u'] path = [] count = 0 def backtracking(n, start): nonlocal count if n == 0: count += 1 return for i in range(start, 5): path.append(d[i]) backtracking(n - 1, i) path.pop() return backtracking(n, 0) return count
class _EventTarget: '''https://developer.mozilla.org/en-US/docs/Web/API/EventTarget''' NotImplemented class _Node(_EventTarget): '''https://developer.mozilla.org/en-US/docs/Web/API/Node''' NotImplemented class _Element(_Node): '''ref of https://developer.mozilla.org/en-US/docs/Web/API/Element''' NotImplemented
class _Eventtarget: """https://developer.mozilla.org/en-US/docs/Web/API/EventTarget""" NotImplemented class _Node(_EventTarget): """https://developer.mozilla.org/en-US/docs/Web/API/Node""" NotImplemented class _Element(_Node): """ref of https://developer.mozilla.org/en-US/docs/Web/API/Element""" NotImplemented
# This is function for sorting the array using bubble sort def bubble_sort(length, array): # It takes two arguments -> Length of the array and the array itself. for i in range(length): j = 0 for j in range(0, length-i-1): if array[j] > array[j+1]: array[j], array[j+1] = array[j+1], array[j] return array #Returns sorted array # This is the main function of the program def main(): length = int(input('Enter the length of the array to be entered : ')) # Taking the length of array array = [int(i) for i in input('Enter Array Elements : ').split()] # Taking array elements sorted_array = bubble_sort(length,array) # Calling the function for sorting the array using bubble sort print("Sorted Array is : ") for i in sorted_array: # Printing the sorted array print(i, end = " ") # Running the main code of the program if __name__ == '__main__': main()
def bubble_sort(length, array): for i in range(length): j = 0 for j in range(0, length - i - 1): if array[j] > array[j + 1]: (array[j], array[j + 1]) = (array[j + 1], array[j]) return array def main(): length = int(input('Enter the length of the array to be entered : ')) array = [int(i) for i in input('Enter Array Elements : ').split()] sorted_array = bubble_sort(length, array) print('Sorted Array is : ') for i in sorted_array: print(i, end=' ') if __name__ == '__main__': main()
print(type(1)) print(type('runnob')) print(type([2])) print(type({0:'zero'}))
print(type(1)) print(type('runnob')) print(type([2])) print(type({0: 'zero'}))
# author: Fei Gao # # Count And Say # # The count-and-say sequence is the sequence of integers beginning as follows: # 1, 11, 21, 1211, 111221, ... # 1 is read off as "one 1" or 11. # 11 is read off as "two 1s" or 21. # 21 is read off as "one 2, then one 1" or 1211. # Given an integer n, generate the nth sequence. # Note: The sequence of integers will be represented as a string. class Solution: # @return a string def countAndSay(self, n): def process(s): l = [] start = 0 for end in range(1, len(s)): if s[end] != s[end-1]: l.append(s[start:end]) start = end l.append(s[start:]) res = '' for ls in l: res += str(len(ls)) + ls[0] return res seq = ['', '1'] for i in range(1, n): seq.append(process(seq[i])) return seq[n] def main(): solver = Solution() for n in range(10): print(n, ': ', solver.countAndSay(n)) pass if __name__ == '__main__': main() pass
class Solution: def count_and_say(self, n): def process(s): l = [] start = 0 for end in range(1, len(s)): if s[end] != s[end - 1]: l.append(s[start:end]) start = end l.append(s[start:]) res = '' for ls in l: res += str(len(ls)) + ls[0] return res seq = ['', '1'] for i in range(1, n): seq.append(process(seq[i])) return seq[n] def main(): solver = solution() for n in range(10): print(n, ': ', solver.countAndSay(n)) pass if __name__ == '__main__': main() pass
file = open('file.txt', 'r') f = file.readlines() readingList = [] for line in f: readingList.append(line.strip()) print(readingList) file.close()
file = open('file.txt', 'r') f = file.readlines() reading_list = [] for line in f: readingList.append(line.strip()) print(readingList) file.close()
#right rotation of array #it avoids unnecessary no. of recursions for large no. of rotations. def right_rot(arr,s):# s is the no. of times to rotate n=len(arr) s=s%n #print(s) for a in range(s): store=arr[n-1] for i in range(n-2,-1,-1): arr[i+1]=arr[i] arr[0]=store return(arr) arr = [11,1,2,3,4] s = 1 print(right_rot(arr,s))
def right_rot(arr, s): n = len(arr) s = s % n for a in range(s): store = arr[n - 1] for i in range(n - 2, -1, -1): arr[i + 1] = arr[i] arr[0] = store return arr arr = [11, 1, 2, 3, 4] s = 1 print(right_rot(arr, s))
n = 0 try: i = 0 while True: m = input() if m[0] == '+': n += 1 elif m[0] == '-': n -= 1 else: i += (len(m.split(':')[1]) * n) except: pass print(i)
n = 0 try: i = 0 while True: m = input() if m[0] == '+': n += 1 elif m[0] == '-': n -= 1 else: i += len(m.split(':')[1]) * n except: pass print(i)
def box(m): m = m.lower() # converting lowercase arr = [0] * len(m) # initializing array with same length as the length i = 0 for n in m: if not ('a' <= n <= 'z'): # excluding special characters continue arr[i] = ord(n) - ord('a') # subtracting ascii character values by a so we can map it to 0-25 i += 1 arr_f = arr[0:i] # array final - to exclude the special character in the array return arr_f def lock(arr_f, y): a = len(arr_f) k = box(y) b = 1 while b < a: # using the loop to make the keys array k.append(k[b - 1]) b += 1 enc = [0] * len(arr_f) # initializing array i = 0 for x in arr_f: enc[i] = (x + k[i]) % 26 # shifting the array to its keys value %26 is for looping from z to a i += 1 enc_f = enc[0:i] return enc_f def unbox(enc_f): m = "" for x in enc_f: m += chr(x + ord('a')) return m def encrypt(m, k): arr = box(m) enc = lock(arr, k) c = unbox(enc) return c def decrypt(c, y): cipher = box(c) a = len(c) k = box(y) b = 1 while b < a: # using the loop to make the keys array k.append(k[b - 1]) b += 1 dec = [0] * len(c) # initializing array i = 0 for x in cipher: dec[i] = (x - k[i]) % 26 # shifting the array to its keys value %26 is for looping from z to a i += 1 dec_f = dec[0:i] plain = unbox(dec_f) return plain def prob(m): a = box(m) b = len(a) arr = [0] * 26 arr1 = [0.082, 0.015, 0.028, 0.043, 0.127, 0.022, 0.020, 0.061, 0.070, 0.002, 0.008, 0.040, 0.024, 0.067, 0.075, 0.019, 0.001, 0.060, 0.063, 0.091, 0.028, 0.010, 0.023, 0.001, 0.020, 0.001] # arr1 is the probability distribution for general english taken from a study resource (professor's video online) j = 0 while j < 26: #these loops are counting the number of letters in the message ctr = 0 i = 0 while i < b: if a[i] == j: ctr += 1 arr[j] = ctr i += 1 j += 1 k = 0 while k < 26: arr[k] = (arr[k]/b) * (arr1[k]) k += 1 return arr def prob1(m): a = box(m) b = len(a) arr = [0] * 26 arr1 = [0.082, 0.015, 0.028, 0.043, 0.127, 0.022, 0.020, 0.061, 0.070, 0.002, 0.008, 0.040, 0.024, 0.067, 0.075, 0.019, 0.001, 0.060, 0.063, 0.091, 0.028, 0.010, 0.023, 0.001, 0.020, 0.001] # arr1 is the probability distribution for general english taken from a study resource (professor's video online) j = 0 while j < 26: #these loops are counting the number of letters in the message ctr = 0 i = 0 while i < b: if a[i] == j: ctr += 1 arr[j] = ctr i += 1 j += 1 k = 0 while k < 26: arr[k] = (arr[k]/b) * (arr[k]/b) k += 1 return arr def sum_prob(arr): s = 0 for i in arr: s = s + i return s def seperate(m, size): source = box(m) # putting the message in the array return [source[i::size] for i in range(size)] # (Condensed everything in one line) seperating that array into a nested array of the specified size chunks
def box(m): m = m.lower() arr = [0] * len(m) i = 0 for n in m: if not 'a' <= n <= 'z': continue arr[i] = ord(n) - ord('a') i += 1 arr_f = arr[0:i] return arr_f def lock(arr_f, y): a = len(arr_f) k = box(y) b = 1 while b < a: k.append(k[b - 1]) b += 1 enc = [0] * len(arr_f) i = 0 for x in arr_f: enc[i] = (x + k[i]) % 26 i += 1 enc_f = enc[0:i] return enc_f def unbox(enc_f): m = '' for x in enc_f: m += chr(x + ord('a')) return m def encrypt(m, k): arr = box(m) enc = lock(arr, k) c = unbox(enc) return c def decrypt(c, y): cipher = box(c) a = len(c) k = box(y) b = 1 while b < a: k.append(k[b - 1]) b += 1 dec = [0] * len(c) i = 0 for x in cipher: dec[i] = (x - k[i]) % 26 i += 1 dec_f = dec[0:i] plain = unbox(dec_f) return plain def prob(m): a = box(m) b = len(a) arr = [0] * 26 arr1 = [0.082, 0.015, 0.028, 0.043, 0.127, 0.022, 0.02, 0.061, 0.07, 0.002, 0.008, 0.04, 0.024, 0.067, 0.075, 0.019, 0.001, 0.06, 0.063, 0.091, 0.028, 0.01, 0.023, 0.001, 0.02, 0.001] j = 0 while j < 26: ctr = 0 i = 0 while i < b: if a[i] == j: ctr += 1 arr[j] = ctr i += 1 j += 1 k = 0 while k < 26: arr[k] = arr[k] / b * arr1[k] k += 1 return arr def prob1(m): a = box(m) b = len(a) arr = [0] * 26 arr1 = [0.082, 0.015, 0.028, 0.043, 0.127, 0.022, 0.02, 0.061, 0.07, 0.002, 0.008, 0.04, 0.024, 0.067, 0.075, 0.019, 0.001, 0.06, 0.063, 0.091, 0.028, 0.01, 0.023, 0.001, 0.02, 0.001] j = 0 while j < 26: ctr = 0 i = 0 while i < b: if a[i] == j: ctr += 1 arr[j] = ctr i += 1 j += 1 k = 0 while k < 26: arr[k] = arr[k] / b * (arr[k] / b) k += 1 return arr def sum_prob(arr): s = 0 for i in arr: s = s + i return s def seperate(m, size): source = box(m) return [source[i::size] for i in range(size)]
# coding=utf-8 # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- class Job: def __init__(self, job: dict): self.display_name = job.get("displayName") self.id = job.get("id") self.group = job.get("group") self.status = job.get("status") self.data = job.get("data") self.description = job.get("description") self.batch = job.get("batch") self.cancellation_threshold = job.get("cancellationThreshold")
class Job: def __init__(self, job: dict): self.display_name = job.get('displayName') self.id = job.get('id') self.group = job.get('group') self.status = job.get('status') self.data = job.get('data') self.description = job.get('description') self.batch = job.get('batch') self.cancellation_threshold = job.get('cancellationThreshold')
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") def grpc_rules_repository(): http_archive( name = "rules_proto_grpc", urls = ["https://github.com/rules-proto-grpc/rules_proto_grpc/archive/2.0.0.tar.gz"], sha256 = "d771584bbff98698e7cb3cb31c132ee206a972569f4dc8b65acbdd934d156b33", strip_prefix = "rules_proto_grpc-2.0.0", )
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive') def grpc_rules_repository(): http_archive(name='rules_proto_grpc', urls=['https://github.com/rules-proto-grpc/rules_proto_grpc/archive/2.0.0.tar.gz'], sha256='d771584bbff98698e7cb3cb31c132ee206a972569f4dc8b65acbdd934d156b33', strip_prefix='rules_proto_grpc-2.0.0')
class Embed: def __init__(self, **kwargs): allowed_args = ("title", "description", "color") for key, value in kwargs.items(): if key in allowed_args: setattr(self, key, value) def set_image(self, *, url: str): self.image = {"url": url} def set_thumbnail(self, *, url: str): self.thumbnail = {"url": url} def set_footer(self, *, text: str, icon_url: str = None): self.footer = {"text": text} if icon_url: self.footer["icon_url"] = icon_url def set_author(self, *, name: str, icon_url: str = None): self.author = {"name": name} if icon_url: self.author["icon_url"] = icon_url def add_field(self, *, name: str, value: str, inline: bool = False): if not hasattr(self, "fields"): self.fields = [] self.fields.append({ "name": name, "value": value, "inline": inline })
class Embed: def __init__(self, **kwargs): allowed_args = ('title', 'description', 'color') for (key, value) in kwargs.items(): if key in allowed_args: setattr(self, key, value) def set_image(self, *, url: str): self.image = {'url': url} def set_thumbnail(self, *, url: str): self.thumbnail = {'url': url} def set_footer(self, *, text: str, icon_url: str=None): self.footer = {'text': text} if icon_url: self.footer['icon_url'] = icon_url def set_author(self, *, name: str, icon_url: str=None): self.author = {'name': name} if icon_url: self.author['icon_url'] = icon_url def add_field(self, *, name: str, value: str, inline: bool=False): if not hasattr(self, 'fields'): self.fields = [] self.fields.append({'name': name, 'value': value, 'inline': inline})
a = 7 b = 3 def func1(c,d): e = c + d e += c e *= d return e f = func1(a,b) print (f)
a = 7 b = 3 def func1(c, d): e = c + d e += c e *= d return e f = func1(a, b) print(f)
a: str a: bool = True my_long_var_aaaaaaaaaaaaaaaaaaaaaaaaaa: MyLongTypeAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA my_long_var_aaaaaaaaaaaaaaaaaaaaaaaaaa: MyLongTypeAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA = 1
a: str a: bool = True my_long_var_aaaaaaaaaaaaaaaaaaaaaaaaaa: MyLongTypeAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA my_long_var_aaaaaaaaaaaaaaaaaaaaaaaaaa: MyLongTypeAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA = 1
class Edge(object): def __init__(self, u, v, w): self.__orig = u self.__dest = v self.__w = w def getOrig(self): return self.__orig def getDest(self): return self.__dest def getW(self): return self.__w
class Edge(object): def __init__(self, u, v, w): self.__orig = u self.__dest = v self.__w = w def get_orig(self): return self.__orig def get_dest(self): return self.__dest def get_w(self): return self.__w
class UltrasonicSensor: def __init__(self, megapi, slot): self._megapi = megapi self._slot = slot self._last_val = 400 def read(self): self._megapi.ultrasonicSensorRead(self._slot, self._on_forward_ultrasonic_read) def get_value(self): return self._last_val def _on_forward_ultrasonic_read(self, val): self._last_val = val
class Ultrasonicsensor: def __init__(self, megapi, slot): self._megapi = megapi self._slot = slot self._last_val = 400 def read(self): self._megapi.ultrasonicSensorRead(self._slot, self._on_forward_ultrasonic_read) def get_value(self): return self._last_val def _on_forward_ultrasonic_read(self, val): self._last_val = val
def f(t): # relation between f and t return value def rxn1(C,t): return np.array([f(t)*C0/v-f(t)*C[0]/v-k*C[0], f(t)*C[0]/v-f(t)*C[1]/v-k*C[1]])
def f(t): return value def rxn1(C, t): return np.array([f(t) * C0 / v - f(t) * C[0] / v - k * C[0], f(t) * C[0] / v - f(t) * C[1] / v - k * C[1]])
name = input("what is your name? ") age = int(input("how old are you {0}? ".format(name))) if (18 <= age < 31): print("welcome to holiday") else: print("you are not 18-30")
name = input('what is your name? ') age = int(input('how old are you {0}? '.format(name))) if 18 <= age < 31: print('welcome to holiday') else: print('you are not 18-30')
a,b = map(int,input().split()) def multiply(a,b): return a*b print(multiply(a,b))
(a, b) = map(int, input().split()) def multiply(a, b): return a * b print(multiply(a, b))
class CoordLinkedList: # a linked list object def __init__ (self,node=None,y=None,x=None,up=None,down=None,left=None,right=None): self.up = up self.down = down self.left = left self.right = right if isinstance(node,(list,set,tuple)) and len(node) == 2: self.node = tuple(node) elif x and y: self.node = (y,x) def receive (self,nodes): if not isinstance(nodes,(list,set,tuple)): nodes = {nodes} for n in nodes: if isinstance(n,(tuple)) and len(n) == 2: if n == (self.node[0]-1,self.node[1]): self.up = n elif n == (self.node[0]+1,self.node[1]): self.down = n elif n == (self.node[0],self.node[1]+1): self.right = n elif n == (self.node[0],self.node[1]-1): self.left = n def send(self,nodes=None): if not nodes: nodes = [] returnlist = [] if self.down: returnlist.append(self.down) if self.up: returnlist.append(self.up) if self.left: returnlist.append(self.left) if self.right: returnlist.append(self.right) return [x for x in returnlist if x not in nodes]
class Coordlinkedlist: def __init__(self, node=None, y=None, x=None, up=None, down=None, left=None, right=None): self.up = up self.down = down self.left = left self.right = right if isinstance(node, (list, set, tuple)) and len(node) == 2: self.node = tuple(node) elif x and y: self.node = (y, x) def receive(self, nodes): if not isinstance(nodes, (list, set, tuple)): nodes = {nodes} for n in nodes: if isinstance(n, tuple) and len(n) == 2: if n == (self.node[0] - 1, self.node[1]): self.up = n elif n == (self.node[0] + 1, self.node[1]): self.down = n elif n == (self.node[0], self.node[1] + 1): self.right = n elif n == (self.node[0], self.node[1] - 1): self.left = n def send(self, nodes=None): if not nodes: nodes = [] returnlist = [] if self.down: returnlist.append(self.down) if self.up: returnlist.append(self.up) if self.left: returnlist.append(self.left) if self.right: returnlist.append(self.right) return [x for x in returnlist if x not in nodes]
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def kthSmallest(self, root: TreeNode, k: int) -> int: data = [] def traverse(node): if node.left: traverse(node.left) data.append(node.val) if node.right: traverse(node.right) traverse(root) return data[k - 1]
class Solution: def kth_smallest(self, root: TreeNode, k: int) -> int: data = [] def traverse(node): if node.left: traverse(node.left) data.append(node.val) if node.right: traverse(node.right) traverse(root) return data[k - 1]
# List custom images def list_custom_images_subparser(subparser): list_images = subparser.add_parser( 'list-custom-images', description=('***List custom' ' saved images of' ' producers/consumers' ' account'), help=('List custom' ' saved images of' ' producers/consumers' ' account')) group_key = list_images.add_mutually_exclusive_group(required=True) group_key.add_argument('-pn', '--producer-username', help="Producer\'s(source account) username") group_key.add_argument('-cn', '--consumer-username', dest='producer_username', metavar='CONSUMER_USERNAME', help="Consumer\'s(destination account) username") group_apikey = list_images.add_mutually_exclusive_group(required=True) group_apikey.add_argument('-pa', '--producer-apikey', help="Producer\'s(source account) apikey") group_apikey.add_argument('-ca', '--consumer-apikey', dest='producer_apikey', metavar='CONSUMER_APIKEY', help="Consumer\'s(destination account) apikey") list_images.add_argument('-u', '--uuid', help="Image ID number")
def list_custom_images_subparser(subparser): list_images = subparser.add_parser('list-custom-images', description='***List custom saved images of producers/consumers account', help='List custom saved images of producers/consumers account') group_key = list_images.add_mutually_exclusive_group(required=True) group_key.add_argument('-pn', '--producer-username', help="Producer's(source account) username") group_key.add_argument('-cn', '--consumer-username', dest='producer_username', metavar='CONSUMER_USERNAME', help="Consumer's(destination account) username") group_apikey = list_images.add_mutually_exclusive_group(required=True) group_apikey.add_argument('-pa', '--producer-apikey', help="Producer's(source account) apikey") group_apikey.add_argument('-ca', '--consumer-apikey', dest='producer_apikey', metavar='CONSUMER_APIKEY', help="Consumer's(destination account) apikey") list_images.add_argument('-u', '--uuid', help='Image ID number')
# # @lc app=leetcode id=543 lang=python3 # # [543] Diameter of Binary Tree # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def diameterOfBinaryTree(self, root): self.ans = 0 self.pathfinder(root) return self.ans def pathfinder(self, root): if root is None: return 0 lh = self.pathfinder(root.left) rh = self.pathfinder(root.right) self.ans = max(self.ans, lh + rh) return max(lh, rh) + 1 # @lc code=end
class Solution: def diameter_of_binary_tree(self, root): self.ans = 0 self.pathfinder(root) return self.ans def pathfinder(self, root): if root is None: return 0 lh = self.pathfinder(root.left) rh = self.pathfinder(root.right) self.ans = max(self.ans, lh + rh) return max(lh, rh) + 1
VISUALIZATION_CONFIG = { 'requirements': ['d3', 'datagramas', 'topojson', 'cartogram'], 'visualization_name': 'datagramas.cartogram', 'figure_id': None, 'container_type': 'svg', 'data': { 'geometry': None, 'area_dataframe': None, }, 'options': { }, 'variables': { 'width': 960, 'height': 500, 'padding': {'left': 0, 'top': 0, 'right': 0, 'bottom': 0}, 'feature_id': 'id', 'label': True, 'path_opacity': 1.0, 'path_stroke': 'gray', 'path_stroke_width': 1.0, 'fill_color': 'none', 'area_value': 'value', 'area_feature_name': 'id', 'area_opacity': 0.75, 'area_transition_delay': 0, 'feature_name': None, 'label_font_size': 10, 'label_color': 'black', 'bounding_box': None, 'na_value': 0.000001 }, 'colorables': { 'area_color': {'value': None, 'palette': None, 'scale': None, 'n_colors': None, 'legend': False}, }, 'auxiliary': { 'path', 'projection', 'original_geometry', 'area_colors', 'area_carto_values' } }
visualization_config = {'requirements': ['d3', 'datagramas', 'topojson', 'cartogram'], 'visualization_name': 'datagramas.cartogram', 'figure_id': None, 'container_type': 'svg', 'data': {'geometry': None, 'area_dataframe': None}, 'options': {}, 'variables': {'width': 960, 'height': 500, 'padding': {'left': 0, 'top': 0, 'right': 0, 'bottom': 0}, 'feature_id': 'id', 'label': True, 'path_opacity': 1.0, 'path_stroke': 'gray', 'path_stroke_width': 1.0, 'fill_color': 'none', 'area_value': 'value', 'area_feature_name': 'id', 'area_opacity': 0.75, 'area_transition_delay': 0, 'feature_name': None, 'label_font_size': 10, 'label_color': 'black', 'bounding_box': None, 'na_value': 1e-06}, 'colorables': {'area_color': {'value': None, 'palette': None, 'scale': None, 'n_colors': None, 'legend': False}}, 'auxiliary': {'path', 'projection', 'original_geometry', 'area_colors', 'area_carto_values'}}
class Solution(object): def reconstructQueue(self, people): people.sort(key=lambda x: (-x[0], x[1])) output = [] for p in people: output.insert(p[1], p) return output m = int(input()) k = Solution() array_input = [] for x in range(m): array_input.append([int(y) for y in input().split()]) gh =k.reconstructQueue(array_input) for s in gh: print(*s)
class Solution(object): def reconstruct_queue(self, people): people.sort(key=lambda x: (-x[0], x[1])) output = [] for p in people: output.insert(p[1], p) return output m = int(input()) k = solution() array_input = [] for x in range(m): array_input.append([int(y) for y in input().split()]) gh = k.reconstructQueue(array_input) for s in gh: print(*s)
def pent_d(n=1, pents=set()): while True: p_n = n*(3*n - 1)//2 for p in pents: if p_n - p in pents and 2*p - p_n in pents: return 2*p - p_n pents.add(p_n) n += 1 print(pent_d()) # Copyright Junipyr. All rights reserved. # https://github.com/Junipyr
def pent_d(n=1, pents=set()): while True: p_n = n * (3 * n - 1) // 2 for p in pents: if p_n - p in pents and 2 * p - p_n in pents: return 2 * p - p_n pents.add(p_n) n += 1 print(pent_d())
n = int(input()) for i in range(n): vet = list(map(int, input().split())) partida = vet[0] qtd = vet[1] if partida % 2 == 0: partida += 1 soma = 0 for j in range(qtd): soma += partida partida += 2 print(soma)
n = int(input()) for i in range(n): vet = list(map(int, input().split())) partida = vet[0] qtd = vet[1] if partida % 2 == 0: partida += 1 soma = 0 for j in range(qtd): soma += partida partida += 2 print(soma)
# Scrapy settings for Scrapy project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://docs.scrapy.org/en/latest/topics/settings.html # https://docs.scrapy.org/en/latest/topics/downloader-middleware.html # https://docs.scrapy.org/en/latest/topics/spider-middleware.html BOT_NAME = 'scrapy_demo' SPIDER_MODULES = ['Scrapy.spiders'] # look for spiders here NEWSPIDER_MODULE = 'Scrapy.spiders' # create new spiders here LOG_LEVEL='INFO' # enable following lines for testing --- CLOSESPIDER_PAGECOUNT = 20 # test a few pages # --- # Crawl responsibly by identifying yourself (and your website) on the user-agent USER_AGENT = 'Scrapy Demo' # Obey robots.txt rules ROBOTSTXT_OBEY = False # Image pipelin settings IMAGES_EXPIRES = 1 # 1 days of delay for images expiration IMAGES_STORE = './images' # Configure item pipelines # See https://docs.scrapy.org/en/latest/topics/item-pipeline.html ITEM_PIPELINES = { 'scrapy.pipelines.images.ImagesPipeline': 1, 'Scrapy.pipelines.BookPipeline': 300 }
bot_name = 'scrapy_demo' spider_modules = ['Scrapy.spiders'] newspider_module = 'Scrapy.spiders' log_level = 'INFO' closespider_pagecount = 20 user_agent = 'Scrapy Demo' robotstxt_obey = False images_expires = 1 images_store = './images' item_pipelines = {'scrapy.pipelines.images.ImagesPipeline': 1, 'Scrapy.pipelines.BookPipeline': 300}
# Copyright 2020 Adobe. All rights reserved. # This file is licensed 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 REPRESENTATIONS # OF ANY KIND, either express or implied. See the License for the specific language # governing permissions and limitations under the License. load("@io_bazel_rules_docker//container:providers.bzl", "PushInfo") load( "@io_bazel_rules_docker//skylib:path.bzl", _get_runfile_path = "runfile", ) load("//skylib:providers.bzl", "ImagePushesInfo") load("//skylib/workspace:aspect.bzl", "pushable_aspect") def _file_to_runfile(ctx, file): return file.owner.workspace_root or ctx.workspace_name + "/" + file.short_path def _workspace_impl(ctx): transitive_executables = [] transitive_runfiles = [] transitive_data = [] for t in ctx.attr.data: transitive_data.append(t[DefaultInfo].files) # flatten & 'uniquify' our list of asset files data = depset(transitive = transitive_data).to_list() runfiles = depset(transitive = transitive_runfiles).to_list() files = [] tars = [] for src in ctx.attr.srcs: tar = src.files.to_list()[0] tars.append(tar) rf = ctx.runfiles(files = runfiles + data + tars + ctx.files._bash_runfiles) trans_img_pushes = [] if ctx.attr.push: trans_img_pushes = depset(transitive = [ obj[ImagePushesInfo].image_pushes for obj in ctx.attr.srcs if ImagePushesInfo in obj ]).to_list() files += [obj.files_to_run.executable for obj in trans_img_pushes] for obj in trans_img_pushes: rf = rf.merge(obj[DefaultInfo].default_runfiles) ctx.actions.expand_template( template = ctx.file._template, substitutions = { "%{workspace_tar_targets}": " ".join([json.encode(_file_to_runfile(ctx, t)) for t in tars]), "%{push_targets}": " ".join([json.encode(_file_to_runfile(ctx, exe.files_to_run.executable)) for exe in trans_img_pushes]), # "async $(rlocation metered/%s)" % exe.files_to_run.executable.short_path }, output = ctx.outputs.executable, ) return [ DefaultInfo( files = depset(files), runfiles = rf, ), ImagePushesInfo( image_pushes = depset( transitive = [ obj[ImagePushesInfo].image_pushes for obj in ctx.attr.srcs if ImagePushesInfo in obj ], ), ), ] workspace = rule( implementation = _workspace_impl, attrs = { "srcs": attr.label_list( # cfg = "host", # allow_files = True, aspects = [pushable_aspect], ), "push": attr.bool(default = True), "data": attr.label_list( # cfg = "host", allow_files = True, ), "_template": attr.label( default = Label("//skylib/workspace:workspace.sh.tpl"), allow_single_file = True, ), "_bash_runfiles": attr.label( allow_files = True, default = "@bazel_tools//tools/bash/runfiles", ), }, executable = True, )
load('@io_bazel_rules_docker//container:providers.bzl', 'PushInfo') load('@io_bazel_rules_docker//skylib:path.bzl', _get_runfile_path='runfile') load('//skylib:providers.bzl', 'ImagePushesInfo') load('//skylib/workspace:aspect.bzl', 'pushable_aspect') def _file_to_runfile(ctx, file): return file.owner.workspace_root or ctx.workspace_name + '/' + file.short_path def _workspace_impl(ctx): transitive_executables = [] transitive_runfiles = [] transitive_data = [] for t in ctx.attr.data: transitive_data.append(t[DefaultInfo].files) data = depset(transitive=transitive_data).to_list() runfiles = depset(transitive=transitive_runfiles).to_list() files = [] tars = [] for src in ctx.attr.srcs: tar = src.files.to_list()[0] tars.append(tar) rf = ctx.runfiles(files=runfiles + data + tars + ctx.files._bash_runfiles) trans_img_pushes = [] if ctx.attr.push: trans_img_pushes = depset(transitive=[obj[ImagePushesInfo].image_pushes for obj in ctx.attr.srcs if ImagePushesInfo in obj]).to_list() files += [obj.files_to_run.executable for obj in trans_img_pushes] for obj in trans_img_pushes: rf = rf.merge(obj[DefaultInfo].default_runfiles) ctx.actions.expand_template(template=ctx.file._template, substitutions={'%{workspace_tar_targets}': ' '.join([json.encode(_file_to_runfile(ctx, t)) for t in tars]), '%{push_targets}': ' '.join([json.encode(_file_to_runfile(ctx, exe.files_to_run.executable)) for exe in trans_img_pushes])}, output=ctx.outputs.executable) return [default_info(files=depset(files), runfiles=rf), image_pushes_info(image_pushes=depset(transitive=[obj[ImagePushesInfo].image_pushes for obj in ctx.attr.srcs if ImagePushesInfo in obj]))] workspace = rule(implementation=_workspace_impl, attrs={'srcs': attr.label_list(aspects=[pushable_aspect]), 'push': attr.bool(default=True), 'data': attr.label_list(allow_files=True), '_template': attr.label(default=label('//skylib/workspace:workspace.sh.tpl'), allow_single_file=True), '_bash_runfiles': attr.label(allow_files=True, default='@bazel_tools//tools/bash/runfiles')}, executable=True)
def changecode(): file1=input("Enter your file name1") file2=input("Enter your file name2") with open(file1,"r") as a: data_a = a.read() with open(file2,"r") as b: data_b = b.read() with open(file1,"w") as a: a.write(data_b) with open(file2,"w") as b: b.write(data_a) changecode()
def changecode(): file1 = input('Enter your file name1') file2 = input('Enter your file name2') with open(file1, 'r') as a: data_a = a.read() with open(file2, 'r') as b: data_b = b.read() with open(file1, 'w') as a: a.write(data_b) with open(file2, 'w') as b: b.write(data_a) changecode()
ll=range(5, 20, 5) for i in ll: print(i) print (ll) x = 'Python' for i in range(len(x)) : print(x[i])
ll = range(5, 20, 5) for i in ll: print(i) print(ll) x = 'Python' for i in range(len(x)): print(x[i])
# Function returns nth element of Padovan sequence def padovan(n): p = 0 if n > 2: p = padovan(n-2) + padovan(n-3) return p else: p = 1 return p def main(): while True: n = int(input("Enter a number: ")) if n >= 0: break print("Invalid number,try again") print(f"P({n}) = {padovan(n)}") main()
def padovan(n): p = 0 if n > 2: p = padovan(n - 2) + padovan(n - 3) return p else: p = 1 return p def main(): while True: n = int(input('Enter a number: ')) if n >= 0: break print('Invalid number,try again') print(f'P({n}) = {padovan(n)}') main()
li = [] for x in range (21): li.append(x) print(li) del(li[4]) print(li)
li = [] for x in range(21): li.append(x) print(li) del li[4] print(li)