content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
limit = 10000 sum_divisors = 0 val = [0, 0] for number in range(2, limit): sum_divisor = 0 for number2 in range(1, int(number / 2) + 1): if (number % number2 == 0): sum_divisor += number2 val.append(sum_divisor) sum_amicable_numbers = 0 for number in range(2, limit): if (val[number] < limit and number != val[number] and val[val[number]] == number): sum_amicable_numbers += number print(sum_amicable_numbers)
limit = 10000 sum_divisors = 0 val = [0, 0] for number in range(2, limit): sum_divisor = 0 for number2 in range(1, int(number / 2) + 1): if number % number2 == 0: sum_divisor += number2 val.append(sum_divisor) sum_amicable_numbers = 0 for number in range(2, limit): if val[number] < limit and number != val[number] and (val[val[number]] == number): sum_amicable_numbers += number print(sum_amicable_numbers)
"""Flask configuration""" class Config: """Setting up config variables""" # General FLASK_ENV = "development" TESTING = True # Database SQLALCHEMY_DATABASE_URI = "sqlite:///sqlite_db/catalogue.db" SQLALCHEMY_TRACK_MODIFICATIONS = False # JWT JWT_SECRET_KEY = 'super-secret' # Tests FAKE_DATABASE_URI = "sqlite:///tests/test.db" FAKE_USER = 'baJeKcrEed09' FAKE_USER_PASSWORD = 'XenomorpH1993' JOKE_FAKE_USER = 'xamarine099' JOKE_FAKE_USER_PASSWORD = 'xiliojio31' FAKE_JOKE = 'A horse and a pigeon walk into a bar...' ANOTHER_FAKE_JOKE = 'What\'s the best thing about Switzerland? ' \ 'I don\'t know, but the flag is a big plus.' # Messages BAD_PARAMETER = "User\'s name can only contain digits " \ "and letters and must be at least 6 " \ "characters long, 20 characters at max" TOO_LONG = b"Joke string is too long. Max allowed size is 900 characters" # Bounds JOKES_LIMIT = 100 # Foreign APIs FOREIGN_API = { 'geek-jokes': 'https://geek-jokes.sameerkumar.website/api?format=json', }
"""Flask configuration""" class Config: """Setting up config variables""" flask_env = 'development' testing = True sqlalchemy_database_uri = 'sqlite:///sqlite_db/catalogue.db' sqlalchemy_track_modifications = False jwt_secret_key = 'super-secret' fake_database_uri = 'sqlite:///tests/test.db' fake_user = 'baJeKcrEed09' fake_user_password = 'XenomorpH1993' joke_fake_user = 'xamarine099' joke_fake_user_password = 'xiliojio31' fake_joke = 'A horse and a pigeon walk into a bar...' another_fake_joke = "What's the best thing about Switzerland? I don't know, but the flag is a big plus." bad_parameter = "User's name can only contain digits and letters and must be at least 6 characters long, 20 characters at max" too_long = b'Joke string is too long. Max allowed size is 900 characters' jokes_limit = 100 foreign_api = {'geek-jokes': 'https://geek-jokes.sameerkumar.website/api?format=json'}
peso_maior = 0 peso_menor = 0 for c in range(1, 6): peso = float(input("Informe o peso da {0} pessoa: ".format(c))) if(c == 1): peso_maior = peso peso_menor = peso else: if(peso > peso_maior): peso_maior = peso if(peso < peso_menor): peso_menor = peso print("O peso MAIOR e {0}Kg!".format(peso_maior)) print("O peso MENOR e {0}Kg!".format(peso_menor))
peso_maior = 0 peso_menor = 0 for c in range(1, 6): peso = float(input('Informe o peso da {0} pessoa: '.format(c))) if c == 1: peso_maior = peso peso_menor = peso else: if peso > peso_maior: peso_maior = peso if peso < peso_menor: peso_menor = peso print('O peso MAIOR e {0}Kg!'.format(peso_maior)) print('O peso MENOR e {0}Kg!'.format(peso_menor))
class Cache: """ Class used for storing a data from one instance and allow a different class instance to access this data. """ _state: dict = { 'Data': '' } def __new__(cls, *args, **kwargs): obj = super().__new__(cls) obj.__dict__ = cls._state return obj def __init__(self, data=None): if data is None: return self._state['Data'] = data def __call__(self): """Return the data by calling this class""" return self._state['Data']
class Cache: """ Class used for storing a data from one instance and allow a different class instance to access this data. """ _state: dict = {'Data': ''} def __new__(cls, *args, **kwargs): obj = super().__new__(cls) obj.__dict__ = cls._state return obj def __init__(self, data=None): if data is None: return self._state['Data'] = data def __call__(self): """Return the data by calling this class""" return self._state['Data']
#Tokenizer of Expression #Example Expression: ~(T & F) | T def tokenize(expr): ac = ["T", "F", "(", ")", "~", "&", "|", " ", "\t"] ls = [] for i in range(0, len(expr)): if expr[i] not in ac: raise Exception("invalid expression") if expr[i] != " ": ls.append(expr[i]) return ls """ Test expressions: (T & F) ~(T | T) T & (~F | ~T) A CFG for this grammar is: E -> (E) | A A -> E & A | O O -> E|O | N N -> ~ E | C C -> T | F """ #Evaluation of Syntax Tree #any expression is either true/false, an and expr, an or expr, or a not expr. def evaluate(sTree): if sTree == True: return True elif sTree == False: return False elif sTree[0] == "and": assert len(sTree) == 3, "invalid syntax Tree" return evaluate(sTree[1]) and evaluate(sTree[2]) elif sTree[0] == "or": assert len(sTree) == 3, "invalid syntax Tree" return evaluate(sTree[1]) or evaluate(sTree[2]) elif sTree[0] == "not": assert len(sTree) == 2, "invalid syntax Tree" return not evaluate(sTree[1]) else: raise Exception("invalid expression") #Evaluator Tests assert evaluate(True) == True, "something bad happened" assert evaluate(["and", True, False]) == False, "unexpected and behavior" assert evaluate(["and", ["not", False], ["or", False, True]]), "unexpected behavior"
def tokenize(expr): ac = ['T', 'F', '(', ')', '~', '&', '|', ' ', '\t'] ls = [] for i in range(0, len(expr)): if expr[i] not in ac: raise exception('invalid expression') if expr[i] != ' ': ls.append(expr[i]) return ls '\nTest expressions:\n(T & F)\n~(T | T)\nT & (~F | ~T)\n\nA CFG for this grammar is:\nE -> (E) | A\nA -> E & A | O\nO -> E|O | N\nN -> ~ E | C\nC -> T | F\n' def evaluate(sTree): if sTree == True: return True elif sTree == False: return False elif sTree[0] == 'and': assert len(sTree) == 3, 'invalid syntax Tree' return evaluate(sTree[1]) and evaluate(sTree[2]) elif sTree[0] == 'or': assert len(sTree) == 3, 'invalid syntax Tree' return evaluate(sTree[1]) or evaluate(sTree[2]) elif sTree[0] == 'not': assert len(sTree) == 2, 'invalid syntax Tree' return not evaluate(sTree[1]) else: raise exception('invalid expression') assert evaluate(True) == True, 'something bad happened' assert evaluate(['and', True, False]) == False, 'unexpected and behavior' assert evaluate(['and', ['not', False], ['or', False, True]]), 'unexpected behavior'
''' this is used to add a comment line or a set of lines that the computer ignores ''' # this is used to add a single comment line print("this is used to" + " concatenate 2 strings") ''' a string and a number cannot be concatenated this way instead we can use a comma to separate the two different data types''' print(9, ' aousnik') #BREAK AND CONTINUE:: magicNumber = 26 for x in range(101): if x is magicNumber: print(x," is a magic number") #once 26 is found it prints the number and breaks the loop break else: print(x) #prints the number anyways '''numbers till 100 divisibe by 4''' print('\n') for i in range(1, 101): x = i%4 if x is 0: print(i)
""" this is used to add a comment line or a set of lines that the computer ignores """ print('this is used to' + ' concatenate 2 strings') '\na string and a number cannot be concatenated this way\ninstead we can use a comma to separate the two different data types' print(9, ' aousnik') magic_number = 26 for x in range(101): if x is magicNumber: print(x, ' is a magic number') break else: print(x) 'numbers till 100 divisibe by 4' print('\n') for i in range(1, 101): x = i % 4 if x is 0: print(i)
''' Created on 11 juni 2017 @author: Wilma '''
""" Created on 11 juni 2017 @author: Wilma """
""" * If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. * Find the sum of all the multiples of 3 or 5 below 1000. """ def sum_multiples(mul, below): first = mul # First multiple of mul last = ((below - 1) // mul) * mul # The last multiple of mul n = ((last - first) // mul) + 1 # The number of multiples return (n * (first + last)) // 2 # Arithmetic progression sum def sum_multiples_3_5(below): sum3 = sum_multiples(3, below) sum5 = sum_multiples(5, below) sum15 = sum_multiples(15, below) return sum3 + sum5 - sum15 if __name__ == "__main__": r = sum_multiples_3_5(1000) print(r)
""" * If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. * Find the sum of all the multiples of 3 or 5 below 1000. """ def sum_multiples(mul, below): first = mul last = (below - 1) // mul * mul n = (last - first) // mul + 1 return n * (first + last) // 2 def sum_multiples_3_5(below): sum3 = sum_multiples(3, below) sum5 = sum_multiples(5, below) sum15 = sum_multiples(15, below) return sum3 + sum5 - sum15 if __name__ == '__main__': r = sum_multiples_3_5(1000) print(r)
num=grt=1 def collatz(no): if no==1: return 1 else: if no%2==0: return 1+collatz(int(no/2)) else: return 1+collatz((3*no)+1) for i in range(2, 1000000, 1): a=collatz(i) if (a>grt): num=i grt=a if (i%1000==0): print(i) print(num)
num = grt = 1 def collatz(no): if no == 1: return 1 elif no % 2 == 0: return 1 + collatz(int(no / 2)) else: return 1 + collatz(3 * no + 1) for i in range(2, 1000000, 1): a = collatz(i) if a > grt: num = i grt = a if i % 1000 == 0: print(i) print(num)
""" Three in One: Describe how you could use a single array to implement three stacks. """ class Stack: def __init__(self, start, parent): self.start = start self.count = 0 self.parent = parent def push(self, value): return self.parent.push(self, value) def pop(self): return self.parent.pop(self) def peek(self): return self.parent.peek(self) def is_empty(self): return self.parent.is_empty(self) class MultiStack: CAPACITY = 10 def __init__(self): self._arr = [None] * self.CAPACITY self.s1 = Stack(0, self) self.s2 = Stack(self.CAPACITY // 3, self) self.s3 = Stack(self.s2.start * 2, self) def stacks(self): return self.s1, self.s2, self.s3 def is_empty(self, stack): return stack.count == 0 def peek(self, stack): if self.is_empty(stack): raise Exception("Empty Stack") i = self.i_within(self.stack_i(stack) - 1) return self._arr[i] def pop(self, stack): result = self.peek(stack) stack.count -= 1 i = self.stack_i(stack) self._arr[i] = None return result def i_within(self, i): return i % len(self._arr) def stack_i(self, stack): i = stack.start + stack.count return self.i_within(i) def collision(self, stack): i = self.stack_i(stack) if stack is self.s1 and i == self.s2.start: return self.s2 elif stack is self.s2 and i == self.s3.start: return self.s3 elif stack is self.s3 and i == self.s1.start: return self.s1 return None def shift(self, collider): i = self.stack_i(collider) if i >= collider.start: # Simple case, in one line, so we shift each value ahead by one # We don't want to loop till collider.start as that one will be shifted by the value before it for j in range(i, collider.start, -1): self._arr[j] = self._arr[j - 1] else: # We need to loop twice and then also handle the middle value # First we move all the values from i to 0 one step forward # Then we copy the value in last index to 0 # Then we move all the values from last index to start one step forward for j in range(i, 0, -1): self._arr[j] = self._arr[j - 1] self._arr[0] = self._arr[len(self._arr) - 1] for j in range(len(self._arr) - 1, collider.start, -1): self._arr[j] = self._arr[j - 1] collider.start += 1 def adjust(self, collider): # There is space between the collider and its next value if not (second_collider := self.collision(collider)): self.shift(collider) # There is at least space between in the second collider and first collider # So, we shift both and create space elif not self.collision(second_collider): self.shift(second_collider) self.shift(collider) # No space in the entire array else: return False return True def push(self, stack, value): # Check if there is a collision if collider := self.collision(stack): # If collision, can we adjust # If we cannot adjust, raise error, else adjust if not self.adjust(collider): raise Exception("No space left in underlying array") # push the new value if no error raised i = self.stack_i(stack) self._arr[i] = value stack.count += 1 if __name__ == "__main__": multi = MultiStack() s1, s2, s3 = multi.stacks() s1.push(1) s2.push(1) s3.push(1) print(multi._arr) s1.push(2) s2.push(3) print(multi._arr) s1.push(3) print(multi._arr) s1.push(4) print(multi._arr) s1.push(5) print(multi._arr) s1.pop() print(multi._arr) s1.pop() print(multi._arr) s3.push(2) print(multi._arr) s3.push(3) print(multi._arr) s3.push(4) print(multi._arr) s2.pop() print(multi._arr) s2.push(2) print(multi._arr) s2.push(3) print(multi._arr) s1.push(6)
""" Three in One: Describe how you could use a single array to implement three stacks. """ class Stack: def __init__(self, start, parent): self.start = start self.count = 0 self.parent = parent def push(self, value): return self.parent.push(self, value) def pop(self): return self.parent.pop(self) def peek(self): return self.parent.peek(self) def is_empty(self): return self.parent.is_empty(self) class Multistack: capacity = 10 def __init__(self): self._arr = [None] * self.CAPACITY self.s1 = stack(0, self) self.s2 = stack(self.CAPACITY // 3, self) self.s3 = stack(self.s2.start * 2, self) def stacks(self): return (self.s1, self.s2, self.s3) def is_empty(self, stack): return stack.count == 0 def peek(self, stack): if self.is_empty(stack): raise exception('Empty Stack') i = self.i_within(self.stack_i(stack) - 1) return self._arr[i] def pop(self, stack): result = self.peek(stack) stack.count -= 1 i = self.stack_i(stack) self._arr[i] = None return result def i_within(self, i): return i % len(self._arr) def stack_i(self, stack): i = stack.start + stack.count return self.i_within(i) def collision(self, stack): i = self.stack_i(stack) if stack is self.s1 and i == self.s2.start: return self.s2 elif stack is self.s2 and i == self.s3.start: return self.s3 elif stack is self.s3 and i == self.s1.start: return self.s1 return None def shift(self, collider): i = self.stack_i(collider) if i >= collider.start: for j in range(i, collider.start, -1): self._arr[j] = self._arr[j - 1] else: for j in range(i, 0, -1): self._arr[j] = self._arr[j - 1] self._arr[0] = self._arr[len(self._arr) - 1] for j in range(len(self._arr) - 1, collider.start, -1): self._arr[j] = self._arr[j - 1] collider.start += 1 def adjust(self, collider): if not (second_collider := self.collision(collider)): self.shift(collider) elif not self.collision(second_collider): self.shift(second_collider) self.shift(collider) else: return False return True def push(self, stack, value): if (collider := self.collision(stack)): if not self.adjust(collider): raise exception('No space left in underlying array') i = self.stack_i(stack) self._arr[i] = value stack.count += 1 if __name__ == '__main__': multi = multi_stack() (s1, s2, s3) = multi.stacks() s1.push(1) s2.push(1) s3.push(1) print(multi._arr) s1.push(2) s2.push(3) print(multi._arr) s1.push(3) print(multi._arr) s1.push(4) print(multi._arr) s1.push(5) print(multi._arr) s1.pop() print(multi._arr) s1.pop() print(multi._arr) s3.push(2) print(multi._arr) s3.push(3) print(multi._arr) s3.push(4) print(multi._arr) s2.pop() print(multi._arr) s2.push(2) print(multi._arr) s2.push(3) print(multi._arr) s1.push(6)
""" The MIT License (MIT) Copyright (c) Serenity Software, LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ # pylint: disable=too-many-arguments class ParseResult(object): """Represents a single result from the parsing process""" type = "Unknown" subtype = "Unknown" confidence = 0 result_value = None data = {} def __init__( self, p_type="Unknown", subtype="Unknown", confidence=0, value=None, additional_data=None ): """ Sets up the parse result object with result data :param p_type: Parse result type :type p_type: str :param subtype: Parse result subtype :type subtype: str :param confidence: How confidence we are in this result, 1-100 :type confidence: int :param value: representation of the parsed data :type value: mixed :param additional_data: any additional data a parser wants to provide :type additional_data: mixed """ if additional_data is None: additional_data = {} self.type = p_type self.subtype = subtype self.confidence = confidence self.result_value = value self.data = additional_data
""" The MIT License (MIT) Copyright (c) Serenity Software, LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ class Parseresult(object): """Represents a single result from the parsing process""" type = 'Unknown' subtype = 'Unknown' confidence = 0 result_value = None data = {} def __init__(self, p_type='Unknown', subtype='Unknown', confidence=0, value=None, additional_data=None): """ Sets up the parse result object with result data :param p_type: Parse result type :type p_type: str :param subtype: Parse result subtype :type subtype: str :param confidence: How confidence we are in this result, 1-100 :type confidence: int :param value: representation of the parsed data :type value: mixed :param additional_data: any additional data a parser wants to provide :type additional_data: mixed """ if additional_data is None: additional_data = {} self.type = p_type self.subtype = subtype self.confidence = confidence self.result_value = value self.data = additional_data
""" Types Base ========== Provides the base types on top of which user visible types will be built. """ # pylint: disable=too-few-public-methods class CFFICDataWrapper(object): """ Base class for exposing Python types and interfaces to pywincffi users: * Wraps a CFFI cdata object in self._cdata. * Delegates attribute getting/setting to self._cdata, supporting structs. * Delegates item getting/setting to self._cdata, supporting arrays. Attribute access is not delegated to the wrapped object if the class itself contains such an attribute and that attribute is a descriptor; this is in place to support @property in sub-classes. :param str cdecl: C type specification as used in ff.new(cdecl) :param cffi.api.FFI ffi: FFI instance used to create wrapped cdata object. """ def __init__(self, cdecl, ffi): self._cdata = ffi.new(cdecl) def __getattr__(self, name): return getattr(self._cdata, name) def __setattr__(self, name, value): # avoid self-recursion setting own attribute: use parent's __setattr__ if name == "_cdata": super(CFFICDataWrapper, self).__setattr__(name, value) return # support descriptor attributes in child classes if hasattr(self.__class__, name): try: # getattr on class, otherwise descriptor's __get__ is called attr = getattr(self.__class__, name) # use descriptor protocol to set attr.__set__(self, value) return except AttributeError: # attr.__set__ raised this: attr is not a descriptor pass # fallback case: delegate to self._cdata setattr(self._cdata, name, value) def __getitem__(self, key): return self._cdata.__getitem__(key) def __setitem__(self, key, value): return self._cdata.__setitem__(key, value)
""" Types Base ========== Provides the base types on top of which user visible types will be built. """ class Cfficdatawrapper(object): """ Base class for exposing Python types and interfaces to pywincffi users: * Wraps a CFFI cdata object in self._cdata. * Delegates attribute getting/setting to self._cdata, supporting structs. * Delegates item getting/setting to self._cdata, supporting arrays. Attribute access is not delegated to the wrapped object if the class itself contains such an attribute and that attribute is a descriptor; this is in place to support @property in sub-classes. :param str cdecl: C type specification as used in ff.new(cdecl) :param cffi.api.FFI ffi: FFI instance used to create wrapped cdata object. """ def __init__(self, cdecl, ffi): self._cdata = ffi.new(cdecl) def __getattr__(self, name): return getattr(self._cdata, name) def __setattr__(self, name, value): if name == '_cdata': super(CFFICDataWrapper, self).__setattr__(name, value) return if hasattr(self.__class__, name): try: attr = getattr(self.__class__, name) attr.__set__(self, value) return except AttributeError: pass setattr(self._cdata, name, value) def __getitem__(self, key): return self._cdata.__getitem__(key) def __setitem__(self, key, value): return self._cdata.__setitem__(key, value)
# Utilities related to colors. # A standard color-blind palette, with equalized luminance, adding another a blue. colors = [ ((165, 54, 0, 255), ["orange", "brown"]), ((179, 45, 181, 255), ["pink"]), ((0, 114, 178, 255), ["blue", "lightBlue", "blue1"]), ((144, 136, 39, 255), ["yellow"]), ((52, 142, 83, 255), ["green"]), ((5, 60, 255, 255), ["darkBlue", "blue2"]) ] colors = [((c[0][0]/255.0, c[0][1]/255.0, c[0][2]/255.0, c[0][3]/255.0), c[1]) for c in colors] def getColor(colorId, colors): if isinstance(colorId, int): # The colorId is an index into the array of colors. if colorId < 0 or colorId >= len(colors): print("Error: color index {} must be between 0 and {}".format(colorId, len(colors) - 1)) return None return colors[colorId][0] elif isinstance(colorId, str): if colorId.startswith("#"): # The colorId is a CSS color, a string of the format "#RRGGBB" where # RR, GG and BB are hex numbers for the red, green and blue channels. # In general, it is recommended to stick with the colors in the palette, # but in some cases, other colors are useful (e.g., match how NeuTu uses # gray for post-synaptic bodies). return tuple([int(colorId[i:i+2], 16) / 255 for i in (1, 3, 5)]) else: # The colorId is a color name, so check for a match with the names in # the palette. Do a little processing so there is a successful match for # "light-blue", "lightblue", "LightBlue", etc. id = colorId.replace("-","").lower() for color in colors: if id in [c.lower() for c in color[1]]: return color[0] print("Error: unknown color name '{}'".format(colorId)) return None else: print("Error: invalid color identifier '{}'".format(colorId)) return None
colors = [((165, 54, 0, 255), ['orange', 'brown']), ((179, 45, 181, 255), ['pink']), ((0, 114, 178, 255), ['blue', 'lightBlue', 'blue1']), ((144, 136, 39, 255), ['yellow']), ((52, 142, 83, 255), ['green']), ((5, 60, 255, 255), ['darkBlue', 'blue2'])] colors = [((c[0][0] / 255.0, c[0][1] / 255.0, c[0][2] / 255.0, c[0][3] / 255.0), c[1]) for c in colors] def get_color(colorId, colors): if isinstance(colorId, int): if colorId < 0 or colorId >= len(colors): print('Error: color index {} must be between 0 and {}'.format(colorId, len(colors) - 1)) return None return colors[colorId][0] elif isinstance(colorId, str): if colorId.startswith('#'): return tuple([int(colorId[i:i + 2], 16) / 255 for i in (1, 3, 5)]) else: id = colorId.replace('-', '').lower() for color in colors: if id in [c.lower() for c in color[1]]: return color[0] print("Error: unknown color name '{}'".format(colorId)) return None else: print("Error: invalid color identifier '{}'".format(colorId)) return None
class Foo: def say(self): return 'bar'
class Foo: def say(self): return 'bar'
######################### # 162. Find Peak Element ######################### class Solution: def findPeakElement(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums)==1: peak = 0 return peak else: if nums[0]>nums[1]: peak = 0 return peak if nums[-1]>nums[-2]: peak = len(nums)-1 return peak for i in range (1,len(nums)-1): if nums[i]>nums[i-1] and nums[i]>nums[i+1]: peak = i return peak s = Solution() print(s.findPeakElement([1,2,1]))
class Solution: def find_peak_element(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 1: peak = 0 return peak else: if nums[0] > nums[1]: peak = 0 return peak if nums[-1] > nums[-2]: peak = len(nums) - 1 return peak for i in range(1, len(nums) - 1): if nums[i] > nums[i - 1] and nums[i] > nums[i + 1]: peak = i return peak s = solution() print(s.findPeakElement([1, 2, 1]))
#works reguardless the size of the strings def compare(_firstString, _secondString): _list = list(set(_firstString.lower()) - set(_secondString.lower())) print("The Non-Common Charecters are: ") for i in _list: print(i) # works only for equal length strings def COMPARE(_firstString, _secondString): print("The Non-Common Charecters are: ") if (len(_firstString) == len(_secondString)): for i in len(_firstString): if (_firstString[i] != _secondString[0]): print(_firstString[i]) if __name__ == "__main__": print("Enter Two Strings: ") first = input() second = input() compare(first, second)
def compare(_firstString, _secondString): _list = list(set(_firstString.lower()) - set(_secondString.lower())) print('The Non-Common Charecters are: ') for i in _list: print(i) def compare(_firstString, _secondString): print('The Non-Common Charecters are: ') if len(_firstString) == len(_secondString): for i in len(_firstString): if _firstString[i] != _secondString[0]: print(_firstString[i]) if __name__ == '__main__': print('Enter Two Strings: ') first = input() second = input() compare(first, second)
class Student(object): def __init__(self, name, score): self.__name = name self._score = score def print_score(self): print('%s: %s' % (self.__name, self.__score)) bart = Student("Zero", 32) print(bart)
class Student(object): def __init__(self, name, score): self.__name = name self._score = score def print_score(self): print('%s: %s' % (self.__name, self.__score)) bart = student('Zero', 32) print(bart)
def rearrange_sorted_list_in_max_into_set(lst): result = [] for i in range(len(lst)//2): result.append((lst[i], lst[-i - 1])) if len(lst) % 2 == 1: result.append(lst[len(lst)//2]) return result
def rearrange_sorted_list_in_max_into_set(lst): result = [] for i in range(len(lst) // 2): result.append((lst[i], lst[-i - 1])) if len(lst) % 2 == 1: result.append(lst[len(lst) // 2]) return result
# Students dictionary students = {"Ahmed" : 87, "Waleed" : 69, "Hesham" : 92} # Khaled grades kh_grades = {"Math": 86, "English": 74} #1 Add Khaled and his grades to students students[________] = _________ # Print out students print(students) #2 Print out Khaled grade in English print(_____________________________)
students = {'Ahmed': 87, 'Waleed': 69, 'Hesham': 92} kh_grades = {'Math': 86, 'English': 74} students[________] = _________ print(students) print(_____________________________)
load("@com_github_pybind_bazel//:build_defs.bzl", "pybind_extension") def pybind_py_library(name, cc_so_name = None, copts = [], features = [], tags = [], cc_srcs = [], cc_deps = [], py_library_rule = native.py_library, py_srcs = [], py_deps = [], py_imports = [], cc_linkopts = [], visibility = None, testonly = None, **kwargs): if not cc_so_name: if name.endswith("_py"): cc_so_name = name[:-3] else: cc_so_name = name pybind_extension( name = cc_so_name, copts = copts, features = features, tags = tags, deps = cc_deps, srcs = cc_srcs, cc_linkopts = cc_linkopts, visibility = visibility, testonly = testonly, **kwargs, ) py_library_rule( name = name, data = [cc_so_name + '.so'], srcs = py_srcs, deps = py_deps, imports = py_imports, testonly = testonly, visibility = visibility, )
load('@com_github_pybind_bazel//:build_defs.bzl', 'pybind_extension') def pybind_py_library(name, cc_so_name=None, copts=[], features=[], tags=[], cc_srcs=[], cc_deps=[], py_library_rule=native.py_library, py_srcs=[], py_deps=[], py_imports=[], cc_linkopts=[], visibility=None, testonly=None, **kwargs): if not cc_so_name: if name.endswith('_py'): cc_so_name = name[:-3] else: cc_so_name = name pybind_extension(name=cc_so_name, copts=copts, features=features, tags=tags, deps=cc_deps, srcs=cc_srcs, cc_linkopts=cc_linkopts, visibility=visibility, testonly=testonly, **kwargs) py_library_rule(name=name, data=[cc_so_name + '.so'], srcs=py_srcs, deps=py_deps, imports=py_imports, testonly=testonly, visibility=visibility)
n = 10000 df = pd.DataFrame({'x': np.random.randn(n), 'y': np.random.randn(n)}) ax = df.plot.hexbin(x='x', y='y', gridsize=20)
n = 10000 df = pd.DataFrame({'x': np.random.randn(n), 'y': np.random.randn(n)}) ax = df.plot.hexbin(x='x', y='y', gridsize=20)
def do_stuff(num): """Adds 5 to passed int""" try: return int(num) + 5 except ValueError as err: return err
def do_stuff(num): """Adds 5 to passed int""" try: return int(num) + 5 except ValueError as err: return err
# # Py Word Permutations # # Author: Afaan Bilal # URL: https://afaan.ml # # Display all possible permutaions for a set of characters. # # (c) 2016 Afaan Bilal # Released under the MIT License # def base_convert(number, fromBase, toBase): ''' Convert numbers to and from decimal ''' i = 0 result = 0 number = int(number) while number > 0: result += (number % toBase) * (fromBase ** i) i += 1 number //= toBase return str(result) def binSearch(arr, s, ubound): ''' Binary Search ''' b = 0 t = ubound mid = (t + b) // 2 if len(arr) <= mid: return False while b <= t: mid = (t + b) // 2 if len(arr) <= mid: return False if arr[mid] < s: b = mid + 1 elif arr[mid] > s: t = mid - 1 else: return True else: return False print("Py Word Permutations") chars = input("Enter characters: ") lcount = len(chars) keys = ''.zfill(lcount) chars = sorted(chars) # find number of unique characters uchars = [] for c in chars[:]: if c in uchars: continue uchars.append(c) ucount = len(uchars) # calculate total number of permutations wcount = lcount ** lcount # calculate number of unique permutaions real_wcount = ucount ** lcount print("Total Characters : {}".format(lcount)) print("Total Permutations: {}".format(wcount)) print("Unique Permutations: {}".format(real_wcount)) # permute the characters words = [] for i in range(wcount): cur_word = [] for j in range(lcount): key = int(keys[j]) cur_word.append(str(chars[int(key)])) c_word = ''.join(cur_word) # calculate the next key string keys = base_convert(keys, lcount, 10) keys_i = int(keys) keys_i += 1 keys = str(keys_i) keys = base_convert(keys, 10, lcount) # pad the key string to have indexes for all places keys = keys.zfill(lcount) # add only unique permutations if not binSearch(words, c_word, len(words)): words.append(c_word) print("WORDS:") for w in words: print(w, end=' ')
def base_convert(number, fromBase, toBase): """ Convert numbers to and from decimal """ i = 0 result = 0 number = int(number) while number > 0: result += number % toBase * fromBase ** i i += 1 number //= toBase return str(result) def bin_search(arr, s, ubound): """ Binary Search """ b = 0 t = ubound mid = (t + b) // 2 if len(arr) <= mid: return False while b <= t: mid = (t + b) // 2 if len(arr) <= mid: return False if arr[mid] < s: b = mid + 1 elif arr[mid] > s: t = mid - 1 else: return True else: return False print('Py Word Permutations') chars = input('Enter characters: ') lcount = len(chars) keys = ''.zfill(lcount) chars = sorted(chars) uchars = [] for c in chars[:]: if c in uchars: continue uchars.append(c) ucount = len(uchars) wcount = lcount ** lcount real_wcount = ucount ** lcount print('Total Characters : {}'.format(lcount)) print('Total Permutations: {}'.format(wcount)) print('Unique Permutations: {}'.format(real_wcount)) words = [] for i in range(wcount): cur_word = [] for j in range(lcount): key = int(keys[j]) cur_word.append(str(chars[int(key)])) c_word = ''.join(cur_word) keys = base_convert(keys, lcount, 10) keys_i = int(keys) keys_i += 1 keys = str(keys_i) keys = base_convert(keys, 10, lcount) keys = keys.zfill(lcount) if not bin_search(words, c_word, len(words)): words.append(c_word) print('WORDS:') for w in words: print(w, end=' ')
temperature = 35 if temperature == 30: print("It's a hot day.") else: print("It's not a hot day.") # Exercise name = input("Enter name: ") if len(name) < 3: print("Name must be at least 3 characters.") elif len(name) > 20: print("Name must be a maximum of 20 characters.") else: print("Name looks good!")
temperature = 35 if temperature == 30: print("It's a hot day.") else: print("It's not a hot day.") name = input('Enter name: ') if len(name) < 3: print('Name must be at least 3 characters.') elif len(name) > 20: print('Name must be a maximum of 20 characters.') else: print('Name looks good!')
#!/usr/bin/python3 # @JUDGE_ID: mobluse 11044 Python 3 "Closed-form expression" t = int(input()) for i in range(t): n, m = [int(x) for x in input().split()] print((n//3)*(m//3))
t = int(input()) for i in range(t): (n, m) = [int(x) for x in input().split()] print(n // 3 * (m // 3))
print("This file tests Elif.") a=99 if a<=0: print("Plese enter a correct number") if a<=60: print('E') elif a<=70: print("D") elif a<=80: print("C") elif a<=90: print("B") elif a<=95: print("A") elif a<=99: print("A+") else: print("A++")
print('This file tests Elif.') a = 99 if a <= 0: print('Plese enter a correct number') if a <= 60: print('E') elif a <= 70: print('D') elif a <= 80: print('C') elif a <= 90: print('B') elif a <= 95: print('A') elif a <= 99: print('A+') else: print('A++')
#!/usr/bin/env python3 # The MIT License # Copyright (c) 2016 Estonian Information System Authority (RIA), Population Register Centre (VRK) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # This module contains test cases that are part of the integration test of the # operational monitoring system. For running the test cases, import them in the # main wrapper. # List the test cases that must be available to the wrapper. # It must be possible to run the test cases in an arbitrary order. __all__ = [ "test_simple_store_and_query", "test_soap_fault", "test_get_metadata", "test_metaservices", "test_attachments", "test_health_data", "test_limited_operational_data_response", "test_service_cluster", "test_outputspec", "test_time_interval", "test_client_filter", "test_zero_buffer_size", ]
__all__ = ['test_simple_store_and_query', 'test_soap_fault', 'test_get_metadata', 'test_metaservices', 'test_attachments', 'test_health_data', 'test_limited_operational_data_response', 'test_service_cluster', 'test_outputspec', 'test_time_interval', 'test_client_filter', 'test_zero_buffer_size']
#!/usr/bin/env python def fac(n): '''compute the factorial of given number''' assert type(n) == int, 'argument must be integer' assert n >= 0, 'argument must be positive' if n > 1: return n*fac(n - 1) else: return 1 if __name__ == '__main__': for i in range(5): print('{0}! = {1}'.format(i, fac(i))) for i in [-2, 0.3, 3.0]: try: print('{0}! = {1}'.format(i, fac(i))) except AssertionError as error: print('{0}! failed: "{1}"'.format(i, error))
def fac(n): """compute the factorial of given number""" assert type(n) == int, 'argument must be integer' assert n >= 0, 'argument must be positive' if n > 1: return n * fac(n - 1) else: return 1 if __name__ == '__main__': for i in range(5): print('{0}! = {1}'.format(i, fac(i))) for i in [-2, 0.3, 3.0]: try: print('{0}! = {1}'.format(i, fac(i))) except AssertionError as error: print('{0}! failed: "{1}"'.format(i, error))
bjobTemplate="""#!/bin/tcsh cd $CMSSW_BASE/src eval `scramv1 runtime -csh` source /afs/cern.ch/cms/caf/setup.csh cd - xrdcp {inputFile} reco.root cmsRun $CMSSW_BASE/src/Alignment/APEEstimation/test/cfgTemplate/apeEstimator_cfg.py {inputCommands} rm -- "$0" """ submitJobTemplate=""" bsub -J {jobName} -e {errorFile} -o {outputFile} -q cmscaf1nd -R "rusage[pool=3000]" tcsh {jobFile} """ checkJobTemplate="bjobs -noheader -a -J {jobName}" killJobTemplate="bkill -J {jobName}" summaryTemplate="cmsRun $CMSSW_BASE/src/Alignment/APEEstimation/test/cfgTemplate/apeEstimatorSummary_cfg.py {inputCommands}" mergeTemplate="hadd {path}/allData.root {inputFiles}" localSettingTemplate="cmsRun $CMSSW_BASE/src/Alignment/APEEstimation/test/cfgTemplate/apeLocalSetting_cfg.py {inputCommands}"
bjob_template = '#!/bin/tcsh\n\ncd $CMSSW_BASE/src\n\neval `scramv1 runtime -csh`\n\nsource /afs/cern.ch/cms/caf/setup.csh\ncd -\n\nxrdcp {inputFile} reco.root\n\ncmsRun $CMSSW_BASE/src/Alignment/APEEstimation/test/cfgTemplate/apeEstimator_cfg.py {inputCommands}\n\nrm -- "$0"\n' submit_job_template = '\nbsub -J {jobName} -e {errorFile} -o {outputFile} -q cmscaf1nd -R "rusage[pool=3000]" tcsh {jobFile}\n' check_job_template = 'bjobs -noheader -a -J {jobName}' kill_job_template = 'bkill -J {jobName}' summary_template = 'cmsRun $CMSSW_BASE/src/Alignment/APEEstimation/test/cfgTemplate/apeEstimatorSummary_cfg.py {inputCommands}' merge_template = 'hadd {path}/allData.root {inputFiles}' local_setting_template = 'cmsRun $CMSSW_BASE/src/Alignment/APEEstimation/test/cfgTemplate/apeLocalSetting_cfg.py {inputCommands}'
# Demonstrate how to use set comprehensions def main(): # define a list of temperature data points ctemps = [5, 10, 12, 14, 10, 23, 41, 30, 12, 24, 12, 18, 29] # TODO: build a set of unique Fahrenheit temperatures # TODO: build a set from an input source if __name__ == "__main__": main()
def main(): ctemps = [5, 10, 12, 14, 10, 23, 41, 30, 12, 24, 12, 18, 29] if __name__ == '__main__': main()
been_called = False def example2(): global been_called been_called = True # example2() # print(been_called) def sort_words_by_length(): fin = open('words.txt') lt = [] for line in fin: line = line.strip() lt.append((len(line), line)) lt.sort(reverse=True) res = [] for _, word in lt: res.append(word) return res x = sort_words_by_length() print(x[0])
been_called = False def example2(): global been_called been_called = True def sort_words_by_length(): fin = open('words.txt') lt = [] for line in fin: line = line.strip() lt.append((len(line), line)) lt.sort(reverse=True) res = [] for (_, word) in lt: res.append(word) return res x = sort_words_by_length() print(x[0])
#!/usr/bin/env python # Copyright (c) 2005-2009 Jaroslav Gresula # # Distributed under the MIT license (See accompanying file # LICENSE.txt or copy at http://jagpdf.org/LICENSE.txt) # # names generator # http://www.neoprogrammics.com/randomisers/random_names_generator/ names_str="""Steven Eden Madelyn E. Vinci Corliss S. Widener Terresa Dumond Lean C. Willison Man King Bettina M. Haslam Angele V. Heidelberg James E. Satter Maryjane Kunkel Chara Y. Cyr Suzanne S. Perrin Emilia V. Noda Aliza R. Charpentier Neva Guida Mariette L. Mcvay Cristine Heid Daisy Weidman Tilda W. Trosclair Jaunita Mathes Janey Tidwell Verline Migliore Etta K. Staley Yvone Pinedo Alexander Gerner Phung X. Vandenbosch Karlene Sandusky Gertrudis H. Newell Emelia Mcninch Khadijah M. Doyal Hollie Donahoe Debera M. Schley Afton T. Blind Fatimah K. Masson Narcisa K. Pollitt Leida C. Portillo Adena Carranza Angeline T. Honore Dominga H. Clyburn Tinisha L. Krol Alene A. Antonelli Jodee S. Yeomans Eveline G. Hedley Sherika Mcgeorge Wei L. Mclaren Aracelis M. Beets Mina Nicholes Stephaine D. Fishback Kathie E. Otten Arla Cannon Janette Bolling Nichelle G. Cronan Lucina T. Severe Nancy M. Moorman Mandie Macdougall Roxana Bancroft Livia Wahl Toshiko S. Fujiwara Delinda J. Cascio Margit L. Shore China Mccurdy Cris Wolfgang Eartha A. Dorrance Thu Florence Nguyet J. Marchetti Julianne D. Shadwick Margherita R. Nimmons Valorie Benevides Scott C. Carolina Ghislaine Johannes Many R. Bosserman Jeanice S. Arevalo Lashaun A. Pritts Leon M. Limon Perry Nicklas Harmony K. Levenson Wendy Crosland Luisa P. Lombardi Roxie Quesenberry Stephen M. Stell Cristie A. Gries Luanne P. Foshee Jen N. Okelley Lily P. Merryman Wynell L. Hamrick Harriette Greenhill Evalyn Welter Indira K. Goguen Epifania Grabowski Lou Espino Nickie P. Guinn Farrah M. Henthorn Mathilde Fraley Ling P. Duren Fern E. Cloninger Tony Goudeau Jana Luker Hue M. Bass Kit Specht Carmon Burgoon""" names=names_str.split('\n')
names_str = 'Steven Eden\nMadelyn E. Vinci\nCorliss S. Widener\nTerresa Dumond\nLean C. Willison\nMan King\nBettina M. Haslam\nAngele V. Heidelberg\nJames E. Satter\nMaryjane Kunkel\nChara Y. Cyr\nSuzanne S. Perrin\nEmilia V. Noda\nAliza R. Charpentier\nNeva Guida\nMariette L. Mcvay\nCristine Heid\nDaisy Weidman\nTilda W. Trosclair\nJaunita Mathes\nJaney Tidwell\nVerline Migliore\nEtta K. Staley\nYvone Pinedo\nAlexander Gerner\nPhung X. Vandenbosch\nKarlene Sandusky\nGertrudis H. Newell\nEmelia Mcninch\nKhadijah M. Doyal\nHollie Donahoe\nDebera M. Schley\nAfton T. Blind\nFatimah K. Masson\nNarcisa K. Pollitt\nLeida C. Portillo\nAdena Carranza\nAngeline T. Honore\nDominga H. Clyburn\nTinisha L. Krol\nAlene A. Antonelli\nJodee S. Yeomans\nEveline G. Hedley\nSherika Mcgeorge\nWei L. Mclaren\nAracelis M. Beets\nMina Nicholes\nStephaine D. Fishback\nKathie E. Otten\nArla Cannon\nJanette Bolling\nNichelle G. Cronan\nLucina T. Severe\nNancy M. Moorman\nMandie Macdougall\nRoxana Bancroft\nLivia Wahl\nToshiko S. Fujiwara\nDelinda J. Cascio\nMargit L. Shore\nChina Mccurdy\nCris Wolfgang\nEartha A. Dorrance\nThu Florence\nNguyet J. Marchetti\nJulianne D. Shadwick\nMargherita R. Nimmons\nValorie Benevides\nScott C. Carolina\nGhislaine Johannes\nMany R. Bosserman\nJeanice S. Arevalo\nLashaun A. Pritts\nLeon M. Limon\nPerry Nicklas\nHarmony K. Levenson\nWendy Crosland\nLuisa P. Lombardi\nRoxie Quesenberry\nStephen M. Stell\nCristie A. Gries\nLuanne P. Foshee\nJen N. Okelley\nLily P. Merryman\nWynell L. Hamrick\nHarriette Greenhill\nEvalyn Welter\nIndira K. Goguen\nEpifania Grabowski\nLou Espino\nNickie P. Guinn\nFarrah M. Henthorn\nMathilde Fraley\nLing P. Duren\nFern E. Cloninger\nTony Goudeau\nJana Luker\nHue M. Bass\nKit Specht\nCarmon Burgoon' names = names_str.split('\n')
# Using the seive of Eratosthenes https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes def sum_primes(n): sum = 0 sieve = [True] * n for i in range(2, n): if sieve[i]: sum += i for j in range(i**2, n, i): sieve[j] = False return sum if __name__ == "__main__": print(sum_primes(2000000))
def sum_primes(n): sum = 0 sieve = [True] * n for i in range(2, n): if sieve[i]: sum += i for j in range(i ** 2, n, i): sieve[j] = False return sum if __name__ == '__main__': print(sum_primes(2000000))
ans=0 x1,y1,r1=map(int,input().split()) x2,y2,r2=map(int,input().split()) x3,y3,r3=map(int,input().split()) for i in range(23001): for j in range(23001): if (x1-i/230+0.0022)**2+(y1-j/230+0.0022)**2<=r1*r1: ans+=1 elif (x2-i/230+0.0022)**2+(y2-j/230+0.0022)**2<=r2*r2: ans+=1 elif (x3-i/230+0.0022)**2+(y3-j/230+0.0022)**2<=r3*r3: ans+=1 print(ans/52900)
ans = 0 (x1, y1, r1) = map(int, input().split()) (x2, y2, r2) = map(int, input().split()) (x3, y3, r3) = map(int, input().split()) for i in range(23001): for j in range(23001): if (x1 - i / 230 + 0.0022) ** 2 + (y1 - j / 230 + 0.0022) ** 2 <= r1 * r1: ans += 1 elif (x2 - i / 230 + 0.0022) ** 2 + (y2 - j / 230 + 0.0022) ** 2 <= r2 * r2: ans += 1 elif (x3 - i / 230 + 0.0022) ** 2 + (y3 - j / 230 + 0.0022) ** 2 <= r3 * r3: ans += 1 print(ans / 52900)
num = int(input("enter any Number")) rev = 0 while num > 0: Rem = num % 10 num = num // 10 rev = rev * 10 + Rem print("The Reverse of the number", rev) ################## # could also simply do this another way num = input() print(int(num[::-1]))
num = int(input('enter any Number')) rev = 0 while num > 0: rem = num % 10 num = num // 10 rev = rev * 10 + Rem print('The Reverse of the number', rev) num = input() print(int(num[::-1]))
# Pyrogram - Telegram MTProto API Client Library for Python # Copyright (C) 2017-2021 Dan <https://github.com/delivrance> # # This file is part of Pyrogram. # # Pyrogram is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Pyrogram is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Pyrogram. If not, see <http://www.gnu.org/licenses/>. count = 425 exceptions = { 406: { "_": "NotAcceptable", "AUTH_KEY_DUPLICATED": "AuthKeyDuplicated", "FILEREF_UPGRADE_NEEDED": "FilerefUpgradeNeeded", "FRESH_CHANGE_ADMINS_FORBIDDEN": "FreshChangeAdminsForbidden", "FRESH_CHANGE_PHONE_FORBIDDEN": "FreshChangePhoneForbidden", "FRESH_RESET_AUTHORISATION_FORBIDDEN": "FreshResetAuthorisationForbidden", "PHONE_NUMBER_INVALID": "PhoneNumberInvalid", "PHONE_PASSWORD_FLOOD": "PhonePasswordFlood", "STICKERSET_INVALID": "StickersetInvalid", "STICKERSET_OWNER_ANONYMOUS": "StickersetOwnerAnonymous", "USERPIC_UPLOAD_REQUIRED": "UserpicUploadRequired", "USER_RESTRICTED": "UserRestricted", }, 500: { "_": "InternalServerError", "API_CALL_ERROR": "ApiCallError", "AUTH_RESTART": "AuthRestart", "CALL_OCCUPY_FAILED": "CallOccupyFailed", "CHAT_ID_GENERATE_FAILED": "ChatIdGenerateFailed", "CHAT_OCCUPY_LOC_FAILED": "ChatOccupyLocFailed", "CHAT_OCCUPY_USERNAME_FAILED": "ChatOccupyUsernameFailed", "CHP_CALL_FAIL": "ChpCallFail", "ENCRYPTION_OCCUPY_ADMIN_FAILED": "EncryptionOccupyAdminFailed", "ENCRYPTION_OCCUPY_FAILED": "EncryptionOccupyFailed", "FOLDER_DEAC_AUTOFIX_ALL": "FolderDeacAutofixAll", "GROUPED_ID_OCCUPY_FAILED": "GroupedIdOccupyFailed", "HISTORY_GET_FAILED": "HistoryGetFailed", "IMAGE_ENGINE_DOWN": "ImageEngineDown", "INTERDC_X_CALL_ERROR": "InterdcCallError", "INTERDC_X_CALL_RICH_ERROR": "InterdcCallRichError", "MEMBER_FETCH_FAILED": "MemberFetchFailed", "MEMBER_NO_LOCATION": "MemberNoLocation", "MEMBER_OCCUPY_PRIMARY_LOC_FAILED": "MemberOccupyPrimaryLocFailed", "MEMBER_OCCUPY_USERNAME_FAILED": "MemberOccupyUsernameFailed", "MSGID_DECREASE_RETRY": "MsgidDecreaseRetry", "MSG_RANGE_UNSYNC": "MsgRangeUnsync", "MT_SEND_QUEUE_TOO_LONG": "MtSendQueueTooLong", "NEED_CHAT_INVALID": "NeedChatInvalid", "NEED_MEMBER_INVALID": "NeedMemberInvalid", "PARTICIPANT_CALL_FAILED": "ParticipantCallFailed", "PERSISTENT_TIMESTAMP_OUTDATED": "PersistentTimestampOutdated", "POSTPONED_TIMEOUT": "PostponedTimeout", "PTS_CHANGE_EMPTY": "PtsChangeEmpty", "RANDOM_ID_DUPLICATE": "RandomIdDuplicate", "REG_ID_GENERATE_FAILED": "RegIdGenerateFailed", "RPC_CALL_FAIL": "RpcCallFail", "RPC_CONNECT_FAILED": "RpcConnectFailed", "RPC_MCGET_FAIL": "RpcMcgetFail", "SIGN_IN_FAILED": "SignInFailed", "STORAGE_CHECK_FAILED": "StorageCheckFailed", "STORE_INVALID_SCALAR_TYPE": "StoreInvalidScalarType", "UNKNOWN_METHOD": "UnknownMethod", "UPLOAD_NO_VOLUME": "UploadNoVolume", "VOLUME_LOC_NOT_FOUND": "VolumeLocNotFound", "WORKER_BUSY_TOO_LONG_RETRY": "WorkerBusyTooLongRetry", "WP_ID_GENERATE_FAILED": "WpIdGenerateFailed", }, 400: { "_": "BadRequest", "ABOUT_TOO_LONG": "AboutTooLong", "ACCESS_TOKEN_EXPIRED": "AccessTokenExpired", "ACCESS_TOKEN_INVALID": "AccessTokenInvalid", "ADMINS_TOO_MUCH": "AdminsTooMuch", "ADMIN_RANK_EMOJI_NOT_ALLOWED": "AdminRankEmojiNotAllowed", "ADMIN_RANK_INVALID": "AdminRankInvalid", "ALBUM_PHOTOS_TOO_MANY": "AlbumPhotosTooMany", "API_ID_INVALID": "ApiIdInvalid", "API_ID_PUBLISHED_FLOOD": "ApiIdPublishedFlood", "ARTICLE_TITLE_EMPTY": "ArticleTitleEmpty", "AUDIO_TITLE_EMPTY": "AudioTitleEmpty", "AUTH_BYTES_INVALID": "AuthBytesInvalid", "AUTH_TOKEN_ALREADY_ACCEPTED": "AuthTokenAlreadyAccepted", "AUTH_TOKEN_EXPIRED": "AuthTokenExpired", "AUTH_TOKEN_INVALID": "AuthTokenInvalid", "AUTOARCHIVE_NOT_AVAILABLE": "AutoarchiveNotAvailable", "BANK_CARD_NUMBER_INVALID": "BankCardNumberInvalid", "BANNED_RIGHTS_INVALID": "BannedRightsInvalid", "BOTS_TOO_MUCH": "BotsTooMuch", "BOT_CHANNELS_NA": "BotChannelsNa", "BOT_COMMAND_DESCRIPTION_INVALID": "BotCommandDescriptionInvalid", "BOT_DOMAIN_INVALID": "BotDomainInvalid", "BOT_GAMES_DISABLED": "BotGamesDisabled", "BOT_GROUPS_BLOCKED": "BotGroupsBlocked", "BOT_INLINE_DISABLED": "BotInlineDisabled", "BOT_INVALID": "BotInvalid", "BOT_METHOD_INVALID": "BotMethodInvalid", "BOT_MISSING": "BotMissing", "BOT_PAYMENTS_DISABLED": "BotPaymentsDisabled", "BOT_POLLS_DISABLED": "BotPollsDisabled", "BOT_RESPONSE_TIMEOUT": "BotResponseTimeout", "BOT_SCORE_NOT_MODIFIED": "BotScoreNotModified", "BROADCAST_ID_INVALID": "BroadcastIdInvalid", "BROADCAST_PUBLIC_VOTERS_FORBIDDEN": "BroadcastPublicVotersForbidden", "BROADCAST_REQUIRED": "BroadcastRequired", "BUTTON_DATA_INVALID": "ButtonDataInvalid", "BUTTON_TYPE_INVALID": "ButtonTypeInvalid", "BUTTON_URL_INVALID": "ButtonUrlInvalid", "CALL_ALREADY_ACCEPTED": "CallAlreadyAccepted", "CALL_ALREADY_DECLINED": "CallAlreadyDeclined", "CALL_PEER_INVALID": "CallPeerInvalid", "CALL_PROTOCOL_FLAGS_INVALID": "CallProtocolFlagsInvalid", "CDN_METHOD_INVALID": "CdnMethodInvalid", "CHANNELS_ADMIN_PUBLIC_TOO_MUCH": "ChannelsAdminPublicTooMuch", "CHANNELS_TOO_MUCH": "ChannelsTooMuch", "CHANNEL_BANNED": "ChannelBanned", "CHANNEL_INVALID": "ChannelInvalid", "CHANNEL_PRIVATE": "ChannelPrivate", "CHANNEL_TOO_LARGE": "ChannelTooLarge", "CHAT_ABOUT_NOT_MODIFIED": "ChatAboutNotModified", "CHAT_ABOUT_TOO_LONG": "ChatAboutTooLong", "CHAT_ADMIN_REQUIRED": "ChatAdminRequired", "CHAT_ID_EMPTY": "ChatIdEmpty", "CHAT_ID_INVALID": "ChatIdInvalid", "CHAT_INVALID": "ChatInvalid", "CHAT_LINK_EXISTS": "ChatLinkExists", "CHAT_NOT_MODIFIED": "ChatNotModified", "CHAT_RESTRICTED": "ChatRestricted", "CHAT_SEND_INLINE_FORBIDDEN": "ChatSendInlineForbidden", "CHAT_TITLE_EMPTY": "ChatTitleEmpty", "CODE_EMPTY": "CodeEmpty", "CODE_HASH_INVALID": "CodeHashInvalid", "CODE_INVALID": "CodeInvalid", "CONNECTION_API_ID_INVALID": "ConnectionApiIdInvalid", "CONNECTION_APP_VERSION_EMPTY": "ConnectionAppVersionEmpty", "CONNECTION_DEVICE_MODEL_EMPTY": "ConnectionDeviceModelEmpty", "CONNECTION_LANG_PACK_INVALID": "ConnectionLangPackInvalid", "CONNECTION_LAYER_INVALID": "ConnectionLayerInvalid", "CONNECTION_NOT_INITED": "ConnectionNotInited", "CONNECTION_SYSTEM_EMPTY": "ConnectionSystemEmpty", "CONNECTION_SYSTEM_LANG_CODE_EMPTY": "ConnectionSystemLangCodeEmpty", "CONTACT_ADD_MISSING": "ContactAddMissing", "CONTACT_ID_INVALID": "ContactIdInvalid", "CONTACT_NAME_EMPTY": "ContactNameEmpty", "CONTACT_REQ_MISSING": "ContactReqMissing", "DATA_INVALID": "DataInvalid", "DATA_JSON_INVALID": "DataJsonInvalid", "DATA_TOO_LONG": "DataTooLong", "DATE_EMPTY": "DateEmpty", "DC_ID_INVALID": "DcIdInvalid", "DH_G_A_INVALID": "DhGAInvalid", "DOCUMENT_INVALID": "DocumentInvalid", "EMAIL_HASH_EXPIRED": "EmailHashExpired", "EMAIL_INVALID": "EmailInvalid", "EMAIL_UNCONFIRMED": "EmailUnconfirmed", "EMAIL_UNCONFIRMED_X": "EmailUnconfirmed", "EMAIL_VERIFY_EXPIRED": "EmailVerifyExpired", "EMOTICON_EMPTY": "EmoticonEmpty", "EMOTICON_INVALID": "EmoticonInvalid", "EMOTICON_STICKERPACK_MISSING": "EmoticonStickerpackMissing", "ENCRYPTED_MESSAGE_INVALID": "EncryptedMessageInvalid", "ENCRYPTION_ALREADY_ACCEPTED": "EncryptionAlreadyAccepted", "ENCRYPTION_ALREADY_DECLINED": "EncryptionAlreadyDeclined", "ENCRYPTION_DECLINED": "EncryptionDeclined", "ENCRYPTION_ID_INVALID": "EncryptionIdInvalid", "ENTITIES_TOO_LONG": "EntitiesTooLong", "ENTITY_MENTION_USER_INVALID": "EntityMentionUserInvalid", "ERROR_TEXT_EMPTY": "ErrorTextEmpty", "EXPORT_CARD_INVALID": "ExportCardInvalid", "EXTERNAL_URL_INVALID": "ExternalUrlInvalid", "FIELD_NAME_EMPTY": "FieldNameEmpty", "FIELD_NAME_INVALID": "FieldNameInvalid", "FILE_ID_INVALID": "FileIdInvalid", "FILE_MIGRATE_X": "FileMigrate", "FILE_PARTS_INVALID": "FilePartsInvalid", "FILE_PART_EMPTY": "FilePartEmpty", "FILE_PART_INVALID": "FilePartInvalid", "FILE_PART_LENGTH_INVALID": "FilePartLengthInvalid", "FILE_PART_SIZE_CHANGED": "FilePartSizeChanged", "FILE_PART_SIZE_INVALID": "FilePartSizeInvalid", "FILE_PART_TOO_BIG": "FilePartTooBig", "FILE_PART_X_MISSING": "FilePartMissing", "FILE_REFERENCE_EMPTY": "FileReferenceEmpty", "FILE_REFERENCE_EXPIRED": "FileReferenceExpired", "FILE_REFERENCE_INVALID": "FileReferenceInvalid", "FILTER_ID_INVALID": "FilterIdInvalid", "FIRSTNAME_INVALID": "FirstnameInvalid", "FOLDER_ID_EMPTY": "FolderIdEmpty", "FOLDER_ID_INVALID": "FolderIdInvalid", "FRESH_CHANGE_ADMINS_FORBIDDEN": "FreshChangeAdminsForbidden", "FROM_MESSAGE_BOT_DISABLED": "FromMessageBotDisabled", "GAME_BOT_INVALID": "GameBotInvalid", "GEO_POINT_INVALID": "GeoPointInvalid", "GIF_CONTENT_TYPE_INVALID": "GifContentTypeInvalid", "GIF_ID_INVALID": "GifIdInvalid", "GRAPH_INVALID_RELOAD": "GraphInvalidReload", "GRAPH_OUTDATED_RELOAD": "GraphOutdatedReload", "GROUPED_MEDIA_INVALID": "GroupedMediaInvalid", "HASH_INVALID": "HashInvalid", "IMAGE_PROCESS_FAILED": "ImageProcessFailed", "INLINE_RESULT_EXPIRED": "InlineResultExpired", "INPUT_CONSTRUCTOR_INVALID": "InputConstructorInvalid", "INPUT_FETCH_ERROR": "InputFetchError", "INPUT_FETCH_FAIL": "InputFetchFail", "INPUT_FILTER_INVALID": "InputFilterInvalid", "INPUT_LAYER_INVALID": "InputLayerInvalid", "INPUT_METHOD_INVALID": "InputMethodInvalid", "INPUT_REQUEST_TOO_LONG": "InputRequestTooLong", "INPUT_USER_DEACTIVATED": "InputUserDeactivated", "INVITE_HASH_EMPTY": "InviteHashEmpty", "INVITE_HASH_EXPIRED": "InviteHashExpired", "INVITE_HASH_INVALID": "InviteHashInvalid", "LANG_PACK_INVALID": "LangPackInvalid", "LASTNAME_INVALID": "LastnameInvalid", "LIMIT_INVALID": "LimitInvalid", "LINK_NOT_MODIFIED": "LinkNotModified", "LOCATION_INVALID": "LocationInvalid", "MAX_ID_INVALID": "MaxIdInvalid", "MAX_QTS_INVALID": "MaxQtsInvalid", "MD5_CHECKSUM_INVALID": "Md5ChecksumInvalid", "MEDIA_CAPTION_TOO_LONG": "MediaCaptionTooLong", "MEDIA_EMPTY": "MediaEmpty", "MEDIA_INVALID": "MediaInvalid", "MEDIA_NEW_INVALID": "MediaNewInvalid", "MEDIA_PREV_INVALID": "MediaPrevInvalid", "MEGAGROUP_ID_INVALID": "MegagroupIdInvalid", "MEGAGROUP_PREHISTORY_HIDDEN": "MegagroupPrehistoryHidden", "MEGAGROUP_REQUIRED": "MegagroupRequired", "MESSAGE_EDIT_TIME_EXPIRED": "MessageEditTimeExpired", "MESSAGE_EMPTY": "MessageEmpty", "MESSAGE_IDS_EMPTY": "MessageIdsEmpty", "MESSAGE_ID_INVALID": "MessageIdInvalid", "MESSAGE_NOT_MODIFIED": "MessageNotModified", "MESSAGE_POLL_CLOSED": "MessagePollClosed", "MESSAGE_TOO_LONG": "MessageTooLong", "METHOD_INVALID": "MethodInvalid", "MSG_ID_INVALID": "MsgIdInvalid", "MSG_WAIT_FAILED": "MsgWaitFailed", "MULTI_MEDIA_TOO_LONG": "MultiMediaTooLong", "NEW_SALT_INVALID": "NewSaltInvalid", "NEW_SETTINGS_INVALID": "NewSettingsInvalid", "OFFSET_INVALID": "OffsetInvalid", "OFFSET_PEER_ID_INVALID": "OffsetPeerIdInvalid", "OPTIONS_TOO_MUCH": "OptionsTooMuch", "OPTION_INVALID": "OptionInvalid", "PACK_SHORT_NAME_INVALID": "PackShortNameInvalid", "PACK_SHORT_NAME_OCCUPIED": "PackShortNameOccupied", "PACK_TITLE_INVALID": "PackTitleInvalid", "PARTICIPANTS_TOO_FEW": "ParticipantsTooFew", "PARTICIPANT_VERSION_OUTDATED": "ParticipantVersionOutdated", "PASSWORD_EMPTY": "PasswordEmpty", "PASSWORD_HASH_INVALID": "PasswordHashInvalid", "PASSWORD_MISSING": "PasswordMissing", "PASSWORD_RECOVERY_NA": "PasswordRecoveryNa", "PASSWORD_REQUIRED": "PasswordRequired", "PASSWORD_TOO_FRESH_X": "PasswordTooFresh", "PAYMENT_PROVIDER_INVALID": "PaymentProviderInvalid", "PEER_FLOOD": "PeerFlood", "PEER_ID_INVALID": "PeerIdInvalid", "PEER_ID_NOT_SUPPORTED": "PeerIdNotSupported", "PERSISTENT_TIMESTAMP_EMPTY": "PersistentTimestampEmpty", "PERSISTENT_TIMESTAMP_INVALID": "PersistentTimestampInvalid", "PHONE_CODE_EMPTY": "PhoneCodeEmpty", "PHONE_CODE_EXPIRED": "PhoneCodeExpired", "PHONE_CODE_HASH_EMPTY": "PhoneCodeHashEmpty", "PHONE_CODE_INVALID": "PhoneCodeInvalid", "PHONE_NUMBER_APP_SIGNUP_FORBIDDEN": "PhoneNumberAppSignupForbidden", "PHONE_NUMBER_BANNED": "PhoneNumberBanned", "PHONE_NUMBER_FLOOD": "PhoneNumberFlood", "PHONE_NUMBER_INVALID": "PhoneNumberInvalid", "PHONE_NUMBER_OCCUPIED": "PhoneNumberOccupied", "PHONE_NUMBER_UNOCCUPIED": "PhoneNumberUnoccupied", "PHONE_PASSWORD_PROTECTED": "PhonePasswordProtected", "PHOTO_CONTENT_TYPE_INVALID": "PhotoContentTypeInvalid", "PHOTO_CONTENT_URL_EMPTY": "PhotoContentUrlEmpty", "PHOTO_CROP_FILE_MISSING": "PhotoCropFileMissing", "PHOTO_CROP_SIZE_SMALL": "PhotoCropSizeSmall", "PHOTO_EXT_INVALID": "PhotoExtInvalid", "PHOTO_FILE_MISSING": "PhotoFileMissing", "PHOTO_ID_INVALID": "PhotoIdInvalid", "PHOTO_INVALID": "PhotoInvalid", "PHOTO_INVALID_DIMENSIONS": "PhotoInvalidDimensions", "PHOTO_SAVE_FILE_INVALID": "PhotoSaveFileInvalid", "PHOTO_THUMB_URL_EMPTY": "PhotoThumbUrlEmpty", "PHOTO_THUMB_URL_INVALID": "PhotoThumbUrlInvalid", "PINNED_DIALOGS_TOO_MUCH": "PinnedDialogsTooMuch", "PIN_RESTRICTED": "PinRestricted", "POLL_ANSWERS_INVALID": "PollAnswersInvalid", "POLL_OPTION_DUPLICATE": "PollOptionDuplicate", "POLL_OPTION_INVALID": "PollOptionInvalid", "POLL_QUESTION_INVALID": "PollQuestionInvalid", "POLL_UNSUPPORTED": "PollUnsupported", "POLL_VOTE_REQUIRED": "PollVoteRequired", "PRIVACY_KEY_INVALID": "PrivacyKeyInvalid", "PRIVACY_TOO_LONG": "PrivacyTooLong", "PRIVACY_VALUE_INVALID": "PrivacyValueInvalid", "QUERY_ID_EMPTY": "QueryIdEmpty", "QUERY_ID_INVALID": "QueryIdInvalid", "QUERY_TOO_SHORT": "QueryTooShort", "QUIZ_CORRECT_ANSWERS_EMPTY": "QuizCorrectAnswersEmpty", "QUIZ_CORRECT_ANSWERS_TOO_MUCH": "QuizCorrectAnswersTooMuch", "QUIZ_CORRECT_ANSWER_INVALID": "QuizCorrectAnswerInvalid", "QUIZ_MULTIPLE_INVALID": "QuizMultipleInvalid", "RANDOM_ID_EMPTY": "RandomIdEmpty", "RANDOM_ID_INVALID": "RandomIdInvalid", "RANDOM_LENGTH_INVALID": "RandomLengthInvalid", "RANGES_INVALID": "RangesInvalid", "REACTION_EMPTY": "ReactionEmpty", "REACTION_INVALID": "ReactionInvalid", "REPLY_MARKUP_BUY_EMPTY": "ReplyMarkupBuyEmpty", "REPLY_MARKUP_GAME_EMPTY": "ReplyMarkupGameEmpty", "REPLY_MARKUP_INVALID": "ReplyMarkupInvalid", "REPLY_MARKUP_TOO_LONG": "ReplyMarkupTooLong", "RESULTS_TOO_MUCH": "ResultsTooMuch", "RESULT_ID_DUPLICATE": "ResultIdDuplicate", "RESULT_ID_EMPTY": "ResultIdEmpty", "RESULT_ID_INVALID": "ResultIdInvalid", "RESULT_TYPE_INVALID": "ResultTypeInvalid", "REVOTE_NOT_ALLOWED": "RevoteNotAllowed", "RSA_DECRYPT_FAILED": "RsaDecryptFailed", "SCHEDULE_BOT_NOT_ALLOWED": "ScheduleBotNotAllowed", "SCHEDULE_DATE_INVALID": "ScheduleDateInvalid", "SCHEDULE_DATE_TOO_LATE": "ScheduleDateTooLate", "SCHEDULE_STATUS_PRIVATE": "ScheduleStatusPrivate", "SCHEDULE_TOO_MUCH": "ScheduleTooMuch", "SEARCH_QUERY_EMPTY": "SearchQueryEmpty", "SECONDS_INVALID": "SecondsInvalid", "SEND_MESSAGE_MEDIA_INVALID": "SendMessageMediaInvalid", "SEND_MESSAGE_TYPE_INVALID": "SendMessageTypeInvalid", "SESSION_TOO_FRESH_X": "SessionTooFresh", "SETTINGS_INVALID": "SettingsInvalid", "SHA256_HASH_INVALID": "Sha256HashInvalid", "SHORTNAME_OCCUPY_FAILED": "ShortnameOccupyFailed", "SLOWMODE_MULTI_MSGS_DISABLED": "SlowmodeMultiMsgsDisabled", "SMS_CODE_CREATE_FAILED": "SmsCodeCreateFailed", "SRP_ID_INVALID": "SrpIdInvalid", "SRP_PASSWORD_CHANGED": "SrpPasswordChanged", "START_PARAM_EMPTY": "StartParamEmpty", "START_PARAM_INVALID": "StartParamInvalid", "START_PARAM_TOO_LONG": "StartParamTooLong", "STICKERSET_INVALID": "StickersetInvalid", "STICKERS_EMPTY": "StickersEmpty", "STICKER_DOCUMENT_INVALID": "StickerDocumentInvalid", "STICKER_EMOJI_INVALID": "StickerEmojiInvalid", "STICKER_FILE_INVALID": "StickerFileInvalid", "STICKER_ID_INVALID": "StickerIdInvalid", "STICKER_INVALID": "StickerInvalid", "STICKER_PNG_DIMENSIONS": "StickerPngDimensions", "STICKER_PNG_NOPNG": "StickerPngNopng", "TAKEOUT_INVALID": "TakeoutInvalid", "TAKEOUT_REQUIRED": "TakeoutRequired", "TEMP_AUTH_KEY_EMPTY": "TempAuthKeyEmpty", "THEME_FILE_INVALID": "ThemeFileInvalid", "THEME_FORMAT_INVALID": "ThemeFormatInvalid", "THEME_INVALID": "ThemeInvalid", "THEME_MIME_INVALID": "ThemeMimeInvalid", "TMP_PASSWORD_DISABLED": "TmpPasswordDisabled", "TOKEN_INVALID": "TokenInvalid", "TTL_DAYS_INVALID": "TtlDaysInvalid", "TTL_MEDIA_INVALID": "TtlMediaInvalid", "TYPES_EMPTY": "TypesEmpty", "TYPE_CONSTRUCTOR_INVALID": "TypeConstructorInvalid", "UNTIL_DATE_INVALID": "UntilDateInvalid", "URL_INVALID": "UrlInvalid", "USERNAME_INVALID": "UsernameInvalid", "USERNAME_NOT_MODIFIED": "UsernameNotModified", "USERNAME_NOT_OCCUPIED": "UsernameNotOccupied", "USERNAME_OCCUPIED": "UsernameOccupied", "USERS_TOO_FEW": "UsersTooFew", "USERS_TOO_MUCH": "UsersTooMuch", "USER_ADMIN_INVALID": "UserAdminInvalid", "USER_ALREADY_PARTICIPANT": "UserAlreadyParticipant", "USER_BANNED_IN_CHANNEL": "UserBannedInChannel", "USER_BLOCKED": "UserBlocked", "USER_BOT": "UserBot", "USER_BOT_INVALID": "UserBotInvalid", "USER_BOT_REQUIRED": "UserBotRequired", "USER_CHANNELS_TOO_MUCH": "UserChannelsTooMuch", "USER_CREATOR": "UserCreator", "USER_ID_INVALID": "UserIdInvalid", "USER_INVALID": "UserInvalid", "USER_IS_BLOCKED": "UserIsBlocked", "USER_IS_BOT": "UserIsBot", "USER_KICKED": "UserKicked", "USER_NOT_MUTUAL_CONTACT": "UserNotMutualContact", "USER_NOT_PARTICIPANT": "UserNotParticipant", "VIDEO_CONTENT_TYPE_INVALID": "VideoContentTypeInvalid", "VIDEO_FILE_INVALID": "VideoFileInvalid", "VOLUME_LOC_NOT_FOUND": "VolumeLocNotFound", "WALLPAPER_FILE_INVALID": "WallpaperFileInvalid", "WALLPAPER_INVALID": "WallpaperInvalid", "WC_CONVERT_URL_INVALID": "WcConvertUrlInvalid", "WEBDOCUMENT_INVALID": "WebdocumentInvalid", "WEBDOCUMENT_MIME_INVALID": "WebdocumentMimeInvalid", "WEBDOCUMENT_SIZE_TOO_BIG": "WebdocumentSizeTooBig", "WEBDOCUMENT_URL_EMPTY": "WebdocumentUrlEmpty", "WEBDOCUMENT_URL_INVALID": "WebdocumentUrlInvalid", "WEBPAGE_CURL_FAILED": "WebpageCurlFailed", "WEBPAGE_MEDIA_EMPTY": "WebpageMediaEmpty", "YOU_BLOCKED_USER": "YouBlockedUser", }, 403: { "_": "Forbidden", "BROADCAST_FORBIDDEN": "BroadcastForbidden", "CHANNEL_PUBLIC_GROUP_NA": "ChannelPublicGroupNa", "CHAT_ADMIN_INVITE_REQUIRED": "ChatAdminInviteRequired", "CHAT_ADMIN_REQUIRED": "ChatAdminRequired", "CHAT_FORBIDDEN": "ChatForbidden", "CHAT_SEND_GIFS_FORBIDDEN": "ChatSendGifsForbidden", "CHAT_SEND_INLINE_FORBIDDEN": "ChatSendInlineForbidden", "CHAT_SEND_MEDIA_FORBIDDEN": "ChatSendMediaForbidden", "CHAT_SEND_POLL_FORBIDDEN": "ChatSendPollForbidden", "CHAT_SEND_STICKERS_FORBIDDEN": "ChatSendStickersForbidden", "CHAT_WRITE_FORBIDDEN": "ChatWriteForbidden", "INLINE_BOT_REQUIRED": "InlineBotRequired", "MESSAGE_AUTHOR_REQUIRED": "MessageAuthorRequired", "MESSAGE_DELETE_FORBIDDEN": "MessageDeleteForbidden", "POLL_VOTE_REQUIRED": "PollVoteRequired", "RIGHT_FORBIDDEN": "RightForbidden", "SENSITIVE_CHANGE_FORBIDDEN": "SensitiveChangeForbidden", "TAKEOUT_REQUIRED": "TakeoutRequired", "USER_BOT_INVALID": "UserBotInvalid", "USER_CHANNELS_TOO_MUCH": "UserChannelsTooMuch", "USER_INVALID": "UserInvalid", "USER_IS_BLOCKED": "UserIsBlocked", "USER_NOT_MUTUAL_CONTACT": "UserNotMutualContact", "USER_PRIVACY_RESTRICTED": "UserPrivacyRestricted", "USER_RESTRICTED": "UserRestricted", }, 401: { "_": "Unauthorized", "ACTIVE_USER_REQUIRED": "ActiveUserRequired", "AUTH_KEY_INVALID": "AuthKeyInvalid", "AUTH_KEY_PERM_EMPTY": "AuthKeyPermEmpty", "AUTH_KEY_UNREGISTERED": "AuthKeyUnregistered", "SESSION_EXPIRED": "SessionExpired", "SESSION_PASSWORD_NEEDED": "SessionPasswordNeeded", "SESSION_REVOKED": "SessionRevoked", "USER_DEACTIVATED": "UserDeactivated", "USER_DEACTIVATED_BAN": "UserDeactivatedBan", }, 420: { "_": "Flood", "FLOOD_TEST_PHONE_WAIT_X": "FloodTestPhoneWait", "FLOOD_WAIT_X": "FloodWait", "SLOWMODE_WAIT_X": "SlowmodeWait", "TAKEOUT_INIT_DELAY_X": "TakeoutInitDelay", }, 303: { "_": "SeeOther", "FILE_MIGRATE_X": "FileMigrate", "NETWORK_MIGRATE_X": "NetworkMigrate", "PHONE_MIGRATE_X": "PhoneMigrate", "STATS_MIGRATE_X": "StatsMigrate", "USER_MIGRATE_X": "UserMigrate", }, }
count = 425 exceptions = {406: {'_': 'NotAcceptable', 'AUTH_KEY_DUPLICATED': 'AuthKeyDuplicated', 'FILEREF_UPGRADE_NEEDED': 'FilerefUpgradeNeeded', 'FRESH_CHANGE_ADMINS_FORBIDDEN': 'FreshChangeAdminsForbidden', 'FRESH_CHANGE_PHONE_FORBIDDEN': 'FreshChangePhoneForbidden', 'FRESH_RESET_AUTHORISATION_FORBIDDEN': 'FreshResetAuthorisationForbidden', 'PHONE_NUMBER_INVALID': 'PhoneNumberInvalid', 'PHONE_PASSWORD_FLOOD': 'PhonePasswordFlood', 'STICKERSET_INVALID': 'StickersetInvalid', 'STICKERSET_OWNER_ANONYMOUS': 'StickersetOwnerAnonymous', 'USERPIC_UPLOAD_REQUIRED': 'UserpicUploadRequired', 'USER_RESTRICTED': 'UserRestricted'}, 500: {'_': 'InternalServerError', 'API_CALL_ERROR': 'ApiCallError', 'AUTH_RESTART': 'AuthRestart', 'CALL_OCCUPY_FAILED': 'CallOccupyFailed', 'CHAT_ID_GENERATE_FAILED': 'ChatIdGenerateFailed', 'CHAT_OCCUPY_LOC_FAILED': 'ChatOccupyLocFailed', 'CHAT_OCCUPY_USERNAME_FAILED': 'ChatOccupyUsernameFailed', 'CHP_CALL_FAIL': 'ChpCallFail', 'ENCRYPTION_OCCUPY_ADMIN_FAILED': 'EncryptionOccupyAdminFailed', 'ENCRYPTION_OCCUPY_FAILED': 'EncryptionOccupyFailed', 'FOLDER_DEAC_AUTOFIX_ALL': 'FolderDeacAutofixAll', 'GROUPED_ID_OCCUPY_FAILED': 'GroupedIdOccupyFailed', 'HISTORY_GET_FAILED': 'HistoryGetFailed', 'IMAGE_ENGINE_DOWN': 'ImageEngineDown', 'INTERDC_X_CALL_ERROR': 'InterdcCallError', 'INTERDC_X_CALL_RICH_ERROR': 'InterdcCallRichError', 'MEMBER_FETCH_FAILED': 'MemberFetchFailed', 'MEMBER_NO_LOCATION': 'MemberNoLocation', 'MEMBER_OCCUPY_PRIMARY_LOC_FAILED': 'MemberOccupyPrimaryLocFailed', 'MEMBER_OCCUPY_USERNAME_FAILED': 'MemberOccupyUsernameFailed', 'MSGID_DECREASE_RETRY': 'MsgidDecreaseRetry', 'MSG_RANGE_UNSYNC': 'MsgRangeUnsync', 'MT_SEND_QUEUE_TOO_LONG': 'MtSendQueueTooLong', 'NEED_CHAT_INVALID': 'NeedChatInvalid', 'NEED_MEMBER_INVALID': 'NeedMemberInvalid', 'PARTICIPANT_CALL_FAILED': 'ParticipantCallFailed', 'PERSISTENT_TIMESTAMP_OUTDATED': 'PersistentTimestampOutdated', 'POSTPONED_TIMEOUT': 'PostponedTimeout', 'PTS_CHANGE_EMPTY': 'PtsChangeEmpty', 'RANDOM_ID_DUPLICATE': 'RandomIdDuplicate', 'REG_ID_GENERATE_FAILED': 'RegIdGenerateFailed', 'RPC_CALL_FAIL': 'RpcCallFail', 'RPC_CONNECT_FAILED': 'RpcConnectFailed', 'RPC_MCGET_FAIL': 'RpcMcgetFail', 'SIGN_IN_FAILED': 'SignInFailed', 'STORAGE_CHECK_FAILED': 'StorageCheckFailed', 'STORE_INVALID_SCALAR_TYPE': 'StoreInvalidScalarType', 'UNKNOWN_METHOD': 'UnknownMethod', 'UPLOAD_NO_VOLUME': 'UploadNoVolume', 'VOLUME_LOC_NOT_FOUND': 'VolumeLocNotFound', 'WORKER_BUSY_TOO_LONG_RETRY': 'WorkerBusyTooLongRetry', 'WP_ID_GENERATE_FAILED': 'WpIdGenerateFailed'}, 400: {'_': 'BadRequest', 'ABOUT_TOO_LONG': 'AboutTooLong', 'ACCESS_TOKEN_EXPIRED': 'AccessTokenExpired', 'ACCESS_TOKEN_INVALID': 'AccessTokenInvalid', 'ADMINS_TOO_MUCH': 'AdminsTooMuch', 'ADMIN_RANK_EMOJI_NOT_ALLOWED': 'AdminRankEmojiNotAllowed', 'ADMIN_RANK_INVALID': 'AdminRankInvalid', 'ALBUM_PHOTOS_TOO_MANY': 'AlbumPhotosTooMany', 'API_ID_INVALID': 'ApiIdInvalid', 'API_ID_PUBLISHED_FLOOD': 'ApiIdPublishedFlood', 'ARTICLE_TITLE_EMPTY': 'ArticleTitleEmpty', 'AUDIO_TITLE_EMPTY': 'AudioTitleEmpty', 'AUTH_BYTES_INVALID': 'AuthBytesInvalid', 'AUTH_TOKEN_ALREADY_ACCEPTED': 'AuthTokenAlreadyAccepted', 'AUTH_TOKEN_EXPIRED': 'AuthTokenExpired', 'AUTH_TOKEN_INVALID': 'AuthTokenInvalid', 'AUTOARCHIVE_NOT_AVAILABLE': 'AutoarchiveNotAvailable', 'BANK_CARD_NUMBER_INVALID': 'BankCardNumberInvalid', 'BANNED_RIGHTS_INVALID': 'BannedRightsInvalid', 'BOTS_TOO_MUCH': 'BotsTooMuch', 'BOT_CHANNELS_NA': 'BotChannelsNa', 'BOT_COMMAND_DESCRIPTION_INVALID': 'BotCommandDescriptionInvalid', 'BOT_DOMAIN_INVALID': 'BotDomainInvalid', 'BOT_GAMES_DISABLED': 'BotGamesDisabled', 'BOT_GROUPS_BLOCKED': 'BotGroupsBlocked', 'BOT_INLINE_DISABLED': 'BotInlineDisabled', 'BOT_INVALID': 'BotInvalid', 'BOT_METHOD_INVALID': 'BotMethodInvalid', 'BOT_MISSING': 'BotMissing', 'BOT_PAYMENTS_DISABLED': 'BotPaymentsDisabled', 'BOT_POLLS_DISABLED': 'BotPollsDisabled', 'BOT_RESPONSE_TIMEOUT': 'BotResponseTimeout', 'BOT_SCORE_NOT_MODIFIED': 'BotScoreNotModified', 'BROADCAST_ID_INVALID': 'BroadcastIdInvalid', 'BROADCAST_PUBLIC_VOTERS_FORBIDDEN': 'BroadcastPublicVotersForbidden', 'BROADCAST_REQUIRED': 'BroadcastRequired', 'BUTTON_DATA_INVALID': 'ButtonDataInvalid', 'BUTTON_TYPE_INVALID': 'ButtonTypeInvalid', 'BUTTON_URL_INVALID': 'ButtonUrlInvalid', 'CALL_ALREADY_ACCEPTED': 'CallAlreadyAccepted', 'CALL_ALREADY_DECLINED': 'CallAlreadyDeclined', 'CALL_PEER_INVALID': 'CallPeerInvalid', 'CALL_PROTOCOL_FLAGS_INVALID': 'CallProtocolFlagsInvalid', 'CDN_METHOD_INVALID': 'CdnMethodInvalid', 'CHANNELS_ADMIN_PUBLIC_TOO_MUCH': 'ChannelsAdminPublicTooMuch', 'CHANNELS_TOO_MUCH': 'ChannelsTooMuch', 'CHANNEL_BANNED': 'ChannelBanned', 'CHANNEL_INVALID': 'ChannelInvalid', 'CHANNEL_PRIVATE': 'ChannelPrivate', 'CHANNEL_TOO_LARGE': 'ChannelTooLarge', 'CHAT_ABOUT_NOT_MODIFIED': 'ChatAboutNotModified', 'CHAT_ABOUT_TOO_LONG': 'ChatAboutTooLong', 'CHAT_ADMIN_REQUIRED': 'ChatAdminRequired', 'CHAT_ID_EMPTY': 'ChatIdEmpty', 'CHAT_ID_INVALID': 'ChatIdInvalid', 'CHAT_INVALID': 'ChatInvalid', 'CHAT_LINK_EXISTS': 'ChatLinkExists', 'CHAT_NOT_MODIFIED': 'ChatNotModified', 'CHAT_RESTRICTED': 'ChatRestricted', 'CHAT_SEND_INLINE_FORBIDDEN': 'ChatSendInlineForbidden', 'CHAT_TITLE_EMPTY': 'ChatTitleEmpty', 'CODE_EMPTY': 'CodeEmpty', 'CODE_HASH_INVALID': 'CodeHashInvalid', 'CODE_INVALID': 'CodeInvalid', 'CONNECTION_API_ID_INVALID': 'ConnectionApiIdInvalid', 'CONNECTION_APP_VERSION_EMPTY': 'ConnectionAppVersionEmpty', 'CONNECTION_DEVICE_MODEL_EMPTY': 'ConnectionDeviceModelEmpty', 'CONNECTION_LANG_PACK_INVALID': 'ConnectionLangPackInvalid', 'CONNECTION_LAYER_INVALID': 'ConnectionLayerInvalid', 'CONNECTION_NOT_INITED': 'ConnectionNotInited', 'CONNECTION_SYSTEM_EMPTY': 'ConnectionSystemEmpty', 'CONNECTION_SYSTEM_LANG_CODE_EMPTY': 'ConnectionSystemLangCodeEmpty', 'CONTACT_ADD_MISSING': 'ContactAddMissing', 'CONTACT_ID_INVALID': 'ContactIdInvalid', 'CONTACT_NAME_EMPTY': 'ContactNameEmpty', 'CONTACT_REQ_MISSING': 'ContactReqMissing', 'DATA_INVALID': 'DataInvalid', 'DATA_JSON_INVALID': 'DataJsonInvalid', 'DATA_TOO_LONG': 'DataTooLong', 'DATE_EMPTY': 'DateEmpty', 'DC_ID_INVALID': 'DcIdInvalid', 'DH_G_A_INVALID': 'DhGAInvalid', 'DOCUMENT_INVALID': 'DocumentInvalid', 'EMAIL_HASH_EXPIRED': 'EmailHashExpired', 'EMAIL_INVALID': 'EmailInvalid', 'EMAIL_UNCONFIRMED': 'EmailUnconfirmed', 'EMAIL_UNCONFIRMED_X': 'EmailUnconfirmed', 'EMAIL_VERIFY_EXPIRED': 'EmailVerifyExpired', 'EMOTICON_EMPTY': 'EmoticonEmpty', 'EMOTICON_INVALID': 'EmoticonInvalid', 'EMOTICON_STICKERPACK_MISSING': 'EmoticonStickerpackMissing', 'ENCRYPTED_MESSAGE_INVALID': 'EncryptedMessageInvalid', 'ENCRYPTION_ALREADY_ACCEPTED': 'EncryptionAlreadyAccepted', 'ENCRYPTION_ALREADY_DECLINED': 'EncryptionAlreadyDeclined', 'ENCRYPTION_DECLINED': 'EncryptionDeclined', 'ENCRYPTION_ID_INVALID': 'EncryptionIdInvalid', 'ENTITIES_TOO_LONG': 'EntitiesTooLong', 'ENTITY_MENTION_USER_INVALID': 'EntityMentionUserInvalid', 'ERROR_TEXT_EMPTY': 'ErrorTextEmpty', 'EXPORT_CARD_INVALID': 'ExportCardInvalid', 'EXTERNAL_URL_INVALID': 'ExternalUrlInvalid', 'FIELD_NAME_EMPTY': 'FieldNameEmpty', 'FIELD_NAME_INVALID': 'FieldNameInvalid', 'FILE_ID_INVALID': 'FileIdInvalid', 'FILE_MIGRATE_X': 'FileMigrate', 'FILE_PARTS_INVALID': 'FilePartsInvalid', 'FILE_PART_EMPTY': 'FilePartEmpty', 'FILE_PART_INVALID': 'FilePartInvalid', 'FILE_PART_LENGTH_INVALID': 'FilePartLengthInvalid', 'FILE_PART_SIZE_CHANGED': 'FilePartSizeChanged', 'FILE_PART_SIZE_INVALID': 'FilePartSizeInvalid', 'FILE_PART_TOO_BIG': 'FilePartTooBig', 'FILE_PART_X_MISSING': 'FilePartMissing', 'FILE_REFERENCE_EMPTY': 'FileReferenceEmpty', 'FILE_REFERENCE_EXPIRED': 'FileReferenceExpired', 'FILE_REFERENCE_INVALID': 'FileReferenceInvalid', 'FILTER_ID_INVALID': 'FilterIdInvalid', 'FIRSTNAME_INVALID': 'FirstnameInvalid', 'FOLDER_ID_EMPTY': 'FolderIdEmpty', 'FOLDER_ID_INVALID': 'FolderIdInvalid', 'FRESH_CHANGE_ADMINS_FORBIDDEN': 'FreshChangeAdminsForbidden', 'FROM_MESSAGE_BOT_DISABLED': 'FromMessageBotDisabled', 'GAME_BOT_INVALID': 'GameBotInvalid', 'GEO_POINT_INVALID': 'GeoPointInvalid', 'GIF_CONTENT_TYPE_INVALID': 'GifContentTypeInvalid', 'GIF_ID_INVALID': 'GifIdInvalid', 'GRAPH_INVALID_RELOAD': 'GraphInvalidReload', 'GRAPH_OUTDATED_RELOAD': 'GraphOutdatedReload', 'GROUPED_MEDIA_INVALID': 'GroupedMediaInvalid', 'HASH_INVALID': 'HashInvalid', 'IMAGE_PROCESS_FAILED': 'ImageProcessFailed', 'INLINE_RESULT_EXPIRED': 'InlineResultExpired', 'INPUT_CONSTRUCTOR_INVALID': 'InputConstructorInvalid', 'INPUT_FETCH_ERROR': 'InputFetchError', 'INPUT_FETCH_FAIL': 'InputFetchFail', 'INPUT_FILTER_INVALID': 'InputFilterInvalid', 'INPUT_LAYER_INVALID': 'InputLayerInvalid', 'INPUT_METHOD_INVALID': 'InputMethodInvalid', 'INPUT_REQUEST_TOO_LONG': 'InputRequestTooLong', 'INPUT_USER_DEACTIVATED': 'InputUserDeactivated', 'INVITE_HASH_EMPTY': 'InviteHashEmpty', 'INVITE_HASH_EXPIRED': 'InviteHashExpired', 'INVITE_HASH_INVALID': 'InviteHashInvalid', 'LANG_PACK_INVALID': 'LangPackInvalid', 'LASTNAME_INVALID': 'LastnameInvalid', 'LIMIT_INVALID': 'LimitInvalid', 'LINK_NOT_MODIFIED': 'LinkNotModified', 'LOCATION_INVALID': 'LocationInvalid', 'MAX_ID_INVALID': 'MaxIdInvalid', 'MAX_QTS_INVALID': 'MaxQtsInvalid', 'MD5_CHECKSUM_INVALID': 'Md5ChecksumInvalid', 'MEDIA_CAPTION_TOO_LONG': 'MediaCaptionTooLong', 'MEDIA_EMPTY': 'MediaEmpty', 'MEDIA_INVALID': 'MediaInvalid', 'MEDIA_NEW_INVALID': 'MediaNewInvalid', 'MEDIA_PREV_INVALID': 'MediaPrevInvalid', 'MEGAGROUP_ID_INVALID': 'MegagroupIdInvalid', 'MEGAGROUP_PREHISTORY_HIDDEN': 'MegagroupPrehistoryHidden', 'MEGAGROUP_REQUIRED': 'MegagroupRequired', 'MESSAGE_EDIT_TIME_EXPIRED': 'MessageEditTimeExpired', 'MESSAGE_EMPTY': 'MessageEmpty', 'MESSAGE_IDS_EMPTY': 'MessageIdsEmpty', 'MESSAGE_ID_INVALID': 'MessageIdInvalid', 'MESSAGE_NOT_MODIFIED': 'MessageNotModified', 'MESSAGE_POLL_CLOSED': 'MessagePollClosed', 'MESSAGE_TOO_LONG': 'MessageTooLong', 'METHOD_INVALID': 'MethodInvalid', 'MSG_ID_INVALID': 'MsgIdInvalid', 'MSG_WAIT_FAILED': 'MsgWaitFailed', 'MULTI_MEDIA_TOO_LONG': 'MultiMediaTooLong', 'NEW_SALT_INVALID': 'NewSaltInvalid', 'NEW_SETTINGS_INVALID': 'NewSettingsInvalid', 'OFFSET_INVALID': 'OffsetInvalid', 'OFFSET_PEER_ID_INVALID': 'OffsetPeerIdInvalid', 'OPTIONS_TOO_MUCH': 'OptionsTooMuch', 'OPTION_INVALID': 'OptionInvalid', 'PACK_SHORT_NAME_INVALID': 'PackShortNameInvalid', 'PACK_SHORT_NAME_OCCUPIED': 'PackShortNameOccupied', 'PACK_TITLE_INVALID': 'PackTitleInvalid', 'PARTICIPANTS_TOO_FEW': 'ParticipantsTooFew', 'PARTICIPANT_VERSION_OUTDATED': 'ParticipantVersionOutdated', 'PASSWORD_EMPTY': 'PasswordEmpty', 'PASSWORD_HASH_INVALID': 'PasswordHashInvalid', 'PASSWORD_MISSING': 'PasswordMissing', 'PASSWORD_RECOVERY_NA': 'PasswordRecoveryNa', 'PASSWORD_REQUIRED': 'PasswordRequired', 'PASSWORD_TOO_FRESH_X': 'PasswordTooFresh', 'PAYMENT_PROVIDER_INVALID': 'PaymentProviderInvalid', 'PEER_FLOOD': 'PeerFlood', 'PEER_ID_INVALID': 'PeerIdInvalid', 'PEER_ID_NOT_SUPPORTED': 'PeerIdNotSupported', 'PERSISTENT_TIMESTAMP_EMPTY': 'PersistentTimestampEmpty', 'PERSISTENT_TIMESTAMP_INVALID': 'PersistentTimestampInvalid', 'PHONE_CODE_EMPTY': 'PhoneCodeEmpty', 'PHONE_CODE_EXPIRED': 'PhoneCodeExpired', 'PHONE_CODE_HASH_EMPTY': 'PhoneCodeHashEmpty', 'PHONE_CODE_INVALID': 'PhoneCodeInvalid', 'PHONE_NUMBER_APP_SIGNUP_FORBIDDEN': 'PhoneNumberAppSignupForbidden', 'PHONE_NUMBER_BANNED': 'PhoneNumberBanned', 'PHONE_NUMBER_FLOOD': 'PhoneNumberFlood', 'PHONE_NUMBER_INVALID': 'PhoneNumberInvalid', 'PHONE_NUMBER_OCCUPIED': 'PhoneNumberOccupied', 'PHONE_NUMBER_UNOCCUPIED': 'PhoneNumberUnoccupied', 'PHONE_PASSWORD_PROTECTED': 'PhonePasswordProtected', 'PHOTO_CONTENT_TYPE_INVALID': 'PhotoContentTypeInvalid', 'PHOTO_CONTENT_URL_EMPTY': 'PhotoContentUrlEmpty', 'PHOTO_CROP_FILE_MISSING': 'PhotoCropFileMissing', 'PHOTO_CROP_SIZE_SMALL': 'PhotoCropSizeSmall', 'PHOTO_EXT_INVALID': 'PhotoExtInvalid', 'PHOTO_FILE_MISSING': 'PhotoFileMissing', 'PHOTO_ID_INVALID': 'PhotoIdInvalid', 'PHOTO_INVALID': 'PhotoInvalid', 'PHOTO_INVALID_DIMENSIONS': 'PhotoInvalidDimensions', 'PHOTO_SAVE_FILE_INVALID': 'PhotoSaveFileInvalid', 'PHOTO_THUMB_URL_EMPTY': 'PhotoThumbUrlEmpty', 'PHOTO_THUMB_URL_INVALID': 'PhotoThumbUrlInvalid', 'PINNED_DIALOGS_TOO_MUCH': 'PinnedDialogsTooMuch', 'PIN_RESTRICTED': 'PinRestricted', 'POLL_ANSWERS_INVALID': 'PollAnswersInvalid', 'POLL_OPTION_DUPLICATE': 'PollOptionDuplicate', 'POLL_OPTION_INVALID': 'PollOptionInvalid', 'POLL_QUESTION_INVALID': 'PollQuestionInvalid', 'POLL_UNSUPPORTED': 'PollUnsupported', 'POLL_VOTE_REQUIRED': 'PollVoteRequired', 'PRIVACY_KEY_INVALID': 'PrivacyKeyInvalid', 'PRIVACY_TOO_LONG': 'PrivacyTooLong', 'PRIVACY_VALUE_INVALID': 'PrivacyValueInvalid', 'QUERY_ID_EMPTY': 'QueryIdEmpty', 'QUERY_ID_INVALID': 'QueryIdInvalid', 'QUERY_TOO_SHORT': 'QueryTooShort', 'QUIZ_CORRECT_ANSWERS_EMPTY': 'QuizCorrectAnswersEmpty', 'QUIZ_CORRECT_ANSWERS_TOO_MUCH': 'QuizCorrectAnswersTooMuch', 'QUIZ_CORRECT_ANSWER_INVALID': 'QuizCorrectAnswerInvalid', 'QUIZ_MULTIPLE_INVALID': 'QuizMultipleInvalid', 'RANDOM_ID_EMPTY': 'RandomIdEmpty', 'RANDOM_ID_INVALID': 'RandomIdInvalid', 'RANDOM_LENGTH_INVALID': 'RandomLengthInvalid', 'RANGES_INVALID': 'RangesInvalid', 'REACTION_EMPTY': 'ReactionEmpty', 'REACTION_INVALID': 'ReactionInvalid', 'REPLY_MARKUP_BUY_EMPTY': 'ReplyMarkupBuyEmpty', 'REPLY_MARKUP_GAME_EMPTY': 'ReplyMarkupGameEmpty', 'REPLY_MARKUP_INVALID': 'ReplyMarkupInvalid', 'REPLY_MARKUP_TOO_LONG': 'ReplyMarkupTooLong', 'RESULTS_TOO_MUCH': 'ResultsTooMuch', 'RESULT_ID_DUPLICATE': 'ResultIdDuplicate', 'RESULT_ID_EMPTY': 'ResultIdEmpty', 'RESULT_ID_INVALID': 'ResultIdInvalid', 'RESULT_TYPE_INVALID': 'ResultTypeInvalid', 'REVOTE_NOT_ALLOWED': 'RevoteNotAllowed', 'RSA_DECRYPT_FAILED': 'RsaDecryptFailed', 'SCHEDULE_BOT_NOT_ALLOWED': 'ScheduleBotNotAllowed', 'SCHEDULE_DATE_INVALID': 'ScheduleDateInvalid', 'SCHEDULE_DATE_TOO_LATE': 'ScheduleDateTooLate', 'SCHEDULE_STATUS_PRIVATE': 'ScheduleStatusPrivate', 'SCHEDULE_TOO_MUCH': 'ScheduleTooMuch', 'SEARCH_QUERY_EMPTY': 'SearchQueryEmpty', 'SECONDS_INVALID': 'SecondsInvalid', 'SEND_MESSAGE_MEDIA_INVALID': 'SendMessageMediaInvalid', 'SEND_MESSAGE_TYPE_INVALID': 'SendMessageTypeInvalid', 'SESSION_TOO_FRESH_X': 'SessionTooFresh', 'SETTINGS_INVALID': 'SettingsInvalid', 'SHA256_HASH_INVALID': 'Sha256HashInvalid', 'SHORTNAME_OCCUPY_FAILED': 'ShortnameOccupyFailed', 'SLOWMODE_MULTI_MSGS_DISABLED': 'SlowmodeMultiMsgsDisabled', 'SMS_CODE_CREATE_FAILED': 'SmsCodeCreateFailed', 'SRP_ID_INVALID': 'SrpIdInvalid', 'SRP_PASSWORD_CHANGED': 'SrpPasswordChanged', 'START_PARAM_EMPTY': 'StartParamEmpty', 'START_PARAM_INVALID': 'StartParamInvalid', 'START_PARAM_TOO_LONG': 'StartParamTooLong', 'STICKERSET_INVALID': 'StickersetInvalid', 'STICKERS_EMPTY': 'StickersEmpty', 'STICKER_DOCUMENT_INVALID': 'StickerDocumentInvalid', 'STICKER_EMOJI_INVALID': 'StickerEmojiInvalid', 'STICKER_FILE_INVALID': 'StickerFileInvalid', 'STICKER_ID_INVALID': 'StickerIdInvalid', 'STICKER_INVALID': 'StickerInvalid', 'STICKER_PNG_DIMENSIONS': 'StickerPngDimensions', 'STICKER_PNG_NOPNG': 'StickerPngNopng', 'TAKEOUT_INVALID': 'TakeoutInvalid', 'TAKEOUT_REQUIRED': 'TakeoutRequired', 'TEMP_AUTH_KEY_EMPTY': 'TempAuthKeyEmpty', 'THEME_FILE_INVALID': 'ThemeFileInvalid', 'THEME_FORMAT_INVALID': 'ThemeFormatInvalid', 'THEME_INVALID': 'ThemeInvalid', 'THEME_MIME_INVALID': 'ThemeMimeInvalid', 'TMP_PASSWORD_DISABLED': 'TmpPasswordDisabled', 'TOKEN_INVALID': 'TokenInvalid', 'TTL_DAYS_INVALID': 'TtlDaysInvalid', 'TTL_MEDIA_INVALID': 'TtlMediaInvalid', 'TYPES_EMPTY': 'TypesEmpty', 'TYPE_CONSTRUCTOR_INVALID': 'TypeConstructorInvalid', 'UNTIL_DATE_INVALID': 'UntilDateInvalid', 'URL_INVALID': 'UrlInvalid', 'USERNAME_INVALID': 'UsernameInvalid', 'USERNAME_NOT_MODIFIED': 'UsernameNotModified', 'USERNAME_NOT_OCCUPIED': 'UsernameNotOccupied', 'USERNAME_OCCUPIED': 'UsernameOccupied', 'USERS_TOO_FEW': 'UsersTooFew', 'USERS_TOO_MUCH': 'UsersTooMuch', 'USER_ADMIN_INVALID': 'UserAdminInvalid', 'USER_ALREADY_PARTICIPANT': 'UserAlreadyParticipant', 'USER_BANNED_IN_CHANNEL': 'UserBannedInChannel', 'USER_BLOCKED': 'UserBlocked', 'USER_BOT': 'UserBot', 'USER_BOT_INVALID': 'UserBotInvalid', 'USER_BOT_REQUIRED': 'UserBotRequired', 'USER_CHANNELS_TOO_MUCH': 'UserChannelsTooMuch', 'USER_CREATOR': 'UserCreator', 'USER_ID_INVALID': 'UserIdInvalid', 'USER_INVALID': 'UserInvalid', 'USER_IS_BLOCKED': 'UserIsBlocked', 'USER_IS_BOT': 'UserIsBot', 'USER_KICKED': 'UserKicked', 'USER_NOT_MUTUAL_CONTACT': 'UserNotMutualContact', 'USER_NOT_PARTICIPANT': 'UserNotParticipant', 'VIDEO_CONTENT_TYPE_INVALID': 'VideoContentTypeInvalid', 'VIDEO_FILE_INVALID': 'VideoFileInvalid', 'VOLUME_LOC_NOT_FOUND': 'VolumeLocNotFound', 'WALLPAPER_FILE_INVALID': 'WallpaperFileInvalid', 'WALLPAPER_INVALID': 'WallpaperInvalid', 'WC_CONVERT_URL_INVALID': 'WcConvertUrlInvalid', 'WEBDOCUMENT_INVALID': 'WebdocumentInvalid', 'WEBDOCUMENT_MIME_INVALID': 'WebdocumentMimeInvalid', 'WEBDOCUMENT_SIZE_TOO_BIG': 'WebdocumentSizeTooBig', 'WEBDOCUMENT_URL_EMPTY': 'WebdocumentUrlEmpty', 'WEBDOCUMENT_URL_INVALID': 'WebdocumentUrlInvalid', 'WEBPAGE_CURL_FAILED': 'WebpageCurlFailed', 'WEBPAGE_MEDIA_EMPTY': 'WebpageMediaEmpty', 'YOU_BLOCKED_USER': 'YouBlockedUser'}, 403: {'_': 'Forbidden', 'BROADCAST_FORBIDDEN': 'BroadcastForbidden', 'CHANNEL_PUBLIC_GROUP_NA': 'ChannelPublicGroupNa', 'CHAT_ADMIN_INVITE_REQUIRED': 'ChatAdminInviteRequired', 'CHAT_ADMIN_REQUIRED': 'ChatAdminRequired', 'CHAT_FORBIDDEN': 'ChatForbidden', 'CHAT_SEND_GIFS_FORBIDDEN': 'ChatSendGifsForbidden', 'CHAT_SEND_INLINE_FORBIDDEN': 'ChatSendInlineForbidden', 'CHAT_SEND_MEDIA_FORBIDDEN': 'ChatSendMediaForbidden', 'CHAT_SEND_POLL_FORBIDDEN': 'ChatSendPollForbidden', 'CHAT_SEND_STICKERS_FORBIDDEN': 'ChatSendStickersForbidden', 'CHAT_WRITE_FORBIDDEN': 'ChatWriteForbidden', 'INLINE_BOT_REQUIRED': 'InlineBotRequired', 'MESSAGE_AUTHOR_REQUIRED': 'MessageAuthorRequired', 'MESSAGE_DELETE_FORBIDDEN': 'MessageDeleteForbidden', 'POLL_VOTE_REQUIRED': 'PollVoteRequired', 'RIGHT_FORBIDDEN': 'RightForbidden', 'SENSITIVE_CHANGE_FORBIDDEN': 'SensitiveChangeForbidden', 'TAKEOUT_REQUIRED': 'TakeoutRequired', 'USER_BOT_INVALID': 'UserBotInvalid', 'USER_CHANNELS_TOO_MUCH': 'UserChannelsTooMuch', 'USER_INVALID': 'UserInvalid', 'USER_IS_BLOCKED': 'UserIsBlocked', 'USER_NOT_MUTUAL_CONTACT': 'UserNotMutualContact', 'USER_PRIVACY_RESTRICTED': 'UserPrivacyRestricted', 'USER_RESTRICTED': 'UserRestricted'}, 401: {'_': 'Unauthorized', 'ACTIVE_USER_REQUIRED': 'ActiveUserRequired', 'AUTH_KEY_INVALID': 'AuthKeyInvalid', 'AUTH_KEY_PERM_EMPTY': 'AuthKeyPermEmpty', 'AUTH_KEY_UNREGISTERED': 'AuthKeyUnregistered', 'SESSION_EXPIRED': 'SessionExpired', 'SESSION_PASSWORD_NEEDED': 'SessionPasswordNeeded', 'SESSION_REVOKED': 'SessionRevoked', 'USER_DEACTIVATED': 'UserDeactivated', 'USER_DEACTIVATED_BAN': 'UserDeactivatedBan'}, 420: {'_': 'Flood', 'FLOOD_TEST_PHONE_WAIT_X': 'FloodTestPhoneWait', 'FLOOD_WAIT_X': 'FloodWait', 'SLOWMODE_WAIT_X': 'SlowmodeWait', 'TAKEOUT_INIT_DELAY_X': 'TakeoutInitDelay'}, 303: {'_': 'SeeOther', 'FILE_MIGRATE_X': 'FileMigrate', 'NETWORK_MIGRATE_X': 'NetworkMigrate', 'PHONE_MIGRATE_X': 'PhoneMigrate', 'STATS_MIGRATE_X': 'StatsMigrate', 'USER_MIGRATE_X': 'UserMigrate'}}
class Node: def __init__(self,name): self.name = name self.left = None self.right = None self.visit = False def insert(self, name): if name < self.name: if self.left is None: self.left = Node(name) else: self.left.insert(name) elif name > self.name: if self.right is None: self.right = Node(name) else: self.right.insert(name) def visit(node): node.visit = True def in_order_traversal(node): if node != None: in_order_traversal(node.left) visit(node) in_order_traversal(node.right) def pre_order_traversal(node): if node != None: visit(node) pre_order_traversal(node.left) pre_order_traversal(node.right) def post_order_traversal(node): if node != None: pre_order_traversal(node.left) pre_order_traversal(node.right) visit(node)
class Node: def __init__(self, name): self.name = name self.left = None self.right = None self.visit = False def insert(self, name): if name < self.name: if self.left is None: self.left = node(name) else: self.left.insert(name) elif name > self.name: if self.right is None: self.right = node(name) else: self.right.insert(name) def visit(node): node.visit = True def in_order_traversal(node): if node != None: in_order_traversal(node.left) visit(node) in_order_traversal(node.right) def pre_order_traversal(node): if node != None: visit(node) pre_order_traversal(node.left) pre_order_traversal(node.right) def post_order_traversal(node): if node != None: pre_order_traversal(node.left) pre_order_traversal(node.right) visit(node)
# fixed constants WEIERSTRASS = 0 EDWARDS = 1 MONTGOMERY = 2 D_TYPE = 0 M_TYPE = 1 NEGATIVEX = 0 POSITIVEX = 1 BN = 0 BLS = 1 ECDH_INVALID_PUBLIC_KEY = -2 ECDH_ERROR = -3
weierstrass = 0 edwards = 1 montgomery = 2 d_type = 0 m_type = 1 negativex = 0 positivex = 1 bn = 0 bls = 1 ecdh_invalid_public_key = -2 ecdh_error = -3
def actuator_add(type='', name="", object=""): '''Add an actuator to the active object :param type: Type, Type of actuator to add :type type: enum in [], (optional) :param name: Name, Name of the Actuator to add :type name: string, (optional, never None) :param object: Object, Name of the Object to add the Actuator to :type object: string, (optional, never None) ''' pass def actuator_move(actuator="", object="", direction='UP'): '''Move Actuator :param actuator: Actuator, Name of the actuator to edit :type actuator: string, (optional, never None) :param object: Object, Name of the object the actuator belongs to :type object: string, (optional, never None) :param direction: Direction, Move Up or Down :type direction: enum in ['UP', 'DOWN'], (optional) ''' pass def actuator_remove(actuator="", object=""): '''Remove an actuator from the active object :param actuator: Actuator, Name of the actuator to edit :type actuator: string, (optional, never None) :param object: Object, Name of the object the actuator belongs to :type object: string, (optional, never None) ''' pass def controller_add(type='LOGIC_AND', name="", object=""): '''Add a controller to the active object :param type: Type, Type of controller to addLOGIC_AND And, Logic And.LOGIC_OR Or, Logic Or.LOGIC_NAND Nand, Logic Nand.LOGIC_NOR Nor, Logic Nor.LOGIC_XOR Xor, Logic Xor.LOGIC_XNOR Xnor, Logic Xnor.EXPRESSION Expression.PYTHON Python. :type type: enum in ['LOGIC_AND', 'LOGIC_OR', 'LOGIC_NAND', 'LOGIC_NOR', 'LOGIC_XOR', 'LOGIC_XNOR', 'EXPRESSION', 'PYTHON'], (optional) :param name: Name, Name of the Controller to add :type name: string, (optional, never None) :param object: Object, Name of the Object to add the Controller to :type object: string, (optional, never None) ''' pass def controller_move(controller="", object="", direction='UP'): '''Move Controller :param controller: Controller, Name of the controller to edit :type controller: string, (optional, never None) :param object: Object, Name of the object the controller belongs to :type object: string, (optional, never None) :param direction: Direction, Move Up or Down :type direction: enum in ['UP', 'DOWN'], (optional) ''' pass def controller_remove(controller="", object=""): '''Remove a controller from the active object :param controller: Controller, Name of the controller to edit :type controller: string, (optional, never None) :param object: Object, Name of the object the controller belongs to :type object: string, (optional, never None) ''' pass def links_cut(path=None, cursor=9): '''Remove logic brick connections :param path: path :type path: bpy_prop_collection of OperatorMousePath, (optional) :param cursor: Cursor :type cursor: int in [0, inf], (optional) ''' pass def properties(): '''Toggle the properties region visibility ''' pass def sensor_add(type='', name="", object=""): '''Add a sensor to the active object :param type: Type, Type of sensor to add :type type: enum in [], (optional) :param name: Name, Name of the Sensor to add :type name: string, (optional, never None) :param object: Object, Name of the Object to add the Sensor to :type object: string, (optional, never None) ''' pass def sensor_move(sensor="", object="", direction='UP'): '''Move Sensor :param sensor: Sensor, Name of the sensor to edit :type sensor: string, (optional, never None) :param object: Object, Name of the object the sensor belongs to :type object: string, (optional, never None) :param direction: Direction, Move Up or Down :type direction: enum in ['UP', 'DOWN'], (optional) ''' pass def sensor_remove(sensor="", object=""): '''Remove a sensor from the active object :param sensor: Sensor, Name of the sensor to edit :type sensor: string, (optional, never None) :param object: Object, Name of the object the sensor belongs to :type object: string, (optional, never None) ''' pass def view_all(): '''Resize view so you can see all logic bricks ''' pass
def actuator_add(type='', name='', object=''): """Add an actuator to the active object :param type: Type, Type of actuator to add :type type: enum in [], (optional) :param name: Name, Name of the Actuator to add :type name: string, (optional, never None) :param object: Object, Name of the Object to add the Actuator to :type object: string, (optional, never None) """ pass def actuator_move(actuator='', object='', direction='UP'): """Move Actuator :param actuator: Actuator, Name of the actuator to edit :type actuator: string, (optional, never None) :param object: Object, Name of the object the actuator belongs to :type object: string, (optional, never None) :param direction: Direction, Move Up or Down :type direction: enum in ['UP', 'DOWN'], (optional) """ pass def actuator_remove(actuator='', object=''): """Remove an actuator from the active object :param actuator: Actuator, Name of the actuator to edit :type actuator: string, (optional, never None) :param object: Object, Name of the object the actuator belongs to :type object: string, (optional, never None) """ pass def controller_add(type='LOGIC_AND', name='', object=''): """Add a controller to the active object :param type: Type, Type of controller to addLOGIC_AND And, Logic And.LOGIC_OR Or, Logic Or.LOGIC_NAND Nand, Logic Nand.LOGIC_NOR Nor, Logic Nor.LOGIC_XOR Xor, Logic Xor.LOGIC_XNOR Xnor, Logic Xnor.EXPRESSION Expression.PYTHON Python. :type type: enum in ['LOGIC_AND', 'LOGIC_OR', 'LOGIC_NAND', 'LOGIC_NOR', 'LOGIC_XOR', 'LOGIC_XNOR', 'EXPRESSION', 'PYTHON'], (optional) :param name: Name, Name of the Controller to add :type name: string, (optional, never None) :param object: Object, Name of the Object to add the Controller to :type object: string, (optional, never None) """ pass def controller_move(controller='', object='', direction='UP'): """Move Controller :param controller: Controller, Name of the controller to edit :type controller: string, (optional, never None) :param object: Object, Name of the object the controller belongs to :type object: string, (optional, never None) :param direction: Direction, Move Up or Down :type direction: enum in ['UP', 'DOWN'], (optional) """ pass def controller_remove(controller='', object=''): """Remove a controller from the active object :param controller: Controller, Name of the controller to edit :type controller: string, (optional, never None) :param object: Object, Name of the object the controller belongs to :type object: string, (optional, never None) """ pass def links_cut(path=None, cursor=9): """Remove logic brick connections :param path: path :type path: bpy_prop_collection of OperatorMousePath, (optional) :param cursor: Cursor :type cursor: int in [0, inf], (optional) """ pass def properties(): """Toggle the properties region visibility """ pass def sensor_add(type='', name='', object=''): """Add a sensor to the active object :param type: Type, Type of sensor to add :type type: enum in [], (optional) :param name: Name, Name of the Sensor to add :type name: string, (optional, never None) :param object: Object, Name of the Object to add the Sensor to :type object: string, (optional, never None) """ pass def sensor_move(sensor='', object='', direction='UP'): """Move Sensor :param sensor: Sensor, Name of the sensor to edit :type sensor: string, (optional, never None) :param object: Object, Name of the object the sensor belongs to :type object: string, (optional, never None) :param direction: Direction, Move Up or Down :type direction: enum in ['UP', 'DOWN'], (optional) """ pass def sensor_remove(sensor='', object=''): """Remove a sensor from the active object :param sensor: Sensor, Name of the sensor to edit :type sensor: string, (optional, never None) :param object: Object, Name of the object the sensor belongs to :type object: string, (optional, never None) """ pass def view_all(): """Resize view so you can see all logic bricks """ pass
def xoppy_calc_black_body(TITLE="Thermal source: Planck distribution",TEMPERATURE=1200000.0,E_MIN=10.0,E_MAX=1000.0,NPOINTS=500): print("Inside xoppy_calc_black_body. ") return(None) def xoppy_calc_mlayer(MODE=0,SCAN=0,F12_FLAG=0,SUBSTRATE="Si",ODD_MATERIAL="Si",EVEN_MATERIAL="W",ENERGY=8050.0,THETA=0.0,SCAN_STEP=0.009999999776483,NPOINTS=600,ODD_THICKNESS=25.0,EVEN_THICKNESS=25.0,NLAYERS=50,FILE="layers.dat"): print("Inside xoppy_calc_mlayer. ") return(None) def xoppy_calc_nsources(TEMPERATURE=300.0,ZONE=0,MAXFLUX_F=200000000000000.0,MAXFLUX_EPI=20000000000000.0,MAXFLUX_TH=200000000000000.0,NPOINTS=500): print("Inside xoppy_calc_nsources. ") return(None) def xoppy_calc_ws(TITLE="Wiggler A at APS",ENERGY=7.0,CUR=100.0,PERIOD=8.5,N=28.0,KX=0.0,KY=8.739999771118164,EMIN=1000.0,EMAX=100000.0,NEE=2000,D=30.0,XPC=0.0,YPC=0.0,XPS=2.0,YPS=2.0,NXP=10,NYP=10): print("Inside xoppy_calc_ws. ") return(None) def xoppy_calc_xtubes(ITUBE=0,VOLTAGE=30.0): print("Inside xoppy_calc_xtubes. ") return(None) def xoppy_calc_xtube_w(VOLTAGE=100.0,RIPPLE=0.0,AL_FILTER=0.0): print("Inside xoppy_calc_xtube_w. ") return(None) def xoppy_calc_xinpro(CRYSTAL_MATERIAL=0,MODE=0,ENERGY=8000.0,MILLER_INDEX_H=1,MILLER_INDEX_K=1,MILLER_INDEX_L=1,ASYMMETRY_ANGLE=0.0,THICKNESS=500.0,TEMPERATURE=300.0,NPOINTS=100,SCALE=0,XFROM=-50.0,XTO=50.0): print("Inside xoppy_calc_xinpro. ") return(None) def xoppy_calc_xcrystal(FILEF0=0,FILEF1F2=0,FILECROSSSEC=0,CRYSTAL_MATERIAL=0,MILLER_INDEX_H=1,MILLER_INDEX_K=1,MILLER_INDEX_L=1,I_ABSORP=2,TEMPER="1.0",MOSAIC=0,GEOMETRY=0,SCAN=2,UNIT=1,SCANFROM=-100.0,SCANTO=100.0,SCANPOINTS=200,ENERGY=8000.0,ASYMMETRY_ANGLE=0.0,THICKNESS=0.7,MOSAIC_FWHM=0.1,RSAG=125.0,RMER=1290.0,ANISOTROPY=0,POISSON=0.22,CUT="2 -1 -1 ; 1 1 1 ; 0 0 0",FILECOMPLIANCE="mycompliance.dat"): print("Inside xoppy_calc_xcrystal. ") return(None) def xoppy_calc_xwiggler(FIELD=0,NPERIODS=12,ULAMBDA=0.125,K=14.0,ENERGY=6.04,PHOT_ENERGY_MIN=100.0,PHOT_ENERGY_MAX=100100.0,NPOINTS=100,LOGPLOT=1,NTRAJPOINTS=101,CURRENT=200.0,FILE="?"): print("Inside xoppy_calc_xwiggler. ") return(None) def xoppy_calc_xxcom(NAME="Pyrex Glass",SUBSTANCE=3,DESCRIPTION="SiO2:B2O3:Na2O:Al2O3:K2O",FRACTION="0.807:0.129:0.038:0.022:0.004",GRID=1,GRIDINPUT=0,GRIDDATA="0.0804:0.2790:0.6616:1.3685:2.7541",ELEMENTOUTPUT=0): print("Inside xoppy_calc_xxcom. ") return(None) def xoppy_calc_xpower(F1F2=0,MU=0,SOURCE=1,DUMMY1="",DUMMY2="",DUMMY3="",ENER_MIN=1000.0,ENER_MAX=50000.0,ENER_N=100,SOURCE_FILE="?",NELEMENTS=1,EL1_FOR="Be",EL1_FLAG=0,EL1_THI=0.5,EL1_ANG=3.0,EL1_ROU=0.0,EL1_DEN="?",EL2_FOR="Rh",EL2_FLAG=1,EL2_THI=0.5,EL2_ANG=3.0,EL2_ROU=0.0,EL2_DEN="?",EL3_FOR="Al",EL3_FLAG=0,EL3_THI=0.5,EL3_ANG=3.0,EL3_ROU=0.0,EL3_DEN="?",EL4_FOR="B",EL4_FLAG=0,EL4_THI=0.5,EL4_ANG=3.0,EL4_ROU=0.0,EL4_DEN="?",EL5_FOR="Pt",EL5_FLAG=1,EL5_THI=0.5,EL5_ANG=3.0,EL5_ROU=0.0,EL5_DEN="?"): print("Inside xoppy_calc_xpower. ") return(None) def xoppy_calc_xbfield(PERIOD=4.0,NPER=42,NPTS=40,IMAGNET=0,ITYPE=0,K=1.379999995231628,GAP=2.0,GAPTAP=10.0,FILE="undul.bf"): print("Inside xoppy_calc_xbfield. ") return(None) def xoppy_calc_xfilter(EMPTY1=" ",EMPTY2=" ",NELEMENTS=1,SOURCE=0,ENER_MIN=1000.0,ENER_MAX=50000.0,ENER_N=100,SOURCE_FILE="SRCOMPW",EL1_SYM="Be",EL1_THI=500.0,EL2_SYM="Al",EL2_THI=50.0,EL3_SYM="Pt",EL3_THI=10.0,EL4_SYM="Au",EL4_THI=10.0,EL5_SYM="Cu",EL5_THI=10.0): print("Inside xoppy_calc_xfilter. ") return(None) def xoppy_calc_xtc(TITLE="APS Undulator A, Beam Parameters for regular lattice nux36nuy39.twi, 1.5% cpl.",ENERGY=7.0,CUR=100.0,SIGE=0.000959999975748,TEXT_MACHINE="",SIGX=0.273999989032745,SIGY=0.010999999940395,SIGX1=0.011300000362098,SIGY1=0.00359999993816,TEXT_BEAM="",PERIOD=3.299999952316284,NP=70,TEXT_UNDULATOR="",EMIN=2950.0,EMAX=13500.0,N=40,TEXT_ENERGY="",IHMIN=1,IHMAX=15,IHSTEP=2,TEXT_HARM="",IHEL=0,METHOD=1,IK=1,NEKS=100,TEXT_PARM="",RUN_MODE_NAME="foreground"): print("Inside xoppy_calc_xtc. ") return(None) def xoppy_calc_xus(TITLE="APS Undulator A, Beam Parameters for regular lattice nux36nuy39.twi, 1.5% cpl.",ENERGY=7.0,CUR=100.0,SIGE=0.000959999975748,TEXT_MACHINE="",SIGX=0.273999989032745,SIGY=0.010999999940395,SIGX1=0.011300000362098,SIGY1=0.00359999993816,TEXT_BEAM="",PERIOD=3.299999952316284,NP=70,KX=0.0,KY=2.75,TEXT_UNDULATOR="",EMIN=1000.0,EMAX=50000.0,N=5000,TEXT_ENERGY="",D=30.0,XPC=0.0,YPC=0.0,XPS=2.5,YPS=1.0,NXP=25,NYP=10,TEXT_PINHOLE="",MODE=2,METHOD=4,IHARM=0,TEXT_MODE="",NPHI=0,NALPHA=0,CALPHA2=0.0,NOMEGA=64,COMEGA=8.0,NSIGMA=0,TEXT_CALC="",RUN_MODE_NAME="foreground"): print("Inside xoppy_calc_xus. ") return(None) def xoppy_calc_xurgent(TITLE="ESRF HIGH BETA UNDULATOR",ENERGY=6.039999961853027,CUR=0.100000001490116,SIGX=0.400000005960464,SIGY=0.079999998211861,SIGX1=0.016000000759959,SIGY1=0.00899999961257,ITYPE=1,PERIOD=0.046000000089407,N=32,KX=0.0,KY=1.700000047683716,PHASE=0.0,EMIN=10000.0,EMAX=50000.0,NENERGY=100,D=27.0,XPC=0.0,YPC=0.0,XPS=3.0,YPS=3.0,NXP=25,NYP=25,MODE=4,ICALC=2,IHARM=-1,NPHI=0,NSIG=0,NALPHA=0,DALPHA=0.0,NOMEGA=0,DOMEGA=0.0): print("Inside xoppy_calc_xurgent. ") return(None) def xoppy_calc_xyaup(TITLE="YAUP EXAMPLE (ESRF BL-8)",PERIOD=4.0,NPER=42,NPTS=40,EMIN=3000.0,EMAX=30000.0,NENERGY=100,ENERGY=6.039999961853027,CUR=0.100000001490116,SIGX=0.425999999046326,SIGY=0.08500000089407,SIGX1=0.017000000923872,SIGY1=0.008500000461936,D=30.0,XPC=0.0,YPC=0.0,XPS=2.0,YPS=2.0,NXP=0,NYP=0,MODE=4,NSIG=2,TRAJECTORY="new+keep",XSYM="yes",HANNING=0,BFILE="undul.bf",TFILE="undul.traj"): print("Inside xoppy_calc_xyaup. ") return(None) def xoppy_calc_xf0(DATASETS=0,MAT_FLAG=0,MAT_LIST=0,DESCRIPTOR="Si",GRID=0,GRIDSTART=0.0,GRIDEND=4.0,GRIDN=100): print("Inside xoppy_calc_xf0. ") return(None) def xoppy_calc_xcrosssec(DATASETS=1,MAT_FLAG=0,MAT_LIST=0,DESCRIPTOR="Si",DENSITY=1.0,CALCULATE="all",GRID=0,GRIDSTART=100.0,GRIDEND=10000.0,GRIDN=200,UNIT=0): print("Inside xoppy_calc_xcrosssec. ") return(None) def xoppy_calc_xf1f2(DATASETS=1,MAT_FLAG=0,MAT_LIST=0,DESCRIPTOR="Si",DENSITY=1.0,CALCULATE=1,GRID=0,GRIDSTART=5000.0,GRIDEND=25000.0,GRIDN=100,THETAGRID=0,ROUGH=0.0,THETA1=2.0,THETA2=5.0,THETAN=50): print("Inside xoppy_calc_xf1f2. ") return(None) def xoppy_calc_xfh(FILEF0=0,FILEF1F2=0,FILECROSSSEC=0,ILATTICE=0,HMILLER=1,KMILLER=1,LMILLER=1,I_ABSORP=2,TEMPER="1.0",ENERGY=8000.0,ENERGY_END=18000.0,NPOINTS=20): print("Inside xoppy_calc_xfh. ") return(None) def xoppy_calc_mare(CRYSTAL=2,H=2,K=2,L=2,HMAX=3,KMAX=3,LMAX=3,FHEDGE=1e-08,DISPLAY=0,LAMBDA=1.54,DELTALAMBDA=0.009999999776483,PHI=-20.0,DELTAPHI=0.1): print("Inside xoppy_calc_mare. ") return(None) def xoppy_calc_bm(TYPE_CALC=0,MACHINE_NAME="ESRF bending magnet",RB_CHOICE=0,MACHINE_R_M=25.0,BFIELD_T=0.8,BEAM_ENERGY_GEV=6.0,CURRENT_A=0.1,HOR_DIV_MRAD=1.0,VER_DIV=0,PHOT_ENERGY_MIN=100.0,PHOT_ENERGY_MAX=100000.0,NPOINTS=500,LOG_CHOICE=1,PSI_MRAD_PLOT=1.0,PSI_MIN=-1.0,PSI_MAX=1.0,PSI_NPOINTS=500): print("Inside xoppy_calc_bm. ") return(None)
def xoppy_calc_black_body(TITLE='Thermal source: Planck distribution', TEMPERATURE=1200000.0, E_MIN=10.0, E_MAX=1000.0, NPOINTS=500): print('Inside xoppy_calc_black_body. ') return None def xoppy_calc_mlayer(MODE=0, SCAN=0, F12_FLAG=0, SUBSTRATE='Si', ODD_MATERIAL='Si', EVEN_MATERIAL='W', ENERGY=8050.0, THETA=0.0, SCAN_STEP=0.009999999776483, NPOINTS=600, ODD_THICKNESS=25.0, EVEN_THICKNESS=25.0, NLAYERS=50, FILE='layers.dat'): print('Inside xoppy_calc_mlayer. ') return None def xoppy_calc_nsources(TEMPERATURE=300.0, ZONE=0, MAXFLUX_F=200000000000000.0, MAXFLUX_EPI=20000000000000.0, MAXFLUX_TH=200000000000000.0, NPOINTS=500): print('Inside xoppy_calc_nsources. ') return None def xoppy_calc_ws(TITLE='Wiggler A at APS', ENERGY=7.0, CUR=100.0, PERIOD=8.5, N=28.0, KX=0.0, KY=8.739999771118164, EMIN=1000.0, EMAX=100000.0, NEE=2000, D=30.0, XPC=0.0, YPC=0.0, XPS=2.0, YPS=2.0, NXP=10, NYP=10): print('Inside xoppy_calc_ws. ') return None def xoppy_calc_xtubes(ITUBE=0, VOLTAGE=30.0): print('Inside xoppy_calc_xtubes. ') return None def xoppy_calc_xtube_w(VOLTAGE=100.0, RIPPLE=0.0, AL_FILTER=0.0): print('Inside xoppy_calc_xtube_w. ') return None def xoppy_calc_xinpro(CRYSTAL_MATERIAL=0, MODE=0, ENERGY=8000.0, MILLER_INDEX_H=1, MILLER_INDEX_K=1, MILLER_INDEX_L=1, ASYMMETRY_ANGLE=0.0, THICKNESS=500.0, TEMPERATURE=300.0, NPOINTS=100, SCALE=0, XFROM=-50.0, XTO=50.0): print('Inside xoppy_calc_xinpro. ') return None def xoppy_calc_xcrystal(FILEF0=0, FILEF1F2=0, FILECROSSSEC=0, CRYSTAL_MATERIAL=0, MILLER_INDEX_H=1, MILLER_INDEX_K=1, MILLER_INDEX_L=1, I_ABSORP=2, TEMPER='1.0', MOSAIC=0, GEOMETRY=0, SCAN=2, UNIT=1, SCANFROM=-100.0, SCANTO=100.0, SCANPOINTS=200, ENERGY=8000.0, ASYMMETRY_ANGLE=0.0, THICKNESS=0.7, MOSAIC_FWHM=0.1, RSAG=125.0, RMER=1290.0, ANISOTROPY=0, POISSON=0.22, CUT='2 -1 -1 ; 1 1 1 ; 0 0 0', FILECOMPLIANCE='mycompliance.dat'): print('Inside xoppy_calc_xcrystal. ') return None def xoppy_calc_xwiggler(FIELD=0, NPERIODS=12, ULAMBDA=0.125, K=14.0, ENERGY=6.04, PHOT_ENERGY_MIN=100.0, PHOT_ENERGY_MAX=100100.0, NPOINTS=100, LOGPLOT=1, NTRAJPOINTS=101, CURRENT=200.0, FILE='?'): print('Inside xoppy_calc_xwiggler. ') return None def xoppy_calc_xxcom(NAME='Pyrex Glass', SUBSTANCE=3, DESCRIPTION='SiO2:B2O3:Na2O:Al2O3:K2O', FRACTION='0.807:0.129:0.038:0.022:0.004', GRID=1, GRIDINPUT=0, GRIDDATA='0.0804:0.2790:0.6616:1.3685:2.7541', ELEMENTOUTPUT=0): print('Inside xoppy_calc_xxcom. ') return None def xoppy_calc_xpower(F1F2=0, MU=0, SOURCE=1, DUMMY1='', DUMMY2='', DUMMY3='', ENER_MIN=1000.0, ENER_MAX=50000.0, ENER_N=100, SOURCE_FILE='?', NELEMENTS=1, EL1_FOR='Be', EL1_FLAG=0, EL1_THI=0.5, EL1_ANG=3.0, EL1_ROU=0.0, EL1_DEN='?', EL2_FOR='Rh', EL2_FLAG=1, EL2_THI=0.5, EL2_ANG=3.0, EL2_ROU=0.0, EL2_DEN='?', EL3_FOR='Al', EL3_FLAG=0, EL3_THI=0.5, EL3_ANG=3.0, EL3_ROU=0.0, EL3_DEN='?', EL4_FOR='B', EL4_FLAG=0, EL4_THI=0.5, EL4_ANG=3.0, EL4_ROU=0.0, EL4_DEN='?', EL5_FOR='Pt', EL5_FLAG=1, EL5_THI=0.5, EL5_ANG=3.0, EL5_ROU=0.0, EL5_DEN='?'): print('Inside xoppy_calc_xpower. ') return None def xoppy_calc_xbfield(PERIOD=4.0, NPER=42, NPTS=40, IMAGNET=0, ITYPE=0, K=1.379999995231628, GAP=2.0, GAPTAP=10.0, FILE='undul.bf'): print('Inside xoppy_calc_xbfield. ') return None def xoppy_calc_xfilter(EMPTY1=' ', EMPTY2=' ', NELEMENTS=1, SOURCE=0, ENER_MIN=1000.0, ENER_MAX=50000.0, ENER_N=100, SOURCE_FILE='SRCOMPW', EL1_SYM='Be', EL1_THI=500.0, EL2_SYM='Al', EL2_THI=50.0, EL3_SYM='Pt', EL3_THI=10.0, EL4_SYM='Au', EL4_THI=10.0, EL5_SYM='Cu', EL5_THI=10.0): print('Inside xoppy_calc_xfilter. ') return None def xoppy_calc_xtc(TITLE='APS Undulator A, Beam Parameters for regular lattice nux36nuy39.twi, 1.5% cpl.', ENERGY=7.0, CUR=100.0, SIGE=0.000959999975748, TEXT_MACHINE='', SIGX=0.273999989032745, SIGY=0.010999999940395, SIGX1=0.011300000362098, SIGY1=0.00359999993816, TEXT_BEAM='', PERIOD=3.299999952316284, NP=70, TEXT_UNDULATOR='', EMIN=2950.0, EMAX=13500.0, N=40, TEXT_ENERGY='', IHMIN=1, IHMAX=15, IHSTEP=2, TEXT_HARM='', IHEL=0, METHOD=1, IK=1, NEKS=100, TEXT_PARM='', RUN_MODE_NAME='foreground'): print('Inside xoppy_calc_xtc. ') return None def xoppy_calc_xus(TITLE='APS Undulator A, Beam Parameters for regular lattice nux36nuy39.twi, 1.5% cpl.', ENERGY=7.0, CUR=100.0, SIGE=0.000959999975748, TEXT_MACHINE='', SIGX=0.273999989032745, SIGY=0.010999999940395, SIGX1=0.011300000362098, SIGY1=0.00359999993816, TEXT_BEAM='', PERIOD=3.299999952316284, NP=70, KX=0.0, KY=2.75, TEXT_UNDULATOR='', EMIN=1000.0, EMAX=50000.0, N=5000, TEXT_ENERGY='', D=30.0, XPC=0.0, YPC=0.0, XPS=2.5, YPS=1.0, NXP=25, NYP=10, TEXT_PINHOLE='', MODE=2, METHOD=4, IHARM=0, TEXT_MODE='', NPHI=0, NALPHA=0, CALPHA2=0.0, NOMEGA=64, COMEGA=8.0, NSIGMA=0, TEXT_CALC='', RUN_MODE_NAME='foreground'): print('Inside xoppy_calc_xus. ') return None def xoppy_calc_xurgent(TITLE='ESRF HIGH BETA UNDULATOR', ENERGY=6.039999961853027, CUR=0.100000001490116, SIGX=0.400000005960464, SIGY=0.079999998211861, SIGX1=0.016000000759959, SIGY1=0.00899999961257, ITYPE=1, PERIOD=0.046000000089407, N=32, KX=0.0, KY=1.700000047683716, PHASE=0.0, EMIN=10000.0, EMAX=50000.0, NENERGY=100, D=27.0, XPC=0.0, YPC=0.0, XPS=3.0, YPS=3.0, NXP=25, NYP=25, MODE=4, ICALC=2, IHARM=-1, NPHI=0, NSIG=0, NALPHA=0, DALPHA=0.0, NOMEGA=0, DOMEGA=0.0): print('Inside xoppy_calc_xurgent. ') return None def xoppy_calc_xyaup(TITLE='YAUP EXAMPLE (ESRF BL-8)', PERIOD=4.0, NPER=42, NPTS=40, EMIN=3000.0, EMAX=30000.0, NENERGY=100, ENERGY=6.039999961853027, CUR=0.100000001490116, SIGX=0.425999999046326, SIGY=0.08500000089407, SIGX1=0.017000000923872, SIGY1=0.008500000461936, D=30.0, XPC=0.0, YPC=0.0, XPS=2.0, YPS=2.0, NXP=0, NYP=0, MODE=4, NSIG=2, TRAJECTORY='new+keep', XSYM='yes', HANNING=0, BFILE='undul.bf', TFILE='undul.traj'): print('Inside xoppy_calc_xyaup. ') return None def xoppy_calc_xf0(DATASETS=0, MAT_FLAG=0, MAT_LIST=0, DESCRIPTOR='Si', GRID=0, GRIDSTART=0.0, GRIDEND=4.0, GRIDN=100): print('Inside xoppy_calc_xf0. ') return None def xoppy_calc_xcrosssec(DATASETS=1, MAT_FLAG=0, MAT_LIST=0, DESCRIPTOR='Si', DENSITY=1.0, CALCULATE='all', GRID=0, GRIDSTART=100.0, GRIDEND=10000.0, GRIDN=200, UNIT=0): print('Inside xoppy_calc_xcrosssec. ') return None def xoppy_calc_xf1f2(DATASETS=1, MAT_FLAG=0, MAT_LIST=0, DESCRIPTOR='Si', DENSITY=1.0, CALCULATE=1, GRID=0, GRIDSTART=5000.0, GRIDEND=25000.0, GRIDN=100, THETAGRID=0, ROUGH=0.0, THETA1=2.0, THETA2=5.0, THETAN=50): print('Inside xoppy_calc_xf1f2. ') return None def xoppy_calc_xfh(FILEF0=0, FILEF1F2=0, FILECROSSSEC=0, ILATTICE=0, HMILLER=1, KMILLER=1, LMILLER=1, I_ABSORP=2, TEMPER='1.0', ENERGY=8000.0, ENERGY_END=18000.0, NPOINTS=20): print('Inside xoppy_calc_xfh. ') return None def xoppy_calc_mare(CRYSTAL=2, H=2, K=2, L=2, HMAX=3, KMAX=3, LMAX=3, FHEDGE=1e-08, DISPLAY=0, LAMBDA=1.54, DELTALAMBDA=0.009999999776483, PHI=-20.0, DELTAPHI=0.1): print('Inside xoppy_calc_mare. ') return None def xoppy_calc_bm(TYPE_CALC=0, MACHINE_NAME='ESRF bending magnet', RB_CHOICE=0, MACHINE_R_M=25.0, BFIELD_T=0.8, BEAM_ENERGY_GEV=6.0, CURRENT_A=0.1, HOR_DIV_MRAD=1.0, VER_DIV=0, PHOT_ENERGY_MIN=100.0, PHOT_ENERGY_MAX=100000.0, NPOINTS=500, LOG_CHOICE=1, PSI_MRAD_PLOT=1.0, PSI_MIN=-1.0, PSI_MAX=1.0, PSI_NPOINTS=500): print('Inside xoppy_calc_bm. ') return None
SS array = [1,1,2,2] array1 = set(array) print(array1) for a in array1: print(a)
SS array = [1, 1, 2, 2] array1 = set(array) print(array1) for a in array1: print(a)
# Humanoid A (2111003) | Magatia (261000000) snowfieldRose = 3335 snowRoseGrows = 926120300 if sm.hasQuest(snowfieldRose): response = sm.sendAskYesNo("Are you ready to grow the Snow Rose?") if response: sm.warpInstanceIn(snowRoseGrows, False) else: sm.sendSayOkay("Remember to bring #bMay Mist#k with you so the Snow Rose can bloom.") else: sm.sendSayOkay("I want to become human. I want to be a human with a warm heart so I can hold her hand. But now...")
snowfield_rose = 3335 snow_rose_grows = 926120300 if sm.hasQuest(snowfieldRose): response = sm.sendAskYesNo('Are you ready to grow the Snow Rose?') if response: sm.warpInstanceIn(snowRoseGrows, False) else: sm.sendSayOkay('Remember to bring #bMay Mist#k with you so the Snow Rose can bloom.') else: sm.sendSayOkay('I want to become human. I want to be a human with a warm heart so I can hold her hand. But now...')
class Algo(object): def generate(self, interface): # TODO: Write algorithm here pass
class Algo(object): def generate(self, interface): pass
class SnakesistError(Exception): """Snakesist base exception class""" pass class SnakesistConfigError(SnakesistError): """Raised if the database connection is improperly configured""" pass class SnakesistReadError(SnakesistError): """Raised if a writing operation fails""" pass class SnakesistNotFound(SnakesistReadError): """Raised if a database resource is not found""" pass class SnakesistWriteError(SnakesistError): """Raised if a reading operation fails""" pass
class Snakesisterror(Exception): """Snakesist base exception class""" pass class Snakesistconfigerror(SnakesistError): """Raised if the database connection is improperly configured""" pass class Snakesistreaderror(SnakesistError): """Raised if a writing operation fails""" pass class Snakesistnotfound(SnakesistReadError): """Raised if a database resource is not found""" pass class Snakesistwriteerror(SnakesistError): """Raised if a reading operation fails""" pass
width = 17 height = 12.0 print(width//2) # should return the quotient print(width/2.0) # should return the quotient in float print(height/3.0) # should return the quotient in float ans = 1 + 2 * 5 # should return 11 print(ans)
width = 17 height = 12.0 print(width // 2) print(width / 2.0) print(height / 3.0) ans = 1 + 2 * 5 print(ans)
""" |||||||||||||||||||||||||||| DECISION THEORY MODEL ||||||||||||||||||||| """ def dt_model_speed_and_distances(self, plot=False, sqrt=True): speed = stats.norm(loc=self.speed_mu, scale=self.speed_sigma) if sqrt: dnoise = math.sqrt(self.distance_noise) else: dnoise = self.distance_noise distances = {a.maze:stats.norm(loc=a[self.ratio], scale=dnoise) for i,a in self.paths_lengths.iterrows()} if plot: f, axarr = create_figure(subplots=True, ncols=2) dist_plot(speed, ax=axarr[0]) for k,v in distances.items(): dist_plot(v, ax=axarr[1], label=k) for ax in axarr: make_legend(ax) return speed, distances def simulate_trials_analytical(self): # Get simulated running speed and path lengths estimates speed, distances = self.dt_model_speed_and_distances(plot=False) # right arm right = distances["maze4"] # Compare each arm to right pR = {k:0 for k in distances.keys()} for left, d in distances.items(): # p(R) = phi(-mu/sigma) and mu=mu_l - mu_r, sigma = sigma_r^2 + sigma_l^2 mu_l, sigma_l = d.mean(), d.std() mu_r, sigma_r = right.mean(), right.std() mu, sigma = mu_l - mu_r, sigma_r**2 + sigma_l**2 pR[left] = round(1 - stats.norm.cdf(-mu/sigma, loc=0, scale=1), 3) return pR def simulate_trials(self, niters=1000): # Get simulated running speed and path lengths estimates speed, distances = self.dt_model_speed_and_distances(plot=False, sqrt=False) # right arm right = distances["maze4"] # Compare each arm to right trials, pR = {k:[] for k in distances.keys()}, {k:0 for k in distances.keys()} for left, d in distances.items(): # simulate n trials for tn in range(niters): # Draw a random length for each arms l, r = d.rvs(), right.rvs() # Draw a random speed and add noise if self.speed_noise > 0: s = speed.rvs() + np.random.normal(0, self.speed_noise, size=1) else: s = speed.rvs() # Calc escape duration on each arma nd keep the fastest # if r/s <= l/s: if r <= l: trials[left].append(1) else: trials[left].append(0) pR[left] = np.mean(trials[left]) return trials, pR def fit_model(self): xp = np.linspace(.8, 1.55, 200) xrange = [.8, 1.55] # Get paths length ratios and p(R) by condition hits, ntrials, p_r, n_mice = self.get_binary_trials_per_condition(self.conditions) # Get modes on individuals posteriors and grouped bayes modes, means, stds = self.get_hb_modes() grouped_modes, grouped_means = self.bayes_by_condition_analytical(mode="grouped", plot=False) # Plot each individual's pR and the group mean as a factor of L/R length ratio f, axarr = create_figure(subplots=True, ncols=2) ax = axarr[1] mseax = axarr[0] lr_ratios_mean_pr = {"grouped":[], "individuals_x":[], "individuals_y":[], "individuals_y_sigma":[]} for i, (condition, pr) in enumerate(p_r.items()): x = self.paths_lengths.loc[self.paths_lengths.maze == condition][self.ratio].values y = means[condition] # ? plot HB PR with errorbars ax.errorbar(x, np.mean(y), yerr=np.std(y), fmt='o', markeredgecolor=self.colors[i+1], markerfacecolor=self.colors[i+1], markersize=15, ecolor=desaturate_color(self.colors[i+1], k=.7), elinewidth=3, capthick=2, alpha=1, zorder=0) def residual(distances, sigma): self.distance_noise = sigma analytical_pr = self.simulate_trials_analytical() return np.sum(np.array(list(analytical_pr.values()))) params = Parameters() params.add("sigma", min=1.e-10, max=.5) model = Model(residual, params=params) params = model.make_params() params["sigma"].min, params["sigma"].max = 1.e-10, 1 ytrue = [np.mean(m) for m in means.values()] x = self.paths_lengths[self.ratio].values result = model.fit(ytrue, distances=x, params=params) # ? Plot best fit # best_sigma = sigma_range[np.argmin(mserr)] best_sigma = result.params["sigma"].value self.distance_noise = best_sigma analytical_pr = self.simulate_trials_analytical() pomp = plot_fitted_curve(sigmoid, self.paths_lengths[self.ratio].values, np.hstack(list(analytical_pr.values())), ax, xrange=xrange, scatter_kwargs={"alpha":0}, line_kwargs={"color":white, "alpha":1, "lw":6, "label":"model pR - $\sigma : {}$".format(round(best_sigma, 2))}) # Fix plotting ortholines(ax, [1, 0,], [1, .5]) ortholines(ax, [0, 0,], [1, 0], ls=":", lw=1, alpha=.3) ax.set(title="best fit logistic regression", ylim=[-0.01, 1.05], ylabel="p(R)", xlabel="Left path length (a.u.)", xticks = self.paths_lengths[self.ratio].values, xticklabels = self.conditions.keys()) make_legend(ax)
""" |||||||||||||||||||||||||||| DECISION THEORY MODEL ||||||||||||||||||||| """ def dt_model_speed_and_distances(self, plot=False, sqrt=True): speed = stats.norm(loc=self.speed_mu, scale=self.speed_sigma) if sqrt: dnoise = math.sqrt(self.distance_noise) else: dnoise = self.distance_noise distances = {a.maze: stats.norm(loc=a[self.ratio], scale=dnoise) for (i, a) in self.paths_lengths.iterrows()} if plot: (f, axarr) = create_figure(subplots=True, ncols=2) dist_plot(speed, ax=axarr[0]) for (k, v) in distances.items(): dist_plot(v, ax=axarr[1], label=k) for ax in axarr: make_legend(ax) return (speed, distances) def simulate_trials_analytical(self): (speed, distances) = self.dt_model_speed_and_distances(plot=False) right = distances['maze4'] p_r = {k: 0 for k in distances.keys()} for (left, d) in distances.items(): (mu_l, sigma_l) = (d.mean(), d.std()) (mu_r, sigma_r) = (right.mean(), right.std()) (mu, sigma) = (mu_l - mu_r, sigma_r ** 2 + sigma_l ** 2) pR[left] = round(1 - stats.norm.cdf(-mu / sigma, loc=0, scale=1), 3) return pR def simulate_trials(self, niters=1000): (speed, distances) = self.dt_model_speed_and_distances(plot=False, sqrt=False) right = distances['maze4'] (trials, p_r) = ({k: [] for k in distances.keys()}, {k: 0 for k in distances.keys()}) for (left, d) in distances.items(): for tn in range(niters): (l, r) = (d.rvs(), right.rvs()) if self.speed_noise > 0: s = speed.rvs() + np.random.normal(0, self.speed_noise, size=1) else: s = speed.rvs() if r <= l: trials[left].append(1) else: trials[left].append(0) pR[left] = np.mean(trials[left]) return (trials, pR) def fit_model(self): xp = np.linspace(0.8, 1.55, 200) xrange = [0.8, 1.55] (hits, ntrials, p_r, n_mice) = self.get_binary_trials_per_condition(self.conditions) (modes, means, stds) = self.get_hb_modes() (grouped_modes, grouped_means) = self.bayes_by_condition_analytical(mode='grouped', plot=False) (f, axarr) = create_figure(subplots=True, ncols=2) ax = axarr[1] mseax = axarr[0] lr_ratios_mean_pr = {'grouped': [], 'individuals_x': [], 'individuals_y': [], 'individuals_y_sigma': []} for (i, (condition, pr)) in enumerate(p_r.items()): x = self.paths_lengths.loc[self.paths_lengths.maze == condition][self.ratio].values y = means[condition] ax.errorbar(x, np.mean(y), yerr=np.std(y), fmt='o', markeredgecolor=self.colors[i + 1], markerfacecolor=self.colors[i + 1], markersize=15, ecolor=desaturate_color(self.colors[i + 1], k=0.7), elinewidth=3, capthick=2, alpha=1, zorder=0) def residual(distances, sigma): self.distance_noise = sigma analytical_pr = self.simulate_trials_analytical() return np.sum(np.array(list(analytical_pr.values()))) params = parameters() params.add('sigma', min=1e-10, max=0.5) model = model(residual, params=params) params = model.make_params() (params['sigma'].min, params['sigma'].max) = (1e-10, 1) ytrue = [np.mean(m) for m in means.values()] x = self.paths_lengths[self.ratio].values result = model.fit(ytrue, distances=x, params=params) best_sigma = result.params['sigma'].value self.distance_noise = best_sigma analytical_pr = self.simulate_trials_analytical() pomp = plot_fitted_curve(sigmoid, self.paths_lengths[self.ratio].values, np.hstack(list(analytical_pr.values())), ax, xrange=xrange, scatter_kwargs={'alpha': 0}, line_kwargs={'color': white, 'alpha': 1, 'lw': 6, 'label': 'model pR - $\\sigma : {}$'.format(round(best_sigma, 2))}) ortholines(ax, [1, 0], [1, 0.5]) ortholines(ax, [0, 0], [1, 0], ls=':', lw=1, alpha=0.3) ax.set(title='best fit logistic regression', ylim=[-0.01, 1.05], ylabel='p(R)', xlabel='Left path length (a.u.)', xticks=self.paths_lengths[self.ratio].values, xticklabels=self.conditions.keys()) make_legend(ax)
# Copyright 2014 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. load("@io_bazel_rules_go//go/private:repositories.bzl", "go_repositories") load("@io_bazel_rules_go//go/private:go_repository.bzl", "go_repository", "new_go_repository") load("@io_bazel_rules_go//go/private:go_prefix.bzl", "go_prefix") load("@io_bazel_rules_go//go/private:library.bzl", "go_library") load("@io_bazel_rules_go//go/private:binary.bzl", "go_binary") load("@io_bazel_rules_go//go/private:test.bzl", "go_test") load("@io_bazel_rules_go//go/private:cgo.bzl", "cgo_library", "cgo_genrule") """These are bare-bones Go rules. In order of priority: - BUILD file must be written by hand. - No support for SWIG - No test sharding or test XML. """
load('@io_bazel_rules_go//go/private:repositories.bzl', 'go_repositories') load('@io_bazel_rules_go//go/private:go_repository.bzl', 'go_repository', 'new_go_repository') load('@io_bazel_rules_go//go/private:go_prefix.bzl', 'go_prefix') load('@io_bazel_rules_go//go/private:library.bzl', 'go_library') load('@io_bazel_rules_go//go/private:binary.bzl', 'go_binary') load('@io_bazel_rules_go//go/private:test.bzl', 'go_test') load('@io_bazel_rules_go//go/private:cgo.bzl', 'cgo_library', 'cgo_genrule') 'These are bare-bones Go rules.\n\nIn order of priority:\n\n- BUILD file must be written by hand.\n\n- No support for SWIG\n\n- No test sharding or test XML.\n\n'
d = {"a": 1, "b": 2, "c": 3} newDict={} for (key,value) in d.items(): if(value<=1): newDict[key]=value # for key,values in d.items(): # if values>1: # d.pop[key] print(newDict)
d = {'a': 1, 'b': 2, 'c': 3} new_dict = {} for (key, value) in d.items(): if value <= 1: newDict[key] = value print(newDict)
__docformat__ = "restructuredtext" __version__ = "0.2.7" __doc__ = """ This<https://github.com/WinVector/wvpy> is a package of example files for teaching data science. """
__docformat__ = 'restructuredtext' __version__ = '0.2.7' __doc__ = '\nThis<https://github.com/WinVector/wvpy> is a package of example files for teaching data science.\n'
#!/usr/bin/env python3 # imports go here # # Free Coding session for 2015-04-02 # Written by Matt Warren # class MyClass(object): def __init__(self): self.meta = self.Meta() class Meta: CONSTANT = 'HELLO' def do_something(self): print(self.meta.CONSTANT) class MySubclass(MyClass): class Meta: CONSTANT = 'MATT IS COOL' if __name__ == '__main__': mc = MyClass() mc.do_something() msc = MySubclass() msc.do_something()
class Myclass(object): def __init__(self): self.meta = self.Meta() class Meta: constant = 'HELLO' def do_something(self): print(self.meta.CONSTANT) class Mysubclass(MyClass): class Meta: constant = 'MATT IS COOL' if __name__ == '__main__': mc = my_class() mc.do_something() msc = my_subclass() msc.do_something()
# coding=utf-8 class Context(object): is_finished = False text = None state = None current_index = 0 is_pair_sign_opened = False has_split_sign = False pair_sign = None back_pair_sign = None token_num = 0 char_num = 0 def __init__(self, text, state, split_signs, pair_signs, soften_split_signs, token_limits=None): self.text = text self.state = state self.current_sentence_builder = [] self.sentences = [] self.split_signs = split_signs self.pair_signs = pair_signs self.soften_split_signs = soften_split_signs self.token_limits = token_limits @property def current_char(self): return self.text[self.current_index] def finish(self): self.is_finished = True def execute(self): while not self.is_finished: self.state.execute(self) def clear_local_state(self): self.current_sentence_builder = [] self.token_num = 0 self.char_num = 0 def is_too_long(self): return (self.token_limits <= self.token_num ) if self.token_limits else False
class Context(object): is_finished = False text = None state = None current_index = 0 is_pair_sign_opened = False has_split_sign = False pair_sign = None back_pair_sign = None token_num = 0 char_num = 0 def __init__(self, text, state, split_signs, pair_signs, soften_split_signs, token_limits=None): self.text = text self.state = state self.current_sentence_builder = [] self.sentences = [] self.split_signs = split_signs self.pair_signs = pair_signs self.soften_split_signs = soften_split_signs self.token_limits = token_limits @property def current_char(self): return self.text[self.current_index] def finish(self): self.is_finished = True def execute(self): while not self.is_finished: self.state.execute(self) def clear_local_state(self): self.current_sentence_builder = [] self.token_num = 0 self.char_num = 0 def is_too_long(self): return self.token_limits <= self.token_num if self.token_limits else False
class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: j=0 for i in range(len(A)): if (A[i]%2)==0: temp = A[i] A[i]=A[j] A[j]=temp j+=1 return A
class Solution: def sort_array_by_parity(self, A: List[int]) -> List[int]: j = 0 for i in range(len(A)): if A[i] % 2 == 0: temp = A[i] A[i] = A[j] A[j] = temp j += 1 return A
def solve(prices, fee): t_i_k_0 = 0 t_i_k_1 = -float('inf') for price in prices: t_i_k_0 = max(t_i_k_0, t_i_k_1 + price - fee) t_i_k_1 = max(t_i_k_1, t_i_k_0 - price) return t_i_k_0 A = [1, 3, 2, 8, 4, 9] B = 2 print(solve(A, B))
def solve(prices, fee): t_i_k_0 = 0 t_i_k_1 = -float('inf') for price in prices: t_i_k_0 = max(t_i_k_0, t_i_k_1 + price - fee) t_i_k_1 = max(t_i_k_1, t_i_k_0 - price) return t_i_k_0 a = [1, 3, 2, 8, 4, 9] b = 2 print(solve(A, B))
class ObjectFactory: '''Generic object factory. Maintains a dictionary of provider objects, which can be created and returned on demand. ''' def __init__(self): self._providers = {} def register_provider(self, key, provider): '''Register a new provider for future use. The `key` value is case- insensitive. `provider` is a callable object which returns an instance of the class associated with `key`. ''' self._providers[key.lower()] = provider def create(self, key, **kwargs): '''Call a provider builder, and return the instance created. The provider builder is determined based on the `key` provided, and it will be called with `**kwargs` passed in to it. ''' provider = self._providers.get(key.lower()) if not provider: raise ValueError(key) return provider(**kwargs)
class Objectfactory: """Generic object factory. Maintains a dictionary of provider objects, which can be created and returned on demand. """ def __init__(self): self._providers = {} def register_provider(self, key, provider): """Register a new provider for future use. The `key` value is case- insensitive. `provider` is a callable object which returns an instance of the class associated with `key`. """ self._providers[key.lower()] = provider def create(self, key, **kwargs): """Call a provider builder, and return the instance created. The provider builder is determined based on the `key` provided, and it will be called with `**kwargs` passed in to it. """ provider = self._providers.get(key.lower()) if not provider: raise value_error(key) return provider(**kwargs)
def test_grade_above_1_is_passing(passing_grade): assert passing_grade.is_passing() is True def test_grade_below_2_is_failing(failing_grade): assert failing_grade.is_passing() is False
def test_grade_above_1_is_passing(passing_grade): assert passing_grade.is_passing() is True def test_grade_below_2_is_failing(failing_grade): assert failing_grade.is_passing() is False
# .split() breaks a string at specified character into a list of strings my_string = "Boulder,CO,80304,106392" my_split_string = my_string.split(",") print(my_split_string) # .strip() will remove leading or trailing whitespace white_str = " Boulder,CO,80304,106392\n" strip_split_str = white_str.split(",").strip() print(strip_split_str)
my_string = 'Boulder,CO,80304,106392' my_split_string = my_string.split(',') print(my_split_string) white_str = ' Boulder,CO,80304,106392\n' strip_split_str = white_str.split(',').strip() print(strip_split_str)
# SPDX-License-Identifier: MIT # Map the entire MMIO range as traceable map_sw(0x2_00000000, 0x2_00000000 | hv.SPTE_TRACE_READ | hv.SPTE_TRACE_WRITE, 0x5_00000000) # Skip some noisy devices try: trace_device("/arm-io/usb-drd0", False) except KeyError: pass try: trace_device("/arm-io/usb-drd1", False) except KeyError: pass trace_device("/arm-io/uart2", False) trace_device("/arm-io/error-handler", False) trace_device("/arm-io/aic", False) trace_device("/arm-io/spi1", False) trace_device("/arm-io/pmgr", False) # Re-map the vuart, which the first map_sw undid... map_vuart()
map_sw(8589934592, 8589934592 | hv.SPTE_TRACE_READ | hv.SPTE_TRACE_WRITE, 21474836480) try: trace_device('/arm-io/usb-drd0', False) except KeyError: pass try: trace_device('/arm-io/usb-drd1', False) except KeyError: pass trace_device('/arm-io/uart2', False) trace_device('/arm-io/error-handler', False) trace_device('/arm-io/aic', False) trace_device('/arm-io/spi1', False) trace_device('/arm-io/pmgr', False) map_vuart()
class AdjNode: def __init__(self, value): self.value = value self.next = None class AdjListGraph: def __init__(self, num_vertices): self.storage = [None] * num_vertices self.num_vertices = num_vertices def add_edge(self, v, w): new_adj_node = AdjNode(w) new_adj_node.next = self.storage[v] self.storage[v] = new_adj_node new_adj_node = AdjNode(v) new_adj_node.next = self.storage[w] self.storage[w] = new_adj_node def adjacent(self, v): adjacent_vertices = [] node = self.storage[v] while (node is not None): adjacent_vertices.append(node.value) node = node.next return adjacent_vertices def num_of_vertices(self): return self.num_vertices def num_of_edges(self): num_edges = 0 for v in range(self.num_vertices): for _ in self.adjacent(v): num_edges += 1 return num_edges / 2 def degree(self, v): count = 0 for _ in self.adjacent(v): count += 1 return count def max_degree(self): max = 0 for v in range(self.num_vertices): d = self.degree(v) if d > max: max = d return max def average_degree(self): return 2 * self.num_of_edges() / self.num_of_vertices() def num_of_self_loops(self): count = 0 for v in range(self.num_vertices): for w in self.adjacent(v): if v == w: count += 1 return count class AdjMatrixGraph: def __init__(self, num_vertices): self.storage = [] for i in range(num_vertices): self.storage.append([0 for j in range(num_vertices)]) self.num_vertices = num_vertices def add_edge(self, v, w): self.storage[v][w] = 1 self.storage[w][v] = 1 def adjacent(self, v): adjacent_vertices = [] for index in range(self.num_vertices): if self.storage[v][index] == 1: adjacent_vertices.append(index) return adjacent_vertices def num_of_vertices(self): return self.num_vertices def num_of_edges(self): num_edges = 0 for v in range(self.num_vertices): for w in range(self.num_vertices): if self.storage[v][w]: num_edges += 1 return num_edges / 2 def degree(self, v): count = 0 for index in range(self.num_vertices): if self.storage[v][index] == 1: count += 1 return count def max_degree(self): max = 0 for v in range(self.num_vertices): d = self.degree(v) if d > max: max = d return max def average_degree(self): return 2 * self.num_of_edges() / self.num_of_vertices() def num_of_self_loops(self): count = 0 for v in range(self.num_vertices): if self.storage[v][v] == 1: count += 1 return count def create_graph_one(graph): graph.add_edge(0, 1) graph.add_edge(0, 2) graph.add_edge(0, 5) graph.add_edge(0, 6) graph.add_edge(3, 4) graph.add_edge(3, 5) graph.add_edge(4, 5) graph.add_edge(4, 6) graph.add_edge(7, 8) graph.add_edge(9, 10) graph.add_edge(9, 11) graph.add_edge(9, 12) graph.add_edge(11, 12) return graph def create_graph_two(graph): for v, w in [(0, 1), (0, 2), (0, 5), (1, 2), (2, 3), (2, 4), (3, 4), (3, 5)]: graph.add_edge(v, w) return graph if __name__ == '__main__': print('*** Adjacency List Graph One ***') adj_list_graph_one = AdjListGraph(13) adj_list_graph_one = create_graph_one(adj_list_graph_one) for v in [3, 9, 1]: print(adj_list_graph_one.adjacent(v)) print(adj_list_graph_one.degree(v)) print(adj_list_graph_one.num_of_vertices()) print(adj_list_graph_one.num_of_edges()) print(adj_list_graph_one.average_degree()) print(adj_list_graph_one.max_degree()) print('\n*** Adjacency Matrix Graph One ***') adj_mat_graph_one = AdjMatrixGraph(13) adj_mat_graph_one = create_graph_one(adj_mat_graph_one) for v in [3, 9, 1]: print(adj_mat_graph_one.adjacent(v)) print(adj_mat_graph_one.degree(v)) print(adj_mat_graph_one.num_of_vertices()) print(adj_mat_graph_one.num_of_edges()) print(adj_mat_graph_one.average_degree()) print(adj_mat_graph_one.max_degree()) print('*** Adjacency List Graph Two ***') adj_list_graph_two = AdjListGraph(6) adj_list_graph_two = create_graph_two(adj_list_graph_two) for v in [3, 5, 1]: print(adj_list_graph_two.adjacent(v)) print(adj_list_graph_two.degree(v)) print(adj_list_graph_two.num_of_vertices()) print(adj_list_graph_two.num_of_edges()) print(adj_list_graph_two.average_degree()) print(adj_list_graph_two.max_degree()) print('\n*** Adjacency Matrix Graph Two ***') adj_mat_graph_two = AdjMatrixGraph(6) adj_mat_graph_two = create_graph_two(adj_mat_graph_two) for v in [3, 5, 1]: print(adj_mat_graph_two.adjacent(v)) print(adj_mat_graph_two.degree(v)) print(adj_mat_graph_two.num_of_vertices()) print(adj_mat_graph_two.num_of_edges()) print(adj_mat_graph_two.average_degree()) print(adj_mat_graph_two.max_degree())
class Adjnode: def __init__(self, value): self.value = value self.next = None class Adjlistgraph: def __init__(self, num_vertices): self.storage = [None] * num_vertices self.num_vertices = num_vertices def add_edge(self, v, w): new_adj_node = adj_node(w) new_adj_node.next = self.storage[v] self.storage[v] = new_adj_node new_adj_node = adj_node(v) new_adj_node.next = self.storage[w] self.storage[w] = new_adj_node def adjacent(self, v): adjacent_vertices = [] node = self.storage[v] while node is not None: adjacent_vertices.append(node.value) node = node.next return adjacent_vertices def num_of_vertices(self): return self.num_vertices def num_of_edges(self): num_edges = 0 for v in range(self.num_vertices): for _ in self.adjacent(v): num_edges += 1 return num_edges / 2 def degree(self, v): count = 0 for _ in self.adjacent(v): count += 1 return count def max_degree(self): max = 0 for v in range(self.num_vertices): d = self.degree(v) if d > max: max = d return max def average_degree(self): return 2 * self.num_of_edges() / self.num_of_vertices() def num_of_self_loops(self): count = 0 for v in range(self.num_vertices): for w in self.adjacent(v): if v == w: count += 1 return count class Adjmatrixgraph: def __init__(self, num_vertices): self.storage = [] for i in range(num_vertices): self.storage.append([0 for j in range(num_vertices)]) self.num_vertices = num_vertices def add_edge(self, v, w): self.storage[v][w] = 1 self.storage[w][v] = 1 def adjacent(self, v): adjacent_vertices = [] for index in range(self.num_vertices): if self.storage[v][index] == 1: adjacent_vertices.append(index) return adjacent_vertices def num_of_vertices(self): return self.num_vertices def num_of_edges(self): num_edges = 0 for v in range(self.num_vertices): for w in range(self.num_vertices): if self.storage[v][w]: num_edges += 1 return num_edges / 2 def degree(self, v): count = 0 for index in range(self.num_vertices): if self.storage[v][index] == 1: count += 1 return count def max_degree(self): max = 0 for v in range(self.num_vertices): d = self.degree(v) if d > max: max = d return max def average_degree(self): return 2 * self.num_of_edges() / self.num_of_vertices() def num_of_self_loops(self): count = 0 for v in range(self.num_vertices): if self.storage[v][v] == 1: count += 1 return count def create_graph_one(graph): graph.add_edge(0, 1) graph.add_edge(0, 2) graph.add_edge(0, 5) graph.add_edge(0, 6) graph.add_edge(3, 4) graph.add_edge(3, 5) graph.add_edge(4, 5) graph.add_edge(4, 6) graph.add_edge(7, 8) graph.add_edge(9, 10) graph.add_edge(9, 11) graph.add_edge(9, 12) graph.add_edge(11, 12) return graph def create_graph_two(graph): for (v, w) in [(0, 1), (0, 2), (0, 5), (1, 2), (2, 3), (2, 4), (3, 4), (3, 5)]: graph.add_edge(v, w) return graph if __name__ == '__main__': print('*** Adjacency List Graph One ***') adj_list_graph_one = adj_list_graph(13) adj_list_graph_one = create_graph_one(adj_list_graph_one) for v in [3, 9, 1]: print(adj_list_graph_one.adjacent(v)) print(adj_list_graph_one.degree(v)) print(adj_list_graph_one.num_of_vertices()) print(adj_list_graph_one.num_of_edges()) print(adj_list_graph_one.average_degree()) print(adj_list_graph_one.max_degree()) print('\n*** Adjacency Matrix Graph One ***') adj_mat_graph_one = adj_matrix_graph(13) adj_mat_graph_one = create_graph_one(adj_mat_graph_one) for v in [3, 9, 1]: print(adj_mat_graph_one.adjacent(v)) print(adj_mat_graph_one.degree(v)) print(adj_mat_graph_one.num_of_vertices()) print(adj_mat_graph_one.num_of_edges()) print(adj_mat_graph_one.average_degree()) print(adj_mat_graph_one.max_degree()) print('*** Adjacency List Graph Two ***') adj_list_graph_two = adj_list_graph(6) adj_list_graph_two = create_graph_two(adj_list_graph_two) for v in [3, 5, 1]: print(adj_list_graph_two.adjacent(v)) print(adj_list_graph_two.degree(v)) print(adj_list_graph_two.num_of_vertices()) print(adj_list_graph_two.num_of_edges()) print(adj_list_graph_two.average_degree()) print(adj_list_graph_two.max_degree()) print('\n*** Adjacency Matrix Graph Two ***') adj_mat_graph_two = adj_matrix_graph(6) adj_mat_graph_two = create_graph_two(adj_mat_graph_two) for v in [3, 5, 1]: print(adj_mat_graph_two.adjacent(v)) print(adj_mat_graph_two.degree(v)) print(adj_mat_graph_two.num_of_vertices()) print(adj_mat_graph_two.num_of_edges()) print(adj_mat_graph_two.average_degree()) print(adj_mat_graph_two.max_degree())
# -*- coding: utf-8 -*- db.define_table('MESSAGE_BOARD', Field('sender', 'text'), Field('receiver', 'text'), Field('message_content', 'text'), # Field('sent_time', 'datetime', requires=IS_DATE(format='%d-%m-%Y %H:%M:%S')), Field('sent_time', 'datetime'), Field('has_read', 'boolean', default=False), Field('comments', 'text'), redefine=True)
db.define_table('MESSAGE_BOARD', field('sender', 'text'), field('receiver', 'text'), field('message_content', 'text'), field('sent_time', 'datetime'), field('has_read', 'boolean', default=False), field('comments', 'text'), redefine=True)
BASE_AUTH = "bemullen_crussack_dharmesh_vinwah" CONTRIBUTOR = "bemullen_crussack_dharmesh_vinwah" BASE_NAME = "bemullen_crussack_dharmesh_vinwah" def setBaseName(baseAuth): global BASE_AUTH global BASE_NAME global CONTRIBUTOR BASE_AUTH = baseAuth CONTRIBUTOR = baseAuth BASE_NAME = baseAuth
base_auth = 'bemullen_crussack_dharmesh_vinwah' contributor = 'bemullen_crussack_dharmesh_vinwah' base_name = 'bemullen_crussack_dharmesh_vinwah' def set_base_name(baseAuth): global BASE_AUTH global BASE_NAME global CONTRIBUTOR base_auth = baseAuth contributor = baseAuth base_name = baseAuth
class Solution(object): def numWays(self, n, k): """ :type n: int :type k: int :rtype: int """ if not n or not k: return 0 if n == 1: return k dp = [0] * (n+1) dp[1] = k dp[2] = k*(k-1) + k for i in range(3, n+1): dp[i] = (dp[i-1]+dp[i-2]) * (k - 1) return dp[-1]
class Solution(object): def num_ways(self, n, k): """ :type n: int :type k: int :rtype: int """ if not n or not k: return 0 if n == 1: return k dp = [0] * (n + 1) dp[1] = k dp[2] = k * (k - 1) + k for i in range(3, n + 1): dp[i] = (dp[i - 1] + dp[i - 2]) * (k - 1) return dp[-1]
def grade(key, submission): if submission == "it_is_only_uphill_from_here_%s" % str(key): return True, "Good luck!" else: return False, "Ask Julius again..."
def grade(key, submission): if submission == 'it_is_only_uphill_from_here_%s' % str(key): return (True, 'Good luck!') else: return (False, 'Ask Julius again...')
class Solution: def solve(self, source, target): locs = defaultdict(list) for i,char in enumerate(source): locs[char].append(i) ans = 0 cur = len(source) for char in target: if char not in locs: return -1 nxt = bisect_left(locs[char],cur+1) if nxt == len(locs[char]): nxt = 0 ans += 1 cur = locs[char][nxt] return ans
class Solution: def solve(self, source, target): locs = defaultdict(list) for (i, char) in enumerate(source): locs[char].append(i) ans = 0 cur = len(source) for char in target: if char not in locs: return -1 nxt = bisect_left(locs[char], cur + 1) if nxt == len(locs[char]): nxt = 0 ans += 1 cur = locs[char][nxt] return ans
def encripter(key,entrada): alfabeto = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"] mapa = [["X0","X1","X2","X3","X4"],["X0","X1","X2","X3","X4"],["X0","X1","X2","X3","X4"],["X0","X1","X2","X3","X4"],["X0","X1","X2","X3","X4"]] x = 0 # index para la matriz y = 0 # index para la matriz contador = 0; # contador control para la incersion de la llave en el mapa entrada = entrada.replace(" ","") # establece la palabra entreda pro el usuario y le quita los espacios key = key.replace(" ","") # establece la llave y le quita los espacios entradaArr = listToUpper(list(entrada)) # convierte la entrada en un arreglo y todos los elementos a mayusculas keyArr = listToUpper(list(key)) # convierte la llave en un arreglo y todos los elementos a mayusculas keyMax = len(keyArr) # guarda la longitud de la llave letRest = [] cntLetRest = 0 for letra in alfabeto: if letra in keyArr: # print("letra en alfabeto") "letra en alfabeto" else: # print("letra no en el alfabeto: " + letra) letRest.append(letra) cntLetRest+=1 # print("letras restantes") # print (letRest) cntInsertLetrasRest = 0; # iteramos el mapa para poder insertar la llave en el for subLis in mapa: for letra in subLis: # print (mapa[x][y]) if(contador < keyMax): mapa[x][y] = keyArr[contador] # inserta la llave en el mapa caracter por caracter # print (keyArr[contador]) else: mapa[x][y] = letRest[cntInsertLetrasRest] cntInsertLetrasRest+=1 contador += 1 y+=1 pass y=0 x+=1 pass x = 0 y = 0 palabraEncriptada = "" # obtenemos la cadena encriptada for i in range(0,(len(entradaArr))): for subLis in mapa: if entradaArr[i] in subLis: palabraEncriptada += str(subLis.index(entradaArr[i])+1) # palabraEncriptada += "." palabraEncriptada += str(mapa.index(subLis)+1) palabraEncriptada += " " # indexLetraBusc +=1 pass pass print ("#############################################################") print ("############ >>>MAPA<<< #####################################") print ("#############################################################") print("") print (" 1 2 3 4 5") print (" 1 " + str(mapa[0])) print (" 2 " + str(mapa[1])) print (" 3 " + str(mapa[2])) print (" 4 " + str(mapa[3])) print (" 5 " + str(mapa[4])) print("") print(">> CLAVE: " + key.upper()) print(">> PALABRA ORIGINAL: " + entrada.upper()) # print("palabra encriptada: " + palabraEncriptada ) return palabraEncriptada def listToUpper(lista): listTam = len(lista) cnt = 0 for item in lista: lista[cnt] = lista[cnt].upper() cnt+=1 # print ("lista en mayusculas: ") # print (lista) return lista print ("ENCRIPTADOR") print (">> Ingrese la palabara clave: ") key = input() print (">> Ingrese la palabra que desea encriptar: ") entrada = input() print(">> PALABRA ENCRIPTADA: " + encripter(key,entrada))
def encripter(key, entrada): alfabeto = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] mapa = [['X0', 'X1', 'X2', 'X3', 'X4'], ['X0', 'X1', 'X2', 'X3', 'X4'], ['X0', 'X1', 'X2', 'X3', 'X4'], ['X0', 'X1', 'X2', 'X3', 'X4'], ['X0', 'X1', 'X2', 'X3', 'X4']] x = 0 y = 0 contador = 0 entrada = entrada.replace(' ', '') key = key.replace(' ', '') entrada_arr = list_to_upper(list(entrada)) key_arr = list_to_upper(list(key)) key_max = len(keyArr) let_rest = [] cnt_let_rest = 0 for letra in alfabeto: if letra in keyArr: 'letra en alfabeto' else: letRest.append(letra) cnt_let_rest += 1 cnt_insert_letras_rest = 0 for sub_lis in mapa: for letra in subLis: if contador < keyMax: mapa[x][y] = keyArr[contador] else: mapa[x][y] = letRest[cntInsertLetrasRest] cnt_insert_letras_rest += 1 contador += 1 y += 1 pass y = 0 x += 1 pass x = 0 y = 0 palabra_encriptada = '' for i in range(0, len(entradaArr)): for sub_lis in mapa: if entradaArr[i] in subLis: palabra_encriptada += str(subLis.index(entradaArr[i]) + 1) palabra_encriptada += str(mapa.index(subLis) + 1) palabra_encriptada += ' ' pass pass print('#############################################################') print('############ >>>MAPA<<< #####################################') print('#############################################################') print('') print(' 1 2 3 4 5') print(' 1 ' + str(mapa[0])) print(' 2 ' + str(mapa[1])) print(' 3 ' + str(mapa[2])) print(' 4 ' + str(mapa[3])) print(' 5 ' + str(mapa[4])) print('') print('>> CLAVE: ' + key.upper()) print('>> PALABRA ORIGINAL: ' + entrada.upper()) return palabraEncriptada def list_to_upper(lista): list_tam = len(lista) cnt = 0 for item in lista: lista[cnt] = lista[cnt].upper() cnt += 1 return lista print('ENCRIPTADOR') print('>> Ingrese la palabara clave: ') key = input() print('>> Ingrese la palabra que desea encriptar: ') entrada = input() print('>> PALABRA ENCRIPTADA: ' + encripter(key, entrada))
# class TreeNode(): # def __init__(self, val=None, left_ptr=None, right_ptr=None): # self.val = val # self.left_ptr = left_ptr # self.right_ptr = right_ptr # complete the function below traversal = [] PRE = 1 PROCESS = 2 POST = 3 # not used def postorderTraversal(root): def postorderHelper(root): stack = [(root, PRE)] while stack: node, state = stack.pop() if not node: continue if state == PRE: stack.append((node, PROCESS)) stack.append((node.right_ptr, PRE)) stack.append((node.left_ptr, PRE)) elif state == PROCESS: traversal.append(node.val) postorderHelper(root) return traversal
traversal = [] pre = 1 process = 2 post = 3 def postorder_traversal(root): def postorder_helper(root): stack = [(root, PRE)] while stack: (node, state) = stack.pop() if not node: continue if state == PRE: stack.append((node, PROCESS)) stack.append((node.right_ptr, PRE)) stack.append((node.left_ptr, PRE)) elif state == PROCESS: traversal.append(node.val) postorder_helper(root) return traversal
expected_output = { "FiveGigabitEthernet1/0/48": { "service_policy": { "output": { "policy_name": { "PWRED-CHILD": { "class_map": { "CWRED": { "afd_wred_stats": { "total_drops_bytes": 0, "total_drops_packets": 0, "virtual_class": { 0: { "afd_weight": 12, "dscp": 1, "max": 20, "min": 10, "random_drop_bytes": 0, "random_drop_packets": 0, "transmit_bytes": 65284071936, "transmit_packets": 68692637637 }, 1: { "afd_weight": 21, "dscp": 10, "max": 30, "min": 20, "random_drop_bytes": 0, "random_drop_packets": 0, "transmit_bytes": 65807437056, "transmit_packets": 68696726426 }, 2: { "afd_weight": 29, "dscp": 46, "max": 40, "min": 30, "random_drop_bytes": 0, "random_drop_packets": 0, "transmit_bytes": 66346804063, "transmit_packets": 68700945419 } } }, "bandwidth_kbps": 200000, "bandwidth_percent": 20, "match": [ "dscp ef (46)", "dscp af11 (10)", "dscp 1" ], "match_evaluation": "match-any", "packets": 0, "queueing": True }, "class-default": { "match": [ "any" ], "match_evaluation": "match-any", "packets": 0 } } } } } } } }
expected_output = {'FiveGigabitEthernet1/0/48': {'service_policy': {'output': {'policy_name': {'PWRED-CHILD': {'class_map': {'CWRED': {'afd_wred_stats': {'total_drops_bytes': 0, 'total_drops_packets': 0, 'virtual_class': {0: {'afd_weight': 12, 'dscp': 1, 'max': 20, 'min': 10, 'random_drop_bytes': 0, 'random_drop_packets': 0, 'transmit_bytes': 65284071936, 'transmit_packets': 68692637637}, 1: {'afd_weight': 21, 'dscp': 10, 'max': 30, 'min': 20, 'random_drop_bytes': 0, 'random_drop_packets': 0, 'transmit_bytes': 65807437056, 'transmit_packets': 68696726426}, 2: {'afd_weight': 29, 'dscp': 46, 'max': 40, 'min': 30, 'random_drop_bytes': 0, 'random_drop_packets': 0, 'transmit_bytes': 66346804063, 'transmit_packets': 68700945419}}}, 'bandwidth_kbps': 200000, 'bandwidth_percent': 20, 'match': ['dscp ef (46)', 'dscp af11 (10)', 'dscp 1'], 'match_evaluation': 'match-any', 'packets': 0, 'queueing': True}, 'class-default': {'match': ['any'], 'match_evaluation': 'match-any', 'packets': 0}}}}}}}}
# # @lc app=leetcode id=4 lang=python3 # # [4] Median of Two Sorted Arrays # # @lc code=start class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: for element in nums2: nums1.append(element) nums1.sort() lenth = len(nums1) if lenth % 2 == 0: n1 = lenth // 2 n2 = n1 - 1 return (nums1[n1] + nums1[n2])/2 else: return nums1[lenth//2] # @lc code=end
class Solution: def find_median_sorted_arrays(self, nums1: List[int], nums2: List[int]) -> float: for element in nums2: nums1.append(element) nums1.sort() lenth = len(nums1) if lenth % 2 == 0: n1 = lenth // 2 n2 = n1 - 1 return (nums1[n1] + nums1[n2]) / 2 else: return nums1[lenth // 2]
""" NeoTrellis M4 Express MIDI synth Adafruit invests time and resources providing this open source code. Please support Adafruit and open source hardware by purchasing products from Adafruit! Written by Dave Astels for Adafruit Industries Copyright (c) 2018 Adafruit Industries Licensed under the MIT license. All text above must be included in any redistribution. """ # Events as defined in http://www.music.mcgill.ca/~ich/classes/mumt306/StandardMIDIfileformat.html # pylint: disable=unused-argument,no-self-use class Event(object): def __init__(self, delta_time): self._delta_time = delta_time @property def time(self): return self._delta_time def execute(self, sequencer): return False class F0SysexEvent(Event): def __init__(self, delta_time, data): Event.__init__(self, delta_time) self._data = data class F7SysexEvent(Event): def __init__(self, delta_time, data): Event.__init__(self, delta_time) self._data = data class MetaEvent(Event): def __init__(self, delta_time): Event.__init__(self, delta_time) class SequenceNumberMetaEvent(MetaEvent): def __init__(self, delta_time, sequence_number): MetaEvent.__init__(self, delta_time) self._sequence_number = sequence_number def __str__(self): return '%d : Sequence Number : %d' % (self._delta_time, self._sequence_number) class TextMetaEvent(MetaEvent): def __init__(self, delta_time, text): MetaEvent.__init__(self, delta_time) self._text = text def __str__(self): return '%d : Text : %s' % (self._delta_time, self._text) class CopyrightMetaEvent(MetaEvent): def __init__(self, delta_time, copyright_notice): MetaEvent.__init__(self, delta_time) self._copyright_notice = copyright_notice def __str__(self): return '%d : Copyright : %s' % (self._delta_time, self._copyright_notice) class TrackNameMetaEvent(MetaEvent): def __init__(self, delta_time, track_name): MetaEvent.__init__(self, delta_time) self._track_name = track_name def __str__(self): return '%d : Track Name : %s' % (self._delta_time, self._track_name) class InstrumentNameMetaEvent(MetaEvent): def __init__(self, delta_time, instrument_name): MetaEvent.__init__(self, delta_time) self._instrument_name = instrument_name def __str__(self): return '%d : Instrument Name : %s' % (self._delta_time, self._instrument_name) class LyricMetaEvent(MetaEvent): def __init__(self, delta_time, lyric): MetaEvent.__init__(self, delta_time) self._lyric = lyric def __str__(self): return '%d : Lyric : %s' % (self._delta_time, self._lyric) class MarkerMetaEvent(MetaEvent): def __init__(self, delta_time, marker): MetaEvent.__init__(self, delta_time) self._marker = marker def __str__(self): return '%d : Marker : %s' % (self._delta_time, self._marker) class CuePointMetaEvent(MetaEvent): def __init__(self, delta_time, cue): MetaEvent.__init__(self, delta_time) self._cue = cue def __str__(self): return '%d : Cue : %s' % (self._delta_time, self._cue) class ChannelPrefixMetaEvent(MetaEvent): def __init__(self, delta_time, channel): MetaEvent.__init__(self, delta_time) self._channel = channel def __str__(self): return '%d: Channel Prefix : %d' % (self._delta_time, self._channel) class EndOfTrackMetaEvent(MetaEvent): def __init__(self, delta_time): MetaEvent.__init__(self, delta_time) def __str__(self): return '%d: End Of Track' % (self._delta_time) def execute(self, sequencer): sequencer.end_track() return True class SetTempoMetaEvent(MetaEvent): def __init__(self, delta_time, tempo): MetaEvent.__init__(self, delta_time) self._tempo = tempo def __str__(self): return '%d: Set Tempo : %d' % (self._delta_time, self._tempo) def execute(self, sequencer): sequencer.set_tempo(self._tempo) return False class SmpteOffsetMetaEvent(MetaEvent): def __init__(self, delta_time, hour, minute, second, fr, rr): MetaEvent.__init__(self, delta_time) self._hour = hour self._minute = minute self._second = second self._fr = fr self._rr = rr def __str__(self): return '%d : SMPTE Offset : %02d:%02d:%02d %d %d' % (self._delta_time, self._hour, self._minute, self._second, self._fr, self._rr) class TimeSignatureMetaEvent(MetaEvent): def __init__(self, delta_time, nn, dd, cc, bb): MetaEvent.__init__(self, delta_time) self._numerator = nn self._denominator = dd self._cc = cc self._bb = bb def __str__(self): return '%d : Time Signature : %d %d %d %d' % (self._delta_time, self._numerator, self._denominator, self._cc, self._bb) def execute(self, sequencer): sequencer.set_time_signature(self._numerator, self._denominator, self._cc) return False class KeySignatureMetaEvent(MetaEvent): def __init__(self, delta_time, sf, mi): MetaEvent.__init__(self, delta_time) self._sf = sf self._mi = mi def __str__(self): return '%d : Key Signature : %d %d' % (self._delta_time, self._sf, self._mi) class SequencerSpecificMetaEvent(MetaEvent): def __init__(self, delta_time, data): MetaEvent.__init__(self, delta_time) self._data = data class MidiEvent(Event): def __init__(self, delta_time, channel): Event.__init__(self, delta_time) self._channel = channel class NoteOffEvent(MidiEvent): def __init__(self, delta_time, channel, key, velocity): MidiEvent.__init__(self, delta_time, channel) self._key = key self._velocity = velocity def __str__(self): return '%d : Note Off : key %d, velocity %d' % (self._delta_time, self._key, self._velocity) def execute(self, sequencer): sequencer.note_off(self._key, self._velocity) return False class NoteOnEvent(MidiEvent): def __init__(self, delta_time, channel, key, velocity): MidiEvent.__init__(self, delta_time, channel) self._key = key self._velocity = velocity def __str__(self): return '%d : Note On : key %d, velocity %d' % (self._delta_time, self._key, self._velocity) def execute(self, sequencer): sequencer.note_on(self._key, self._velocity) return False class PolyphonicKeyPressureEvent(MidiEvent): def __init__(self, delta_time, channel, key, pressure): MidiEvent.__init__(self, delta_time, channel) self._key = key self._pressure = pressure def __str__(self): return '%d : Poly Key Pressure : key %d, velocity %d' % (self._delta_time, self._key, self._pressure) class ControlChangeEvent(MidiEvent): def __init__(self, delta_time, channel, controller, value): MidiEvent.__init__(self, delta_time, channel) self._controller = controller self._value = value def __str__(self): return '%d : Control Change : controller %d, value %d' % (self._delta_time, self._controller, self._value) class ProgramChangeEvent(MidiEvent): def __init__(self, delta_time, channel, program_number): MidiEvent.__init__(self, delta_time, channel) self._program_number = program_number def __str__(self): return '%d : Program Change : program %d' % (self._delta_time, self._program_number) class ChannelPressureEvent(MidiEvent): def __init__(self, delta_time, channel, pressure): MidiEvent.__init__(self, delta_time, channel) self._pressure = pressure def __str__(self): return '%d : Channel Pressure : %d' % (self._delta_time, self._channel) class PitchWheelChangeEvent(MidiEvent): def __init__(self, delta_time, channel, value): MidiEvent.__init__(self, delta_time, channel) self._value = value def __str__(self): return '%d : Pitch Wheel Change : %d' % (self._delta_time, self._value) class SystemExclusiveEvent(MidiEvent): def __init__(self, delta_time, channel, data): MidiEvent.__init__(self, delta_time, channel) self._data = data class SongPositionPointerEvent(MidiEvent): def __init__(self, delta_time, beats): MidiEvent.__init__(self, delta_time, None) self._beats = beats def __str__(self): return '%d: SongPositionPointerEvent(beats %d)' % (self._delta_time, self._beats) class SongSelectEvent(MidiEvent): def __init__(self, delta_time, song): MidiEvent.__init__(self, delta_time, None) self._song = song def __str__(self): return '%d: SongSelectEvent(song %d)' % (self._delta_time, self._song) class TuneRequestEvent(MidiEvent): def __init__(self, delta_time): MidiEvent.__init__(self, delta_time, None) def __str__(self): return '%d : Tune Request' % (self._delta_time) class TimingClockEvent(MidiEvent): def __init__(self, delta_time): MidiEvent.__init__(self, delta_time, None) def __str__(self): return '%d : Timing Clock' % (self._delta_time) class StartEvent(MidiEvent): def __init__(self, delta_time): MidiEvent.__init__(self, delta_time, None) def __str__(self): return '%d : Start' % (self._delta_time) class ContinueEvent(MidiEvent): def __init__(self, delta_time): MidiEvent.__init__(self, delta_time, None) def __str__(self): return '%d : Continue' % (self._delta_time) class StopEvent(MidiEvent): def __init__(self, delta_time): MidiEvent.__init__(self, delta_time, None) def __str__(self): return '%d : Stop' % (self._delta_time) class ActiveSensingEvent(MidiEvent): def __init__(self, delta_time): MidiEvent.__init__(self, delta_time, None) def __str__(self): return '%d : Active Sensing' % (self._delta_time) class ResetEvent(MidiEvent): def __init__(self, delta_time): MidiEvent.__init__(self, delta_time, None) def __str__(self): return '%d : Reset' % (self._delta_time)
""" NeoTrellis M4 Express MIDI synth Adafruit invests time and resources providing this open source code. Please support Adafruit and open source hardware by purchasing products from Adafruit! Written by Dave Astels for Adafruit Industries Copyright (c) 2018 Adafruit Industries Licensed under the MIT license. All text above must be included in any redistribution. """ class Event(object): def __init__(self, delta_time): self._delta_time = delta_time @property def time(self): return self._delta_time def execute(self, sequencer): return False class F0Sysexevent(Event): def __init__(self, delta_time, data): Event.__init__(self, delta_time) self._data = data class F7Sysexevent(Event): def __init__(self, delta_time, data): Event.__init__(self, delta_time) self._data = data class Metaevent(Event): def __init__(self, delta_time): Event.__init__(self, delta_time) class Sequencenumbermetaevent(MetaEvent): def __init__(self, delta_time, sequence_number): MetaEvent.__init__(self, delta_time) self._sequence_number = sequence_number def __str__(self): return '%d : Sequence Number : %d' % (self._delta_time, self._sequence_number) class Textmetaevent(MetaEvent): def __init__(self, delta_time, text): MetaEvent.__init__(self, delta_time) self._text = text def __str__(self): return '%d : Text : %s' % (self._delta_time, self._text) class Copyrightmetaevent(MetaEvent): def __init__(self, delta_time, copyright_notice): MetaEvent.__init__(self, delta_time) self._copyright_notice = copyright_notice def __str__(self): return '%d : Copyright : %s' % (self._delta_time, self._copyright_notice) class Tracknamemetaevent(MetaEvent): def __init__(self, delta_time, track_name): MetaEvent.__init__(self, delta_time) self._track_name = track_name def __str__(self): return '%d : Track Name : %s' % (self._delta_time, self._track_name) class Instrumentnamemetaevent(MetaEvent): def __init__(self, delta_time, instrument_name): MetaEvent.__init__(self, delta_time) self._instrument_name = instrument_name def __str__(self): return '%d : Instrument Name : %s' % (self._delta_time, self._instrument_name) class Lyricmetaevent(MetaEvent): def __init__(self, delta_time, lyric): MetaEvent.__init__(self, delta_time) self._lyric = lyric def __str__(self): return '%d : Lyric : %s' % (self._delta_time, self._lyric) class Markermetaevent(MetaEvent): def __init__(self, delta_time, marker): MetaEvent.__init__(self, delta_time) self._marker = marker def __str__(self): return '%d : Marker : %s' % (self._delta_time, self._marker) class Cuepointmetaevent(MetaEvent): def __init__(self, delta_time, cue): MetaEvent.__init__(self, delta_time) self._cue = cue def __str__(self): return '%d : Cue : %s' % (self._delta_time, self._cue) class Channelprefixmetaevent(MetaEvent): def __init__(self, delta_time, channel): MetaEvent.__init__(self, delta_time) self._channel = channel def __str__(self): return '%d: Channel Prefix : %d' % (self._delta_time, self._channel) class Endoftrackmetaevent(MetaEvent): def __init__(self, delta_time): MetaEvent.__init__(self, delta_time) def __str__(self): return '%d: End Of Track' % self._delta_time def execute(self, sequencer): sequencer.end_track() return True class Settempometaevent(MetaEvent): def __init__(self, delta_time, tempo): MetaEvent.__init__(self, delta_time) self._tempo = tempo def __str__(self): return '%d: Set Tempo : %d' % (self._delta_time, self._tempo) def execute(self, sequencer): sequencer.set_tempo(self._tempo) return False class Smpteoffsetmetaevent(MetaEvent): def __init__(self, delta_time, hour, minute, second, fr, rr): MetaEvent.__init__(self, delta_time) self._hour = hour self._minute = minute self._second = second self._fr = fr self._rr = rr def __str__(self): return '%d : SMPTE Offset : %02d:%02d:%02d %d %d' % (self._delta_time, self._hour, self._minute, self._second, self._fr, self._rr) class Timesignaturemetaevent(MetaEvent): def __init__(self, delta_time, nn, dd, cc, bb): MetaEvent.__init__(self, delta_time) self._numerator = nn self._denominator = dd self._cc = cc self._bb = bb def __str__(self): return '%d : Time Signature : %d %d %d %d' % (self._delta_time, self._numerator, self._denominator, self._cc, self._bb) def execute(self, sequencer): sequencer.set_time_signature(self._numerator, self._denominator, self._cc) return False class Keysignaturemetaevent(MetaEvent): def __init__(self, delta_time, sf, mi): MetaEvent.__init__(self, delta_time) self._sf = sf self._mi = mi def __str__(self): return '%d : Key Signature : %d %d' % (self._delta_time, self._sf, self._mi) class Sequencerspecificmetaevent(MetaEvent): def __init__(self, delta_time, data): MetaEvent.__init__(self, delta_time) self._data = data class Midievent(Event): def __init__(self, delta_time, channel): Event.__init__(self, delta_time) self._channel = channel class Noteoffevent(MidiEvent): def __init__(self, delta_time, channel, key, velocity): MidiEvent.__init__(self, delta_time, channel) self._key = key self._velocity = velocity def __str__(self): return '%d : Note Off : key %d, velocity %d' % (self._delta_time, self._key, self._velocity) def execute(self, sequencer): sequencer.note_off(self._key, self._velocity) return False class Noteonevent(MidiEvent): def __init__(self, delta_time, channel, key, velocity): MidiEvent.__init__(self, delta_time, channel) self._key = key self._velocity = velocity def __str__(self): return '%d : Note On : key %d, velocity %d' % (self._delta_time, self._key, self._velocity) def execute(self, sequencer): sequencer.note_on(self._key, self._velocity) return False class Polyphonickeypressureevent(MidiEvent): def __init__(self, delta_time, channel, key, pressure): MidiEvent.__init__(self, delta_time, channel) self._key = key self._pressure = pressure def __str__(self): return '%d : Poly Key Pressure : key %d, velocity %d' % (self._delta_time, self._key, self._pressure) class Controlchangeevent(MidiEvent): def __init__(self, delta_time, channel, controller, value): MidiEvent.__init__(self, delta_time, channel) self._controller = controller self._value = value def __str__(self): return '%d : Control Change : controller %d, value %d' % (self._delta_time, self._controller, self._value) class Programchangeevent(MidiEvent): def __init__(self, delta_time, channel, program_number): MidiEvent.__init__(self, delta_time, channel) self._program_number = program_number def __str__(self): return '%d : Program Change : program %d' % (self._delta_time, self._program_number) class Channelpressureevent(MidiEvent): def __init__(self, delta_time, channel, pressure): MidiEvent.__init__(self, delta_time, channel) self._pressure = pressure def __str__(self): return '%d : Channel Pressure : %d' % (self._delta_time, self._channel) class Pitchwheelchangeevent(MidiEvent): def __init__(self, delta_time, channel, value): MidiEvent.__init__(self, delta_time, channel) self._value = value def __str__(self): return '%d : Pitch Wheel Change : %d' % (self._delta_time, self._value) class Systemexclusiveevent(MidiEvent): def __init__(self, delta_time, channel, data): MidiEvent.__init__(self, delta_time, channel) self._data = data class Songpositionpointerevent(MidiEvent): def __init__(self, delta_time, beats): MidiEvent.__init__(self, delta_time, None) self._beats = beats def __str__(self): return '%d: SongPositionPointerEvent(beats %d)' % (self._delta_time, self._beats) class Songselectevent(MidiEvent): def __init__(self, delta_time, song): MidiEvent.__init__(self, delta_time, None) self._song = song def __str__(self): return '%d: SongSelectEvent(song %d)' % (self._delta_time, self._song) class Tunerequestevent(MidiEvent): def __init__(self, delta_time): MidiEvent.__init__(self, delta_time, None) def __str__(self): return '%d : Tune Request' % self._delta_time class Timingclockevent(MidiEvent): def __init__(self, delta_time): MidiEvent.__init__(self, delta_time, None) def __str__(self): return '%d : Timing Clock' % self._delta_time class Startevent(MidiEvent): def __init__(self, delta_time): MidiEvent.__init__(self, delta_time, None) def __str__(self): return '%d : Start' % self._delta_time class Continueevent(MidiEvent): def __init__(self, delta_time): MidiEvent.__init__(self, delta_time, None) def __str__(self): return '%d : Continue' % self._delta_time class Stopevent(MidiEvent): def __init__(self, delta_time): MidiEvent.__init__(self, delta_time, None) def __str__(self): return '%d : Stop' % self._delta_time class Activesensingevent(MidiEvent): def __init__(self, delta_time): MidiEvent.__init__(self, delta_time, None) def __str__(self): return '%d : Active Sensing' % self._delta_time class Resetevent(MidiEvent): def __init__(self, delta_time): MidiEvent.__init__(self, delta_time, None) def __str__(self): return '%d : Reset' % self._delta_time
r,g,b = map(int,input().split()) l=[] for i in range(min(r+1,g+1,b+1,3)): l.append(i+(r-i)//3+(g-i)//3+(b-i)//3) print(max(l))
(r, g, b) = map(int, input().split()) l = [] for i in range(min(r + 1, g + 1, b + 1, 3)): l.append(i + (r - i) // 3 + (g - i) // 3 + (b - i) // 3) print(max(l))
""" This script encrypt http and transfer it to port 443. By Olivier Soucy. """ def request(context, flow): flow.request.port = 443 flow.request.scheme = "https"
""" This script encrypt http and transfer it to port 443. By Olivier Soucy. """ def request(context, flow): flow.request.port = 443 flow.request.scheme = 'https'
#!/usr/bin/env python NAME = 'Comodo WAF' def is_waf(self): return self.matchheader(('server', "Protected by COMODO WAF"))
name = 'Comodo WAF' def is_waf(self): return self.matchheader(('server', 'Protected by COMODO WAF'))
def read_groups(full_text: str) -> []: "Separate groups from newlines and join answers." lines = full_text.splitlines() groups = [] group = [] for line in lines: line = line.strip() if line != '': group += [line] else: groups.append(group) group = [] groups.append(group) return groups def union_answers(group: list) -> int: answers = set() for person in group: person_answers = set(person) answers.update(person_answers) return len(answers) def intersection_answers(group: list) -> int: answers = set(group[0]) for person in group[1:]: person_answers = set(person) answers.intersection_update(person_answers) return len(answers) def main(): with open('answers.txt') as ifh: full_text = ifh.read() groups = read_groups(full_text) total_answers = 0 for group in groups: total_answers += union_answers(group) total_answers2 = 0 for group in groups: total_answers2 += intersection_answers(group) print(total_answers) print(f'answer 6b, {total_answers2}') if __name__ == '__main__': main()
def read_groups(full_text: str) -> []: """Separate groups from newlines and join answers.""" lines = full_text.splitlines() groups = [] group = [] for line in lines: line = line.strip() if line != '': group += [line] else: groups.append(group) group = [] groups.append(group) return groups def union_answers(group: list) -> int: answers = set() for person in group: person_answers = set(person) answers.update(person_answers) return len(answers) def intersection_answers(group: list) -> int: answers = set(group[0]) for person in group[1:]: person_answers = set(person) answers.intersection_update(person_answers) return len(answers) def main(): with open('answers.txt') as ifh: full_text = ifh.read() groups = read_groups(full_text) total_answers = 0 for group in groups: total_answers += union_answers(group) total_answers2 = 0 for group in groups: total_answers2 += intersection_answers(group) print(total_answers) print(f'answer 6b, {total_answers2}') if __name__ == '__main__': main()
""" @author: Anirudh Sharma """ # Example #1 def sum_of_list_elements(L): total = 0 for i in L: total += L[i - 1] return total L = [1, 2, 3, 4, 5, 6] print(sum_of_list_elements(L)) # Example #2 def list_operations(L1, L2): L3 = L1 + L2 print("L1 + L2: ", L3) L1.remove(2) L2.remove(6) print("Mutated L1 after remove:", L1) print("Mutated L2 after remove:", L2) L1.append(7) L2.append(9) print("Mutated L1 after add: ", L1) print("Mutated L2 after add:", L2) del(L1[1]) print("Mutated L1 after deleting element at index 1:", L1) print("Popping from L2: ", L2.pop()) L1 = [1, 2, 3] L2 = [4, 5, 6] list_operations(L1, L2) # Example #3 def string_and_list_manipulations(L, s): # Convert string to list print(list(s)) print(s.split(' ')) # Convert list to string print(''.join(L)) print('_'.join(L)) s = "I <3 CS" L = ['A', 'n', 'i', 'r', 'u', 'd', 'h'] string_and_list_manipulations(L, s) # Example #4 def more_list_operations(L1, L2): L.sort() print("Sorted but mutated list:", L) print("Sorted but immutable list:", sorted(L)) # Reverse the list L.reverse() print("Reversed List:", L) L1 = [5, 8, -9, -1, 3] L2 = [5, 8, -9, -1, 3] more_list_operations(L1, L2) # Example #5 def aliasing(L): newL = L print("L:", L) print("New L:", newL) newL.append("Five") print("L after appending in newL:", L) print("New L after appending in newL:", newL) L = ["One", "Two", "Three", "Four"] aliasing(L) # Example #6 def cloning(L): newL = L[:] print("L:", L) print("New L:", newL) newL.append("Five") print("L after appending in newL:", L) print("New L after appending in newL:", newL) L = ["One", "Two", "Three", "Four"] cloning(L) # Example #7 def list_of_list(): warm = ["orange", "yellow"] hot = ["red"] bright = [warm] print(bright) bright.append(hot) print(bright) hot.append("pink") print(hot) print(bright) list_of_list() # Example # 8 def remove_duplicates(L1, L2): L1_copy = L1[:] for i in L1_copy: if i in L2: L1.remove(i) L1 = [1, 2, 3, 4] L2 = [1, 2, 5, 6] remove_duplicates(L1, L2) print(L1, L2)
""" @author: Anirudh Sharma """ def sum_of_list_elements(L): total = 0 for i in L: total += L[i - 1] return total l = [1, 2, 3, 4, 5, 6] print(sum_of_list_elements(L)) def list_operations(L1, L2): l3 = L1 + L2 print('L1 + L2: ', L3) L1.remove(2) L2.remove(6) print('Mutated L1 after remove:', L1) print('Mutated L2 after remove:', L2) L1.append(7) L2.append(9) print('Mutated L1 after add: ', L1) print('Mutated L2 after add:', L2) del L1[1] print('Mutated L1 after deleting element at index 1:', L1) print('Popping from L2: ', L2.pop()) l1 = [1, 2, 3] l2 = [4, 5, 6] list_operations(L1, L2) def string_and_list_manipulations(L, s): print(list(s)) print(s.split(' ')) print(''.join(L)) print('_'.join(L)) s = 'I <3 CS' l = ['A', 'n', 'i', 'r', 'u', 'd', 'h'] string_and_list_manipulations(L, s) def more_list_operations(L1, L2): L.sort() print('Sorted but mutated list:', L) print('Sorted but immutable list:', sorted(L)) L.reverse() print('Reversed List:', L) l1 = [5, 8, -9, -1, 3] l2 = [5, 8, -9, -1, 3] more_list_operations(L1, L2) def aliasing(L): new_l = L print('L:', L) print('New L:', newL) newL.append('Five') print('L after appending in newL:', L) print('New L after appending in newL:', newL) l = ['One', 'Two', 'Three', 'Four'] aliasing(L) def cloning(L): new_l = L[:] print('L:', L) print('New L:', newL) newL.append('Five') print('L after appending in newL:', L) print('New L after appending in newL:', newL) l = ['One', 'Two', 'Three', 'Four'] cloning(L) def list_of_list(): warm = ['orange', 'yellow'] hot = ['red'] bright = [warm] print(bright) bright.append(hot) print(bright) hot.append('pink') print(hot) print(bright) list_of_list() def remove_duplicates(L1, L2): l1_copy = L1[:] for i in L1_copy: if i in L2: L1.remove(i) l1 = [1, 2, 3, 4] l2 = [1, 2, 5, 6] remove_duplicates(L1, L2) print(L1, L2)
X, N = [int(x) for x in input().split()] PS = [int(x) for x in input().split()] mindist = 1e+99 for p in PS: dist = abs(X - p) if dist < mindist: mindist = dist answer = p elif dist == mindist: if p < answer: ansewr = p print(answer)
(x, n) = [int(x) for x in input().split()] ps = [int(x) for x in input().split()] mindist = 1e+99 for p in PS: dist = abs(X - p) if dist < mindist: mindist = dist answer = p elif dist == mindist: if p < answer: ansewr = p print(answer)
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ @author: Jesus Salgado @contact: jesusjuansalgado@gmail.com European Space Astronomy Centre (ESAC) European Space Agency (ESA) Created on 15 July 2020 """
""" @author: Jesus Salgado @contact: jesusjuansalgado@gmail.com European Space Astronomy Centre (ESAC) European Space Agency (ESA) Created on 15 July 2020 """
N = int(input()) A = list(map(int, input().split())) result = [] for i in range(N): x = i j = 1 x = A[x] - 1 while x != i: x = A[x] - 1 j += 1 result.append(j) print(*result)
n = int(input()) a = list(map(int, input().split())) result = [] for i in range(N): x = i j = 1 x = A[x] - 1 while x != i: x = A[x] - 1 j += 1 result.append(j) print(*result)
def increasing_or_decreasing(seq): is_up = False is_down = False length = len(seq) if length == 1: return False if seq[0] > seq[1]: is_down = True elif seq[0] < seq[1]: is_up = True for i in range(1, length - 1): if(seq[i] > seq[i + 1] and is_up) or \ (seq[i] < seq[i + 1] and is_down) or \ (seq[i] == seq[i + 1]): return False if is_up: return 'Up!' if is_down: return 'Down!' def main(): print(increasing_or_decreasing([1,2,3,4,5])) # Expected output : Up! print(increasing_or_decreasing([5,6,-10])) # Expected output : False print(increasing_or_decreasing([1,1,1,1])) # Expected output : False print(increasing_or_decreasing([9,8,7,6])) # Expected output : Down! if __name__ == '__main__': main()
def increasing_or_decreasing(seq): is_up = False is_down = False length = len(seq) if length == 1: return False if seq[0] > seq[1]: is_down = True elif seq[0] < seq[1]: is_up = True for i in range(1, length - 1): if seq[i] > seq[i + 1] and is_up or (seq[i] < seq[i + 1] and is_down) or seq[i] == seq[i + 1]: return False if is_up: return 'Up!' if is_down: return 'Down!' def main(): print(increasing_or_decreasing([1, 2, 3, 4, 5])) print(increasing_or_decreasing([5, 6, -10])) print(increasing_or_decreasing([1, 1, 1, 1])) print(increasing_or_decreasing([9, 8, 7, 6])) if __name__ == '__main__': main()
# errors from Transition function TransitionComplete = 10 TransitionDbConnectionFailed = 11 TransitionDbRetrieveFailed = 12 TransitionFunctionException = 13 # errors from JobStatusReceiver JobStatusReceiverRetrieveArgoSubJobFailed = 21 JobStatusReceiverRetrieveArgoJobFailed = 22 JobStatusReceiverBalsamStateMapFailure = 23 JobStatusReceiverCompleted = 24 JobStatusReceiverMessageNoBody = 25 JobStatusReceiverFailed = 26 msg_codes = { 0:'NoMessageCode', TransitionComplete:'TransitionComplete', TransitionDbConnectionFailed:'TransitionDbConnectionFailed', TransitionDbRetrieveFailed:'TransitionDbRetrieveFailed', TransitionFunctionException:'TransitionFunctionException', JobStatusReceiverRetrieveArgoSubJobFailed:'JobStatusReceiverRetrieveArgoSubJobFailed', JobStatusReceiverRetrieveArgoJobFailed:'JobStatusReceiverRetrieveArgoJobFailed', JobStatusReceiverBalsamStateMapFailure:'JobStatusReceiverBalsamStateMapFailure', JobStatusReceiverCompleted:'JobStatusReceiverCompleted', JobStatusReceiverMessageNoBody:'JobStatusReceiverMessageNoBody', JobStatusReceiverFailed:'JobStatusReceiverFailed', } class QueueMessage: ''' a message used to communicate with the balsam_service main loop ''' def __init__(self,pk=0,code=0,message=''): self.pk = pk self.code = code self.message = message def __str__(self): s = '' s = '%i:%s:%s' % (self.pk,self.msg_codes[self.msg_code],self.message) return s
transition_complete = 10 transition_db_connection_failed = 11 transition_db_retrieve_failed = 12 transition_function_exception = 13 job_status_receiver_retrieve_argo_sub_job_failed = 21 job_status_receiver_retrieve_argo_job_failed = 22 job_status_receiver_balsam_state_map_failure = 23 job_status_receiver_completed = 24 job_status_receiver_message_no_body = 25 job_status_receiver_failed = 26 msg_codes = {0: 'NoMessageCode', TransitionComplete: 'TransitionComplete', TransitionDbConnectionFailed: 'TransitionDbConnectionFailed', TransitionDbRetrieveFailed: 'TransitionDbRetrieveFailed', TransitionFunctionException: 'TransitionFunctionException', JobStatusReceiverRetrieveArgoSubJobFailed: 'JobStatusReceiverRetrieveArgoSubJobFailed', JobStatusReceiverRetrieveArgoJobFailed: 'JobStatusReceiverRetrieveArgoJobFailed', JobStatusReceiverBalsamStateMapFailure: 'JobStatusReceiverBalsamStateMapFailure', JobStatusReceiverCompleted: 'JobStatusReceiverCompleted', JobStatusReceiverMessageNoBody: 'JobStatusReceiverMessageNoBody', JobStatusReceiverFailed: 'JobStatusReceiverFailed'} class Queuemessage: """ a message used to communicate with the balsam_service main loop """ def __init__(self, pk=0, code=0, message=''): self.pk = pk self.code = code self.message = message def __str__(self): s = '' s = '%i:%s:%s' % (self.pk, self.msg_codes[self.msg_code], self.message) return s
# -*- coding: utf-8 -*- DATA_SET = [ ( [u"123", u"12345"], [1, 3], ([3, 5], [3, 5]) ), ( [u"123", u"12345"], [4, 3], ([3, 5], [4, 5]) ), ( [u"123", u"12345"], [5, 8], ([3, 5], [5, 8]) ), ( [u"123", u"12345", u"lorem ipsum"], [5, 3, 4], ([3, 5, 11], [5, 5, 11]) ), ]
data_set = [([u'123', u'12345'], [1, 3], ([3, 5], [3, 5])), ([u'123', u'12345'], [4, 3], ([3, 5], [4, 5])), ([u'123', u'12345'], [5, 8], ([3, 5], [5, 8])), ([u'123', u'12345', u'lorem ipsum'], [5, 3, 4], ([3, 5, 11], [5, 5, 11]))]
def cep(*args): try: telaPrincipal = args[0] telaErro = args[1] pycep_correios = args[2] cep = telaPrincipal.cep.text() end = pycep_correios.get_address_from_cep(cep) telaPrincipal.end.setText(end['logradouro']) telaPrincipal.bairro.setText(end['bairro']) except: telaErro.show() telaErro.label.setText(" CEP invalido, verifique por favor")
def cep(*args): try: tela_principal = args[0] tela_erro = args[1] pycep_correios = args[2] cep = telaPrincipal.cep.text() end = pycep_correios.get_address_from_cep(cep) telaPrincipal.end.setText(end['logradouro']) telaPrincipal.bairro.setText(end['bairro']) except: telaErro.show() telaErro.label.setText(' CEP invalido, verifique por favor')
""" Exception classes - Subclassing to check for specific errors """ class AlpineException(Exception): """ General Alpine Exception """ def __init__(self, reason, *args): super(AlpineException, self).__init__(reason, *args) self.reason = reason def __repr__(self): return 'AlpineException: %s' % self.reason def __str__(self): return 'AlpineException: %s' % self.reason class AlpineSessionNotFoundException(AlpineException): """ """ pass class UserNotFoundException(AlpineException): """ """ pass class DataSourceNotFoundException(AlpineException): """ """ pass class DataSourceTypeNotFoundException(AlpineException): """ """ pass class WorkspaceNotFoundException(AlpineException): """ """ pass class WorkspaceMemberNotFoundException(AlpineException): """ """ pass class WorkfileNotFoundException(AlpineException): """ """ pass class JobNotFoundException(AlpineException): """ """ pass class TaskNotFoundException(AlpineException): """ """ pass class RunJobFailureException(AlpineException): """ """ pass class LoginFailureException(AlpineException): """ """ pass class RunFlowFailureException(AlpineException): """ """ pass class RunFlowTimeoutException(AlpineException): """ """ pass class StopFlowFailureException(AlpineException): """ """ pass class ResultsNotFoundException(AlpineException): """ """ pass class FlowResultsMalformedException(AlpineException): """ """ pass class WorkflowVariableException(AlpineException): """ """ pass class InvalidResponseCodeException(AlpineException): """ """ pass
""" Exception classes - Subclassing to check for specific errors """ class Alpineexception(Exception): """ General Alpine Exception """ def __init__(self, reason, *args): super(AlpineException, self).__init__(reason, *args) self.reason = reason def __repr__(self): return 'AlpineException: %s' % self.reason def __str__(self): return 'AlpineException: %s' % self.reason class Alpinesessionnotfoundexception(AlpineException): """ """ pass class Usernotfoundexception(AlpineException): """ """ pass class Datasourcenotfoundexception(AlpineException): """ """ pass class Datasourcetypenotfoundexception(AlpineException): """ """ pass class Workspacenotfoundexception(AlpineException): """ """ pass class Workspacemembernotfoundexception(AlpineException): """ """ pass class Workfilenotfoundexception(AlpineException): """ """ pass class Jobnotfoundexception(AlpineException): """ """ pass class Tasknotfoundexception(AlpineException): """ """ pass class Runjobfailureexception(AlpineException): """ """ pass class Loginfailureexception(AlpineException): """ """ pass class Runflowfailureexception(AlpineException): """ """ pass class Runflowtimeoutexception(AlpineException): """ """ pass class Stopflowfailureexception(AlpineException): """ """ pass class Resultsnotfoundexception(AlpineException): """ """ pass class Flowresultsmalformedexception(AlpineException): """ """ pass class Workflowvariableexception(AlpineException): """ """ pass class Invalidresponsecodeexception(AlpineException): """ """ pass
def up(config, conn, semester, course): with conn.cursor() as cursor: cursor.execute("""CREATE TABLE IF NOT EXISTS notification_settings ( user_id character varying NOT NULL, merge_threads BOOLEAN DEFAULT FALSE NOT NULL, all_new_threads BOOLEAN DEFAULT FALSE NOT NULL, all_new_posts BOOLEAN DEFAULT FALSE NOT NULL, all_modifications_forum BOOLEAN DEFAULT FALSE NOT NULL, reply_in_post_thread BOOLEAN DEFAULT FALSE NOT NULL);""") cursor.execute("ALTER TABLE ONLY notification_settings DROP CONSTRAINT IF EXISTS notification_settings_pkey;") cursor.execute("ALTER TABLE ONLY notification_settings DROP CONSTRAINT IF EXISTS notification_settings_fkey;") cursor.execute("ALTER TABLE ONLY notification_settings ADD CONSTRAINT notification_settings_pkey PRIMARY KEY (user_id);") cursor.execute("ALTER TABLE ONLY notification_settings ADD CONSTRAINT notification_settings_fkey FOREIGN KEY (user_id) REFERENCES users(user_id) ON UPDATE CASCADE;") cursor.execute("INSERT INTO notification_settings SELECT user_id from users ON CONFLICT DO NOTHING") def down(config, conn, semester, course): pass
def up(config, conn, semester, course): with conn.cursor() as cursor: cursor.execute('CREATE TABLE IF NOT EXISTS notification_settings (\n\t\t\t\t\t\t\tuser_id character varying NOT NULL,\n\t\t\t\t\t\t\tmerge_threads BOOLEAN DEFAULT FALSE NOT NULL,\n\t\t\t\t\t\t\tall_new_threads BOOLEAN DEFAULT FALSE NOT NULL,\n\t\t\t\t\t\t\tall_new_posts BOOLEAN DEFAULT FALSE NOT NULL,\n\t\t\t\t\t\t\tall_modifications_forum BOOLEAN DEFAULT FALSE NOT NULL,\n\t\t\t\t\t\t\treply_in_post_thread BOOLEAN DEFAULT FALSE NOT NULL);') cursor.execute('ALTER TABLE ONLY notification_settings DROP CONSTRAINT IF EXISTS notification_settings_pkey;') cursor.execute('ALTER TABLE ONLY notification_settings DROP CONSTRAINT IF EXISTS notification_settings_fkey;') cursor.execute('ALTER TABLE ONLY notification_settings ADD CONSTRAINT notification_settings_pkey PRIMARY KEY (user_id);') cursor.execute('ALTER TABLE ONLY notification_settings ADD CONSTRAINT notification_settings_fkey FOREIGN KEY (user_id) REFERENCES users(user_id) ON UPDATE CASCADE;') cursor.execute('INSERT INTO notification_settings SELECT user_id from users ON CONFLICT DO NOTHING') def down(config, conn, semester, course): pass
""" File: phillips_hue.py George Farris <farrisg@gmsys.com> Copyright (c), 2015 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Description: This is a driver for the Phillips HUE colour LED interface. The HUE supports a number of devices such as 120VAC LED lights, Low voltage LED strips, wireless dimmer switches to name a few. This driver uses the phue library created by Nathanael Lecaude and can be found at: https://github.com/studioimaginaire/phue Author(s): George Farris <farrisg@gmsys.com> Copyright (c), 2015 License: This free software is licensed under the terms of the GNU public license, Version 3 Versions and changes: Initial version created on Nov 29, 2015 Nov 29, 2015 - 1.0 - Initial version Jan 06, 2016 - 1.1 - Added support for groups Jan 09, 2016 - 1.2 - Added update_status command Jan 25, 2016 - 1.3 - Updated status check so it won't trigger unless required """ """ #import threading import time #import re from Queue import Queue from binascii import unhexlify from phue import Bridge from .common import * from .ha_interface import HAInterface class PhillipsHue(HAInterface): VERSION = '1.3' valid_commands = ('bri','hue','sat','ct','rgb','tr','eft') def __init__(self, *args, **kwargs): super(PhillipsHue, self).__init__(None, *args, **kwargs) # Instance should be hue = PhillipsHue(address = '192.168.0.2', poll=10) def _init(self, *args, **kwargs): super(PhillipsHue, self)._init(*args, **kwargs) self._iteration = 0 self._poll_secs = kwargs.get('poll', 60) self.last_status = {} # get the ip address and connect to the bridge self._ip = kwargs.get('address', None) print "Phillips HUE Bridge address -> {0}".format(self._ip) try: self.interface = Bridge(self._ip) self.interface.connect() self._logger.debug("[Hue] Connected to interface at {0}...\n".format(self._ip)) except Exception, ex: self._logger.debug('[Hue] Could not connect to bridge: {0}'.format(str(ex))) print "\nCouldn't connect to HUE bridge, please press the LINK button\n" print "on the bridge and restart Pytomation within 30 seconds..." sys.exit() # Get the initial configuration of the Bridge so we can see models of lights etc # self.bridge_config['lights']['1']['modelid'] # Eventually we will build a table of device capabilites, for example if the # light is dimmable self.bridge_config = self.interface.get_api() #devices = self._build_device_table() self.version() def _readInterface(self, lastPacketHash): # We need to dial back how often we check the bridge.. Lets not bombard it! if not self._iteration < self._poll_secs: self._logger.debug('[HUE] Retrieving status from bridge.') self._iteration = 0 #check to see if there is anything we need to read try: # get dictionary of lights lights = self.interface.get_light_objects('id') #print lights for d in self._devices: #print d.address,d.state,lights[int(d.address[1:])].on if d.state == 'off' and lights[int(d.address[1:])].on == True: time.sleep(.01) #wait 10ms to see if state will change if d.state == 'off' and lights[int(d.address[1:])].on == True: contact = Command.OFF self._logger.debug('Light {0} status -> {1}'.format(d.address, contact)) self._onCommand(address="{0}".format(d.address),command=contact) elif d.state == 'on' and lights[int(d.address[1:])].on == False: time.sleep(.01) #wait 10ms to see if state will change if d.state == 'on' and lights[int(d.address[1:])].on == False: bri = int(round(int(lights[l].brightness) / 255.0 * 100)) contact = (Command.LEVEL, bri) self._logger.debug('Light {0} status -> {1}'.format(d.address, contact)) self._onCommand(address="{0}".format(d.address),command=contact) except Exception, ex: self._logger.error('Could not process data from bridge: '+ str(ex)) else: self._iteration+=1 time.sleep(1) # one sec iteration def on(self, address): # TODO Check the type of bulb and then command accordingly # an 'on' command always sets level to 100% and colour to white cmd = {'transitiontime' : 0, 'on' : True, 'bri' : 255, 'ct' : 370} if address[:1] == 'L': result = self.interface.set_light(int(address[1:]), cmd) elif address[:1] == 'G': result = self.interface.set_group(int(address[1:]), cmd) else: self._logger.error("{name} not a valid HUE address {addr}".format( name=self.name, addr=address, )) return # TODO parse result def off(self, address): cmd = {'transitiontime' : 0, 'on' : False} if address[:1] == 'L': result = self.interface.set_light(int(address[1:]), cmd) elif address[:1] == 'G': result = self.interface.set_group(int(address[1:]), cmd) else: self._logger.error("{name} not a valid HUE address {addr}".format( name=self.name, addr=address, )) return # Level for the HUE is capable of setting the following: # brightness : level = (int) - int is from 0 to 100 (mapped to 255) # hue : level = ('hue':int') - int is from 0 to 65535 # saturation : level = ('sat':int') - int is from 0 to 255 # hue and sat: level = ('hue':int', 'sat:int') - int is from 0 to 65535 # ct : level = ('ct':int') - int is from 153 to 500 # rgb : level = ('rgb':hex) - hex is from 000000 to ffffff # transition : level = ('tr':int') int is from 0 to 3000 in 1/10 seconds # effect : level = ('eft':colorloop|none') put bulb in colour loop # Not all RGB colours will produce a colour in the HUE lamps. # ct values are translated kelvin temperature values from 2000K to 6500K # 2000K maps to 500 and 6500K maps to 153 # If the lamp is already on don't send an on command # TODO check if bulb type can perform the selected operation def level(self, address, level, timeout=None, rate=None): cmd = {} #print level if (isinstance(level, tuple)): for i in level: if isinstance(i, int): #classic pytomation brightness i = 'bri:{0}'.format(i) cmd = dict(self._build_hue_command(i).items() + cmd.items()) #print cmd if address[:1] == 'L': result = self.interface.set_light(int(address[1:]), cmd) elif address[:1] == 'G': result = self.interface.set_group(int(address[1:]), cmd) else: self._logger.error("{name} not a valid HUE address {addr}".format( name=self.name, addr=address, )) return else: if isinstance(level, int): #classic pytomation brightness level = 'bri:{0}'.format(level) if level.split(':')[0] not in self.valid_commands: self._logger.error("{name} not a valid HUE command {level}".format( name=self.name, level=level, )) return cmd = self._build_hue_command(level) if address[:1] == 'L': result = self.interface.set_light(int(address[1:]), cmd) elif address[:1] == 'G': result = self.interface.set_group(int(address[1:]), cmd) else: self._logger.error("{name} not a valid HUE address {addr}".format( name=self.name, addr=address, )) return def hue(self, address): pass def saturation(self, address): pass def _build_hue_command(self, level): if (isinstance(level, tuple)): pass else: huecmd = level.split(':')[0] hueval = level.split(':')[1] if huecmd == 'bri': hueval = int(hueval) if self._check_range(huecmd, hueval, 0, 100): # if level is 0 or 1 turn hue off if hueval == 0 or hueval == 1: return {'on' : False} else: # make it 0 to 255 brimapped = int((int(hueval) / 100.0) * int(0xFF)) return {'on' : True, huecmd : brimapped} else: return None elif huecmd == 'hue': hueval = int(hueval) if self._check_range(huecmd, hueval, 0, 65535): return {'on' : True, huecmd : hueval} else: return None elif huecmd == 'sat': hueval = int(hueval) if self._check_range(huecmd, hueval, 0, 255): return {'on' : True, huecmd : hueval} else: return None elif huecmd == 'ct': hueval = int(hueval) if self._check_range(huecmd, hueval, 153, 500): return {'on' : True, huecmd : hueval} else: return None elif huecmd == 'tr': hueval = int(hueval) if self._check_range(huecmd, hueval, 0, 3000): return {'on' : True, 'transitiontime' : hueval} else: return None elif huecmd == 'rgb': if self._check_range(huecmd, int(hueval, 16), 0, 16777215): xy = () # no colour # convert the hex colour ('000000' to 'ffffff') to RGB red = int(hueval[0:2], 16) #red green = int(hueval[2:4], 16) #green blue = int(hueval[4:6], 16) #blue xy = self._rgb2xy(red, green, blue) return {'on' : True, 'xy' : xy} else: return None elif huecmd == 'eft': if hueval == 'colorloop' or hueval == 'none': return {'on' : True, 'effect' : hueval} else: return None def update_status(self): lights = self.interface.get_light_objects('id') for d in self._devices: print "Getting status for HUE -> ", d.address if lights[int(d.address[1:])].on == True: bri = int(round(int(lights[int(d.address[1:])].brightness) / 255.0 * 100)) contact = (Command.LEVEL, bri) else: contact = Command.OFF self._logger.debug('Light L{0} status -> {1}'.format(d.address, contact)) self._onCommand(address="{0}".format(d.address),command=contact) def _check_range(self, cmd, val, minv, maxv): if val > maxv or val < minv: self._logger.error("hue cannot set {level} beyond {mn} - {mx}".format(level=cmd, mn=minv, mx=maxv, )) return False else: return True def _rgb2xy(self, red, green, blue): # Returns xy point containing the closest available gamut colour (cie 1931) r = ((red + 0.055) / (1.0 + 0.055))**2.4 if (red > 0.04045) else (red / 12.92) g = ((green + 0.055) / (1.0 + 0.055))**2.4 if (green > 0.04045) else (green / 12.92) b = ((blue + 0.055) / (1.0 + 0.055))**2.4 if (blue > 0.04045) else (blue / 12.92) x = r * 0.4360747 + g * 0.3850649 + b * 0.0930804 y = r * 0.2225045 + g * 0.7168786 + b * 0.0406169 z = r * 0.0139322 + g * 0.0971045 + b * 0.7141733 if x + y + z == 0: cx = cy = 0 else: cx = x / (x + y + z) cy = y / (x + y + z) # Check if the given xy value is within the colour reach of our lamps. xyPoint = cx, cy, return xyPoint def version(self): self._logger.info("Phillips HUE Pytomation driver version " + self.VERSION + '\n') """
""" File: phillips_hue.py George Farris <farrisg@gmsys.com> Copyright (c), 2015 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Description: This is a driver for the Phillips HUE colour LED interface. The HUE supports a number of devices such as 120VAC LED lights, Low voltage LED strips, wireless dimmer switches to name a few. This driver uses the phue library created by Nathanael Lecaude and can be found at: https://github.com/studioimaginaire/phue Author(s): George Farris <farrisg@gmsys.com> Copyright (c), 2015 License: This free software is licensed under the terms of the GNU public license, Version 3 Versions and changes: Initial version created on Nov 29, 2015 Nov 29, 2015 - 1.0 - Initial version Jan 06, 2016 - 1.1 - Added support for groups Jan 09, 2016 - 1.2 - Added update_status command Jan 25, 2016 - 1.3 - Updated status check so it won't trigger unless required """ '\n#import threading\nimport time\n#import re\nfrom Queue import Queue\nfrom binascii import unhexlify\nfrom phue import Bridge\n\nfrom .common import *\nfrom .ha_interface import HAInterface\n\n\nclass PhillipsHue(HAInterface):\n VERSION = \'1.3\'\n valid_commands = (\'bri\',\'hue\',\'sat\',\'ct\',\'rgb\',\'tr\',\'eft\')\n\n def __init__(self, *args, **kwargs):\n super(PhillipsHue, self).__init__(None, *args, **kwargs)\n\n # Instance should be hue = PhillipsHue(address = \'192.168.0.2\', poll=10)\n def _init(self, *args, **kwargs):\n super(PhillipsHue, self)._init(*args, **kwargs)\n self._iteration = 0\n self._poll_secs = kwargs.get(\'poll\', 60)\n self.last_status = {}\n\n # get the ip address and connect to the bridge\n self._ip = kwargs.get(\'address\', None)\n print "Phillips HUE Bridge address -> {0}".format(self._ip)\n try:\n self.interface = Bridge(self._ip)\n self.interface.connect()\n self._logger.debug("[Hue] Connected to interface at {0}...\n".format(self._ip))\n except Exception, ex:\n self._logger.debug(\'[Hue] Could not connect to bridge: {0}\'.format(str(ex)))\n print "\nCouldn\'t connect to HUE bridge, please press the LINK button\n"\n print "on the bridge and restart Pytomation within 30 seconds..."\n sys.exit()\n\n # Get the initial configuration of the Bridge so we can see models of lights etc\n # self.bridge_config[\'lights\'][\'1\'][\'modelid\']\n # Eventually we will build a table of device capabilites, for example if the\n # light is dimmable\n self.bridge_config = self.interface.get_api()\n #devices = self._build_device_table()\n self.version()\n\n def _readInterface(self, lastPacketHash):\n # We need to dial back how often we check the bridge.. Lets not bombard it!\n if not self._iteration < self._poll_secs:\n self._logger.debug(\'[HUE] Retrieving status from bridge.\')\n self._iteration = 0\n #check to see if there is anything we need to read\n try:\n # get dictionary of lights\n lights = self.interface.get_light_objects(\'id\')\n #print lights\n for d in self._devices:\n #print d.address,d.state,lights[int(d.address[1:])].on\n if d.state == \'off\' and lights[int(d.address[1:])].on == True:\n time.sleep(.01) #wait 10ms to see if state will change\n if d.state == \'off\' and lights[int(d.address[1:])].on == True:\n contact = Command.OFF\n self._logger.debug(\'Light {0} status -> {1}\'.format(d.address, contact))\n self._onCommand(address="{0}".format(d.address),command=contact)\n elif d.state == \'on\' and lights[int(d.address[1:])].on == False:\n time.sleep(.01) #wait 10ms to see if state will change\n if d.state == \'on\' and lights[int(d.address[1:])].on == False:\n bri = int(round(int(lights[l].brightness) / 255.0 * 100))\n contact = (Command.LEVEL, bri)\n self._logger.debug(\'Light {0} status -> {1}\'.format(d.address, contact))\n self._onCommand(address="{0}".format(d.address),command=contact)\n except Exception, ex:\n self._logger.error(\'Could not process data from bridge: \'+ str(ex))\n\n else:\n self._iteration+=1\n time.sleep(1) # one sec iteration\n\n\n def on(self, address):\n # TODO Check the type of bulb and then command accordingly\n\n # an \'on\' command always sets level to 100% and colour to white\n cmd = {\'transitiontime\' : 0, \'on\' : True, \'bri\' : 255, \'ct\' : 370}\n\n if address[:1] == \'L\':\n result = self.interface.set_light(int(address[1:]), cmd)\n elif address[:1] == \'G\':\n result = self.interface.set_group(int(address[1:]), cmd)\n else:\n self._logger.error("{name} not a valid HUE address {addr}".format(\n name=self.name,\n addr=address,\n ))\n return\n # TODO parse result\n\n\n def off(self, address):\n cmd = {\'transitiontime\' : 0, \'on\' : False}\n if address[:1] == \'L\':\n result = self.interface.set_light(int(address[1:]), cmd)\n elif address[:1] == \'G\':\n result = self.interface.set_group(int(address[1:]), cmd)\n else:\n self._logger.error("{name} not a valid HUE address {addr}".format(\n name=self.name,\n addr=address,\n ))\n return\n\n\n # Level for the HUE is capable of setting the following:\n # brightness : level = (int) - int is from 0 to 100 (mapped to 255)\n # hue : level = (\'hue\':int\') - int is from 0 to 65535\n # saturation : level = (\'sat\':int\') - int is from 0 to 255\n # hue and sat: level = (\'hue\':int\', \'sat:int\') - int is from 0 to 65535\n # ct : level = (\'ct\':int\') - int is from 153 to 500\n # rgb : level = (\'rgb\':hex) - hex is from 000000 to ffffff\n # transition : level = (\'tr\':int\') int is from 0 to 3000 in 1/10 seconds\n # effect : level = (\'eft\':colorloop|none\') put bulb in colour loop\n # Not all RGB colours will produce a colour in the HUE lamps.\n # ct values are translated kelvin temperature values from 2000K to 6500K\n # 2000K maps to 500 and 6500K maps to 153\n # If the lamp is already on don\'t send an on command\n\n # TODO check if bulb type can perform the selected operation\n def level(self, address, level, timeout=None, rate=None):\n cmd = {}\n #print level\n if (isinstance(level, tuple)):\n for i in level:\n if isinstance(i, int): #classic pytomation brightness\n i = \'bri:{0}\'.format(i)\n cmd = dict(self._build_hue_command(i).items() + cmd.items())\n #print cmd\n if address[:1] == \'L\':\n result = self.interface.set_light(int(address[1:]), cmd)\n elif address[:1] == \'G\':\n result = self.interface.set_group(int(address[1:]), cmd)\n else:\n self._logger.error("{name} not a valid HUE address {addr}".format(\n name=self.name,\n addr=address,\n ))\n return\n\n else:\n if isinstance(level, int): #classic pytomation brightness\n level = \'bri:{0}\'.format(level)\n\n if level.split(\':\')[0] not in self.valid_commands:\n self._logger.error("{name} not a valid HUE command {level}".format(\n name=self.name,\n level=level,\n ))\n return\n cmd = self._build_hue_command(level)\n if address[:1] == \'L\':\n result = self.interface.set_light(int(address[1:]), cmd)\n elif address[:1] == \'G\':\n result = self.interface.set_group(int(address[1:]), cmd)\n else:\n self._logger.error("{name} not a valid HUE address {addr}".format(\n name=self.name,\n addr=address,\n ))\n return\n\n def hue(self, address):\n pass\n\n def saturation(self, address):\n pass\n\n def _build_hue_command(self, level):\n if (isinstance(level, tuple)):\n pass\n else:\n huecmd = level.split(\':\')[0]\n hueval = level.split(\':\')[1]\n if huecmd == \'bri\':\n hueval = int(hueval)\n if self._check_range(huecmd, hueval, 0, 100):\n # if level is 0 or 1 turn hue off\n if hueval == 0 or hueval == 1:\n return {\'on\' : False}\n else:\n # make it 0 to 255\n brimapped = int((int(hueval) / 100.0) * int(0xFF))\n return {\'on\' : True, huecmd : brimapped}\n else:\n return None\n\n elif huecmd == \'hue\':\n hueval = int(hueval)\n if self._check_range(huecmd, hueval, 0, 65535):\n return {\'on\' : True, huecmd : hueval}\n else:\n return None\n\n elif huecmd == \'sat\':\n hueval = int(hueval)\n if self._check_range(huecmd, hueval, 0, 255):\n return {\'on\' : True, huecmd : hueval}\n else:\n return None\n\n elif huecmd == \'ct\':\n hueval = int(hueval)\n if self._check_range(huecmd, hueval, 153, 500):\n return {\'on\' : True, huecmd : hueval}\n else:\n return None\n\n elif huecmd == \'tr\':\n hueval = int(hueval)\n if self._check_range(huecmd, hueval, 0, 3000):\n return {\'on\' : True, \'transitiontime\' : hueval}\n else:\n return None\n\n elif huecmd == \'rgb\':\n if self._check_range(huecmd, int(hueval, 16), 0, 16777215):\n xy = () # no colour\n # convert the hex colour (\'000000\' to \'ffffff\') to RGB\n red = int(hueval[0:2], 16) #red\n green = int(hueval[2:4], 16) #green\n blue = int(hueval[4:6], 16) #blue\n xy = self._rgb2xy(red, green, blue)\n\n return {\'on\' : True, \'xy\' : xy}\n else:\n return None\n\n elif huecmd == \'eft\':\n if hueval == \'colorloop\' or hueval == \'none\':\n return {\'on\' : True, \'effect\' : hueval}\n else:\n return None\n\n def update_status(self):\n lights = self.interface.get_light_objects(\'id\')\n for d in self._devices:\n print "Getting status for HUE -> ", d.address\n if lights[int(d.address[1:])].on == True:\n bri = int(round(int(lights[int(d.address[1:])].brightness) / 255.0 * 100))\n contact = (Command.LEVEL, bri)\n else:\n contact = Command.OFF\n self._logger.debug(\'Light L{0} status -> {1}\'.format(d.address, contact))\n self._onCommand(address="{0}".format(d.address),command=contact)\n\n\n def _check_range(self, cmd, val, minv, maxv):\n if val > maxv or val < minv:\n self._logger.error("hue cannot set {level} beyond {mn} - {mx}".format(level=cmd,\n mn=minv,\n mx=maxv,\n ))\n return False\n else:\n return True\n\n\n def _rgb2xy(self, red, green, blue):\n # Returns xy point containing the closest available gamut colour (cie 1931)\n\n r = ((red + 0.055) / (1.0 + 0.055))**2.4 if (red > 0.04045) else (red / 12.92)\n g = ((green + 0.055) / (1.0 + 0.055))**2.4 if (green > 0.04045) else (green / 12.92)\n b = ((blue + 0.055) / (1.0 + 0.055))**2.4 if (blue > 0.04045) else (blue / 12.92)\n\n x = r * 0.4360747 + g * 0.3850649 + b * 0.0930804\n y = r * 0.2225045 + g * 0.7168786 + b * 0.0406169\n z = r * 0.0139322 + g * 0.0971045 + b * 0.7141733\n\n if x + y + z == 0:\n cx = cy = 0\n else:\n cx = x / (x + y + z)\n cy = y / (x + y + z)\n\n # Check if the given xy value is within the colour reach of our lamps.\n xyPoint = cx, cy,\n\n return xyPoint\n\n\n def version(self):\n self._logger.info("Phillips HUE Pytomation driver version " + self.VERSION + \'\n\')\n'
# V0 # V1 # https://blog.csdn.net/fuxuemingzhu/article/details/81079015 class Solution(object): def asteroidCollision(self, asteroids): """ :type asteroids: List[int] :rtype: List[int] """ stack = [] for ast in asteroids: while stack and ast < 0 and stack[-1] >= 0: pre = stack.pop() if ast == -pre: ast = None break elif -ast < pre: ast = pre if ast != None: stack.append(ast) return stack # V2 # Time: O(n) # Space: O(n) class Solution(object): def asteroidCollision(self, asteroids): """ :type asteroids: List[int] :rtype: List[int] """ result = [] for asteroid in asteroids: while result and asteroid < 0 < result[-1]: if result[-1] < -asteroid: result.pop() continue elif result[-1] == -asteroid: result.pop() break else: result.append(asteroid) return result
class Solution(object): def asteroid_collision(self, asteroids): """ :type asteroids: List[int] :rtype: List[int] """ stack = [] for ast in asteroids: while stack and ast < 0 and (stack[-1] >= 0): pre = stack.pop() if ast == -pre: ast = None break elif -ast < pre: ast = pre if ast != None: stack.append(ast) return stack class Solution(object): def asteroid_collision(self, asteroids): """ :type asteroids: List[int] :rtype: List[int] """ result = [] for asteroid in asteroids: while result and asteroid < 0 < result[-1]: if result[-1] < -asteroid: result.pop() continue elif result[-1] == -asteroid: result.pop() break else: result.append(asteroid) return result
class Solution: def maximumProduct(self, nums: List[int]) -> int: min1 = min2 = inf max1 = max2 = max3 = -inf for n in nums: if n < min1: min2, min1 = min1, n elif n < min2: min2 = n if n > max1: max3, max2, max1 = max2, max1, n elif n > max2: max3, max2 = max2, n elif n > max3: max3 = n return max(min1 * min2 * max1, max1 * max2 * max3)
class Solution: def maximum_product(self, nums: List[int]) -> int: min1 = min2 = inf max1 = max2 = max3 = -inf for n in nums: if n < min1: (min2, min1) = (min1, n) elif n < min2: min2 = n if n > max1: (max3, max2, max1) = (max2, max1, n) elif n > max2: (max3, max2) = (max2, n) elif n > max3: max3 = n return max(min1 * min2 * max1, max1 * max2 * max3)
OUTCOMES = [ [None, "Buzz"], ["Fizz", "FizzBuzz"], ] def fizzbuzz(number: int) -> str: mod3 = number % 3 == 0 mod5 = number % 5 == 0 outcome = OUTCOMES[mod3][mod5] return outcome or str(number) def main(): for i in range(101): fbi = fizzbuzz(i) print(fbi) if __name__ == "__main__": main()
outcomes = [[None, 'Buzz'], ['Fizz', 'FizzBuzz']] def fizzbuzz(number: int) -> str: mod3 = number % 3 == 0 mod5 = number % 5 == 0 outcome = OUTCOMES[mod3][mod5] return outcome or str(number) def main(): for i in range(101): fbi = fizzbuzz(i) print(fbi) if __name__ == '__main__': main()
_.targets # unused attribute (packages/cli/odahuflow/cli/parsers/local/packaging.py:118) build_client # unused function (packages/sdk/odahuflow/sdk/clients/api_aggregated.py:88) ConfigurationClient # unused class (packages/sdk/odahuflow/sdk/clients/configuration.py:28) AsyncConfigurationClient # unused class (packages/sdk/odahuflow/sdk/clients/configuration.py:51) PROCESSING_STATE # unused variable (packages/sdk/odahuflow/sdk/clients/deployment.py:30) log_message # unused function (packages/sdk/odahuflow/sdk/clients/oauth_handler.py:251) do_GET # unused function (packages/sdk/odahuflow/sdk/clients/oauth_handler.py:280) SCHEDULING_STATE # unused variable (packages/sdk/odahuflow/sdk/clients/packaging.py:26) RUNNING_STATE # unused variable (packages/sdk/odahuflow/sdk/clients/packaging.py:27) UNKNOWN_STATE # unused variable (packages/sdk/odahuflow/sdk/clients/packaging.py:30) PROCESSING_STATE # unused variable (packages/sdk/odahuflow/sdk/clients/route.py:29) reset_context # unused function (packages/sdk/odahuflow/sdk/config.py:35) get_config_file_section # unused function (packages/sdk/odahuflow/sdk/config.py:91) ODAHUFLOWCTL_OAUTH_AUTH_URL # unused variable (packages/sdk/odahuflow/sdk/config.py:398) JUPYTER_REDIRECT_URL # unused variable (packages/sdk/odahuflow/sdk/config.py:404) REQUEST_ID # unused variable (packages/sdk/odahuflow/sdk/containers/headers.py:20) MODEL_REQUEST_ID # unused variable (packages/sdk/odahuflow/sdk/containers/headers.py:21) MODEL_NAME # unused variable (packages/sdk/odahuflow/sdk/containers/headers.py:22) MODEL_VERSION # unused variable (packages/sdk/odahuflow/sdk/containers/headers.py:23) get_model_output_sample # unused function (packages/sdk/odahuflow/sdk/gppi/entrypoint_invoke.py:176) args_ # unused variable (packages/sdk/odahuflow/sdk/gppi/entrypoint_invoke.py:273)
_.targets build_client ConfigurationClient AsyncConfigurationClient PROCESSING_STATE log_message do_GET SCHEDULING_STATE RUNNING_STATE UNKNOWN_STATE PROCESSING_STATE reset_context get_config_file_section ODAHUFLOWCTL_OAUTH_AUTH_URL JUPYTER_REDIRECT_URL REQUEST_ID MODEL_REQUEST_ID MODEL_NAME MODEL_VERSION get_model_output_sample args_
class Schema(object): def __init__(self, name, tag_name, tag_case_sensitive, model, validators, attributes, children, content): self.name = name self.tag_name = tag_name self.tag_case_sensitive = tag_case_sensitive self.model = model self.validators = validators self.attributes = attributes self.children = children self.content = content def compare_tag_name(self, other_name): tag_name = self.tag_name if not self.tag_case_sensitive: tag_name = tag_name.lower() other_name = other_name.lower() return tag_name == other_name
class Schema(object): def __init__(self, name, tag_name, tag_case_sensitive, model, validators, attributes, children, content): self.name = name self.tag_name = tag_name self.tag_case_sensitive = tag_case_sensitive self.model = model self.validators = validators self.attributes = attributes self.children = children self.content = content def compare_tag_name(self, other_name): tag_name = self.tag_name if not self.tag_case_sensitive: tag_name = tag_name.lower() other_name = other_name.lower() return tag_name == other_name
""" Problem Statement Given a target amount n and a list (array) of distinct coin values, what's the fewest coins needed to make the change amount. For example: If n = 10 and coins = [1,5,10]. Then there are 4 possible ways to make change: 1+1+1+1+1+1+1+1+1+1 5 + 1+1+1+1+1 5+5 10 With 1 coin being the minimum amount. """ # worst solution def rec_coin(target, coins): # default value set to target min_coins = target # base case if target in coins: return 1 else: for i in [c for c in coins if c <= target]: num_coins = 1 + rec_coin(target - i, coins) # reset minimum if new num_coins less than minimum coins if num_coins < min_coins: min_coins = num_coins return min_coins def rec_coin_dyn(target, coins, cache): min_coins = target # base case if target in coins: cache[target] = 1 return 1 # return a known result if it in cache elif cache[target] > 0: return cache[target] else: # for every coin value i <= target for i in [c for c in coins if c <= target]: num_coins = 1 + rec_coin_dyn(target - i, coins, cache) if num_coins < min_coins: min_coins = num_coins # reset cache result cache[target] = min_coins return min_coins # Solution from Wikipedia def _get_change_making_matrix(set_of_coins, r): m = [[0 for _ in range(r + 1)] for _ in range(len(set_of_coins) + 1)] for i in range(r + 1): m[0][i] = i return m def change_making(coins, n): """This function assumes that all coins are available infinitely. n is the number to obtain with the fewest coins. coins is a list or tuple with the available denominations.""" matrix = _get_change_making_matrix(coins, n) for c in range(1, len(coins) + 1): for r in range(1, n + 1): # Just use the coin coins[c - 1]. if coins[c - 1] == r: matrix[c][r] = 1 # coins[c - 1] cannot be included. # Use the previous solution for making r, # excluding coins[c - 1]. elif coins[c - 1] > r: matrix[c][r] = matrix[c - 1][r] # coins[c - 1] can be used. # Decide which one of the following solutions is the best: # 1. Using the previous solution for making r (without using coins[c - 1]). # 2. Using the previous solution for making r - coins[c - 1] (without # using coins[c - 1]) plus this 1 extra coin. else: matrix[c][r] = min(matrix[c - 1][r], 1 + matrix[c][r - coins[c - 1]]) return matrix[-1][-1] if __name__ == '__main__': print(rec_coin(15, [1, 5, 10])) # print(rec_coin(63, [1, 5, 10, 25])) takes a lot of time target_amount = 754 coins_list = [1, 5, 10, 25] cache_storage = [0] * (target_amount + 1) print(rec_coin_dyn(target_amount, coins=coins_list, cache=cache_storage))
""" Problem Statement Given a target amount n and a list (array) of distinct coin values, what's the fewest coins needed to make the change amount. For example: If n = 10 and coins = [1,5,10]. Then there are 4 possible ways to make change: 1+1+1+1+1+1+1+1+1+1 5 + 1+1+1+1+1 5+5 10 With 1 coin being the minimum amount. """ def rec_coin(target, coins): min_coins = target if target in coins: return 1 else: for i in [c for c in coins if c <= target]: num_coins = 1 + rec_coin(target - i, coins) if num_coins < min_coins: min_coins = num_coins return min_coins def rec_coin_dyn(target, coins, cache): min_coins = target if target in coins: cache[target] = 1 return 1 elif cache[target] > 0: return cache[target] else: for i in [c for c in coins if c <= target]: num_coins = 1 + rec_coin_dyn(target - i, coins, cache) if num_coins < min_coins: min_coins = num_coins cache[target] = min_coins return min_coins def _get_change_making_matrix(set_of_coins, r): m = [[0 for _ in range(r + 1)] for _ in range(len(set_of_coins) + 1)] for i in range(r + 1): m[0][i] = i return m def change_making(coins, n): """This function assumes that all coins are available infinitely. n is the number to obtain with the fewest coins. coins is a list or tuple with the available denominations.""" matrix = _get_change_making_matrix(coins, n) for c in range(1, len(coins) + 1): for r in range(1, n + 1): if coins[c - 1] == r: matrix[c][r] = 1 elif coins[c - 1] > r: matrix[c][r] = matrix[c - 1][r] else: matrix[c][r] = min(matrix[c - 1][r], 1 + matrix[c][r - coins[c - 1]]) return matrix[-1][-1] if __name__ == '__main__': print(rec_coin(15, [1, 5, 10])) target_amount = 754 coins_list = [1, 5, 10, 25] cache_storage = [0] * (target_amount + 1) print(rec_coin_dyn(target_amount, coins=coins_list, cache=cache_storage))
{ 'variables': { 'linear_sample_parent_path': '/', }, 'targets': [ { 'target_name': 'tcp_client_sample', 'type': 'executable', 'sources': [ 'tcp_client_sample.cpp', ], }, { 'target_name': 'tcp_server_sample', 'type': 'executable', 'sources': [ 'tcp_server_sample.cpp', ], }, { 'target_name': 'ws_client_sample', 'type': 'executable', 'sources': [ 'ws_client_sample.cpp', ], }, { 'target_name': 'ws_server_sample', 'type': 'executable', 'sources': [ 'ws_server_sample.cpp', ], }, ], 'conditions': [ [ 'with_ssl != "false"', { 'targets': [ { 'target_name': 'ssl_client_sample', 'type': 'executable', 'sources': [ 'ssl_client_sample.cpp', ], }, { 'target_name': 'ssl_server_sample', 'type': 'executable', 'sources': [ 'ssl_server_sample.cpp', ], }, { 'target_name': 'wss_client_sample', 'type': 'executable', 'sources': [ 'wss_client_sample.cpp', ], }, { 'target_name': 'wss_server_sample', 'type': 'executable', 'sources': [ 'wss_server_sample.cpp', ], }, ], }], ], }
{'variables': {'linear_sample_parent_path': '/'}, 'targets': [{'target_name': 'tcp_client_sample', 'type': 'executable', 'sources': ['tcp_client_sample.cpp']}, {'target_name': 'tcp_server_sample', 'type': 'executable', 'sources': ['tcp_server_sample.cpp']}, {'target_name': 'ws_client_sample', 'type': 'executable', 'sources': ['ws_client_sample.cpp']}, {'target_name': 'ws_server_sample', 'type': 'executable', 'sources': ['ws_server_sample.cpp']}], 'conditions': [['with_ssl != "false"', {'targets': [{'target_name': 'ssl_client_sample', 'type': 'executable', 'sources': ['ssl_client_sample.cpp']}, {'target_name': 'ssl_server_sample', 'type': 'executable', 'sources': ['ssl_server_sample.cpp']}, {'target_name': 'wss_client_sample', 'type': 'executable', 'sources': ['wss_client_sample.cpp']}, {'target_name': 'wss_server_sample', 'type': 'executable', 'sources': ['wss_server_sample.cpp']}]}]]}
def rna_to_protein(rna): ''' Takes a string and returns a protein sequence WIHOUT using biopython Input params: rna = rna string Output params: protein = protein sequence ''' codon = [] protein = [] while rna: codon.append(rna[:3]) rna = rna[3:] for triplet in codon: if triplet == 'AUG': protein.append('M') elif triplet == 'GCC' or triplet == 'GCG' or triplet == 'GCU' or triplet == 'GCA': protein.append('A') elif triplet == 'UUU' or triplet == 'UUC': protein.append('F') elif triplet == 'UUA' or triplet == 'UUG': protein.append('L') elif triplet == 'UCU' or triplet == 'UCC' or triplet == 'UCA' or triplet == 'UCG': protein.append('S') elif triplet == 'UAU' or triplet == 'UAC': protein.append('Y') elif triplet == 'UAA' or triplet == 'UGA': break #stop codon elif triplet == 'UGU' or triplet == 'UGC': protein.append('C') elif triplet == 'UGG': protein.append('W') elif triplet == 'CUU' or triplet == 'CUC' or triplet == 'CUA' or triplet == 'CUG': protein.append('L') elif triplet == 'CCU' or triplet == 'CCC' or triplet == 'CCA' or triplet == 'CCG': protein.append('P') elif triplet == 'CAU' or triplet == 'CAC': protein.append('H') elif triplet == 'CAA' or triplet == 'CAG': protein.append('Q') elif triplet == 'CGU' or triplet == 'CGC' or triplet == 'CGA' or triplet == 'CGG': protein.append('R') elif triplet == 'AUU' or triplet == 'AUC' or triplet == 'AUA': protein.append('I') elif triplet == 'ACU' or triplet == 'ACC' or triplet == 'ACA' or triplet == 'ACG': protein.append('T') elif triplet == 'AAU' or triplet == 'AAC': protein.append('N') elif triplet == 'AAA' or triplet == 'AAG': protein.append('K') elif triplet == 'AGU' or triplet == 'AGC': protein.append('S') elif triplet == 'AGA' or triplet == 'AGG': protein.append('R') elif triplet == 'GUU' or triplet == 'GUC' or triplet == 'GUA' or triplet == 'GUG': protein.append('V') elif triplet == 'GAU' or triplet == 'GAC': protein.append('D') elif triplet == 'GAA' or triplet == 'GAG': protein.append('E') elif triplet == 'GGU' or triplet == 'GGC' or triplet == 'GGA' or triplet == 'GGG': protein.append('G') protein = ''.join(protein) return protein rna = 'AUGAGUUGCCCGACCCUCCGUAUCUCAAAAAUUUUUGUACGAUCAACAUACAAAAAUCCUGCCAUUAACAUCUGGAUGCGCAGCUUUGCCUUAUGUGGAAGGUAUCGGGAGGCACAGGAUCUGUCUGAGGGAAGAAGGGAUUUAAACCUAUGUGCCAUUUCGUUUGGUAACAUUCCGUUCGGACCGUUGCGCUUAUCAACGUGCGUACUCACACCAAACAAAUCCAUACCUCUGAUAGUAAGCCUCAAUUAUCGCCAUCUCGUAUGUUCAGGCUUCGUGUCAGUCUGUUGGAUUUGCGUGAUUGUACUAUCUCCACCCCGCCGGAAUGUUCAAAGCCUCCAAUACGAACAUAAACUCCGAUGCGUUACAAACUACCGACAAGGCCCAUCCGAGUCAUGGAUCCUAAUACACGUAAUUAGUGGUAACGCCGGAAAGCUUCGUAGGGAGUACUUCAACACUCGAGAAGCGCUCUUUCCUAUAUCCUGUCAGUCAGAUGGCGGCCGGCGAACUAGUCUAAUGGUGGACGUUUGUGUAAUAUCCUAUACUUGGAACUUCUUCACUAUUCAUGGGCCCCUUCUAUUAGGCGGUAGCGUUUACAAGUUAUGGCCUGUCGUCGAGUCCUUGCCGUCCAGUUUAUCUGAUAACCUUCGGCCGUACCAGGUGAAGGGGGUCCUUCUCUCCUUUUGUAGGAUUUCCCCUUCAUUGUGCGCGGGACUAUUUAGCCCACGCAAGGGAUUGCAUUAUUCUGAGGCGUCUAGUGCUAGACAAUCGUCUGUCGCACCGUACGCUGGGGGUUUAACUACUCGAACCCGAGCCUUAACUGGGUGCCAGAGCAUACUCCAACGCGAAGAGGGUAGCGUGCGAAUAAAAAUCCUUCCUACUAGCGACACGCUUAUCCAUGAUGGGAAGAGCCGAACGCCCCAGCACGGAGAUCCCUCACCGACAGUGACAUGGCUUGAUCUGUUACGUAUUACUUUCAUCCUACCCAUGCGCGGACAUGUCGAGGGCCGACAGAAUAACUUGUCCAUGAUGUCGCUUUCGUGCGGGGUGUGGCUCGGGGCAGAAGCGUCCUUACCGGGACAGGUACUAUUUAUAUAUGGAUCAUCGUCUAAGAUUUCACCCUCGUACAAAGCGGAGGCCAGACCGCAUAGUCGACGUUGCGGAAUGCCUCCUGACGACGUCUAUCACGGUACUGCUUCGUUGGAUGGUGAGGGCCUCGCAUUUGCGUGCUUACCAGGGCUGAUUUCAUUCAGGCCUGGUACCGACGAAAGAUAUCAUCGUGAGUCUAUGACCCGCGCCUUCGAGGAAUGCUGUGCUUAUGACCCACGACUAGUUGUCACGCUACAGCAAGGGCCGCAGCGCUGUAGGUACGCAUAUAUUCUCCGGAAACCAUCACAAAGUCUCCGCCCCGCUGCCGAUGUGAACGACACUAACAAAGAACUUUCAGAUCCGUGCGUUCCGCUACUAACAUUCCGAUCCUGUAUGGGUUUCUGCUUGCGUCGAAUCACAACGACGAUAAGGGCCAAUCCUUCUAAAGUGACCGGGCACGUGAUAUUACAUCUGGGUGUUCUGGCGGCUAAGGACAAUGCCGGCGCAUUGGAAUACCGUACCGGGUCUCUUGGAGUCCAAUACGCCUGGGCUCAUUACCAUCAUCGAACUUACGUCUACUCCCAUGCAACCACGGGAUUAGAUACAAAGGGGUCCUACUCCCGCCGUUCCGAGAUCUGUCAAAUAAAGCAGUUUCGCGACACGUCGCAUGAUGGCGUAUGCGAUUACUUGUAUUUUGAAAAUACGCUUGCUCGAACGAGUGUGCCCCAAAUAAUACAUAUCGCUUUAUCAAACUUCACCGAGUACGGAUGCGUAGGACGAUCGCUUCGUGCCCAGUCAAGGUACAUCUACCCGGAUGGCGUACUAUACCGCGAAGGUAGAGGUAGGAGUUUAGCCAUUUUGGCUCGGGGGUGUGCGCUUGAAUUACACCGUGGGUCUCUGCGUGGGAACUCUGGCGCUAACACUAGGCUCGCUGGGCUUGGCAUAGCCGACCAUAGGUCUCAACGACGAUGCCUUUACGGCAUUGAAAGUCUGGUGGUGGUAGUGUCUAAAGGUCGAUUGGUAUGUCACUGGAUGAACGUUCCACAUCUCACUCCCCUAUACGCAUAUGCUACAAUAGAGCAUAACUCUUUCGGCCAAGUCUGUGGCGAAUUCCGAGGCAUGACCCCACUGCAGUCGGCAAUACAAGCCGAGCAAGAUUGGGUUUUUGCAUCUGAAGUCUUCGUUGGCACGACCGGCAUACAUCAGCAUCAGGCACAGGACUCGCAAUUUUUGCGGGCAGUUAUGUGUACACCAGUUCUAUCUGGCGCCGGUAGUCUUCAAAAUCUUGGCCUGCUUCGAAUUGCAAAGCUAUGGGGCUUUUCGUAUACAGCCCUUAAAGCCUGGUACCUCGUACGAUGGCGCAGGUUACUCCGAUUUCCAUCAAAAAAUAGGACCGCGGCACACCAUGUAGCAGGUCGGAAUGCCUUGGUCUGUAGAUCCGGAAUUGCUACCCCUUACGCGCGGUUUAGCGGCGCCCCAAACGGGGGCAGCAUUUCAGUCUCAUCUUCCGUUAGUGUUUUCCACACGCCCGGCAAGCUAAGGCCCGAACUGCACGCUCGCCCGACCCUUGCGCCCAAAGCGACGAGACAAGACAAACUCAACAGGACGAGCUGCAUUGUCGGGCGCAUCUACGCCUGCAGCAUGAUUAAUCGCCAUAAGCCCAUGAAGCAACCUUUGGGCACAUCUGCCGCCUGGGUUCUGCGUCAAACGCCGUUGACAUGUUGUUCUGGAGAAUCUAACGAGCCUAUCGUAAACGUACGCAUAGGUCAGGAUGAUGCGGUGGAAUCCCUCAAAUCCAAGGAGUGCCCUCCAUAUCUAACCUAUAAAGUCCAUGCCAGGCUGAGCGCAUACGUCAAGCGAUUCUGCCAUCGGCACACAGGCCCAUAUGCCUCAGCUGAUAGUGAACCUGAUGCGGACGCCGAUUUAGGUUUACGUUCACUUGUCCCUCAGCAAGAGACGAGUGAUGCUUCGCUAAAAGGGCGGCACCAGGGCUACAUCUUUCAUAUCAGAGAAGUAACGUUUUGUGCGAUUCGUGUCGAGUUUCCAUUUGGUGGUGACUGUCGAGUCUGUCCCUGUGGUUCACCUGGACCCUUAGCAACGGAGAUUGUAUUCCUAGCCUGGACCGGCCCCCAGCUACAUCUUGAUCGCAUAUCAACCCCCUAUAUAGUCGGGGGUUUCUUUAAACGGGGACCGCUUCCUACAGCCACUUCUUUUAAACGUCACACGCAGGAAGAGGCAGCCUUUUCGUCCCUGUCCGAACGCCAAGUGCAAGGUCUUGCACAUCCACGAGGAGGCUAUAGUUGCUCGAUACUUGAAAAAUAUGCAACGCAACAUUCGUCCGAAGUACACCAAGGUAGUCGAGUCAACGCCCGACGAGUUCUUUGGACUUCCAUUACAUUUACGGAGCAGGUGCAAGCGACUACGGUUUUGGGCCGAUUUCAUUCUAGUCGCCUUCGGUCCGUCCCUUGUACGGUCGGGGCUCAGAUCAGCCUGUAUUGUUCUAAAAGUACUAGUAUAAGGACUAGACCUCUGCUGUCCGUUGAUCUGGUAAAUUGCCGUGCGAAUUUGCUUGCAGCGUCAAGAAACAUCGGGACGGAGUUAUUGGAUGAAUGGCAUCAGGAUGCAGGGACAAACGGGCCUCUCGGCUGCUCGUAUUUAGCGUGCCUCGCUGGAAUAUGUCUAAUUACGUGUACAACGCACCUAAACCACGCUGCGCACGGACAACAUCUUUUACUCCCGCUGGCCGGGUCUACGUCGCCGGUCCUUGACAGGGGGGAUCUAUGCCCGGGCGAUUCGGCUCUUCGUCGGACUGGACAGGGGAAAGCAUAUUCUAGAUUUGAGGUUUUCAGUCAGCGGAUGUGUUUUUCAAUACCGCGGAAGGUCAGCCAUACACUCCAGAUCCCGGGCACGCUGCUAAUCUAUCAAGGGGGACUGAUUUUAUACUGCCGGACCCAUUGUAUCACUUUUUCAAGCAGCGACGUGGCCCGUGCUGUUACCGCACUCGCACAAAGCUCGCGUAUUCGGAGACGUUCGGACCCUCACCUGGGAGCACGGAACCGCCGCGAAGCGAGCGUGGAUGACCGUGCGCUACUCCUGCGUCAACGUUGGUGGGAUAUCCCACCGAUACCAGAGUCUUCUGUAUCCACCACGACUAUGUUCGCGCACCCCUACUUGAGGAGACGACUUGCACAAGGUUGGGAAAACAUAAUCCAGCCUCGUCAACUUGUCGCCAACUUCGCGAUUUUGCACUUUCGCGCAACCCCCCAAAGUGUACCUGGAGAAACCAACAAAAGUGGUGUAGCCGUCAGAAAUGUGAGGGGGGUCCGGUUUUAUGCAAGGUUGAGAGUAGGCGAGGUACAUGGUGCCACGGGGAGGCUCGAAGCCUGGCCGUCCUUGGAGAUCACUGGGCUGCUGGAUACGCCAGUGUUAUCGCAAGGACAUCUCCAACGGGUUCGCUCACACCCCAAUCAUCGAUCGGUGCGAAAUGCCAAUUGGGAACACGGACCGAAACACAUCGAUAGACUAAGUUCGGGAUUCCUUUGUGCUCGGCCCGUGCUGGUUGAACUCCAUCAAGUGCUCAGCACUGUGACACGGGAUUCGGGAGCGCAAUCGAGCGGGGGAGAAAUUUACGCAUGUGGUUCGCGCAACUAUGUUUUACAAGAGGCUAUGAGGCCCACUCAUGCUAUGCCUACGGUUCCCAUAGCUAAAACACCAUACGGAACGCUACGUCACCGGGCUAGAGGACCCAGCUUGAGCACAACUCAUAUAGAUUCACCCGUACCGCGCAAGUCACGAAGUAGGUCAAUCAUGCGGUGUCAGUCCUAUUCGACGCACCUCCUGCAGCCGACGGUCAACCGCAUGCUGGAAAGCUAUUCCGCAAACGUAAACACUUGUUUCUUUUCGGCAAACCGUAUAAGUCGCCUGCCCAUUGAAGACUCUAAUCUAAACAGUUCAAUUGAGAUACAUCGGCGGGCAUGCACCAGGAAUCUAUUGAACAACCAUUCAAUAAGGGAAGUAUGCAACGAGCUAGAUUGGGCCGCGGCGCAGAGUAUCUCAUCUUAUAGUUCACCUACGCUUGUUAGGAAUCUGUGCAACGUUUACAGUACACAACAGGGAAAGUCCGACGAGAUAGGGGAGAGGCAGGUACGGUGUUCGUACAAGCCUUCGGUUCUGGUCAAUUUGUCUGUGCCUUGGAAAUACAUCAGGCGGUCGAUAGACCGACCCCUAAAGUGCCCGUGCAGGCUGCUUCUUCAAGGCUCGUGUGGAACGAAAUUACCUUCUUUAUAUCUUGUUACGGUAGCCUUCUCAGGGCAACAUGGCGGCAUUGCCUCUGGCCGAUUAGUGCGCAGCCGCGAAGGGUGUUUAGUACAUCAAUACGGGGGUGAUACCCGAAAUUCCUUAUAUGCAAAUGAAGCGGGUGCGAGUGGGCUAAGUUCAUACCGAACUGUGGGAGGCGCGAUUGCUCUGCACCCCGCAAAAGUGAUCCUCCAUGGUCUCCAUGCGAACCUUACUUUACUGGGAAUGGUCCGACGGUUAGCUUAUACAUAUAACUUGGCAGGGAGGAAGAUGCUUCAUUAUGUUAUUGCGUAUAAUUGUAGAUUGAGACACGCGGUAAUAGUACAUCAGAGCCGUCGAGACCUCUGUCCCUCCAGACUCGUACCAGGGUCUCUAUUUCAUUUACAAGAUGUGUUAGGGGUGACAUGGGGGAACGUAUCAGAGACUCCUAGUUGGUACAGGAGCGAAUAUCAGCCAGCAUUCCUAACGACGGGUACGCUUAAUGCGCCACGCUUCUGCAAGGGUAAGCUCAAACUACAGGACUUGAAACAUCCCCAUUAUCAGUGUAUCCGCCAUUCCUUCAGACAGACAUUAUCCGUGUACCGACCCGGUCCGAGUAUCGGCAUAGCGUUAAAUCGAGUAAAACUUUUAGAGAUGAAUUGUGUACCCGAGAUGCGCUAUGUCUACAGGAAAAAGAGCAGUGCAAUUCCAAUUGUGUCAGGUUUGUUAGUGCGUACGGAGAAUUUAGCCAUUACAAUGCGGGGCCGAUCGUAUGGGCAGGGCUGCCAUUCAUUUACGCAAACUAUAUUGCGGCAUGAAAUGGGAAUUUUCUCGCUGCCCGCGGCCGCCGCUCCCUACGUUCAAGUGACUCGAUCCGGUUCUCCGUCGUCCAACGUGCUAGAAACAGUUGAGUCGAAUCGAUUCCGUAACAAACGCGUGGUGUUUUACCAUACAUCCACGCAGAGCCGUGUCGCCCUUCGGUUGCUAGCCGCCUCGUCAAUUCAGGGCUCGACGACACGGCAGCCUACGCAAGAAUUCACGCAGCCAAGUAGUGUUACUUGGGUCUGGAGUUACCGCAUACCUGAAGACGCAUCGGCUAUCACCUUCUCCAUCGUGUCUGUGUCGGAAUGGUGCUUUAACACCAAACUGGAAAGAUACUGCAAUUGGGUGAUAUGUCCAUUGCAUUUGUUCAGCGCCAUCCCCACGUUAAUGGCGAGCCAAGAAGAACAUCGACCGCCUGCUUCCGACUGCGCGAGGAUGGUAGCCCCUCGUUACGCACCAUUCUACCCAGAUUGUAGCGAAGUUUGGCCGGUGUGGCCACUCCAUAUGAGUGUCGGGGAAGUGAGUAGAAAGCGCCCUUUCGACAGUGUGACUAAAGCGUGUUGUGAAACUCCCGCGCGUAAGCUGUCUGAGUAUUCAGCACGUACGGGCUUCGUGUCAAUGCUGGACGCAACAAGAAGAGGAUAUGUCUGUUCAAUGUCGGACAUUGAGGACUACCCUGUAGAUUUGGUCCAGGUCUCCGAUCGGUGUUUCUGGGUCAACUUACUAUCUCUCCCGUAUCACGCCAGGUGGGCUAUUUCACGGCAACCCUCCAUUGCGCUAUUAAGUCGCCCCAUGCGGAUGUUAGUUAACAGAGGCACAUUGGUCCUUACUACCGCGACAAUACGGUCGGAAGCACCAUUUUUUGAAAGCCGUUCCUCAGGAGUGUCGAUUACGUGUGUCAAGUCCUUAGUAUCUAUCGAAGUCGACUUACUUGUGCCGCCCUGCCUGAGAUGUCGCCUAAGUAAAGGCAGGCAUCGCAGCCACACCGUUAUAGCAUUGGUACUGCAAUACCUCAUCCUUAAGAUACACAUUCUUGGAGUAGGCGGCUUUACUGGGCGAACUCUACACCAUACAUUUAGAACAGACUCAUGGGCAUACGUAUGGUGUCCAAAUCCCAUCAUUUUACUUUUGGUUGACUGCUCUCUAGAACGUUCGUCCGCAAACUACUCGCUGACAUCAAGGGCUUGGACGCGGCAAAAAGGGACUAUAGGCAUUAUCCAUUACGGGACUGACAGAAAUGGCCCUCCAGAGAUCAGCCCUGUACUGAUCGCUACUUUUAAAGCUACCUUCAGGAGUCCAUUAAAGCUUACGUUCCACUACUCCAAAGUACGUGUUCCCCCUGAUAGUGCUAUAGACAGGGAGUCAGCAUACCUCGGGUCCUUGGUUCACCUACGCAAAAAUCGAGGGGCUCUUGCGGGCUCUCGCAUGUACCGCAACAUUGGCCAACUAACUGCCCCCUUGCCAGGCCUAACACACAAUCUCAUUUUCCACACCUACACCGAUGAAGCUUCCGUGCAAAACUGGACGCGGCCCUUCUCCCUAGAUAAAAUCGCGGCGGGCGUAGCGUCACUAGCCCCUAGAGGAGUCGGGCACAGGCCGGUCUUCGCUAUUACUCGUAGGGUACUAAGGGGGGGCGGACGGAAUUCUGGUCGCUCUAUGGCUCACAUUAGGCAUACACCCACCAUAGGCUGCAGCCAGGUUCAAAUUCUCUCUUUGACCACGAUAAUUAUCUGCCGAAGGCUUUCUGACCAGGCGCCACCGUUGGGGAAAAGGUCUCAUCGCCUGCGGGCUCUCGGCAACAACGUCCUACCAGGCAGUUGGCGUUAUGAUCAACGAAAUGAAACGACUGGGUGUUUUUUUCGGAUGAGGUGGAUGAAAGGAACGGCAGUAGCCCCUAACCCCCCUCAUGACAAGAUAUCAUCUAAUCUCAACACGAUCCCUGUGGCAAGCAGUGAGUCGCCCUUUCCGAGGUUAGAAAGUCUACCCGGAUUAUAUCCGCGCCCAGGAAGGAGCGUCAUACAUGCUGCAAAUGCUGCUACAGCGAGAACAGUGUGUUGUUACCAAGUCGUGAGAGGCUCAUCUCACCGUAGGCGUACUGAAUUCUUCGAGGUGCGUUUAGACGGUGAUCGAGGCGCCCAAGUCCUUGGGACACGAAAAGCCGUAUCGAGCGCAACGAAUUCGGGCAGGUUAUACACUCAGCUUACAUUUGUAGUCAUAUAUCGGCUGGUAACUGCGGCGCCUACAUUCAAGUCUUCACCGAAAGCCUAUUGCCAAACCGCCGACGAAGACAACUCGUCUGGUAUAUGUGUCAUAGAAGCAGUACUGAAGCUGCUUCCUGCUACGAUGCCCACUAAGCCCUUCGCCACGUGGGCCUCACUACACAUAAGAGCGCCGCGACAUGGAAGCGUUGGACAAUAUUGGAUACUCGGUCCAAGCGGUGGAAAGAUUACUUCUUCACCGCUCUCGAAGCACCGGCAGAACGGGAGUUCUGGGACCAAAUCGUCGAUUGCCGACGAAAUAUUAGGCUUGUUGGCGUUCAGUACAUCUCCCACUAUUACUAUGCGACAAGGGCCUACUGCCGCGAUUUUCACCAAUGGCAACGGGGUAAUGCCCCGGCGCUGGACACAAUGGCGUAGCCCUUACGCUAUACCCCGCGCACCCUCGGCAGGUCACUACCCAACUGUUGUGUCAAGUAAAAAGAUCGGGUGGAUGUCCAACACCAGUCGAAUGGCUUCAAAGGAUGGUCUCCUGCUACGCCUUGUGAAGGUUCCCGAACGCUUUAAGCGGAGCAUACAGGGGCCCGAAAGUUCCUGGCCCAAGUUUGCACGGUACGCGUAUGCGCCUAUACCUCAAACGUAUUUUUCUUUGCCGCAGCGGUAUUGCAUACAUCGUUUCGGUUUAUUUAGCACGCUCCCUCGUAAGCUUUAUCGAGGUCACGAGAAAAAUCUCUGGAAUUUGCAGCCAUGUGGUUACCACACCACUCUGCGAAGAACCUCGGCCGACGCACGGGCAUCACGCAUAGUUGGUACUUCGGAGGAGUGGGUCAGAGAGCUAGGGCCAGGUGAGGCGAGCAGCAUCGCGGGGAGUGGUGCUUCUCUGAGCAGUUGUUCUUCGAGUGUCUUCAGGGGGCAGCGUGAGAGGCUAUCACACAUUACAAAUUCGUCCAUGCUCCGCUCUUAUCUGUCGCCACUGUACUGUCAGGUACCUUAG' print(rna_to_protein(rna))
def rna_to_protein(rna): """ Takes a string and returns a protein sequence WIHOUT using biopython Input params: rna = rna string Output params: protein = protein sequence """ codon = [] protein = [] while rna: codon.append(rna[:3]) rna = rna[3:] for triplet in codon: if triplet == 'AUG': protein.append('M') elif triplet == 'GCC' or triplet == 'GCG' or triplet == 'GCU' or (triplet == 'GCA'): protein.append('A') elif triplet == 'UUU' or triplet == 'UUC': protein.append('F') elif triplet == 'UUA' or triplet == 'UUG': protein.append('L') elif triplet == 'UCU' or triplet == 'UCC' or triplet == 'UCA' or (triplet == 'UCG'): protein.append('S') elif triplet == 'UAU' or triplet == 'UAC': protein.append('Y') elif triplet == 'UAA' or triplet == 'UGA': break elif triplet == 'UGU' or triplet == 'UGC': protein.append('C') elif triplet == 'UGG': protein.append('W') elif triplet == 'CUU' or triplet == 'CUC' or triplet == 'CUA' or (triplet == 'CUG'): protein.append('L') elif triplet == 'CCU' or triplet == 'CCC' or triplet == 'CCA' or (triplet == 'CCG'): protein.append('P') elif triplet == 'CAU' or triplet == 'CAC': protein.append('H') elif triplet == 'CAA' or triplet == 'CAG': protein.append('Q') elif triplet == 'CGU' or triplet == 'CGC' or triplet == 'CGA' or (triplet == 'CGG'): protein.append('R') elif triplet == 'AUU' or triplet == 'AUC' or triplet == 'AUA': protein.append('I') elif triplet == 'ACU' or triplet == 'ACC' or triplet == 'ACA' or (triplet == 'ACG'): protein.append('T') elif triplet == 'AAU' or triplet == 'AAC': protein.append('N') elif triplet == 'AAA' or triplet == 'AAG': protein.append('K') elif triplet == 'AGU' or triplet == 'AGC': protein.append('S') elif triplet == 'AGA' or triplet == 'AGG': protein.append('R') elif triplet == 'GUU' or triplet == 'GUC' or triplet == 'GUA' or (triplet == 'GUG'): protein.append('V') elif triplet == 'GAU' or triplet == 'GAC': protein.append('D') elif triplet == 'GAA' or triplet == 'GAG': protein.append('E') elif triplet == 'GGU' or triplet == 'GGC' or triplet == 'GGA' or (triplet == 'GGG'): protein.append('G') protein = ''.join(protein) return protein rna = 'AUGAGUUGCCCGACCCUCCGUAUCUCAAAAAUUUUUGUACGAUCAACAUACAAAAAUCCUGCCAUUAACAUCUGGAUGCGCAGCUUUGCCUUAUGUGGAAGGUAUCGGGAGGCACAGGAUCUGUCUGAGGGAAGAAGGGAUUUAAACCUAUGUGCCAUUUCGUUUGGUAACAUUCCGUUCGGACCGUUGCGCUUAUCAACGUGCGUACUCACACCAAACAAAUCCAUACCUCUGAUAGUAAGCCUCAAUUAUCGCCAUCUCGUAUGUUCAGGCUUCGUGUCAGUCUGUUGGAUUUGCGUGAUUGUACUAUCUCCACCCCGCCGGAAUGUUCAAAGCCUCCAAUACGAACAUAAACUCCGAUGCGUUACAAACUACCGACAAGGCCCAUCCGAGUCAUGGAUCCUAAUACACGUAAUUAGUGGUAACGCCGGAAAGCUUCGUAGGGAGUACUUCAACACUCGAGAAGCGCUCUUUCCUAUAUCCUGUCAGUCAGAUGGCGGCCGGCGAACUAGUCUAAUGGUGGACGUUUGUGUAAUAUCCUAUACUUGGAACUUCUUCACUAUUCAUGGGCCCCUUCUAUUAGGCGGUAGCGUUUACAAGUUAUGGCCUGUCGUCGAGUCCUUGCCGUCCAGUUUAUCUGAUAACCUUCGGCCGUACCAGGUGAAGGGGGUCCUUCUCUCCUUUUGUAGGAUUUCCCCUUCAUUGUGCGCGGGACUAUUUAGCCCACGCAAGGGAUUGCAUUAUUCUGAGGCGUCUAGUGCUAGACAAUCGUCUGUCGCACCGUACGCUGGGGGUUUAACUACUCGAACCCGAGCCUUAACUGGGUGCCAGAGCAUACUCCAACGCGAAGAGGGUAGCGUGCGAAUAAAAAUCCUUCCUACUAGCGACACGCUUAUCCAUGAUGGGAAGAGCCGAACGCCCCAGCACGGAGAUCCCUCACCGACAGUGACAUGGCUUGAUCUGUUACGUAUUACUUUCAUCCUACCCAUGCGCGGACAUGUCGAGGGCCGACAGAAUAACUUGUCCAUGAUGUCGCUUUCGUGCGGGGUGUGGCUCGGGGCAGAAGCGUCCUUACCGGGACAGGUACUAUUUAUAUAUGGAUCAUCGUCUAAGAUUUCACCCUCGUACAAAGCGGAGGCCAGACCGCAUAGUCGACGUUGCGGAAUGCCUCCUGACGACGUCUAUCACGGUACUGCUUCGUUGGAUGGUGAGGGCCUCGCAUUUGCGUGCUUACCAGGGCUGAUUUCAUUCAGGCCUGGUACCGACGAAAGAUAUCAUCGUGAGUCUAUGACCCGCGCCUUCGAGGAAUGCUGUGCUUAUGACCCACGACUAGUUGUCACGCUACAGCAAGGGCCGCAGCGCUGUAGGUACGCAUAUAUUCUCCGGAAACCAUCACAAAGUCUCCGCCCCGCUGCCGAUGUGAACGACACUAACAAAGAACUUUCAGAUCCGUGCGUUCCGCUACUAACAUUCCGAUCCUGUAUGGGUUUCUGCUUGCGUCGAAUCACAACGACGAUAAGGGCCAAUCCUUCUAAAGUGACCGGGCACGUGAUAUUACAUCUGGGUGUUCUGGCGGCUAAGGACAAUGCCGGCGCAUUGGAAUACCGUACCGGGUCUCUUGGAGUCCAAUACGCCUGGGCUCAUUACCAUCAUCGAACUUACGUCUACUCCCAUGCAACCACGGGAUUAGAUACAAAGGGGUCCUACUCCCGCCGUUCCGAGAUCUGUCAAAUAAAGCAGUUUCGCGACACGUCGCAUGAUGGCGUAUGCGAUUACUUGUAUUUUGAAAAUACGCUUGCUCGAACGAGUGUGCCCCAAAUAAUACAUAUCGCUUUAUCAAACUUCACCGAGUACGGAUGCGUAGGACGAUCGCUUCGUGCCCAGUCAAGGUACAUCUACCCGGAUGGCGUACUAUACCGCGAAGGUAGAGGUAGGAGUUUAGCCAUUUUGGCUCGGGGGUGUGCGCUUGAAUUACACCGUGGGUCUCUGCGUGGGAACUCUGGCGCUAACACUAGGCUCGCUGGGCUUGGCAUAGCCGACCAUAGGUCUCAACGACGAUGCCUUUACGGCAUUGAAAGUCUGGUGGUGGUAGUGUCUAAAGGUCGAUUGGUAUGUCACUGGAUGAACGUUCCACAUCUCACUCCCCUAUACGCAUAUGCUACAAUAGAGCAUAACUCUUUCGGCCAAGUCUGUGGCGAAUUCCGAGGCAUGACCCCACUGCAGUCGGCAAUACAAGCCGAGCAAGAUUGGGUUUUUGCAUCUGAAGUCUUCGUUGGCACGACCGGCAUACAUCAGCAUCAGGCACAGGACUCGCAAUUUUUGCGGGCAGUUAUGUGUACACCAGUUCUAUCUGGCGCCGGUAGUCUUCAAAAUCUUGGCCUGCUUCGAAUUGCAAAGCUAUGGGGCUUUUCGUAUACAGCCCUUAAAGCCUGGUACCUCGUACGAUGGCGCAGGUUACUCCGAUUUCCAUCAAAAAAUAGGACCGCGGCACACCAUGUAGCAGGUCGGAAUGCCUUGGUCUGUAGAUCCGGAAUUGCUACCCCUUACGCGCGGUUUAGCGGCGCCCCAAACGGGGGCAGCAUUUCAGUCUCAUCUUCCGUUAGUGUUUUCCACACGCCCGGCAAGCUAAGGCCCGAACUGCACGCUCGCCCGACCCUUGCGCCCAAAGCGACGAGACAAGACAAACUCAACAGGACGAGCUGCAUUGUCGGGCGCAUCUACGCCUGCAGCAUGAUUAAUCGCCAUAAGCCCAUGAAGCAACCUUUGGGCACAUCUGCCGCCUGGGUUCUGCGUCAAACGCCGUUGACAUGUUGUUCUGGAGAAUCUAACGAGCCUAUCGUAAACGUACGCAUAGGUCAGGAUGAUGCGGUGGAAUCCCUCAAAUCCAAGGAGUGCCCUCCAUAUCUAACCUAUAAAGUCCAUGCCAGGCUGAGCGCAUACGUCAAGCGAUUCUGCCAUCGGCACACAGGCCCAUAUGCCUCAGCUGAUAGUGAACCUGAUGCGGACGCCGAUUUAGGUUUACGUUCACUUGUCCCUCAGCAAGAGACGAGUGAUGCUUCGCUAAAAGGGCGGCACCAGGGCUACAUCUUUCAUAUCAGAGAAGUAACGUUUUGUGCGAUUCGUGUCGAGUUUCCAUUUGGUGGUGACUGUCGAGUCUGUCCCUGUGGUUCACCUGGACCCUUAGCAACGGAGAUUGUAUUCCUAGCCUGGACCGGCCCCCAGCUACAUCUUGAUCGCAUAUCAACCCCCUAUAUAGUCGGGGGUUUCUUUAAACGGGGACCGCUUCCUACAGCCACUUCUUUUAAACGUCACACGCAGGAAGAGGCAGCCUUUUCGUCCCUGUCCGAACGCCAAGUGCAAGGUCUUGCACAUCCACGAGGAGGCUAUAGUUGCUCGAUACUUGAAAAAUAUGCAACGCAACAUUCGUCCGAAGUACACCAAGGUAGUCGAGUCAACGCCCGACGAGUUCUUUGGACUUCCAUUACAUUUACGGAGCAGGUGCAAGCGACUACGGUUUUGGGCCGAUUUCAUUCUAGUCGCCUUCGGUCCGUCCCUUGUACGGUCGGGGCUCAGAUCAGCCUGUAUUGUUCUAAAAGUACUAGUAUAAGGACUAGACCUCUGCUGUCCGUUGAUCUGGUAAAUUGCCGUGCGAAUUUGCUUGCAGCGUCAAGAAACAUCGGGACGGAGUUAUUGGAUGAAUGGCAUCAGGAUGCAGGGACAAACGGGCCUCUCGGCUGCUCGUAUUUAGCGUGCCUCGCUGGAAUAUGUCUAAUUACGUGUACAACGCACCUAAACCACGCUGCGCACGGACAACAUCUUUUACUCCCGCUGGCCGGGUCUACGUCGCCGGUCCUUGACAGGGGGGAUCUAUGCCCGGGCGAUUCGGCUCUUCGUCGGACUGGACAGGGGAAAGCAUAUUCUAGAUUUGAGGUUUUCAGUCAGCGGAUGUGUUUUUCAAUACCGCGGAAGGUCAGCCAUACACUCCAGAUCCCGGGCACGCUGCUAAUCUAUCAAGGGGGACUGAUUUUAUACUGCCGGACCCAUUGUAUCACUUUUUCAAGCAGCGACGUGGCCCGUGCUGUUACCGCACUCGCACAAAGCUCGCGUAUUCGGAGACGUUCGGACCCUCACCUGGGAGCACGGAACCGCCGCGAAGCGAGCGUGGAUGACCGUGCGCUACUCCUGCGUCAACGUUGGUGGGAUAUCCCACCGAUACCAGAGUCUUCUGUAUCCACCACGACUAUGUUCGCGCACCCCUACUUGAGGAGACGACUUGCACAAGGUUGGGAAAACAUAAUCCAGCCUCGUCAACUUGUCGCCAACUUCGCGAUUUUGCACUUUCGCGCAACCCCCCAAAGUGUACCUGGAGAAACCAACAAAAGUGGUGUAGCCGUCAGAAAUGUGAGGGGGGUCCGGUUUUAUGCAAGGUUGAGAGUAGGCGAGGUACAUGGUGCCACGGGGAGGCUCGAAGCCUGGCCGUCCUUGGAGAUCACUGGGCUGCUGGAUACGCCAGUGUUAUCGCAAGGACAUCUCCAACGGGUUCGCUCACACCCCAAUCAUCGAUCGGUGCGAAAUGCCAAUUGGGAACACGGACCGAAACACAUCGAUAGACUAAGUUCGGGAUUCCUUUGUGCUCGGCCCGUGCUGGUUGAACUCCAUCAAGUGCUCAGCACUGUGACACGGGAUUCGGGAGCGCAAUCGAGCGGGGGAGAAAUUUACGCAUGUGGUUCGCGCAACUAUGUUUUACAAGAGGCUAUGAGGCCCACUCAUGCUAUGCCUACGGUUCCCAUAGCUAAAACACCAUACGGAACGCUACGUCACCGGGCUAGAGGACCCAGCUUGAGCACAACUCAUAUAGAUUCACCCGUACCGCGCAAGUCACGAAGUAGGUCAAUCAUGCGGUGUCAGUCCUAUUCGACGCACCUCCUGCAGCCGACGGUCAACCGCAUGCUGGAAAGCUAUUCCGCAAACGUAAACACUUGUUUCUUUUCGGCAAACCGUAUAAGUCGCCUGCCCAUUGAAGACUCUAAUCUAAACAGUUCAAUUGAGAUACAUCGGCGGGCAUGCACCAGGAAUCUAUUGAACAACCAUUCAAUAAGGGAAGUAUGCAACGAGCUAGAUUGGGCCGCGGCGCAGAGUAUCUCAUCUUAUAGUUCACCUACGCUUGUUAGGAAUCUGUGCAACGUUUACAGUACACAACAGGGAAAGUCCGACGAGAUAGGGGAGAGGCAGGUACGGUGUUCGUACAAGCCUUCGGUUCUGGUCAAUUUGUCUGUGCCUUGGAAAUACAUCAGGCGGUCGAUAGACCGACCCCUAAAGUGCCCGUGCAGGCUGCUUCUUCAAGGCUCGUGUGGAACGAAAUUACCUUCUUUAUAUCUUGUUACGGUAGCCUUCUCAGGGCAACAUGGCGGCAUUGCCUCUGGCCGAUUAGUGCGCAGCCGCGAAGGGUGUUUAGUACAUCAAUACGGGGGUGAUACCCGAAAUUCCUUAUAUGCAAAUGAAGCGGGUGCGAGUGGGCUAAGUUCAUACCGAACUGUGGGAGGCGCGAUUGCUCUGCACCCCGCAAAAGUGAUCCUCCAUGGUCUCCAUGCGAACCUUACUUUACUGGGAAUGGUCCGACGGUUAGCUUAUACAUAUAACUUGGCAGGGAGGAAGAUGCUUCAUUAUGUUAUUGCGUAUAAUUGUAGAUUGAGACACGCGGUAAUAGUACAUCAGAGCCGUCGAGACCUCUGUCCCUCCAGACUCGUACCAGGGUCUCUAUUUCAUUUACAAGAUGUGUUAGGGGUGACAUGGGGGAACGUAUCAGAGACUCCUAGUUGGUACAGGAGCGAAUAUCAGCCAGCAUUCCUAACGACGGGUACGCUUAAUGCGCCACGCUUCUGCAAGGGUAAGCUCAAACUACAGGACUUGAAACAUCCCCAUUAUCAGUGUAUCCGCCAUUCCUUCAGACAGACAUUAUCCGUGUACCGACCCGGUCCGAGUAUCGGCAUAGCGUUAAAUCGAGUAAAACUUUUAGAGAUGAAUUGUGUACCCGAGAUGCGCUAUGUCUACAGGAAAAAGAGCAGUGCAAUUCCAAUUGUGUCAGGUUUGUUAGUGCGUACGGAGAAUUUAGCCAUUACAAUGCGGGGCCGAUCGUAUGGGCAGGGCUGCCAUUCAUUUACGCAAACUAUAUUGCGGCAUGAAAUGGGAAUUUUCUCGCUGCCCGCGGCCGCCGCUCCCUACGUUCAAGUGACUCGAUCCGGUUCUCCGUCGUCCAACGUGCUAGAAACAGUUGAGUCGAAUCGAUUCCGUAACAAACGCGUGGUGUUUUACCAUACAUCCACGCAGAGCCGUGUCGCCCUUCGGUUGCUAGCCGCCUCGUCAAUUCAGGGCUCGACGACACGGCAGCCUACGCAAGAAUUCACGCAGCCAAGUAGUGUUACUUGGGUCUGGAGUUACCGCAUACCUGAAGACGCAUCGGCUAUCACCUUCUCCAUCGUGUCUGUGUCGGAAUGGUGCUUUAACACCAAACUGGAAAGAUACUGCAAUUGGGUGAUAUGUCCAUUGCAUUUGUUCAGCGCCAUCCCCACGUUAAUGGCGAGCCAAGAAGAACAUCGACCGCCUGCUUCCGACUGCGCGAGGAUGGUAGCCCCUCGUUACGCACCAUUCUACCCAGAUUGUAGCGAAGUUUGGCCGGUGUGGCCACUCCAUAUGAGUGUCGGGGAAGUGAGUAGAAAGCGCCCUUUCGACAGUGUGACUAAAGCGUGUUGUGAAACUCCCGCGCGUAAGCUGUCUGAGUAUUCAGCACGUACGGGCUUCGUGUCAAUGCUGGACGCAACAAGAAGAGGAUAUGUCUGUUCAAUGUCGGACAUUGAGGACUACCCUGUAGAUUUGGUCCAGGUCUCCGAUCGGUGUUUCUGGGUCAACUUACUAUCUCUCCCGUAUCACGCCAGGUGGGCUAUUUCACGGCAACCCUCCAUUGCGCUAUUAAGUCGCCCCAUGCGGAUGUUAGUUAACAGAGGCACAUUGGUCCUUACUACCGCGACAAUACGGUCGGAAGCACCAUUUUUUGAAAGCCGUUCCUCAGGAGUGUCGAUUACGUGUGUCAAGUCCUUAGUAUCUAUCGAAGUCGACUUACUUGUGCCGCCCUGCCUGAGAUGUCGCCUAAGUAAAGGCAGGCAUCGCAGCCACACCGUUAUAGCAUUGGUACUGCAAUACCUCAUCCUUAAGAUACACAUUCUUGGAGUAGGCGGCUUUACUGGGCGAACUCUACACCAUACAUUUAGAACAGACUCAUGGGCAUACGUAUGGUGUCCAAAUCCCAUCAUUUUACUUUUGGUUGACUGCUCUCUAGAACGUUCGUCCGCAAACUACUCGCUGACAUCAAGGGCUUGGACGCGGCAAAAAGGGACUAUAGGCAUUAUCCAUUACGGGACUGACAGAAAUGGCCCUCCAGAGAUCAGCCCUGUACUGAUCGCUACUUUUAAAGCUACCUUCAGGAGUCCAUUAAAGCUUACGUUCCACUACUCCAAAGUACGUGUUCCCCCUGAUAGUGCUAUAGACAGGGAGUCAGCAUACCUCGGGUCCUUGGUUCACCUACGCAAAAAUCGAGGGGCUCUUGCGGGCUCUCGCAUGUACCGCAACAUUGGCCAACUAACUGCCCCCUUGCCAGGCCUAACACACAAUCUCAUUUUCCACACCUACACCGAUGAAGCUUCCGUGCAAAACUGGACGCGGCCCUUCUCCCUAGAUAAAAUCGCGGCGGGCGUAGCGUCACUAGCCCCUAGAGGAGUCGGGCACAGGCCGGUCUUCGCUAUUACUCGUAGGGUACUAAGGGGGGGCGGACGGAAUUCUGGUCGCUCUAUGGCUCACAUUAGGCAUACACCCACCAUAGGCUGCAGCCAGGUUCAAAUUCUCUCUUUGACCACGAUAAUUAUCUGCCGAAGGCUUUCUGACCAGGCGCCACCGUUGGGGAAAAGGUCUCAUCGCCUGCGGGCUCUCGGCAACAACGUCCUACCAGGCAGUUGGCGUUAUGAUCAACGAAAUGAAACGACUGGGUGUUUUUUUCGGAUGAGGUGGAUGAAAGGAACGGCAGUAGCCCCUAACCCCCCUCAUGACAAGAUAUCAUCUAAUCUCAACACGAUCCCUGUGGCAAGCAGUGAGUCGCCCUUUCCGAGGUUAGAAAGUCUACCCGGAUUAUAUCCGCGCCCAGGAAGGAGCGUCAUACAUGCUGCAAAUGCUGCUACAGCGAGAACAGUGUGUUGUUACCAAGUCGUGAGAGGCUCAUCUCACCGUAGGCGUACUGAAUUCUUCGAGGUGCGUUUAGACGGUGAUCGAGGCGCCCAAGUCCUUGGGACACGAAAAGCCGUAUCGAGCGCAACGAAUUCGGGCAGGUUAUACACUCAGCUUACAUUUGUAGUCAUAUAUCGGCUGGUAACUGCGGCGCCUACAUUCAAGUCUUCACCGAAAGCCUAUUGCCAAACCGCCGACGAAGACAACUCGUCUGGUAUAUGUGUCAUAGAAGCAGUACUGAAGCUGCUUCCUGCUACGAUGCCCACUAAGCCCUUCGCCACGUGGGCCUCACUACACAUAAGAGCGCCGCGACAUGGAAGCGUUGGACAAUAUUGGAUACUCGGUCCAAGCGGUGGAAAGAUUACUUCUUCACCGCUCUCGAAGCACCGGCAGAACGGGAGUUCUGGGACCAAAUCGUCGAUUGCCGACGAAAUAUUAGGCUUGUUGGCGUUCAGUACAUCUCCCACUAUUACUAUGCGACAAGGGCCUACUGCCGCGAUUUUCACCAAUGGCAACGGGGUAAUGCCCCGGCGCUGGACACAAUGGCGUAGCCCUUACGCUAUACCCCGCGCACCCUCGGCAGGUCACUACCCAACUGUUGUGUCAAGUAAAAAGAUCGGGUGGAUGUCCAACACCAGUCGAAUGGCUUCAAAGGAUGGUCUCCUGCUACGCCUUGUGAAGGUUCCCGAACGCUUUAAGCGGAGCAUACAGGGGCCCGAAAGUUCCUGGCCCAAGUUUGCACGGUACGCGUAUGCGCCUAUACCUCAAACGUAUUUUUCUUUGCCGCAGCGGUAUUGCAUACAUCGUUUCGGUUUAUUUAGCACGCUCCCUCGUAAGCUUUAUCGAGGUCACGAGAAAAAUCUCUGGAAUUUGCAGCCAUGUGGUUACCACACCACUCUGCGAAGAACCUCGGCCGACGCACGGGCAUCACGCAUAGUUGGUACUUCGGAGGAGUGGGUCAGAGAGCUAGGGCCAGGUGAGGCGAGCAGCAUCGCGGGGAGUGGUGCUUCUCUGAGCAGUUGUUCUUCGAGUGUCUUCAGGGGGCAGCGUGAGAGGCUAUCACACAUUACAAAUUCGUCCAUGCUCCGCUCUUAUCUGUCGCCACUGUACUGUCAGGUACCUUAG' print(rna_to_protein(rna))
PROG_NAME = "MTSv" VERSION = "2.0.0" DEFAULT_CFG_FNAME = "mtsv.cfg" DEFAULT_LOG_FNAME = "mtsv_{COMMAND}_{TIMESTAMP}.log" CONFIG_STRING = """ # NOTE: Changes to the config file in the middle of the pipeline # may force previous steps to be rerun. # # =============================================================== # # READPREP: {readprep_description} # # =============================================================== # {fastq_pattern_description} fastq_pattern: {fastq_pattern_default} # {fastp_params_description} fastp_params: {fastp_params_default} # {kmer_size_description} kmer_size: {kmer_size_default} # =============================================================== # # BINNING: {binning_description} # # =============================================================== # {database_config_description} database_config: {database_path} # {edits_description} edits: {edits_default} # {binning_mode_description} binning_mode: {binning_mode_default} # {max_hits_description} max_hits: {max_hits_default} # {seed_size_description} # Uncomment (remove "#" before name) to modify this parameter # This will override the value set for the BINNING_MODE. # seed_size: # {min_seeds_description} # Uncomment (remove "#" before name) to modify this parameter # This will override the value set for the BINNING_MODE. # min_seeds: # {seed_gap_description} # Uncomment (remove "#" before name) to modify this parameter # This will override the value set for the BINNING_MODE. # seed_gap: # =============================================================== # # ANALYSIS: {analyze_description} # # =============================================================== # {filter_rule_description} filter_rule: {filter_rule_default} # {filter_value_description} filter_value: {filter_value_default} # {filter_column_description} filter_column: {filter_column_default} # {datastore_description} datastore: {datastore} # {sample_n_kmers_description} sample_n_kmers: {sample_n_kmers_default} # {alpha_description} alpha: {alpha_default} # {h_description} h: {h_default} # {figure_kwargs_description} figure_kwargs: {figure_kwargs_default} # =============================================================== # # EXTRACT: {extract_description} # # =============================================================== # {extract_taxids_description} extract_taxids: {extract_taxids_default} """ CLUSTER_CONFIG = """ __default__: cpus: '{threads}' mem: 5000 log: '{log}.cluster' jobname: 'mtsv_{rule}' time: "30:00" fastp: jobname: "fastp" readprep: jobname: "readprep" binning: jobname: "binning" mem: 32000 cpus: 12 time: "2:00:00" collapse: jobname: "collapse" init_taxdump: jobname: "init_taxdump" summary: jobname: "summary" time: "2:00:00" mem: 30000 cpus: 1 filter_candidate_taxa: jobname: "filter_candidate_taxa" get_candidates_not_in_database: jobname: "get_candidates_not_in_database" random_kmers: jobname: "random_kmers" analyze_binning: jobname: "analyze_binning" mem: 30000 time: "1:00:00" analyze_collapse: jobname: "analyze_collapse" update_datastore: jobname: "update_datastore" analysis: jobname: "analysis" analysis_figure: jobname: "analysis_figure" analysis_html: jobname: "analysis_html" extract: jobname: "extract" unaligned_queries: jobname: "unaligned_queries" mem: 8000 """
prog_name = 'MTSv' version = '2.0.0' default_cfg_fname = 'mtsv.cfg' default_log_fname = 'mtsv_{COMMAND}_{TIMESTAMP}.log' config_string = '\n# NOTE: Changes to the config file in the middle of the pipeline\n# may force previous steps to be rerun.\n# \n# ===============================================================\n#\n# READPREP: {readprep_description}\n#\n# ===============================================================\n\n# {fastq_pattern_description}\n\n \nfastq_pattern: {fastq_pattern_default}\n \n\n# {fastp_params_description}\n\n \nfastp_params: {fastp_params_default}\n \n\n# {kmer_size_description}\n\n \nkmer_size: {kmer_size_default}\n \n\n# ===============================================================\n#\n# BINNING: {binning_description}\n#\n# ===============================================================\n\n# {database_config_description}\n\n \ndatabase_config: {database_path}\n\n\n# {edits_description}\n\n \nedits: {edits_default}\n \n\n# {binning_mode_description}\n\n \nbinning_mode: {binning_mode_default}\n\n\n# {max_hits_description}\n\n\nmax_hits: {max_hits_default}\n\n \n\n# {seed_size_description}\n# Uncomment (remove "#" before name) to modify this parameter\n# This will override the value set for the BINNING_MODE.\n\n \n# seed_size: \n \n\n# {min_seeds_description}\n# Uncomment (remove "#" before name) to modify this parameter\n# This will override the value set for the BINNING_MODE.\n\n \n# min_seeds:\n \n\n# {seed_gap_description}\n# Uncomment (remove "#" before name) to modify this parameter\n# This will override the value set for the BINNING_MODE.\n\n \n# seed_gap: \n \n\n# ===============================================================\n# \n# ANALYSIS: {analyze_description}\n#\n# ===============================================================\n\n# {filter_rule_description}\n\n \nfilter_rule: {filter_rule_default}\n \n\n# {filter_value_description}\n\n \nfilter_value: {filter_value_default}\n \n\n# {filter_column_description}\n\n \nfilter_column: {filter_column_default}\n \n\n# {datastore_description}\n\n \ndatastore: {datastore}\n \n\n# {sample_n_kmers_description}\n\n \nsample_n_kmers: {sample_n_kmers_default}\n \n\n# {alpha_description}\n\n \nalpha: {alpha_default}\n \n\n# {h_description}\n\n\nh: {h_default}\n\n\n# {figure_kwargs_description}\n\n\nfigure_kwargs: {figure_kwargs_default}\n \n\n# ===============================================================\n#\n# EXTRACT: {extract_description}\n#\n# ===============================================================\n \n# {extract_taxids_description}\n\n\nextract_taxids: {extract_taxids_default}\n\n\n' cluster_config = '\n__default__:\n cpus: \'{threads}\'\n mem: 5000\n log: \'{log}.cluster\'\n jobname: \'mtsv_{rule}\'\n time: "30:00"\n\nfastp:\n jobname: "fastp"\n\nreadprep:\n jobname: "readprep"\n\nbinning:\n jobname: "binning"\n mem: 32000\n cpus: 12\n time: "2:00:00"\n\ncollapse:\n jobname: "collapse"\n\ninit_taxdump:\n jobname: "init_taxdump"\n\nsummary:\n jobname: "summary"\n time: "2:00:00"\n mem: 30000\n cpus: 1\n\nfilter_candidate_taxa:\n jobname: "filter_candidate_taxa"\n\nget_candidates_not_in_database:\n jobname: "get_candidates_not_in_database"\n\nrandom_kmers:\n jobname: "random_kmers"\n\nanalyze_binning:\n jobname: "analyze_binning"\n mem: 30000\n time: "1:00:00"\n\nanalyze_collapse:\n jobname: "analyze_collapse"\n\nupdate_datastore:\n jobname: "update_datastore"\n\nanalysis:\n jobname: "analysis"\n\nanalysis_figure:\n jobname: "analysis_figure"\n\nanalysis_html:\n jobname: "analysis_html"\n\nextract:\n jobname: "extract"\n\nunaligned_queries:\n jobname: "unaligned_queries"\n mem: 8000\n\n'
class Solution: def isTransformable(self, s: str, t: str) -> bool: positions = defaultdict(list) for i in reversed(range(len(s))): positions[int(s[i])].append(i) for char in t: num = int(char) if not positions[num]: return False i = positions[num][-1] for j in range(num): if positions[j] and positions[j][-1] < i: return False positions[num].pop() return True
class Solution: def is_transformable(self, s: str, t: str) -> bool: positions = defaultdict(list) for i in reversed(range(len(s))): positions[int(s[i])].append(i) for char in t: num = int(char) if not positions[num]: return False i = positions[num][-1] for j in range(num): if positions[j] and positions[j][-1] < i: return False positions[num].pop() return True
class Solution: def solve(self, intervals, types): sorted_endpoints = sorted(list({end for interval in intervals for end in interval})) counts = defaultdict(int) for start, end in intervals: counts[start] += 1 counts[end] -= 1 counts = dict(zip(sorted_endpoints, accumulate(x[1] for x in sorted(counts.items())))) ans = [] cur_count = 0 for end in sorted_endpoints: if cur_count != 0: ans[-1][1] = end cur_count = counts[end] if cur_count != 0: ans.append([end, None, cur_count]) return ans
class Solution: def solve(self, intervals, types): sorted_endpoints = sorted(list({end for interval in intervals for end in interval})) counts = defaultdict(int) for (start, end) in intervals: counts[start] += 1 counts[end] -= 1 counts = dict(zip(sorted_endpoints, accumulate((x[1] for x in sorted(counts.items()))))) ans = [] cur_count = 0 for end in sorted_endpoints: if cur_count != 0: ans[-1][1] = end cur_count = counts[end] if cur_count != 0: ans.append([end, None, cur_count]) return ans
def add_data_opts(parser): data_opts = parser.add_argument_group("General Data Options") data_opts.add_argument('--manifest-dir', default='./', type=str, help='Output directory for manifests') data_opts.add_argument('--min-duration', default=1, type=int, help='Prunes training samples shorter than the min duration (given in seconds, default 1)') data_opts.add_argument('--max-duration', default=15, type=int, help='Prunes training samples longer than the max duration (given in seconds, default 15)') parser.add_argument('--num-workers', default=4, type=int, help='Number of workers for processing data.') parser.add_argument('--sample-rate', default=16000, type=int, help='Sample rate') return parser
def add_data_opts(parser): data_opts = parser.add_argument_group('General Data Options') data_opts.add_argument('--manifest-dir', default='./', type=str, help='Output directory for manifests') data_opts.add_argument('--min-duration', default=1, type=int, help='Prunes training samples shorter than the min duration (given in seconds, default 1)') data_opts.add_argument('--max-duration', default=15, type=int, help='Prunes training samples longer than the max duration (given in seconds, default 15)') parser.add_argument('--num-workers', default=4, type=int, help='Number of workers for processing data.') parser.add_argument('--sample-rate', default=16000, type=int, help='Sample rate') return parser
class object_ustr(object): def __unicode__(self): '''This should really be overriden in subclasses''' class_name = self.__class__.__name__ attr_pairs = ('%s=%s' % (key, val) for key, val in self.__dict__.items()) return u'<%s %s>' % (class_name, ' '.join(attr_pairs)) def __str__(self): '''This won't usually be overridden in subclasses''' return unicode(self).encode('utf8') def __repr__(self): return str(self)
class Object_Ustr(object): def __unicode__(self): """This should really be overriden in subclasses""" class_name = self.__class__.__name__ attr_pairs = ('%s=%s' % (key, val) for (key, val) in self.__dict__.items()) return u'<%s %s>' % (class_name, ' '.join(attr_pairs)) def __str__(self): """This won't usually be overridden in subclasses""" return unicode(self).encode('utf8') def __repr__(self): return str(self)
# The gameboy color has no cpu opcodes for multiplication. I could write some # complicated algorithm to do this stuff on the gameboy's cpu, but I'm going to # cheat and just use canned data. If you feed the assembly code for a color # palette into this script, it will output a canned fade animation, 32 steps in # size. # # e.g. of input data: # DB $00,$00, $69,$72, $1A,$20, $03,$00, # DB $00,$00, $FF,$7F, $F8,$37, $5F,$19, # DB $00,$00, $54,$62, $F8,$37, $1A,$20, # DB $00,$00, $00,$00, $00,$00, $00,$00, # DB $00,$00, $00,$00, $00,$00, $00,$00, # DB $00,$00, $00,$00, $00,$00, $00,$00, # DB $00,$00, $00,$00, $00,$00, $00,$00, # DB $00,$00, $00,$00, $00,$00, $00,$00, # def get_rgb(bgr_555): r = 0x1F & bgr_555 g = (0x3E0 & bgr_555) >> 5 b = (0x7C00 & bgr_555) >> 10 return (r, g, b) lines = [] with open('palette_data.txt') as data: for line in data: vector = [] parsed = line[3:].split(',') parity = False coll = "" for elem in parsed: p = elem.strip() p = p.strip("$") if parity: # Add strs in this order intentionally, to unswap the byteorder. coll = p + coll coll.strip() parity = False vector.append(get_rgb(int(coll, 16))) coll = "" else: coll = p + coll parity = True lines.append(vector) def lerp(a, b, t): return a * t + (1 - t) * b def blend(lhs, rhs, amount): return (int(lerp(lhs[0], rhs[0], amount)), int(lerp(lhs[1], rhs[1], amount)), int(lerp(lhs[2], rhs[2], amount))) black = (0, 0, 1) tan = (27, 24, 18) white = (31, 31, 31) def to_gbc_color(c): fmt = '{0:0{1}X}'.format(((c[0]) + ((c[1]) << 5) + ((c[2]) << 10)), 4) # The byte order is swapped on the gbc print("$" + fmt[2:4] + ",$" + fmt[0:2], end = ", ") print("black::") for i in range(0, 32): print(".blend_" + str(i) + "::") for line in lines: print("DB ", end="") for elem in line: to_gbc_color(blend(black, elem, i / 31)) print("") print(".blend_" + str(i) + "_end::") print("tan::") for i in range(0, 32): print(".blend_" + str(i) + "::") for line in lines: print("DB ", end="") for elem in line: to_gbc_color(blend(tan, elem, i / 31)) print("") print(".blend_" + str(i) + "_end::") print("white::") for i in range(0, 32): print(".blend_" + str(i) + "::") for line in lines: print("DB ", end="") for elem in line: to_gbc_color(blend(white, elem, i / 31)) print("") print(".blend_" + str(i) + "_end::")
def get_rgb(bgr_555): r = 31 & bgr_555 g = (992 & bgr_555) >> 5 b = (31744 & bgr_555) >> 10 return (r, g, b) lines = [] with open('palette_data.txt') as data: for line in data: vector = [] parsed = line[3:].split(',') parity = False coll = '' for elem in parsed: p = elem.strip() p = p.strip('$') if parity: coll = p + coll coll.strip() parity = False vector.append(get_rgb(int(coll, 16))) coll = '' else: coll = p + coll parity = True lines.append(vector) def lerp(a, b, t): return a * t + (1 - t) * b def blend(lhs, rhs, amount): return (int(lerp(lhs[0], rhs[0], amount)), int(lerp(lhs[1], rhs[1], amount)), int(lerp(lhs[2], rhs[2], amount))) black = (0, 0, 1) tan = (27, 24, 18) white = (31, 31, 31) def to_gbc_color(c): fmt = '{0:0{1}X}'.format(c[0] + (c[1] << 5) + (c[2] << 10), 4) print('$' + fmt[2:4] + ',$' + fmt[0:2], end=', ') print('black::') for i in range(0, 32): print('.blend_' + str(i) + '::') for line in lines: print('DB ', end='') for elem in line: to_gbc_color(blend(black, elem, i / 31)) print('') print('.blend_' + str(i) + '_end::') print('tan::') for i in range(0, 32): print('.blend_' + str(i) + '::') for line in lines: print('DB ', end='') for elem in line: to_gbc_color(blend(tan, elem, i / 31)) print('') print('.blend_' + str(i) + '_end::') print('white::') for i in range(0, 32): print('.blend_' + str(i) + '::') for line in lines: print('DB ', end='') for elem in line: to_gbc_color(blend(white, elem, i / 31)) print('') print('.blend_' + str(i) + '_end::')
""" Video encoding names """ class EncodingNames: """Simple class to hold encoding names""" ORIGINAL = "original" HLS = "HLS" SMALL = "small" BASIC = "basic" MEDIUM = "medium" LARGE = "large" HD = "HD" MP4 = [HD, LARGE, MEDIUM, BASIC, SMALL]
""" Video encoding names """ class Encodingnames: """Simple class to hold encoding names""" original = 'original' hls = 'HLS' small = 'small' basic = 'basic' medium = 'medium' large = 'large' hd = 'HD' mp4 = [HD, LARGE, MEDIUM, BASIC, SMALL]
# # PySNMP MIB module IEEE8021-CFM-V2-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IEEE8021-CFM-V2-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:40:39 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, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsUnion", "ValueSizeConstraint", "ConstraintsIntersection", "ValueRangeConstraint") Dot1agCfmIdPermission, dot1agCfmMaIndex, dot1agCfmConfigErrorList, Dot1agCfmMDLevel, ieee8021CfmMaNetGroup, dot1agCfmNotificationsGroup, dot1agCfmMepGroup, Dot1agCfmMepIdOrZero, dot1agCfmCompliances, dot1agCfmMa, dot1agCfmMepLbrBadMsdu, dot1agCfmGroups, ieee8021CfmDefaultMdDefGroup, dot1agCfmVlan, ieee8021CfmPbbTeExtensionGroup, Dot1agCfmMpDirection, dot1agCfmMepRowStatus, dot1agCfmMdIndex, dot1agCfmStack, ieee8021CfmPbbTeTrafficBitGroup, Dot1agCfmMDLevelOrNone, dot1agCfmMdRowStatus, dot1agCfmMepDbGroup, dot1agCfmMdGroup, Dot1agCfmMhfCreation, dot1agCfmMaNetRowStatus, dot1agCfmDefaultMd, Dot1agCfmConfigErrors, dot1agCfmMaMepListRowStatus = mibBuilder.importSymbols("IEEE8021-CFM-MIB", "Dot1agCfmIdPermission", "dot1agCfmMaIndex", "dot1agCfmConfigErrorList", "Dot1agCfmMDLevel", "ieee8021CfmMaNetGroup", "dot1agCfmNotificationsGroup", "dot1agCfmMepGroup", "Dot1agCfmMepIdOrZero", "dot1agCfmCompliances", "dot1agCfmMa", "dot1agCfmMepLbrBadMsdu", "dot1agCfmGroups", "ieee8021CfmDefaultMdDefGroup", "dot1agCfmVlan", "ieee8021CfmPbbTeExtensionGroup", "Dot1agCfmMpDirection", "dot1agCfmMepRowStatus", "dot1agCfmMdIndex", "dot1agCfmStack", "ieee8021CfmPbbTeTrafficBitGroup", "Dot1agCfmMDLevelOrNone", "dot1agCfmMdRowStatus", "dot1agCfmMepDbGroup", "dot1agCfmMdGroup", "Dot1agCfmMhfCreation", "dot1agCfmMaNetRowStatus", "dot1agCfmDefaultMd", "Dot1agCfmConfigErrors", "dot1agCfmMaMepListRowStatus") IEEE8021ServiceSelectorValue, IEEE8021ServiceSelectorType, IEEE8021ServiceSelectorValueOrNone, IEEE8021PbbComponentIdentifier, ieee802dot1mibs = mibBuilder.importSymbols("IEEE8021-TC-MIB", "IEEE8021ServiceSelectorValue", "IEEE8021ServiceSelectorType", "IEEE8021ServiceSelectorValueOrNone", "IEEE8021PbbComponentIdentifier", "ieee802dot1mibs") InterfaceIndex, = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex") NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup") ObjectIdentity, Counter32, Bits, IpAddress, TimeTicks, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, MibIdentifier, Counter64, Gauge32, Unsigned32, iso, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "ObjectIdentity", "Counter32", "Bits", "IpAddress", "TimeTicks", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "MibIdentifier", "Counter64", "Gauge32", "Unsigned32", "iso", "Integer32") MacAddress, RowStatus, TextualConvention, TruthValue, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "MacAddress", "RowStatus", "TextualConvention", "TruthValue", "DisplayString") ieee8021CfmV2Mib = ModuleIdentity((1, 3, 111, 2, 802, 1, 1, 7)) ieee8021CfmV2Mib.setRevisions(('2014-12-15 00:00', '2011-02-27 00:00', '2008-11-18 00:00', '2008-10-15 00:00',)) if mibBuilder.loadTexts: ieee8021CfmV2Mib.setLastUpdated('201412150000Z') if mibBuilder.loadTexts: ieee8021CfmV2Mib.setOrganization('IEEE 802.1 Working Group') ieee8021CfmStackTable = MibTable((1, 3, 111, 2, 802, 1, 1, 8, 1, 1, 2), ) if mibBuilder.loadTexts: ieee8021CfmStackTable.setStatus('current') ieee8021CfmStackEntry = MibTableRow((1, 3, 111, 2, 802, 1, 1, 8, 1, 1, 2, 1), ).setIndexNames((0, "IEEE8021-CFM-V2-MIB", "ieee8021CfmStackifIndex"), (0, "IEEE8021-CFM-V2-MIB", "ieee8021CfmStackServiceSelectorType"), (0, "IEEE8021-CFM-V2-MIB", "ieee8021CfmStackServiceSelectorOrNone"), (0, "IEEE8021-CFM-V2-MIB", "ieee8021CfmStackMdLevel"), (0, "IEEE8021-CFM-V2-MIB", "ieee8021CfmStackDirection")) if mibBuilder.loadTexts: ieee8021CfmStackEntry.setStatus('current') ieee8021CfmStackifIndex = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 1, 2, 1, 1), InterfaceIndex()) if mibBuilder.loadTexts: ieee8021CfmStackifIndex.setStatus('current') ieee8021CfmStackServiceSelectorType = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 1, 2, 1, 2), IEEE8021ServiceSelectorType()) if mibBuilder.loadTexts: ieee8021CfmStackServiceSelectorType.setStatus('current') ieee8021CfmStackServiceSelectorOrNone = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 1, 2, 1, 3), IEEE8021ServiceSelectorValueOrNone()) if mibBuilder.loadTexts: ieee8021CfmStackServiceSelectorOrNone.setStatus('current') ieee8021CfmStackMdLevel = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 1, 2, 1, 4), Dot1agCfmMDLevel()) if mibBuilder.loadTexts: ieee8021CfmStackMdLevel.setStatus('current') ieee8021CfmStackDirection = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 1, 2, 1, 5), Dot1agCfmMpDirection()) if mibBuilder.loadTexts: ieee8021CfmStackDirection.setStatus('current') ieee8021CfmStackMdIndex = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 1, 2, 1, 6), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ieee8021CfmStackMdIndex.setStatus('current') ieee8021CfmStackMaIndex = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 1, 2, 1, 7), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ieee8021CfmStackMaIndex.setStatus('current') ieee8021CfmStackMepId = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 1, 2, 1, 8), Dot1agCfmMepIdOrZero()).setMaxAccess("readonly") if mibBuilder.loadTexts: ieee8021CfmStackMepId.setStatus('current') ieee8021CfmStackMacAddress = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 1, 2, 1, 9), MacAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: ieee8021CfmStackMacAddress.setStatus('current') ieee8021CfmVlanTable = MibTable((1, 3, 111, 2, 802, 1, 1, 8, 1, 3, 2), ) if mibBuilder.loadTexts: ieee8021CfmVlanTable.setStatus('current') ieee8021CfmVlanEntry = MibTableRow((1, 3, 111, 2, 802, 1, 1, 8, 1, 3, 2, 1), ).setIndexNames((0, "IEEE8021-CFM-V2-MIB", "ieee8021CfmVlanComponentId"), (0, "IEEE8021-CFM-V2-MIB", "ieee8021CfmVlanSelector")) if mibBuilder.loadTexts: ieee8021CfmVlanEntry.setStatus('current') ieee8021CfmVlanComponentId = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 3, 2, 1, 1), IEEE8021PbbComponentIdentifier()) if mibBuilder.loadTexts: ieee8021CfmVlanComponentId.setStatus('current') ieee8021CfmVlanSelector = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 3, 2, 1, 3), IEEE8021ServiceSelectorValue()) if mibBuilder.loadTexts: ieee8021CfmVlanSelector.setStatus('current') ieee8021CfmVlanPrimarySelector = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 3, 2, 1, 5), IEEE8021ServiceSelectorValue()).setMaxAccess("readcreate") if mibBuilder.loadTexts: ieee8021CfmVlanPrimarySelector.setStatus('current') ieee8021CfmVlanRowStatus = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 3, 2, 1, 6), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: ieee8021CfmVlanRowStatus.setStatus('current') ieee8021CfmDefaultMdTable = MibTable((1, 3, 111, 2, 802, 1, 1, 8, 1, 2, 5), ) if mibBuilder.loadTexts: ieee8021CfmDefaultMdTable.setStatus('current') ieee8021CfmDefaultMdEntry = MibTableRow((1, 3, 111, 2, 802, 1, 1, 8, 1, 2, 5, 1), ).setIndexNames((0, "IEEE8021-CFM-V2-MIB", "ieee8021CfmDefaultMdComponentId"), (0, "IEEE8021-CFM-V2-MIB", "ieee8021CfmDefaultMdPrimarySelectorType"), (0, "IEEE8021-CFM-V2-MIB", "ieee8021CfmDefaultMdPrimarySelector")) if mibBuilder.loadTexts: ieee8021CfmDefaultMdEntry.setStatus('current') ieee8021CfmDefaultMdComponentId = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 2, 5, 1, 1), IEEE8021PbbComponentIdentifier()) if mibBuilder.loadTexts: ieee8021CfmDefaultMdComponentId.setStatus('current') ieee8021CfmDefaultMdPrimarySelectorType = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 2, 5, 1, 2), IEEE8021ServiceSelectorType()) if mibBuilder.loadTexts: ieee8021CfmDefaultMdPrimarySelectorType.setStatus('current') ieee8021CfmDefaultMdPrimarySelector = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 2, 5, 1, 3), IEEE8021ServiceSelectorValue()) if mibBuilder.loadTexts: ieee8021CfmDefaultMdPrimarySelector.setStatus('current') ieee8021CfmDefaultMdStatus = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 2, 5, 1, 4), TruthValue()).setMaxAccess("readonly") if mibBuilder.loadTexts: ieee8021CfmDefaultMdStatus.setStatus('current') ieee8021CfmDefaultMdLevel = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 2, 5, 1, 5), Dot1agCfmMDLevelOrNone().clone(-1)).setMaxAccess("readwrite") if mibBuilder.loadTexts: ieee8021CfmDefaultMdLevel.setStatus('current') ieee8021CfmDefaultMdMhfCreation = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 2, 5, 1, 6), Dot1agCfmMhfCreation().clone('defMHFdefer')).setMaxAccess("readwrite") if mibBuilder.loadTexts: ieee8021CfmDefaultMdMhfCreation.setStatus('current') ieee8021CfmDefaultMdIdPermission = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 2, 5, 1, 7), Dot1agCfmIdPermission().clone('sendIdDefer')).setMaxAccess("readwrite") if mibBuilder.loadTexts: ieee8021CfmDefaultMdIdPermission.setStatus('current') ieee8021CfmConfigErrorListTable = MibTable((1, 3, 111, 2, 802, 1, 1, 8, 1, 4, 2), ) if mibBuilder.loadTexts: ieee8021CfmConfigErrorListTable.setStatus('current') ieee8021CfmConfigErrorListEntry = MibTableRow((1, 3, 111, 2, 802, 1, 1, 8, 1, 4, 2, 1), ).setIndexNames((0, "IEEE8021-CFM-V2-MIB", "ieee8021CfmConfigErrorListSelectorType"), (0, "IEEE8021-CFM-V2-MIB", "ieee8021CfmConfigErrorListSelector"), (0, "IEEE8021-CFM-V2-MIB", "ieee8021CfmConfigErrorListIfIndex")) if mibBuilder.loadTexts: ieee8021CfmConfigErrorListEntry.setStatus('current') ieee8021CfmConfigErrorListSelectorType = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 4, 2, 1, 1), IEEE8021ServiceSelectorType()) if mibBuilder.loadTexts: ieee8021CfmConfigErrorListSelectorType.setStatus('current') ieee8021CfmConfigErrorListSelector = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 4, 2, 1, 2), IEEE8021ServiceSelectorValue()) if mibBuilder.loadTexts: ieee8021CfmConfigErrorListSelector.setStatus('current') ieee8021CfmConfigErrorListIfIndex = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 4, 2, 1, 3), InterfaceIndex()) if mibBuilder.loadTexts: ieee8021CfmConfigErrorListIfIndex.setStatus('current') ieee8021CfmConfigErrorListErrorType = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 4, 2, 1, 4), Dot1agCfmConfigErrors()).setMaxAccess("readonly") if mibBuilder.loadTexts: ieee8021CfmConfigErrorListErrorType.setStatus('current') ieee8021CfmMaCompTable = MibTable((1, 3, 111, 2, 802, 1, 1, 8, 1, 6, 4), ) if mibBuilder.loadTexts: ieee8021CfmMaCompTable.setStatus('current') ieee8021CfmMaCompEntry = MibTableRow((1, 3, 111, 2, 802, 1, 1, 8, 1, 6, 4, 1), ).setIndexNames((0, "IEEE8021-CFM-V2-MIB", "ieee8021CfmMaComponentId"), (0, "IEEE8021-CFM-MIB", "dot1agCfmMdIndex"), (0, "IEEE8021-CFM-MIB", "dot1agCfmMaIndex")) if mibBuilder.loadTexts: ieee8021CfmMaCompEntry.setStatus('current') ieee8021CfmMaComponentId = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 6, 4, 1, 1), IEEE8021PbbComponentIdentifier()) if mibBuilder.loadTexts: ieee8021CfmMaComponentId.setStatus('current') ieee8021CfmMaCompPrimarySelectorType = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 6, 4, 1, 2), IEEE8021ServiceSelectorType()).setMaxAccess("readcreate") if mibBuilder.loadTexts: ieee8021CfmMaCompPrimarySelectorType.setStatus('current') ieee8021CfmMaCompPrimarySelectorOrNone = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 6, 4, 1, 3), IEEE8021ServiceSelectorValueOrNone()).setMaxAccess("readcreate") if mibBuilder.loadTexts: ieee8021CfmMaCompPrimarySelectorOrNone.setStatus('current') ieee8021CfmMaCompMhfCreation = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 6, 4, 1, 4), Dot1agCfmMhfCreation().clone('defMHFdefer')).setMaxAccess("readcreate") if mibBuilder.loadTexts: ieee8021CfmMaCompMhfCreation.setStatus('current') ieee8021CfmMaCompIdPermission = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 6, 4, 1, 5), Dot1agCfmIdPermission().clone('sendIdDefer')).setMaxAccess("readcreate") if mibBuilder.loadTexts: ieee8021CfmMaCompIdPermission.setStatus('current') ieee8021CfmMaCompNumberOfVids = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 6, 4, 1, 6), Unsigned32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: ieee8021CfmMaCompNumberOfVids.setStatus('current') ieee8021CfmMaCompRowStatus = MibTableColumn((1, 3, 111, 2, 802, 1, 1, 8, 1, 6, 4, 1, 7), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: ieee8021CfmMaCompRowStatus.setStatus('current') ieee8021CfmStackGroup = ObjectGroup((1, 3, 111, 2, 802, 1, 1, 8, 2, 2, 12)).setObjects(("IEEE8021-CFM-V2-MIB", "ieee8021CfmStackMdIndex"), ("IEEE8021-CFM-V2-MIB", "ieee8021CfmStackMaIndex"), ("IEEE8021-CFM-V2-MIB", "ieee8021CfmStackMepId"), ("IEEE8021-CFM-V2-MIB", "ieee8021CfmStackMacAddress")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ieee8021CfmStackGroup = ieee8021CfmStackGroup.setStatus('current') ieee8021CfmMaGroup = ObjectGroup((1, 3, 111, 2, 802, 1, 1, 8, 2, 2, 13)).setObjects(("IEEE8021-CFM-V2-MIB", "ieee8021CfmMaCompPrimarySelectorType"), ("IEEE8021-CFM-V2-MIB", "ieee8021CfmMaCompPrimarySelectorOrNone"), ("IEEE8021-CFM-V2-MIB", "ieee8021CfmMaCompMhfCreation"), ("IEEE8021-CFM-V2-MIB", "ieee8021CfmMaCompIdPermission"), ("IEEE8021-CFM-V2-MIB", "ieee8021CfmMaCompRowStatus"), ("IEEE8021-CFM-V2-MIB", "ieee8021CfmMaCompNumberOfVids")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ieee8021CfmMaGroup = ieee8021CfmMaGroup.setStatus('current') ieee8021CfmDefaultMdGroup = ObjectGroup((1, 3, 111, 2, 802, 1, 1, 8, 2, 2, 14)).setObjects(("IEEE8021-CFM-V2-MIB", "ieee8021CfmDefaultMdStatus"), ("IEEE8021-CFM-V2-MIB", "ieee8021CfmDefaultMdLevel"), ("IEEE8021-CFM-V2-MIB", "ieee8021CfmDefaultMdMhfCreation"), ("IEEE8021-CFM-V2-MIB", "ieee8021CfmDefaultMdIdPermission")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ieee8021CfmDefaultMdGroup = ieee8021CfmDefaultMdGroup.setStatus('current') ieee8021CfmVlanIdGroup = ObjectGroup((1, 3, 111, 2, 802, 1, 1, 8, 2, 2, 15)).setObjects(("IEEE8021-CFM-V2-MIB", "ieee8021CfmVlanPrimarySelector"), ("IEEE8021-CFM-V2-MIB", "ieee8021CfmVlanRowStatus")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ieee8021CfmVlanIdGroup = ieee8021CfmVlanIdGroup.setStatus('current') ieee8021CfmConfigErrorListGroup = ObjectGroup((1, 3, 111, 2, 802, 1, 1, 8, 2, 2, 16)).setObjects(("IEEE8021-CFM-V2-MIB", "ieee8021CfmConfigErrorListErrorType")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ieee8021CfmConfigErrorListGroup = ieee8021CfmConfigErrorListGroup.setStatus('current') ieee8021CfmComplianceV2 = ModuleCompliance((1, 3, 111, 2, 802, 1, 1, 8, 2, 1, 2)).setObjects(("IEEE8021-CFM-V2-MIB", "ieee8021CfmStackGroup"), ("IEEE8021-CFM-V2-MIB", "ieee8021CfmMaGroup"), ("IEEE8021-CFM-V2-MIB", "ieee8021CfmDefaultMdGroup"), ("IEEE8021-CFM-V2-MIB", "ieee8021CfmConfigErrorListGroup"), ("IEEE8021-CFM-V2-MIB", "ieee8021CfmVlanIdGroup"), ("IEEE8021-CFM-MIB", "dot1agCfmMdGroup"), ("IEEE8021-CFM-MIB", "dot1agCfmMepGroup"), ("IEEE8021-CFM-MIB", "dot1agCfmMepDbGroup"), ("IEEE8021-CFM-MIB", "dot1agCfmNotificationsGroup"), ("IEEE8021-CFM-MIB", "ieee8021CfmDefaultMdDefGroup"), ("IEEE8021-CFM-MIB", "ieee8021CfmMaNetGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ieee8021CfmComplianceV2 = ieee8021CfmComplianceV2.setStatus('current') dot1agCfmWithPbbTeCompliance = ModuleCompliance((1, 3, 111, 2, 802, 1, 1, 8, 2, 1, 3)).setObjects(("IEEE8021-CFM-V2-MIB", "ieee8021CfmStackGroup"), ("IEEE8021-CFM-V2-MIB", "ieee8021CfmMaGroup"), ("IEEE8021-CFM-V2-MIB", "ieee8021CfmDefaultMdGroup"), ("IEEE8021-CFM-V2-MIB", "ieee8021CfmConfigErrorListGroup"), ("IEEE8021-CFM-V2-MIB", "ieee8021CfmVlanIdGroup"), ("IEEE8021-CFM-MIB", "dot1agCfmMdGroup"), ("IEEE8021-CFM-MIB", "dot1agCfmMepGroup"), ("IEEE8021-CFM-MIB", "dot1agCfmMepDbGroup"), ("IEEE8021-CFM-MIB", "dot1agCfmNotificationsGroup"), ("IEEE8021-CFM-MIB", "ieee8021CfmDefaultMdDefGroup"), ("IEEE8021-CFM-MIB", "ieee8021CfmMaNetGroup"), ("IEEE8021-CFM-MIB", "ieee8021CfmPbbTeExtensionGroup"), ("IEEE8021-CFM-MIB", "ieee8021CfmPbbTeTrafficBitGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): dot1agCfmWithPbbTeCompliance = dot1agCfmWithPbbTeCompliance.setStatus('current') mibBuilder.exportSymbols("IEEE8021-CFM-V2-MIB", ieee8021CfmDefaultMdStatus=ieee8021CfmDefaultMdStatus, ieee8021CfmDefaultMdComponentId=ieee8021CfmDefaultMdComponentId, ieee8021CfmStackServiceSelectorType=ieee8021CfmStackServiceSelectorType, ieee8021CfmMaCompRowStatus=ieee8021CfmMaCompRowStatus, ieee8021CfmDefaultMdPrimarySelectorType=ieee8021CfmDefaultMdPrimarySelectorType, ieee8021CfmConfigErrorListErrorType=ieee8021CfmConfigErrorListErrorType, ieee8021CfmStackGroup=ieee8021CfmStackGroup, ieee8021CfmVlanEntry=ieee8021CfmVlanEntry, ieee8021CfmDefaultMdMhfCreation=ieee8021CfmDefaultMdMhfCreation, ieee8021CfmConfigErrorListTable=ieee8021CfmConfigErrorListTable, ieee8021CfmMaCompEntry=ieee8021CfmMaCompEntry, ieee8021CfmVlanIdGroup=ieee8021CfmVlanIdGroup, ieee8021CfmConfigErrorListSelectorType=ieee8021CfmConfigErrorListSelectorType, ieee8021CfmMaCompTable=ieee8021CfmMaCompTable, dot1agCfmWithPbbTeCompliance=dot1agCfmWithPbbTeCompliance, ieee8021CfmMaCompMhfCreation=ieee8021CfmMaCompMhfCreation, ieee8021CfmDefaultMdEntry=ieee8021CfmDefaultMdEntry, ieee8021CfmDefaultMdTable=ieee8021CfmDefaultMdTable, ieee8021CfmComplianceV2=ieee8021CfmComplianceV2, ieee8021CfmDefaultMdGroup=ieee8021CfmDefaultMdGroup, ieee8021CfmStackTable=ieee8021CfmStackTable, ieee8021CfmMaComponentId=ieee8021CfmMaComponentId, ieee8021CfmMaCompPrimarySelectorOrNone=ieee8021CfmMaCompPrimarySelectorOrNone, ieee8021CfmStackMepId=ieee8021CfmStackMepId, ieee8021CfmDefaultMdLevel=ieee8021CfmDefaultMdLevel, ieee8021CfmStackMdLevel=ieee8021CfmStackMdLevel, ieee8021CfmConfigErrorListGroup=ieee8021CfmConfigErrorListGroup, ieee8021CfmStackDirection=ieee8021CfmStackDirection, PYSNMP_MODULE_ID=ieee8021CfmV2Mib, ieee8021CfmDefaultMdPrimarySelector=ieee8021CfmDefaultMdPrimarySelector, ieee8021CfmStackServiceSelectorOrNone=ieee8021CfmStackServiceSelectorOrNone, ieee8021CfmMaCompPrimarySelectorType=ieee8021CfmMaCompPrimarySelectorType, ieee8021CfmVlanPrimarySelector=ieee8021CfmVlanPrimarySelector, ieee8021CfmV2Mib=ieee8021CfmV2Mib, ieee8021CfmMaCompIdPermission=ieee8021CfmMaCompIdPermission, ieee8021CfmVlanTable=ieee8021CfmVlanTable, ieee8021CfmConfigErrorListSelector=ieee8021CfmConfigErrorListSelector, ieee8021CfmMaGroup=ieee8021CfmMaGroup, ieee8021CfmVlanSelector=ieee8021CfmVlanSelector, ieee8021CfmStackMacAddress=ieee8021CfmStackMacAddress, ieee8021CfmConfigErrorListEntry=ieee8021CfmConfigErrorListEntry, ieee8021CfmConfigErrorListIfIndex=ieee8021CfmConfigErrorListIfIndex, ieee8021CfmMaCompNumberOfVids=ieee8021CfmMaCompNumberOfVids, ieee8021CfmVlanComponentId=ieee8021CfmVlanComponentId, ieee8021CfmVlanRowStatus=ieee8021CfmVlanRowStatus, ieee8021CfmStackMaIndex=ieee8021CfmStackMaIndex, ieee8021CfmStackMdIndex=ieee8021CfmStackMdIndex, ieee8021CfmStackEntry=ieee8021CfmStackEntry, ieee8021CfmDefaultMdIdPermission=ieee8021CfmDefaultMdIdPermission, ieee8021CfmStackifIndex=ieee8021CfmStackifIndex)
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, constraints_union, value_size_constraint, constraints_intersection, value_range_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ConstraintsUnion', 'ValueSizeConstraint', 'ConstraintsIntersection', 'ValueRangeConstraint') (dot1ag_cfm_id_permission, dot1ag_cfm_ma_index, dot1ag_cfm_config_error_list, dot1ag_cfm_md_level, ieee8021_cfm_ma_net_group, dot1ag_cfm_notifications_group, dot1ag_cfm_mep_group, dot1ag_cfm_mep_id_or_zero, dot1ag_cfm_compliances, dot1ag_cfm_ma, dot1ag_cfm_mep_lbr_bad_msdu, dot1ag_cfm_groups, ieee8021_cfm_default_md_def_group, dot1ag_cfm_vlan, ieee8021_cfm_pbb_te_extension_group, dot1ag_cfm_mp_direction, dot1ag_cfm_mep_row_status, dot1ag_cfm_md_index, dot1ag_cfm_stack, ieee8021_cfm_pbb_te_traffic_bit_group, dot1ag_cfm_md_level_or_none, dot1ag_cfm_md_row_status, dot1ag_cfm_mep_db_group, dot1ag_cfm_md_group, dot1ag_cfm_mhf_creation, dot1ag_cfm_ma_net_row_status, dot1ag_cfm_default_md, dot1ag_cfm_config_errors, dot1ag_cfm_ma_mep_list_row_status) = mibBuilder.importSymbols('IEEE8021-CFM-MIB', 'Dot1agCfmIdPermission', 'dot1agCfmMaIndex', 'dot1agCfmConfigErrorList', 'Dot1agCfmMDLevel', 'ieee8021CfmMaNetGroup', 'dot1agCfmNotificationsGroup', 'dot1agCfmMepGroup', 'Dot1agCfmMepIdOrZero', 'dot1agCfmCompliances', 'dot1agCfmMa', 'dot1agCfmMepLbrBadMsdu', 'dot1agCfmGroups', 'ieee8021CfmDefaultMdDefGroup', 'dot1agCfmVlan', 'ieee8021CfmPbbTeExtensionGroup', 'Dot1agCfmMpDirection', 'dot1agCfmMepRowStatus', 'dot1agCfmMdIndex', 'dot1agCfmStack', 'ieee8021CfmPbbTeTrafficBitGroup', 'Dot1agCfmMDLevelOrNone', 'dot1agCfmMdRowStatus', 'dot1agCfmMepDbGroup', 'dot1agCfmMdGroup', 'Dot1agCfmMhfCreation', 'dot1agCfmMaNetRowStatus', 'dot1agCfmDefaultMd', 'Dot1agCfmConfigErrors', 'dot1agCfmMaMepListRowStatus') (ieee8021_service_selector_value, ieee8021_service_selector_type, ieee8021_service_selector_value_or_none, ieee8021_pbb_component_identifier, ieee802dot1mibs) = mibBuilder.importSymbols('IEEE8021-TC-MIB', 'IEEE8021ServiceSelectorValue', 'IEEE8021ServiceSelectorType', 'IEEE8021ServiceSelectorValueOrNone', 'IEEE8021PbbComponentIdentifier', 'ieee802dot1mibs') (interface_index,) = mibBuilder.importSymbols('IF-MIB', 'InterfaceIndex') (notification_group, module_compliance, object_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance', 'ObjectGroup') (object_identity, counter32, bits, ip_address, time_ticks, notification_type, mib_scalar, mib_table, mib_table_row, mib_table_column, module_identity, mib_identifier, counter64, gauge32, unsigned32, iso, integer32) = mibBuilder.importSymbols('SNMPv2-SMI', 'ObjectIdentity', 'Counter32', 'Bits', 'IpAddress', 'TimeTicks', 'NotificationType', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ModuleIdentity', 'MibIdentifier', 'Counter64', 'Gauge32', 'Unsigned32', 'iso', 'Integer32') (mac_address, row_status, textual_convention, truth_value, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'MacAddress', 'RowStatus', 'TextualConvention', 'TruthValue', 'DisplayString') ieee8021_cfm_v2_mib = module_identity((1, 3, 111, 2, 802, 1, 1, 7)) ieee8021CfmV2Mib.setRevisions(('2014-12-15 00:00', '2011-02-27 00:00', '2008-11-18 00:00', '2008-10-15 00:00')) if mibBuilder.loadTexts: ieee8021CfmV2Mib.setLastUpdated('201412150000Z') if mibBuilder.loadTexts: ieee8021CfmV2Mib.setOrganization('IEEE 802.1 Working Group') ieee8021_cfm_stack_table = mib_table((1, 3, 111, 2, 802, 1, 1, 8, 1, 1, 2)) if mibBuilder.loadTexts: ieee8021CfmStackTable.setStatus('current') ieee8021_cfm_stack_entry = mib_table_row((1, 3, 111, 2, 802, 1, 1, 8, 1, 1, 2, 1)).setIndexNames((0, 'IEEE8021-CFM-V2-MIB', 'ieee8021CfmStackifIndex'), (0, 'IEEE8021-CFM-V2-MIB', 'ieee8021CfmStackServiceSelectorType'), (0, 'IEEE8021-CFM-V2-MIB', 'ieee8021CfmStackServiceSelectorOrNone'), (0, 'IEEE8021-CFM-V2-MIB', 'ieee8021CfmStackMdLevel'), (0, 'IEEE8021-CFM-V2-MIB', 'ieee8021CfmStackDirection')) if mibBuilder.loadTexts: ieee8021CfmStackEntry.setStatus('current') ieee8021_cfm_stackif_index = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 1, 2, 1, 1), interface_index()) if mibBuilder.loadTexts: ieee8021CfmStackifIndex.setStatus('current') ieee8021_cfm_stack_service_selector_type = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 1, 2, 1, 2), ieee8021_service_selector_type()) if mibBuilder.loadTexts: ieee8021CfmStackServiceSelectorType.setStatus('current') ieee8021_cfm_stack_service_selector_or_none = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 1, 2, 1, 3), ieee8021_service_selector_value_or_none()) if mibBuilder.loadTexts: ieee8021CfmStackServiceSelectorOrNone.setStatus('current') ieee8021_cfm_stack_md_level = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 1, 2, 1, 4), dot1ag_cfm_md_level()) if mibBuilder.loadTexts: ieee8021CfmStackMdLevel.setStatus('current') ieee8021_cfm_stack_direction = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 1, 2, 1, 5), dot1ag_cfm_mp_direction()) if mibBuilder.loadTexts: ieee8021CfmStackDirection.setStatus('current') ieee8021_cfm_stack_md_index = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 1, 2, 1, 6), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: ieee8021CfmStackMdIndex.setStatus('current') ieee8021_cfm_stack_ma_index = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 1, 2, 1, 7), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: ieee8021CfmStackMaIndex.setStatus('current') ieee8021_cfm_stack_mep_id = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 1, 2, 1, 8), dot1ag_cfm_mep_id_or_zero()).setMaxAccess('readonly') if mibBuilder.loadTexts: ieee8021CfmStackMepId.setStatus('current') ieee8021_cfm_stack_mac_address = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 1, 2, 1, 9), mac_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: ieee8021CfmStackMacAddress.setStatus('current') ieee8021_cfm_vlan_table = mib_table((1, 3, 111, 2, 802, 1, 1, 8, 1, 3, 2)) if mibBuilder.loadTexts: ieee8021CfmVlanTable.setStatus('current') ieee8021_cfm_vlan_entry = mib_table_row((1, 3, 111, 2, 802, 1, 1, 8, 1, 3, 2, 1)).setIndexNames((0, 'IEEE8021-CFM-V2-MIB', 'ieee8021CfmVlanComponentId'), (0, 'IEEE8021-CFM-V2-MIB', 'ieee8021CfmVlanSelector')) if mibBuilder.loadTexts: ieee8021CfmVlanEntry.setStatus('current') ieee8021_cfm_vlan_component_id = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 3, 2, 1, 1), ieee8021_pbb_component_identifier()) if mibBuilder.loadTexts: ieee8021CfmVlanComponentId.setStatus('current') ieee8021_cfm_vlan_selector = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 3, 2, 1, 3), ieee8021_service_selector_value()) if mibBuilder.loadTexts: ieee8021CfmVlanSelector.setStatus('current') ieee8021_cfm_vlan_primary_selector = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 3, 2, 1, 5), ieee8021_service_selector_value()).setMaxAccess('readcreate') if mibBuilder.loadTexts: ieee8021CfmVlanPrimarySelector.setStatus('current') ieee8021_cfm_vlan_row_status = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 3, 2, 1, 6), row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: ieee8021CfmVlanRowStatus.setStatus('current') ieee8021_cfm_default_md_table = mib_table((1, 3, 111, 2, 802, 1, 1, 8, 1, 2, 5)) if mibBuilder.loadTexts: ieee8021CfmDefaultMdTable.setStatus('current') ieee8021_cfm_default_md_entry = mib_table_row((1, 3, 111, 2, 802, 1, 1, 8, 1, 2, 5, 1)).setIndexNames((0, 'IEEE8021-CFM-V2-MIB', 'ieee8021CfmDefaultMdComponentId'), (0, 'IEEE8021-CFM-V2-MIB', 'ieee8021CfmDefaultMdPrimarySelectorType'), (0, 'IEEE8021-CFM-V2-MIB', 'ieee8021CfmDefaultMdPrimarySelector')) if mibBuilder.loadTexts: ieee8021CfmDefaultMdEntry.setStatus('current') ieee8021_cfm_default_md_component_id = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 2, 5, 1, 1), ieee8021_pbb_component_identifier()) if mibBuilder.loadTexts: ieee8021CfmDefaultMdComponentId.setStatus('current') ieee8021_cfm_default_md_primary_selector_type = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 2, 5, 1, 2), ieee8021_service_selector_type()) if mibBuilder.loadTexts: ieee8021CfmDefaultMdPrimarySelectorType.setStatus('current') ieee8021_cfm_default_md_primary_selector = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 2, 5, 1, 3), ieee8021_service_selector_value()) if mibBuilder.loadTexts: ieee8021CfmDefaultMdPrimarySelector.setStatus('current') ieee8021_cfm_default_md_status = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 2, 5, 1, 4), truth_value()).setMaxAccess('readonly') if mibBuilder.loadTexts: ieee8021CfmDefaultMdStatus.setStatus('current') ieee8021_cfm_default_md_level = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 2, 5, 1, 5), dot1ag_cfm_md_level_or_none().clone(-1)).setMaxAccess('readwrite') if mibBuilder.loadTexts: ieee8021CfmDefaultMdLevel.setStatus('current') ieee8021_cfm_default_md_mhf_creation = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 2, 5, 1, 6), dot1ag_cfm_mhf_creation().clone('defMHFdefer')).setMaxAccess('readwrite') if mibBuilder.loadTexts: ieee8021CfmDefaultMdMhfCreation.setStatus('current') ieee8021_cfm_default_md_id_permission = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 2, 5, 1, 7), dot1ag_cfm_id_permission().clone('sendIdDefer')).setMaxAccess('readwrite') if mibBuilder.loadTexts: ieee8021CfmDefaultMdIdPermission.setStatus('current') ieee8021_cfm_config_error_list_table = mib_table((1, 3, 111, 2, 802, 1, 1, 8, 1, 4, 2)) if mibBuilder.loadTexts: ieee8021CfmConfigErrorListTable.setStatus('current') ieee8021_cfm_config_error_list_entry = mib_table_row((1, 3, 111, 2, 802, 1, 1, 8, 1, 4, 2, 1)).setIndexNames((0, 'IEEE8021-CFM-V2-MIB', 'ieee8021CfmConfigErrorListSelectorType'), (0, 'IEEE8021-CFM-V2-MIB', 'ieee8021CfmConfigErrorListSelector'), (0, 'IEEE8021-CFM-V2-MIB', 'ieee8021CfmConfigErrorListIfIndex')) if mibBuilder.loadTexts: ieee8021CfmConfigErrorListEntry.setStatus('current') ieee8021_cfm_config_error_list_selector_type = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 4, 2, 1, 1), ieee8021_service_selector_type()) if mibBuilder.loadTexts: ieee8021CfmConfigErrorListSelectorType.setStatus('current') ieee8021_cfm_config_error_list_selector = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 4, 2, 1, 2), ieee8021_service_selector_value()) if mibBuilder.loadTexts: ieee8021CfmConfigErrorListSelector.setStatus('current') ieee8021_cfm_config_error_list_if_index = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 4, 2, 1, 3), interface_index()) if mibBuilder.loadTexts: ieee8021CfmConfigErrorListIfIndex.setStatus('current') ieee8021_cfm_config_error_list_error_type = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 4, 2, 1, 4), dot1ag_cfm_config_errors()).setMaxAccess('readonly') if mibBuilder.loadTexts: ieee8021CfmConfigErrorListErrorType.setStatus('current') ieee8021_cfm_ma_comp_table = mib_table((1, 3, 111, 2, 802, 1, 1, 8, 1, 6, 4)) if mibBuilder.loadTexts: ieee8021CfmMaCompTable.setStatus('current') ieee8021_cfm_ma_comp_entry = mib_table_row((1, 3, 111, 2, 802, 1, 1, 8, 1, 6, 4, 1)).setIndexNames((0, 'IEEE8021-CFM-V2-MIB', 'ieee8021CfmMaComponentId'), (0, 'IEEE8021-CFM-MIB', 'dot1agCfmMdIndex'), (0, 'IEEE8021-CFM-MIB', 'dot1agCfmMaIndex')) if mibBuilder.loadTexts: ieee8021CfmMaCompEntry.setStatus('current') ieee8021_cfm_ma_component_id = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 6, 4, 1, 1), ieee8021_pbb_component_identifier()) if mibBuilder.loadTexts: ieee8021CfmMaComponentId.setStatus('current') ieee8021_cfm_ma_comp_primary_selector_type = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 6, 4, 1, 2), ieee8021_service_selector_type()).setMaxAccess('readcreate') if mibBuilder.loadTexts: ieee8021CfmMaCompPrimarySelectorType.setStatus('current') ieee8021_cfm_ma_comp_primary_selector_or_none = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 6, 4, 1, 3), ieee8021_service_selector_value_or_none()).setMaxAccess('readcreate') if mibBuilder.loadTexts: ieee8021CfmMaCompPrimarySelectorOrNone.setStatus('current') ieee8021_cfm_ma_comp_mhf_creation = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 6, 4, 1, 4), dot1ag_cfm_mhf_creation().clone('defMHFdefer')).setMaxAccess('readcreate') if mibBuilder.loadTexts: ieee8021CfmMaCompMhfCreation.setStatus('current') ieee8021_cfm_ma_comp_id_permission = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 6, 4, 1, 5), dot1ag_cfm_id_permission().clone('sendIdDefer')).setMaxAccess('readcreate') if mibBuilder.loadTexts: ieee8021CfmMaCompIdPermission.setStatus('current') ieee8021_cfm_ma_comp_number_of_vids = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 6, 4, 1, 6), unsigned32()).setMaxAccess('readcreate') if mibBuilder.loadTexts: ieee8021CfmMaCompNumberOfVids.setStatus('current') ieee8021_cfm_ma_comp_row_status = mib_table_column((1, 3, 111, 2, 802, 1, 1, 8, 1, 6, 4, 1, 7), row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: ieee8021CfmMaCompRowStatus.setStatus('current') ieee8021_cfm_stack_group = object_group((1, 3, 111, 2, 802, 1, 1, 8, 2, 2, 12)).setObjects(('IEEE8021-CFM-V2-MIB', 'ieee8021CfmStackMdIndex'), ('IEEE8021-CFM-V2-MIB', 'ieee8021CfmStackMaIndex'), ('IEEE8021-CFM-V2-MIB', 'ieee8021CfmStackMepId'), ('IEEE8021-CFM-V2-MIB', 'ieee8021CfmStackMacAddress')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ieee8021_cfm_stack_group = ieee8021CfmStackGroup.setStatus('current') ieee8021_cfm_ma_group = object_group((1, 3, 111, 2, 802, 1, 1, 8, 2, 2, 13)).setObjects(('IEEE8021-CFM-V2-MIB', 'ieee8021CfmMaCompPrimarySelectorType'), ('IEEE8021-CFM-V2-MIB', 'ieee8021CfmMaCompPrimarySelectorOrNone'), ('IEEE8021-CFM-V2-MIB', 'ieee8021CfmMaCompMhfCreation'), ('IEEE8021-CFM-V2-MIB', 'ieee8021CfmMaCompIdPermission'), ('IEEE8021-CFM-V2-MIB', 'ieee8021CfmMaCompRowStatus'), ('IEEE8021-CFM-V2-MIB', 'ieee8021CfmMaCompNumberOfVids')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ieee8021_cfm_ma_group = ieee8021CfmMaGroup.setStatus('current') ieee8021_cfm_default_md_group = object_group((1, 3, 111, 2, 802, 1, 1, 8, 2, 2, 14)).setObjects(('IEEE8021-CFM-V2-MIB', 'ieee8021CfmDefaultMdStatus'), ('IEEE8021-CFM-V2-MIB', 'ieee8021CfmDefaultMdLevel'), ('IEEE8021-CFM-V2-MIB', 'ieee8021CfmDefaultMdMhfCreation'), ('IEEE8021-CFM-V2-MIB', 'ieee8021CfmDefaultMdIdPermission')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ieee8021_cfm_default_md_group = ieee8021CfmDefaultMdGroup.setStatus('current') ieee8021_cfm_vlan_id_group = object_group((1, 3, 111, 2, 802, 1, 1, 8, 2, 2, 15)).setObjects(('IEEE8021-CFM-V2-MIB', 'ieee8021CfmVlanPrimarySelector'), ('IEEE8021-CFM-V2-MIB', 'ieee8021CfmVlanRowStatus')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ieee8021_cfm_vlan_id_group = ieee8021CfmVlanIdGroup.setStatus('current') ieee8021_cfm_config_error_list_group = object_group((1, 3, 111, 2, 802, 1, 1, 8, 2, 2, 16)).setObjects(('IEEE8021-CFM-V2-MIB', 'ieee8021CfmConfigErrorListErrorType')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ieee8021_cfm_config_error_list_group = ieee8021CfmConfigErrorListGroup.setStatus('current') ieee8021_cfm_compliance_v2 = module_compliance((1, 3, 111, 2, 802, 1, 1, 8, 2, 1, 2)).setObjects(('IEEE8021-CFM-V2-MIB', 'ieee8021CfmStackGroup'), ('IEEE8021-CFM-V2-MIB', 'ieee8021CfmMaGroup'), ('IEEE8021-CFM-V2-MIB', 'ieee8021CfmDefaultMdGroup'), ('IEEE8021-CFM-V2-MIB', 'ieee8021CfmConfigErrorListGroup'), ('IEEE8021-CFM-V2-MIB', 'ieee8021CfmVlanIdGroup'), ('IEEE8021-CFM-MIB', 'dot1agCfmMdGroup'), ('IEEE8021-CFM-MIB', 'dot1agCfmMepGroup'), ('IEEE8021-CFM-MIB', 'dot1agCfmMepDbGroup'), ('IEEE8021-CFM-MIB', 'dot1agCfmNotificationsGroup'), ('IEEE8021-CFM-MIB', 'ieee8021CfmDefaultMdDefGroup'), ('IEEE8021-CFM-MIB', 'ieee8021CfmMaNetGroup')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ieee8021_cfm_compliance_v2 = ieee8021CfmComplianceV2.setStatus('current') dot1ag_cfm_with_pbb_te_compliance = module_compliance((1, 3, 111, 2, 802, 1, 1, 8, 2, 1, 3)).setObjects(('IEEE8021-CFM-V2-MIB', 'ieee8021CfmStackGroup'), ('IEEE8021-CFM-V2-MIB', 'ieee8021CfmMaGroup'), ('IEEE8021-CFM-V2-MIB', 'ieee8021CfmDefaultMdGroup'), ('IEEE8021-CFM-V2-MIB', 'ieee8021CfmConfigErrorListGroup'), ('IEEE8021-CFM-V2-MIB', 'ieee8021CfmVlanIdGroup'), ('IEEE8021-CFM-MIB', 'dot1agCfmMdGroup'), ('IEEE8021-CFM-MIB', 'dot1agCfmMepGroup'), ('IEEE8021-CFM-MIB', 'dot1agCfmMepDbGroup'), ('IEEE8021-CFM-MIB', 'dot1agCfmNotificationsGroup'), ('IEEE8021-CFM-MIB', 'ieee8021CfmDefaultMdDefGroup'), ('IEEE8021-CFM-MIB', 'ieee8021CfmMaNetGroup'), ('IEEE8021-CFM-MIB', 'ieee8021CfmPbbTeExtensionGroup'), ('IEEE8021-CFM-MIB', 'ieee8021CfmPbbTeTrafficBitGroup')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): dot1ag_cfm_with_pbb_te_compliance = dot1agCfmWithPbbTeCompliance.setStatus('current') mibBuilder.exportSymbols('IEEE8021-CFM-V2-MIB', ieee8021CfmDefaultMdStatus=ieee8021CfmDefaultMdStatus, ieee8021CfmDefaultMdComponentId=ieee8021CfmDefaultMdComponentId, ieee8021CfmStackServiceSelectorType=ieee8021CfmStackServiceSelectorType, ieee8021CfmMaCompRowStatus=ieee8021CfmMaCompRowStatus, ieee8021CfmDefaultMdPrimarySelectorType=ieee8021CfmDefaultMdPrimarySelectorType, ieee8021CfmConfigErrorListErrorType=ieee8021CfmConfigErrorListErrorType, ieee8021CfmStackGroup=ieee8021CfmStackGroup, ieee8021CfmVlanEntry=ieee8021CfmVlanEntry, ieee8021CfmDefaultMdMhfCreation=ieee8021CfmDefaultMdMhfCreation, ieee8021CfmConfigErrorListTable=ieee8021CfmConfigErrorListTable, ieee8021CfmMaCompEntry=ieee8021CfmMaCompEntry, ieee8021CfmVlanIdGroup=ieee8021CfmVlanIdGroup, ieee8021CfmConfigErrorListSelectorType=ieee8021CfmConfigErrorListSelectorType, ieee8021CfmMaCompTable=ieee8021CfmMaCompTable, dot1agCfmWithPbbTeCompliance=dot1agCfmWithPbbTeCompliance, ieee8021CfmMaCompMhfCreation=ieee8021CfmMaCompMhfCreation, ieee8021CfmDefaultMdEntry=ieee8021CfmDefaultMdEntry, ieee8021CfmDefaultMdTable=ieee8021CfmDefaultMdTable, ieee8021CfmComplianceV2=ieee8021CfmComplianceV2, ieee8021CfmDefaultMdGroup=ieee8021CfmDefaultMdGroup, ieee8021CfmStackTable=ieee8021CfmStackTable, ieee8021CfmMaComponentId=ieee8021CfmMaComponentId, ieee8021CfmMaCompPrimarySelectorOrNone=ieee8021CfmMaCompPrimarySelectorOrNone, ieee8021CfmStackMepId=ieee8021CfmStackMepId, ieee8021CfmDefaultMdLevel=ieee8021CfmDefaultMdLevel, ieee8021CfmStackMdLevel=ieee8021CfmStackMdLevel, ieee8021CfmConfigErrorListGroup=ieee8021CfmConfigErrorListGroup, ieee8021CfmStackDirection=ieee8021CfmStackDirection, PYSNMP_MODULE_ID=ieee8021CfmV2Mib, ieee8021CfmDefaultMdPrimarySelector=ieee8021CfmDefaultMdPrimarySelector, ieee8021CfmStackServiceSelectorOrNone=ieee8021CfmStackServiceSelectorOrNone, ieee8021CfmMaCompPrimarySelectorType=ieee8021CfmMaCompPrimarySelectorType, ieee8021CfmVlanPrimarySelector=ieee8021CfmVlanPrimarySelector, ieee8021CfmV2Mib=ieee8021CfmV2Mib, ieee8021CfmMaCompIdPermission=ieee8021CfmMaCompIdPermission, ieee8021CfmVlanTable=ieee8021CfmVlanTable, ieee8021CfmConfigErrorListSelector=ieee8021CfmConfigErrorListSelector, ieee8021CfmMaGroup=ieee8021CfmMaGroup, ieee8021CfmVlanSelector=ieee8021CfmVlanSelector, ieee8021CfmStackMacAddress=ieee8021CfmStackMacAddress, ieee8021CfmConfigErrorListEntry=ieee8021CfmConfigErrorListEntry, ieee8021CfmConfigErrorListIfIndex=ieee8021CfmConfigErrorListIfIndex, ieee8021CfmMaCompNumberOfVids=ieee8021CfmMaCompNumberOfVids, ieee8021CfmVlanComponentId=ieee8021CfmVlanComponentId, ieee8021CfmVlanRowStatus=ieee8021CfmVlanRowStatus, ieee8021CfmStackMaIndex=ieee8021CfmStackMaIndex, ieee8021CfmStackMdIndex=ieee8021CfmStackMdIndex, ieee8021CfmStackEntry=ieee8021CfmStackEntry, ieee8021CfmDefaultMdIdPermission=ieee8021CfmDefaultMdIdPermission, ieee8021CfmStackifIndex=ieee8021CfmStackifIndex)
SPEC = \ { "input": [ { "name": "first number", "type": "int" }, { "name": "second number", "type": "int" } ], "output": [ { "name": "number sum", "type": "int" } ], "package": { "author": "Stefan Maetschke", "author_email": "stefan.maetschke@gmail.com", "description": "Adds two numbers", "type": "Adder", "version": "1.0.0" }, }
spec = {'input': [{'name': 'first number', 'type': 'int'}, {'name': 'second number', 'type': 'int'}], 'output': [{'name': 'number sum', 'type': 'int'}], 'package': {'author': 'Stefan Maetschke', 'author_email': 'stefan.maetschke@gmail.com', 'description': 'Adds two numbers', 'type': 'Adder', 'version': '1.0.0'}}