content
stringlengths
7
1.05M
class DBSession(object): def __init__(self, pool, select_func): """得到一个线程安全连接""" self.__conn = pool.dedicated_connection() self.__cursor = self.__conn.cursor() self.__select = select_func def insert(self, sql: str, values: tuple = None, lastrowid: bool = False) -> int: return self._query(sql, values, lastrowid) def update(self, sql: str, values: tuple = None) -> int: return self._query(sql, values) def delete(self, sql: str, values: tuple = None) -> int: return self._query(sql, values) def select(self, sql: str, values: tuple = None, retry_times: int = 0, retry_interval: int = 1) -> list: return self.__select(sql, values=values, retry_times=retry_times, retry_interval=retry_interval) def query(self, sql: str, values: tuple = None, lastrowid: bool = False): """ query func :param sql: sql :param values: sql中需要初始化的值 :param lastrowid: :return: """ return self._query(sql, values=values, lastrowid=lastrowid) def _query(self, sql: str, values: tuple = None, lastrowid: bool = False): if values is None: result = self.__cursor.execute(sql) else: result = self.__cursor.execute(sql, values) if lastrowid: return self.__cursor.lastrowid else: return result def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): if exc_type or exc_val or exc_tb: self.__cursor.close() self.__conn.close() return False else: self.__cursor.close() self.__conn.commit() self.__conn.close() return True
#!/usr/bin/env python3 # encoding: utf-8 # author: cappyclearl # Given an array and a value, remove all instances of that value in-place and return the new length. # Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. # The order of elements can be changed. It doesn't matter what you leave beyond the new length. # Example: # Given nums = [3,2,2,3], val = 3, # Your function should return length = 2, with the first two elements of nums being 2. class Solution: def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ remove_count = nums.count(val) for i in range(remove_count): nums.remove(val) return len(nums)
# Link: https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/ class Solution: # @return an integer def lengthOfLongestSubstring(self, s): d = {} start = 0 maxlen = 0 for i, c in enumerate(s): if c not in d.keys(): if (i - start + 1) > maxlen: maxlen = i - start + 1 d[c] = i else: for _ in range(start, d[c]): d.pop(s[_]) start = d[c] + 1 d[c] = i return maxlen
class Number_Pad_To_Words(): let_to_num = { 'a': '2', 'b': '2', 'c': '2', 'd': '3', 'e': '3', 'f': '3', 'g': '4', 'h': '4', 'i': '4', 'j': '5', 'k': '5', 'l': '5', 'm': '6', 'n': '6', 'o': '6', 'p': '7', 'q': '7', 'r': '7', 's': '7', 't': '8', 'u': '8', 'v': '8', 'w': '9', 'x': '9', 'y': '9', 'z': '9' } # O(ns) n -> number of words, s -> num of letters def __init__(self, words): self.num_to_words = {} for word in words: ans = '' for let in word: ans+= self.let_to_num[let] if ans not in self.num_to_words: self.num_to_words[ans] = [word] else: self.num_to_words[ans].append(word) # O(1) lookup time def get_num_to_words(self, num): if str(num) not in self.num_to_words: return [] return self.num_to_words[str(num)]
JOB_TYPES = [ ('Delivery driver'), ('Web developer'), ('Lecturer'), ]
# -*- coding: utf-8 -*- """ Created on Fri Jun 30 18:05:06 2017 @author: pfduc """ class BookingError(Exception): def __init__(self, arg): self.message = arg class TimeSlotError(BookingError): def __init__(self, arg): self.message = arg
class Shazam: pass def foo(p): """ @param p: the magic word @type p: Shazam @return: """
#!/usr/bin/env python3 """ Write a function called in_bisect that takes a sorted list and a target value and returns True if the word is in the list and False if it’s not. """ def in_bisect(li, value): upper_limit = len(li)-1 lower_limit = 0 while upper_limit >= lower_limit: word_position = (lower_limit + upper_limit)//2 if li[word_position] == value: return True if bef_aft(li[word_position], value) == 1: lower_limit = word_position+1 else: upper_limit = word_position-1 return False def bef_aft(word1, word2): tmp_list = [] tmp_list.append(word1) tmp_list.append(word2) tmp_list.sort() if tmp_list[0] == word1: return 1 # if word1 is before word2 else: return 2 if __name__ == '__main__': fin = open("../Chapter9/words.txt") li = [] for words in fin: swords = words.strip() li.append(swords) print(in_bisect(li, "aaa"))
''' mymod.py - counts the number of lines and chars in the file. ''' def countLines(name): ''' countLines(name) - counts the number of lines in the file "name". Example: countLines("/home/test_user1/test_dir1/test.txt") ''' file = open(name) return len(file.readlines()) def countChars(name): ''' countChars(name) - counts the number of chars in the file "name". Example: countChars("/home/test_user1/test_dir1/test.txt") ''' file = open(name) return sum(len(x) for x in file.read()) def countLines1(file): file.seek(0) return len(file.readlines()) def countChars1(file): file.seek(0) return sum(len(x) for x in file.read()) def test(name): if type(name) == str: return "File {0} contains: {1} lines; {2} chars.".format(name, countLines(name), countChars(name)) else: return "File {0} contains: {1} lines; {2} chars.".format(name.name, countLines1(name), countChars1(name)) if __name__ == '__main__': print(test('mymod.py'))
#!/usr/bin/env python3 # Parse input with open("14/input.txt", "r") as fd: seq = list(fd.readline().rstrip()) fd.readline() line = fd.readline().rstrip() instr = dict() while line: i = tuple([x for x in line.split(" -> ")]) instr[i[0]] = i[1] line = fd.readline().rstrip() # Simulate Polymer # Count initial pairs counts = dict() for i, k in zip(seq, seq[1:]): pair = "".join([i, k]) counts[pair] = counts.get(pair, 0) + 1 # Simulate pairwise counts for i in range(40): copy = dict() for k, v in counts.items(): if k in instr.keys(): r = instr[k] copy[f"{k[0]}{r}"] = copy.get(f"{k[0]}{r}", 0) + v copy[f"{r}{k[1]}"] = copy.get(f"{r}{k[1]}", 0) + v counts = copy # Count occurences of characters element_count = dict() for k, v in counts.items(): for c in k: element_count[c] = element_count.get(c, 0) + v element_count[seq[0]] += 1 element_count[seq[-1]] += 1 max_e = int(max(element_count.values()) / 2) min_e = int(min(element_count.values()) / 2) print(max_e - min_e)
x=5 while x < 10: print(x) x += 1
num = int(input('digite um numero para saber se ele é par ou impar: ')) poi = num%2 if poi == 0: print('este numero é par') else: print('este numero é ímpar')
src = Split(''' prov_app.c ''') if aos_global_config.get("ERASE") == 1: component.add_macros(CONFIG_ERASE_KEY); component = aos_component('prov_app', src) component.add_comp_deps('kernel/yloop', 'tools/cli', 'security/prov', 'security/prov/test') component.add_global_macros('AOS_NO_WIFI')
#!/usr/bin/env python3 # https://agc001.contest.atcoder.jp/tasks/agc001_a n = int(input()) l = [int(x) for x in input().split()] l.sort() print(sum(l[::2]))
""" This module provides basic methods for unit conversion and calculation of basic wind plant variables """ def convert_power_to_energy(power_col, sample_rate_min="10T"): """ Compute energy [kWh] from power [kw] and return the data column Args: df(:obj:`pandas.DataFrame`): the existing data frame to append to col(:obj:`string`): Power column to use if not power_kw sample_rate_min(:obj:`float`): Sampling rate in minutes to use for conversion, if not ten minutes Returns: :obj:`pandas.Series`: Energy in kWh that matches the length of the input data frame 'df' """ time_conversion = {"1T": 1.0, "5T": 5.0, "10T": 10.0, "30T": 30.0, "1H": 60.0} energy_kwh = power_col * time_conversion[sample_rate_min] / 60.0 return energy_kwh def compute_gross_energy( net_energy, avail_losses, curt_losses, avail_type="frac", curt_type="frac" ): """ This function computes gross energy for a wind plant or turbine by adding reported availability and curtailment losses to reported net energy. Account is made of whether availabilty or curtailment loss data is reported in energy ('energy') or fractional units ('frac'). If in energy units, this function assumes that net energy, availability loss, and curtailment loss are all reported in the same units Args: net energy (numpy array of Pandas series): reported net energy for wind plant or turbine avail (numpy array of Pandas series): reported availability losses for wind plant or turbine curt (numpy array of Pandas series): reported curtailment losses for wind plant or turbine Returns: gross (numpy array of Pandas series): calculated gross energy for wind plant or turbine """ if (avail_type == "frac") & (curt_type == "frac"): gross = net_energy / (1 - avail_losses - curt_losses) elif (avail_type == "frac") & (curt_type == "energy"): gross = net_energy / (1 - avail_losses) + curt_losses elif (avail_type == "energy") & (curt_type == "frac"): gross = net_energy / (1 - curt_losses) + avail_losses elif (avail_type == "energy") & (curt_type == "energy"): gross = net_energy + curt_losses + avail_losses if len(gross[gross < net_energy]) > 0: raise Exception("Gross energy cannot be less than net energy. Check your input values") if (len(avail_losses[avail_losses < 0]) > 0) | (len(curt_losses[curt_losses < 0]) > 0): raise Exception( "Cannot have negative availability or curtailment input values. Check your data" ) return gross def convert_feet_to_meter(variable): """ Compute variable in [meter] from [feet] and return the data column Args: df(:obj:`pandas.Series`): the existing data frame to append to variable(:obj:`string`): variable in feet Returns: :obj:`pandas.Series`: variable in meters of the input data frame 'df' """ out = variable * 0.3048 return out
""" Pattern Matching: You are given two strings, pattern and value. The pattern string consists of just the letters a and b, describing a pattern within a string. For example, the string "catcatgocatgo" matches the pattern "aabab" (where cat is a and go is b). It also matches patterns like a, ab, and b. Write a method to determine if value matches pattern. (16.18, p511) SOLUTION: Backtracking N is length of `value` string and length of pattern can't exceed N. Time O(N^2) Space O(N) """ def _matches( pattern: str, value: str, main_size: int, alt_size: int, first_alt: int ) -> bool: """Return True if value matches pattern, False otherwise. The main and alternate pattern strings are known. :param pattern: pattern to match :param value: string :param main_size: length of the main pattern :param alt_size: length of the alternate pattern :param first_alt: beginning index of the first occurrence of the alternate pattern in `value` :return: True if value matches pattern, False otherwise. """ # Let i be the index of `pattern` and j be index of `value`. v = main_size main = value[:main_size] # worst case O(N) space alt = value[first_alt : first_alt + alt_size] for p in range(1, len(pattern)): is_main = pattern[p] == pattern[0] size = main_size if is_main else alt_size _next = value[v : v + size] if is_main and main != _next: return False if not is_main and alt != _next: return False v += size return True def matches(pattern: str, value: str) -> bool: if pattern is None or len(pattern) == 0: raise ValueError("pattern must not be empty string") if value is None or len(value) == 0: return False main = pattern[0] alt = "b" if main == "a" else "a" n_main = pattern.count(main) n_alt = len(pattern) - n_main first_alt: int = pattern.find(alt) max_main_size = int(len(value) / n_main) # round down for main_size in range(1, max_main_size + 1): remainder = len(value) - main_size * n_main if n_alt == 0 or remainder % n_alt == 0: # index of first `alt` substring occurs after how many repetitions of `main` substring alt_index = first_alt * main_size alt_size = 0 if n_alt == 0 else int(remainder / n_alt) # round down if _matches(pattern, value, main_size, alt_size, alt_index): return True return False
""" This program repeatedly asks a user to guess a number. The program ends when they're geussed correctly. """ # Secret number my_number = 10 # Ask the user to guess guess = int(input("Enter a guess: ")) # Keep asking until the guess becomes equal to the secret number while guess != my_number: print("Guess again!") guess = int(input("Enter a guess: ")) print("Good job, you got it!")
N,*H = [int(x) for x in open(0).read().split()] def solve(l, r): if l>r: return 0 min_=min(H[l:r+1]) for i in range(l,r+1): H[i]-=min_ count=min_ i=l while i<r: while i<=r and H[i]==0: i+=1 s=i while i<=r and H[i]>0: i+=1 count+=solve(s,i-1) return count print(solve(0, len(H)-1))
# FizzBuzz # Getting input from users for the max number to go to for FizzBuzz ip = input("Enter the max number to go for FizzBuzz: \n") # If user inputs a number this is executed if (ip != ""): for i in range(1, int(ip) + 1): if (i % 3 == 0 and i%5 == 0): print("FizzBuzz") elif (i % 3 == 0): print("Fizz") elif (i % 5 == 0): print("Buzz") else: print(i) # If the input is empty, the value is taken as 100 else: for i in range(1, 101): if (i % 3 == 0 and i%5 == 0): print("FizzBuzz") elif (i % 3 == 0): print("Fizz") elif (i % 5 == 0): print("Buzz") else: print(i)
town = input().lower() sell_count = float(input()) if 0<=sell_count<=500: if town == "sofia": comission = sell_count*0.05 print(f'{comission:.2f}') elif town=="varna": comission = sell_count * 0.045 print(f'{comission:.2f}') elif town == "plovdiv": comission = sell_count * 0.055 print(f'{comission:.2f}') else: print('error') elif 500<sell_count<=1000: if town == "sofia": comission = sell_count*0.07 print(f'{comission:.2f}') elif town=="varna": comission = sell_count * 0.075 print(f'{comission:.2f}') elif town == "plovdiv": comission = sell_count * 0.08 print(f'{comission:.2f}') else: print('error') elif 1000<sell_count<=10000: if town == "sofia": comission = sell_count*0.08 print(f'{comission:.2f}') elif town=="varna": comission = sell_count * 0.10 print(f'{comission:.2f}') elif town == "plovdiv": comission = sell_count * 0.12 print(f'{comission:.2f}') else: print('error') elif 10000 < sell_count: if town == "sofia": comission = sell_count*0.12 print(f'{comission:.2f}') elif town=="varna": comission = sell_count * 0.13 print(f'{comission:.2f}') elif town == "plovdiv": comission = sell_count * 0.145 print(f'{comission:.2f}') else: print('error') else: print('error')
class Keyword(object): """ Represents a keyword that can be intercepted from a message. """ def __init__(self, keyword, has_args, handler): self.keyword = keyword self.has_args = has_args self.handler = handler def handle(self, args=None): """ Calls the handler of a `Keyword` object with an optional argument. :param args: Argument in text form. :returns: Return value from calling the handler function. """ # Check if the keyword has arguments if self.has_args: return self.handler(args) else: if args is not None and len(args) > 0: raise ValueError('Keyword does not accept arguments.') return self.handler() class KeywordManager(object): """ A collection class for Keywords. """ def __init__(self, keywords_list): self.keywords = [] for keyword in keywords_list: self.add(**keyword) def add(self, type, keyword, has_args, handler, **kwargs): """ Add a `Keyword` to the collection. :param keyword_type: Type of keyword to add. :param keyword: The keyword string. :param has_args: Boolean value indicating whether the handler accepts arguments. :param handler: A handler function to call when keyword is detected. :param kwargs: Additional arguments to the keyword type """ # Check if keyword already exists in collection. for word in self.keywords: if word.keyword == keyword: raise ValueError('Keyword already exists') # Check for a keyword type if issubclass(type, Keyword): keyword = type( keyword=keyword, has_args=has_args, handler=handler, **kwargs) else: raise ValueError( 'No keyword type of \'{}\' exists'.format(type)) self.keywords.append(keyword) def get(self, keyword): """ Get a `Keyword` by keyword string. :param keyword: Keyword string of the `Keyword` to get. :returns: A `Keyword` object. :rtype: Keyword """ # Search through the list of keywords for the matching one for word in self.keywords: if word.keyword == keyword: return word # Return `None` if not found return None
class Compass(object): def __init__(self, spacedomains): self.categories = tuple(spacedomains) self.spacedomains = spacedomains # check time compatibility between components self._check_spacedomain_compatibilities(spacedomains) def _check_spacedomain_compatibilities(self, spacedomains): for category in spacedomains: # check that components' spacedomains are equal # (to stay until spatial supermesh supported) if not spacedomains[category].spans_same_region_as( spacedomains[self.categories[0]]): raise NotImplementedError( "components' spacedomains are not identical")
""" LeetCode Problem 801. Minimum Swaps To Make Sequences Increasing Link: https://leetcode.com/problems/minimum-swaps-to-make-sequences-increasing/ Written by: Mostofa Adib Shakib Language: Python Time complexity: O(n) Space complexity: O(n) Explanation: 1) A[i - 1] < A[i] && B[i - 1] < B[i]. In this case, if we want to keep A and B increasing before the index i, can only have two choices. -> 1.1 don't swap at (i-1) and don't swap at i, we can get not_swap[i] = not_swap[i-1] -> 1.2 swap at (i-1) and swap at i, we can get swap[i] = swap[i-1]+1 If swap at (i-1) and do not swap at i, we can not guarantee A and B increasing. 2) A[i-1] < B[i] && B[i-1] < A[i] In this case, if we want to keep A and B increasing before the index i, can only have two choices. -> 2.1 swap at (i-1) and do not swap at i, we can get notswap[i] = Math.min(swap[i-1], notswap[i] ) -> 2.2 do not swap at (i-1) and swap at i, we can get swap[i]=Math.min(notswap[i-1]+1, swap[i]) """ class Solution: def minSwap(self, A: List[int], B: List[int]) -> int: length = len(A) not_swap = [0] + [float('inf')] * (length-1) swap = [1] + [float('inf')] * (length-1) for i in range(1, length): if A[i - 1] < A[i] and B[i - 1] < B[i]: swap[i] = swap[i - 1] + 1 not_swap[i] = not_swap[i - 1] if A[i - 1] < B[i] and B[i - 1] < A[i]: swap[i] = min(swap[i], not_swap[i - 1] + 1) not_swap[i] = min(not_swap[i], swap[i - 1]) return min(swap[-1], not_swap[-1])
time1 = int(input()) time2 = int(input()) time3 = int(input()) sum = time1 + time2 + time3 minutes = int(sum / 60) seconds = sum % 60 if seconds <= 9: print('{0}:0{1}'.format(minutes, seconds)) else: print('{0}:{1}'.format(minutes, seconds))
"""packer_builder/release.py""" # Version tracking for package. __author__ = 'Larry Smith Jr.' __version__ = '0.1.0' __package_name__ = 'packer_builder'
# # @lc app=leetcode id=908 lang=python3 # # [908] Smallest Range I # # @lc code=start class Solution: def smallestRangeI(self, A: List[int], K: int) -> int: mi, ma = min(A), max(A) return 0 if ma - mi - 2*K <= 0 else ma - mi - 2*K # @lc code=end
class RandomizedSet(object): def __init__(self): """ Initialize your data structure here. """ self.d = {} # key - position in list self.l = [] # numbers def insert(self, val): """ Inserts a value to the set. Returns true if the set did not already contain the specified element. :type val: int :rtype: bool """ # check if already exist in l if val in self.d: return False # append to l and add key to d index = len(self.l) self.l.append(val) self.d[val] = index return True def remove(self, val): """ Removes a value from the set. Returns true if the set contained the specified element. :type val: int :rtype: bool """ # check if not in l if val not in self.d: return False # find index through d and get val, then move the last element to this index and update that key if self.d[val]==len(self.l)-1: self.d.pop(val) self.l.pop() return True index = self.d[val] last = self.l.pop() self.l[index] = last self.d[last] = index self.d.pop(val) return True def getRandom(self): """ Get a random element from the set. :rtype: int """ # pick a random index in [0:len(l)] return random.choice(self.l) # Your RandomizedSet object will be instantiated and called as such: # obj = RandomizedSet() # param_1 = obj.insert(val) # param_2 = obj.remove(val) # param_3 = obj.getRandom()
a = [[10,0],[10,0],[10,0],[10,0],[10,0],[10,0],[10,0],[10,0],[10,0],[10,0]] step=30 def setup(): size(500,500) smooth() noStroke() myInit() def myInit(): for i in range(len(a)): a[i]=[random(0,10)] for j in range(len(a[i])): a[i][j]=random(0,30) def draw(): global step fill(180,50) background(10) for i in range(len(a)): for j in range(len(a[i])): stroke(100) strokeWeight(1) fill(50) rect(i*step+100,j*step+100,step,step) noStroke() fill(250,90) ellipse (i*step +115 , j*step +115 , a[i][j], a[i][j]) def mouseClicked(): myInit()
#Crie um algoritimo que leia um número e imprima na tela #o mesmo, o seu antecessor e o seu sucessor. n1 = int(input("Digite um número para essa operação: ")) print("O nuúmero que você digitou foi {}.\nO seu antecessor é {}.\nO seu sucessor é {}.".format(n1, (n1-1), (n1+1)))
# porownania print('----------') print((1, 2, 3) < (1, 2, 4)) print([1, 2, 3] < [1, 2, 4]) print('ABC' < 'C' < 'Pascal' < 'Python') print((1, 2, 3, 4) < (1, 2, 4)) print((1, 2) < (1, 2, -1)) print((1, 2, 3) == (1.0, 2.0, 3.0)) print((1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)) print('--- inne ---') print(list((1, 2, 3)) < [1, 2, 3]) print((1, 2, 3) > tuple([1, 2, 3])) print(0 == 0 == 0.0 == 0j)
# Error handler class GeneralError(Exception): """ This is for general error """ def __init__(self, error, severity, status_code): self.error = error self.severity = severity self.status_code = status_code
################################### SERVER'S SIDE ################################### #const mask = 0xffffffff #bitwise operations have the least priority #Note 1: all variables are unsigned 32-bit quantities and wrap modulo 2**32 when calculating, except for #ml, message length: 64-bit quantity, and #hh, message digest: 160-bit quantity #Note 2: big endian key = b'SuPeR_sEcReT_kEy,_NoT_tO_bE_gUeSsEd_So_EaSiLy' def big_endian_64_bit( num ): num = hex(num).replace('0x','').rjust(16,'0') return bytes([int(num[i:i+2], 16) for i in range(0, len(num), 2)]) def leftrot( num ): return ((num << 1) & mask) + (num >> 31) def bytes2int( block ): return sum([block[len(block)-1-i] * (256**i) for i in range(len(block))]) def leftrotate(num, offset): num_type = type(num) if num_type == bytes: num = bytes2int(num) for i in range(offset): num = leftrot(num) if num_type == bytes: num = big_endian_64_bit( num )[4:] return num def XOR( block1, block2, block3, block4 ): return bytes([x^y^z^t for x,y,z,t in zip(block1, block2, block3, block4)]) def SHA1( message ): #the inner mechanism only #Initialize variable: h0 = 0x67452301 h1 = 0xEFCDAB89 h2 = 0x98BADCFE h3 = 0x10325476 h4 = 0xC3D2E1F0 ml = len(message) * 8 #Pre-processing message += b'\x80' while (len(message) * 8) % 512 != 448: message += b'\x00' message += big_endian_64_bit( ml % (2**64)) #Process the message in successive 512-bit chunks: chunks = [message[i:i+64] for i in range(0, len(message), 64)] for chunk in chunks: w = [chunk[i:i+4] for i in range(0, 64, 4)] #Message schedule: extend the sixteen 32-bit words into eighty 32-bit words: for i in range(16, 80): #Note 3: SHA-0 differs by not having this leftrotate. w += [leftrotate( XOR(w[i-3], w[i-8], w[i-14], w[i-16]), 1 )] #Initialize hash value for this chunk: a = h0 b = h1 c = h2 d = h3 e = h4 #Main loop: for i in range(80): f = 0 k = 0 if i in range(20): f = (b & c) | ((b ^ mask) & d) k = 0x5A827999 elif i in range(20,40): f = b ^ c ^ d k = 0x6ED9EBA1 elif i in range(40,60): f = (b & c) | (b & d) | (c & d) k = 0x8F1BBCDC elif i in range(60,80): f = b ^ c ^ d k = 0xCA62C1D6 temp = (leftrotate(a, 5) + f + e + k + bytes2int(w[i])) % (2**32) e = d d = c c = leftrotate(b, 30) b = a a = temp #Add this chunk's hash to result so far: h0 = (h0 + a) % (2**32) h1 = (h1 + b) % (2**32) h2 = (h2 + c) % (2**32) h3 = (h3 + d) % (2**32) h4 = (h4 + e) % (2**32) #Produce the final hash value (big-endian) as a 160-bit number: hh = (h0 << 128) | (h1 << 96) | (h2 << 64) | (h3 << 32) | h4 return hh def isValid( message, hh ): res = False if SHA1(key + message) == hh: res = True return res ################################### ATTACKER'S SIDE ################################### def pad( bytelength ): #MD_padding ml = bytelength * 8 #Pre-processing padding = b'\x80' while ((bytelength + len(padding)) * 8) % 512 != 448: padding += b'\x00' padding += big_endian_64_bit( ml ) return padding def SHA1_LE(old_hh, wanna_be, length): if (len(wanna_be + pad(length)) * 8) % 512 != 0: hh = -1 else: #Initialize variable: h0 = (old_hh & (mask << 128)) >> 128 h1 = (old_hh & (mask << 96)) >> 96 h2 = (old_hh & (mask << 64)) >> 64 h3 = (old_hh & (mask << 32)) >> 32 h4 = old_hh & mask ml = length * 8 #Pre-processing message = wanna_be + pad(length) #Process the message in successive 512-bit chunks: chunks = [message[i:i+64] for i in range(0, len(message), 64)] for chunk in chunks: w = [chunk[i:i+4] for i in range(0, 64, 4)] #Message schedule: extend the sixteen 32-bit words into eighty 32-bit words: for i in range(16, 80): #Note 3: SHA-0 differs by not having this leftrotate. w += [leftrotate( XOR(w[i-3], w[i-8], w[i-14], w[i-16]), 1 )] #Initialize hash value for this chunk: a = h0 b = h1 c = h2 d = h3 e = h4 #Main loop: for i in range(80): f = 0 k = 0 if i in range(20): f = (b & c) | ((b ^ mask) & d) k = 0x5A827999 elif i in range(20,40): f = b ^ c ^ d k = 0x6ED9EBA1 elif i in range(40,60): f = (b & c) | (b & d) | (c & d) k = 0x8F1BBCDC elif i in range(60,80): f = b ^ c ^ d k = 0xCA62C1D6 temp = (leftrotate(a, 5) + f + e + k + bytes2int(w[i])) % (2**32) e = d d = c c = leftrotate(b, 30) b = a a = temp #Add this chunk's hash to result so far: h0 = (h0 + a) % (2**32) h1 = (h1 + b) % (2**32) h2 = (h2 + c) % (2**32) h3 = (h3 + d) % (2**32) h4 = (h4 + e) % (2**32) #Produce the final hash value (big-endian) as a 160-bit number: hh = (h0 << 128) | (h1 << 96) | (h2 << 64) | (h3 << 32) | h4 return hh def main(): print('========= A user is granting access to the server =========') #user has this message mes = b'comment1=cooking%20MCs;userdata=foo;comment2=%20like%20a%20pound%20of%20bacon' #user sign it with a common key shared with the server old_hh = SHA1(key + mes) #user use the message and its signature to the server valid = isValid(mes, old_hh) if valid: print('Welcome back!') else: print('Invalid signature, please check your information again.') print('\n========= And an attack has retrieve the user\'s message and corresponding hash =========') print(mes) print(hex(old_hh).replace('0x','').rjust(40,'0')) print('\nNow he will implement the length extension attack on SHA-1 to make a new valid message') print('with signature without any knowledge of the secret key itself...') wanna_be = b';admin=true' keyl = -1 message = b'' hh = -1 while not isValid(message, hh): keyl += 1 message = mes + pad(keyl + len(mes)) + wanna_be hh = SHA1_LE(old_hh, wanna_be, keyl + len(message)) print('\nFINALLY!!!!!!!!!!!') print('Keyl = ' + str(keyl)) print(message) print(hex(SHA1(key + message)).replace('0x','').rjust(40,'0')) #for demonstration purpose only print(hex(hh).replace('0x','').rjust(40,'0')) if __name__ == '__main__': main()
# DOCUMENTATION # main def main(): canadian = {"red", "white"} british = {"red", "blue", "white"} italian = {"red", "white", "green"} if canadian.issubset(british): print("canadian flag colours occur in british") if not italian.issubset(british): print("not all italian flag colors occur in british") french = {"red", "white", "blue"} if french == british: print("all colors in french occur in british") french.add("transparent") print(french) french.discard("transparent") print(french) print(canadian.union(italian)) print(british.intersection(italian)) print(british.difference(italian)) try: french.remove("waldo") except Exception: print("waldo not found") print(french.clear()) # PROGRAM RUN if __name__ == "__main__": main()
#encoding = utf-8 __author__ = 'lg' with open('H:\Programming\Python_Workspace\in.txt','r') as f: list1 = f.readline().split() list2 = f.readline().split() print(list1) print(list2) #两个list的交集(法一) 时间复杂度为O(n^2) def intersect(a,b): listRes = [] for i in range(len(a)): for j in range(len(b)): if a[i] == b[j]: if a[i] not in listRes: listRes.append(a[i]) listRes.sort() print(listRes) #两个list的交集(法二)  时间复杂度为O(n^2) def intersect_1(a,b): listRes = [] for i in range(len(a)): if a[i] in b: if a[i] not in listRes: listRes.append(a[i]) print(sorted(listRes)) #两个list的差集 def minus(a,b): listRes = [] for i in range(len(a)): if a[i] not in b: listRes.append(a[i]) print(sorted(listRes)) # list1 intersect list2 intersect(list1,list2) # list1 minus list2 minus(list1,list2) # list2 minus list1 minus(list2,list1)
# @desc Predict the returned value # @desc by Savonnah '23 def calc(num): if num <= 10: result = num * 2 else: result = num * 10 return result def main(): print(calc(1)) print(calc(41)) print(calc(-5)) print(calc(3)) print(calc(10)) if __name__ == '__main__': main()
### PROBLEM 3 degF = 40.5 degC = (5/9) * (degF - 32) print(degC) #when degF is -40.0, degC is -40.0 ##when degF is 40.5, degC is 4.72
# # @lc app=leetcode id=1290 lang=python3 # # [1290] Convert Binary Number in a Linked List to Integer # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def getDecimalValue(self, head: ListNode) -> int: decimal = 0 while head: decimal <<= 1 decimal |= head.val head = head.next return decimal # @lc code=end
#!/usr/bin/python3 # -*- coding: utf-8 -*- a = [1, 3, -1, -7, 2, 4, -6] b = [n if n > 0 else 0 for n in a] print(b) c = [n for n in a if n > 0] print(c) """ c = (a > b) ? a : b 等价于 c = a if a > b else b """
#!/usr/bin/python3 def palindrome(num): if num == num[::-1]: return True return False def addOne(num): num = int(num) + 1 return str(num) def isPalindrome(num): num = str(num) num = num.zfill(6) value = palindrome(num[2:]) if value: num = num.zfill(6) value2 = palindrome(num[1:]) if value2: num = num.zfill(6) value3 = palindrome(num[1:-2]) if value3: num = num.zfill(6) value4 = palindrome(num) if value4: return True return False resultList = [] for i in range(1, 999996): result = isPalindrome(i) if result: resultList.append(i) print(resultList)
a = int(input()) b = int(a/5) if (a%5 == 0): print(b) else: print(b+1)
# Day8 of my 100DaysOfCode Challenge # Program to open a file in append mode file = open('Day8/new.txt', 'a') file.write("This is a really great experience") file.close()
#!/usr/bin/python def max_in_list(list_of_numbers): ''' Finds the largest number in a list ''' biggest_num = 0 for i in list_of_numbers: if i > biggest_num: biggest_num = i return(biggest_num)
{ "targets":[ { "target_name": "accessor", "sources": ["accessor.cpp"] } ] }
# terrascript/data/Trois-Six/sendgrid.py # Automatically generated by tools/makecode.py (24-Sep-2021 15:26:45 UTC) __all__ = []
__author__ = 'arobres, jfernandez' # PUPPET WRAPPER CONFIGURATION PUPPET_MASTER_PROTOCOL = 'https' PUPPET_WRAPPER_IP = 'puppet-master.dev-havana.fi-ware.org' PUPPET_WRAPPER_PORT = 8443 PUPPET_MASTER_USERNAME = 'root' PUPPET_MASTER_PWD = '**********' PUPPET_WRAPPER_MONGODB_PORT = 27017 PUPPET_WRAPPER_MONGODB_DB_NAME = 'puppetWrapper' PUPPET_WRAPPER_MONGODB_COLLECTION = 'nodes' #AUTHENTICATION CONFIG_KEYSTONE_URL = 'http://130.206.80.57:4731/v2.0/tokens' CONFIG_KEYSTONE_TENANT_NAME_VALUE = '**********' CONFIG_KEYSTONE_USERNAME_VALUE = '**********' CONFIG_KEYSTONE_PWD_VALUE = '**********'
''' A simple programme to print hex grid on terminal screen. Tip: I have used `raw` strings. Author: Sunil Dhaka ''' GRID_WIDTH=20 GRID_HEIGHT=16 def main(): for _ in range(GRID_HEIGHT): for _ in range(GRID_WIDTH): print(r'/ \_',end='') print() for _ in range(GRID_WIDTH): print(r'\_/ ',end='') print() if __name__=='__main__': main()
''' Order the following functions by asymptotic growth rate. 4nlog n+2n 210 2log n 3n+100log n 4n 2n n2 +10n n3 nlog n ''' ''' 2^10 O(1) 3n+100log(n) O(log(n)) 4n O(n) 4nlog(n)+2n and O(nlog(n)) n^2+10n and O(n^2) n^3 O(n^3) 2^(log(n)) O(2^(log(n))) 2^n O(2^n) '''
# encoding = utf-8 class GreekGetter: def get(self, msgid): return msgid[::-1] class EnglishGetter: def get(self, msgid): return msgid[:] def get_localizer(language="English"): languages = dict(English=EnglishGetter, Greek=GreekGetter) return languages[language]() # Create our localizers e, g = get_localizer("English"), get_localizer("Greek") # Localize some text print([(e.get(msgid), g.get(msgid)) for msgid in "dog parrot cat bear".split()])
print("Enter the number of terms:") n=int(input()) a=0 b=1 for i in range(n+1): c=a+b a=b b=c print(c,end=" ")
class Foo: def __init__(self): self.tmp = False def extract_method(self, condition1, condition2, condition3, condition4): list = (1, 2, 3) a = 6 b = False if a in list or self.tmp: if condition1: print(condition1) if b is not condition2: print(b) else: self.bar(condition3, condition4) def bar(self, condition3_new, condition4_new): self.tmp2 = True if condition3_new: print(condition3_new) if condition4_new: print(condition4_new) print("misterious extract method test") f = Foo() f.extract_method(True, True, True, True)
# Escape Sequences # \\ # \' # \" # \n course_name = "Pyton Mastery \n with Mosh" print(course_name)
# @Title: 二进制矩阵中的特殊位置 (Special Positions in a Binary Matrix) # @Author: KivenC # @Date: 2020-09-13 10:54:22 # @Runtime: 64 ms # @Memory: 13.7 MB class Solution: def numSpecial(self, mat: List[List[int]]) -> int: m, n = len(mat), len(mat[0]) row = [sum(r) == 1 for r in mat] col = [sum([mat[i][j] for i in range(m)]) == 1 for j in range(n)] res = 0 for i in range(m): for j in range(n): if mat[i][j] == 1 and row[i] and col[j]: res += 1 return res
# Section05-2 # 파이썬 흐름제어(반복문) # 반복문 실습 # 코딩의 핵심 -> 조건 해결 중요 # 기본 반복문 : for, while v1 = 1 while v1 < 11: print("v1 is :", v1) v1 += 1 for v2 in range(10): print("v2 is: ", v2) for v3 in range(1,11): print("v3 is :", v3) # 1 ~ 100합 sum1 = 0 cnt1 = 0 while cnt1 <= 100: sum1 += cnt1 cnt1 += 1 print('1 ~ 100: ', sum1) print('1 ~ 100: ', sum(range(1, 101))) print('1 ~ 100: ', sum(range(1, 101, 2))) # 시퀀스(순서가 있는)자료형 반복 # 문자열, 리스트, 튜플, 집합, 사전 # iterable 리턴함수 : range, reversed, enumerate, filter, map, zip names = ["Kim", "Park", "Cho", "Choi", "Yoo"] for name in names: print("You are : ", name) word = "dreams" for s in word: print("word :", s) my_info = { "name": "kim", "age" : 33, "city" : "Seoul" } # 기본값은 키 for key in my_info: print("my_info", key) #값 for key in my_info.values(): print("my_info", key) #키 for key in my_info.keys(): print("my_info", key) # 키 and 값 for k, v in my_info.items(): print("my_info", k, v) name = "KennRY" for n in name: if n.isupper(): print(n.lower()) else: print(n.upper()) # break numbers = [14, 3, 4, 7, 10, 24, 17, 2, 33, 15, 34, 36, 38] # for-else 구문(반복문이 정상적으로 수행된 경우 else 블럭 수행) for num in numbers: if num == 33: print("found : 33!") break else: print("not fund : 33!") else: print("Not found 33.....") # continue lt = ["1", 2, 5, True, 4.3, complex(4)] for v in lt: if type(v) is float: continue print("타입 :", type(v)) name = "NiceMan" print(reversed(name)) print(list(reversed(name))) print(tuple(reversed(name)))
class VolumeRaidLevels(object): def read_get(self, name, idx_name, unity_client): return unity_client.get_lun_raid_type(idx_name) class VolumeRaidLevelsColumn(object): def get_idx(self, name, idx, unity_client): return unity_client.get_luns()
NORTH = 0 EAST = 1 SOUTH = 2 WEST = 3 X_MOD = [0,1,0,-1] Y_MOD = [1,0,-1,0] num_states = 0 state_trans = [] infected_state = 0 class Node: def __init__(self, state, x, y): self.x = x self.y = y self.state = state def updateDir(self, dir): ''' Directions can be anything from 0 to 3 trans state tells us where to jump to based on the current state ''' dir = (dir + state_trans[self.state]) % 4 return dir def updateState(self): ''' states always increment and are bounded by max # states ''' self.state = ((self.state) + 1) % num_states return self.state def getNextNode(self, dir, nodes): ''' based on direction an current position, find the next node if we've never seen it before, create it ''' x = self.x + X_MOD[dir] y = self.y + Y_MOD[dir] name = 'x%dy%d' % (x,y) if not name in nodes: nodes[name] = Node(0,x,y) return nodes[name] def update(self, dir, nodes): ''' determine new direction, state and node return 1) if we infected the node 2) the next node to process 3) the direction we are facing on the next node ''' dir = self.updateDir(dir) self.updateState() return (self.state == infected_state), self.getNextNode(dir, nodes), dir def solveInfected(lines, iterations): ''' cretes the base list of nodes based on input then determine how many infections occur ''' nodes = {} startx = (len(lines[0].strip()) // 2) starty = (len(lines) // 2) * -1 startname = 'x%dy%d' % (startx, starty) y = 0 for line in lines: x = 0 for c in line.strip(): name = 'x%dy%d' % (x,y) if c == '#': nodes[name] = Node(infected_state,x,y) else: nodes[name] = Node(0,x,y) x += 1 y -= 1 node = nodes[startname] infect_count = 0 dir = NORTH for i in range(iterations): infected, node, dir = node.update(dir, nodes) if infected: infect_count += 1 print(infect_count) with open("input") as f: lines = f.readlines() # for part 1, two states # state 0, CLEAN, causes a right turn # state 1, INFECTED, causes a left turn (or 3 right turns) num_states = 2 state_trans = [3, 1] infected_state = 1 solveInfected(lines, 10000) # for part 2, fpir states # state 0, CLEAN, causes a right turn # state 1, WEAKENED, does not turn # state 2, INFECTED, causes a left turn (or 3 right turns) # state 3, FLAGGED, causes a turn around (or 2 right turns) num_states = 4 state_trans = [3, 0, 1, 2] infected_state = 2 solveInfected(lines, 10000000)
class Node: def __init__(self, data=None, next_node=None): self.data = data self.next_node = next_node def __str__(self): p = self nums = [] while p: nums.append(p.data) p = p.next_node return "[" + ", ".join(map(str, nums)) + "]" @staticmethod def list_to_LL(L): """ Converts the given Python list into a linked list. """ head = None for i in range(len(L) - 1, -1, -1): head = Node(L[i], head) return head def reverse_list(head): #--------------------------------------------------------------------------- # Method 1: Recursive. #--------------------------------------------------------------------------- # if head: # new_head = reverse_list(head.next_node) # # Right now, head.next_node is the tail of the sublist. # # We need the sublist's tail to be the (old) head instead. # if new_head: # head.next_node.next_node = head # head.next_node = None # return new_head # return head # Linked list is just one node. # return None # Linked list is empty. #--------------------------------------------------------------------------- # Method 2: Tail recursive (the recursive call is at the end). #--------------------------------------------------------------------------- # In languages other than Python, the compiler uses tail call optimization. # So for each recursive call, we can simply reuse the current stack frame. # It's also easy to convert tail recursive to iterative. #--------------------------------------------------------------------------- # return tail_recurse(None, head) #--------------------------------------------------------------------------- # Method 3: Iterative. #--------------------------------------------------------------------------- prev = None while head: head.next_node, prev, head = prev, head, head.next_node return prev def tail_recurse(prev, curr): """ Using tail recursion, reverses the linked list starting at curr, then joins the end of this linked list to the linked list starting at prev. """ if curr: new_curr = curr.next_node if new_curr: curr.next_node = prev return tail_recurse(curr, new_curr) # We've reached the end. curr.next_node = prev return curr return None # Linked list is empty/ if __name__ == "__main__": testHeads = [ Node.list_to_LL([]), Node.list_to_LL([1]), Node.list_to_LL([1, 2]), Node.list_to_LL([1, 2, 3]), Node.list_to_LL([1, 2, 3, 4]) ] for (index, head) in enumerate(testHeads): print("Test List #{}:".format(index + 1)) print(" BEFORE: {}".format(head)) head = reverse_list(head) print(" AFTER: {}".format(head))
# #todo -- make these constants configurable via admin # https://django-constance.readthedocs.io/en/latest/ # note that the constants below are example only (different constants were used during the application process) R0_YESES_NEEDED = 2 # R0_NOS_NEEDED = 2 R0_RATINGS_NEEDED = 3 # changed from 2 to 3 in 2018 (this number should never be reached) -- "yes" + "no" moved the application to R1, which was undesired this year (in 2017, a single "yes" was enough to move this on) R0_R1_NOS_TO_BLACKLIST = 2 # if this number of negative reviews are reached across R0 and R1, the application is blacklisted MINIMUM_RATED_QUERYSET_LENGTH = 20 MAX_REVIEWS_ROUND_ONE = 2 MAX_REVIEWS_ROUND_TWO = 2 RATING_R1_LOW_THRESHOLD = 5 # 2017-07-06`06:34:08 -- changed option to 0 to prevent from being active: "This is a last resort, and isn’t as relevant this year anyways since we have R0." NEEDED_RATING_TO_ROUND2 = 7.5 NEEDED_RATING_FOR_THIRD_REVIEW_ROUND1 = 5 NEEDED_DIFFERENCE_FOR_THIRD_REVIEW_ROUND1 = 2 APPLICATION_DEADLINE = '2018/07/14 11:59' # YEAR/MONTH/DAY HOUR:MINUTE -- 24h format, UTC -- CAREFUL: consider using 23:59 in the last time zone on Earth, like in 2017 and 2018 -- or Hawaii time (discuss with Nicole) # NOTE: Constants can be adjusted as needed over time, though depending on implementation changes may result in brief downtime or short temporary inconsistency while the database recalculates ("docker-compose run django python manage.py recalculate_ratings"). Default values are provided for reference. # amusingly, there is no consensus whether "yeses" or "yesses" is the correct plural of "yes" but "yeses" is preferable # https://web.archive.org/web/20170706034418/https://english.stackexchange.com/questions/168675/plural-of-yes
# uncompyle6 version 3.2.0 # Python bytecode 2.4 (62061) # Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] # Embedded file name: pirates.makeapirate.MakeAPirateGlobals BODYSHOP = 0 HEADSHOP = 1 MOUTHSHOP = 2 EYESSHOP = 3 NOSESHOP = 4 EARSHOP = 5 HAIRSHOP = 6 CLOTHESSHOP = 7 NAMESHOP = 8 TATTOOSHOP = 9 JEWELRYSHOP = 10 AVATAR_PIRATE = 0 AVATAR_SKELETON = 1 AVATAR_NAVY = 2 AVATAR_CAST = 3 ShopNames = [ 'BodyShop', 'HeadShop', 'MouthShop', 'EyesShop', 'NoseShop', 'EarShop', 'HairShop', 'ClothesShop', 'NameShop', 'TattooShop', 'JewelryShop'] LODList = [ 2000, 1000, 500] AnimList = [ 'idle', 'attention', 'axe_chop_idle', 'axe_chop_look_idle', 'bar_talk01_idle', 'bar_talk01_into_look', 'bar_talk01_look_idle', 'bar_talk01_outof_look', 'bar_talk02_idle', 'bar_talk02_into_look', 'bar_talk02_look_idle', 'bar_talk02_outof_look', 'bar_wipe', 'bar_wipe_into_look', 'bar_wipe_look_idle', 'bar_wipe_outof_look', 'bar_write_idle', 'bar_write_into_look', 'bar_write_look_idle', 'bar_write_outof_look', 'barrel_hide_idle', 'barrel_hide_into_look', 'barrel_hide_look_idle', 'barrel_hide_outof_look', 'bayonet_attackA', 'bayonet_attackB', 'bayonet_attackC', 'bayonet_attack_idle', 'bayonet_attack_walk', 'bayonet_drill', 'bayonet_fall_ground', 'bayonet_idle', 'bayonet_idle_to_fight_idle', 'bayonet_jump', 'bayonet_run', 'bayonet_turn_left', 'bayonet_turn_right', 'bayonet_walk', 'bigbomb_charge', 'bigbomb_charge_loop', 'bigbomb_charge_throw', 'bigbomb_draw', 'bigbomb_idle', 'bigbomb_throw', 'bigbomb_walk', 'bigbomb_walk_left', 'bigbomb_walk_left_diagonal', 'bigbomb_walk_right', 'bigbomb_walk_right_diagonal', 'bindPose', 'blacksmith_work_idle', 'blacksmith_work_into_look', 'blacksmith_work_look_idle', 'blacksmith_work_outof_look', 'blunderbuss_reload', 'board', 'bomb_charge', 'bomb_charge_loop', 'bomb_charge_throw', 'bomb_draw', 'bomb_hurt', 'bomb_idle', 'bomb_receive', 'bomb_throw', 'boxing_fromidle', 'boxing_haymaker', 'boxing_hit_head_right', 'boxing_idle', 'boxing_idle_alt', 'boxing_kick', 'boxing_punch', 'broadsword_combo', 'cards_bad_tell', 'cards_bet', 'cards_blackjack_hit', 'cards_blackjack_stay', 'cards_cheat', 'cards_check', 'cards_good_tell', 'cards_hide', 'cards_hide_hit', 'cards_hide_idle', 'cards_pick_up', 'cards_pick_up_idle', 'cards_set_down', 'cards_set_down_lose', 'cards_set_down_win', 'cards_set_down_win_show', 'cargomaster_work_idle', 'cargomaster_work_into_look', 'cargomaster_work_look_idle', 'cargomaster_work_outof_look', 'chant_a_idle', 'chant_b_idle', 'chest_idle', 'chest_kneel_to_steal', 'chest_putdown', 'chest_steal', 'chest_strafe_left', 'chest_strafe_right', 'chest_walk', 'coin_flip_idle', 'coin_flip_look_idle', 'coin_flip_old_idle', 'cower_idle', 'cower_into', 'cower_outof', 'crazy_idle', 'crazy_look_idle', 'cutlass_attention', 'cutlass_bladestorm', 'cutlass_combo', 'cutlass_headbutt', 'cutlass_hurt', 'cutlass_kick', 'cutlass_multihit', 'cutlass_sweep', 'cutlass_taunt', 'cutlass_walk_navy', 'dagger_asp', 'dagger_backstab', 'dagger_combo', 'dagger_coup', 'dagger_hurt', 'dagger_receive', 'dagger_throw_combo', 'dagger_throw_sand', 'dagger_vipers_nest', 'deal', 'deal_idle', 'deal_left', 'deal_right', 'death', 'death2', 'death3', 'death4', 'doctor_work_idle', 'doctor_work_into_look', 'doctor_work_look_idle', 'doctor_work_outof_look', 'drink_potion', 'dualcutlass_combo', 'dualcutlass_draw', 'dualcutlass_idle', 'emote_anger', 'emote_blow_kiss', 'emote_celebrate', 'emote_clap', 'emote_coin_toss', 'emote_crazy', 'emote_cut_throat', 'emote_dance_jig', 'emote_duhhh', 'emote_embarrassed', 'emote_face_smack', 'emote_fear', 'emote_flex', 'emote_flirt', 'emote_hand_it_over', 'emote_head_scratch', 'emote_laugh', 'emote_navy_scared', 'emote_navy_wants_fight', 'emote_nervous', 'emote_newyears', 'emote_no', 'emote_sad', 'emote_sassy', 'emote_scared', 'emote_show_me_the_money', 'emote_shrug', 'emote_sincere_thanks', 'emote_smile', 'emote_snarl', 'emote_talk_to_the_hand', 'emote_thriller', 'emote_wave', 'emote_wink', 'emote_yawn', 'emote_yes', 'fall_ground', 'flute_idle', 'flute_look_idle', 'foil_coup', 'foil_hack', 'foil_idle', 'foil_kick', 'foil_slash', 'foil_thrust', 'friend_pose', 'gun_aim_idle', 'gun_draw', 'gun_fire', 'gun_hurt', 'gun_pointedup_idle', 'gun_putaway', 'gun_reload', 'gun_strafe_left', 'hand_curse_check', 'hand_curse_get_sword', 'hand_curse_reaction', 'idle_B_shiftWeight', 'idle_butt_scratch', 'idle_flex', 'idle_handhip', 'idle_handhip_from_idle', 'idle_head_scratch', 'idle_head_scratch_side', 'idle_hit', 'idle_sit', 'idle_sit_alt', 'idle_yawn', 'injured_fall', 'injured_healing_into', 'injured_healing_loop', 'injured_healing_outof', 'injured_idle', 'injured_idle_shakehead', 'injured_standup', 'into_deal', 'jail_dropinto', 'jail_idle', 'jail_standup', 'jump', 'jump_idle', 'kick_door', 'kick_door_loop', 'kneel', 'kneel_fromidle', 'knife_throw', 'kraken_fight_idle', 'kraken_struggle_idle', 'left_face', 'loom_idle', 'loom_into_look', 'loom_look_idle', 'loom_outof_look', 'lute_idle', 'lute_into_look', 'lute_look_idle', 'lute_outof_look', 'map_head_into_look_left', 'map_head_look_left_idle', 'map_head_outof_look_left', 'map_look_arm_left', 'map_look_arm_right', 'map_look_boot_left', 'map_look_boot_right', 'map_look_pant_right', 'march', 'patient_work_idle', 'primp_idle', 'primp_into_look', 'primp_look_idle', 'primp_outof_look', 'repair_bench', 'repairfloor_idle', 'repairfloor_into', 'repairfloor_outof', 'rifle_fight_forward_diagonal_left', 'rifle_fight_forward_diagonal_right', 'rifle_fight_idle', 'rifle_fight_run_strafe_left', 'rifle_fight_run_strafe_right', 'rifle_fight_shoot_high', 'rifle_fight_shoot_high_idle', 'rifle_fight_shoot_hip', 'rifle_fight_walk', 'rifle_fight_walk_back_diagonal_left', 'rifle_fight_walk_back_diagonal_right', 'rifle_fight_walk_strafe_left', 'rifle_fight_walk_strafe_right', 'rifle_idle_to_fight_idle', 'rifle_reload_hip', 'rigging_climb', 'rigTest', 'rope_board', 'rope_dismount', 'rope_grab', 'rope_grab_from_idle', 'run', 'run_diagonal_left', 'run_diagonal_right', 'run_with_weapon', 'sabre_combo', 'sabre_comboA', 'sabre_comboB', 'sand_in_eyes', 'sand_in_eyes_holdweapon_noswing', 'screenshot_pose', 'search_low', 'search_med', 'semi_conscious_loop', 'semi_conscious_standup', 'shovel', 'shovel_idle', 'shovel_idle_into_dig', 'sit', 'sit_cower_idle', 'sit_cower_into_sleep', 'sit_hanginglegs_idle', 'sit_hanginglegs_into_look', 'sit_hanginglegs_look_idle', 'sit_hanginglegs_outof_look', 'sit_idle', 'sit_sleep_idle', 'sit_sleep_into_cower', 'sit_sleep_into_look', 'sit_sleep_look_idle', 'sit_sleep_outof_look', 'sleep_idle', 'sleep_into_look', 'sleep_outof_look', 'sleep_sick_idle', 'sleep_sick_into_look', 'sleep_sick_look_idle', 'sleep_sick_outof_look', 'sow_idle', 'sow_into_look', 'sow_look_idle', 'sow_outof_look', 'spin_left', 'spin_right', 'stir_idle', 'stir_into_look', 'stir_look_idle', 'stir_outof_look', 'stock_idle', 'stock_sleep', 'stock_sleep_to_idle', 'stowaway_get_in_crate', 'strafe_left', 'strafe_right', 'summon_idle', 'sweep', 'sweep_idle', 'sweep_into_look', 'sweep_look_idle', 'sweep_outof_look', 'swim', 'swim_back', 'swim_back_diagonal_left', 'swim_back_diagonal_right', 'swim_into_tread_water', 'swim_left', 'swim_left_diagonal', 'swim_right', 'swim_right_diagonal', 'swing_aboard', 'sword_cleave', 'sword_comboA', 'sword_draw', 'sword_hit', 'sword_idle', 'sword_lunge', 'sword_putaway', 'sword_roll_thrust', 'sword_slash', 'sword_thrust', 'tatoo_idle', 'tatoo_into_look', 'tatoo_look_idle', 'tatoo_outof_look', 'tatoo_receive_idle', 'tatoo_receive_into_look', 'tatoo_receive_look_idle', 'tatoo_receive_outof_look', 'teleport', 'tentacle_idle', 'tentacle_squeeze', 'tread_water', 'tread_water_into_teleport', 'turn_left', 'turn_right', 'voodoo_doll_hurt', 'voodoo_doll_poke', 'voodoo_draw', 'voodoo_idle', 'voodoo_swarm', 'voodoo_tune', 'voodoo_walk', 'walk', 'walk_back_diagonal_left', 'walk_back_diagonal_right', 'wand_cast_fire', 'wand_cast_idle', 'wand_cast_start', 'wand_hurt', 'wand_idle', 'wheel_idle', 'barf', 'burp', 'fart', 'fsh_idle', 'fsh_smallCast', 'fsh_bigCast', 'fsh_smallSuccess', 'fsh_bigSuccess', 'kneel_dizzy', 'mixing_idle'] SkeletonBodyTypes = [ '1', '2', '4', '8', 'djcr', 'djjm', 'djko', 'djpa', 'djtw', 'sp1', 'sp2', 'sp3', 'sp4', 'fr1', 'fr2', 'fr3', 'fr4'] CastBodyTypes = [ 'js', 'wt', 'es', 'cb', 'td', 'dj', 'jg', 'jr', 'fl', 'sl'] COMPLECTIONTYPES = {0: [[9, 14, 15, 16, 17, 19], [6]], 1: [[4, 10, 11, 12, 13], [1, 6]], 2: [[5, 6, 7, 8], [0, 1, 3, 5, 6]], 3: [[0, 1, 2, 3], [0, 1, 2, 3, 4, 6]]} MALE_BODYTYPE_SELECTIONS = [ 0, 1, 1, 2, 2, 2, 3, 3, 4, 4] FEMALE_BODYTYPE_SELECTIONS = [0, 1, 1, 2, 2, 2, 3, 3, 3, 4] PREFERRED_MALE_HAIR_SELECTIONS = [ 1, 2, 5, 6] PREFERRED_FEMALE_HAIR_SELECTIONS = [] PREFERRED_MALE_BEARD_SELECTIONS = [ 1, 2, 3, 4] MALE_NOSE_RANGES = [ ( -1.0, 1.0), (-1.0, 1.0), (-0.8, 0.5), (-0.5, 0.5), (-1.0, 1.0), (-1.0, 0.7), (-0.7, 0.7), (-0.7, 0.7)] FEMALE_NOSE_RANGES = [ ( -1.0, 1.0), (-0.7, 0.6), (-0.7, 1.0), (-0.3, 0.3), (-0.5, 0.75), (-1.0, 1.0), (-0.5, 0.5), (-0.5, 0.5)]
def bubble_sort(nums: list[float]) -> list[float]: is_sorted = True for loop in range(len(nums) - 1): for indx in range(len(nums) - loop - 1): if nums[indx] > nums[indx + 1]: is_sorted = False nums[indx], nums[indx + 1] = nums[indx + 1], nums[indx] if is_sorted: break return nums algorithm = bubble_sort name = 'optimized'
# # PySNMP MIB module MPLS-LSR-STD-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MPLS-LSR-STD-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:43:25 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ConstraintsIntersection, SingleValueConstraint, ValueSizeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsUnion") AddressFamilyNumbers, = mibBuilder.importSymbols("IANA-ADDRESS-FAMILY-NUMBERS-MIB", "AddressFamilyNumbers") ifCounterDiscontinuityGroup, InterfaceIndexOrZero, ifGeneralInformationGroup = mibBuilder.importSymbols("IF-MIB", "ifCounterDiscontinuityGroup", "InterfaceIndexOrZero", "ifGeneralInformationGroup") InetAddressType, InetAddress = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddressType", "InetAddress") MplsLabel, MplsBitRate, MplsOwner, mplsStdMIB, MplsLSPID = mibBuilder.importSymbols("MPLS-TC-STD-MIB", "MplsLabel", "MplsBitRate", "MplsOwner", "mplsStdMIB", "MplsLSPID") ObjectGroup, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "NotificationGroup", "ModuleCompliance") NotificationType, zeroDotZero, MibIdentifier, iso, Bits, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, Integer32, ModuleIdentity, Unsigned32, Counter64, TimeTicks, IpAddress, Counter32, Gauge32 = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "zeroDotZero", "MibIdentifier", "iso", "Bits", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Integer32", "ModuleIdentity", "Unsigned32", "Counter64", "TimeTicks", "IpAddress", "Counter32", "Gauge32") TextualConvention, RowStatus, StorageType, RowPointer, TruthValue, DisplayString, TimeStamp = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "RowStatus", "StorageType", "RowPointer", "TruthValue", "DisplayString", "TimeStamp") mplsLsrStdMIB = ModuleIdentity((1, 3, 6, 1, 2, 1, 10, 166, 2)) mplsLsrStdMIB.setRevisions(('2004-06-03 00:00',)) if mibBuilder.loadTexts: mplsLsrStdMIB.setLastUpdated('200406030000Z') if mibBuilder.loadTexts: mplsLsrStdMIB.setOrganization('Multiprotocol Label Switching (MPLS) Working Group') class MplsIndexType(TextualConvention, OctetString): status = 'current' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(1, 24) class MplsIndexNextType(TextualConvention, OctetString): status = 'current' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(1, 24) mplsLsrNotifications = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 166, 2, 0)) mplsLsrObjects = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 166, 2, 1)) mplsLsrConformance = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 166, 2, 2)) mplsInterfaceTable = MibTable((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 1), ) if mibBuilder.loadTexts: mplsInterfaceTable.setStatus('current') mplsInterfaceEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 1, 1), ).setIndexNames((0, "MPLS-LSR-STD-MIB", "mplsInterfaceIndex")) if mibBuilder.loadTexts: mplsInterfaceEntry.setStatus('current') mplsInterfaceIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 1, 1, 1), InterfaceIndexOrZero()) if mibBuilder.loadTexts: mplsInterfaceIndex.setStatus('current') mplsInterfaceLabelMinIn = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 1, 1, 2), MplsLabel()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsInterfaceLabelMinIn.setStatus('current') mplsInterfaceLabelMaxIn = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 1, 1, 3), MplsLabel()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsInterfaceLabelMaxIn.setStatus('current') mplsInterfaceLabelMinOut = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 1, 1, 4), MplsLabel()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsInterfaceLabelMinOut.setStatus('current') mplsInterfaceLabelMaxOut = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 1, 1, 5), MplsLabel()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsInterfaceLabelMaxOut.setStatus('current') mplsInterfaceTotalBandwidth = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 1, 1, 6), MplsBitRate()).setUnits('kilobits per second').setMaxAccess("readonly") if mibBuilder.loadTexts: mplsInterfaceTotalBandwidth.setStatus('current') mplsInterfaceAvailableBandwidth = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 1, 1, 7), MplsBitRate()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsInterfaceAvailableBandwidth.setStatus('current') mplsInterfaceLabelParticipationType = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 1, 1, 8), Bits().clone(namedValues=NamedValues(("perPlatform", 0), ("perInterface", 1)))).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsInterfaceLabelParticipationType.setStatus('current') mplsInterfacePerfTable = MibTable((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 2), ) if mibBuilder.loadTexts: mplsInterfacePerfTable.setStatus('current') mplsInterfacePerfEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 2, 1), ) mplsInterfaceEntry.registerAugmentions(("MPLS-LSR-STD-MIB", "mplsInterfacePerfEntry")) mplsInterfacePerfEntry.setIndexNames(*mplsInterfaceEntry.getIndexNames()) if mibBuilder.loadTexts: mplsInterfacePerfEntry.setStatus('current') mplsInterfacePerfInLabelsInUse = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 2, 1, 1), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsInterfacePerfInLabelsInUse.setStatus('current') mplsInterfacePerfInLabelLookupFailures = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 2, 1, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsInterfacePerfInLabelLookupFailures.setStatus('current') mplsInterfacePerfOutLabelsInUse = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 2, 1, 3), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsInterfacePerfOutLabelsInUse.setStatus('current') mplsInterfacePerfOutFragmentedPkts = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 2, 1, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsInterfacePerfOutFragmentedPkts.setStatus('current') mplsInSegmentIndexNext = MibScalar((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 3), MplsIndexNextType()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsInSegmentIndexNext.setStatus('current') mplsInSegmentTable = MibTable((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 4), ) if mibBuilder.loadTexts: mplsInSegmentTable.setStatus('current') mplsInSegmentEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 4, 1), ).setIndexNames((0, "MPLS-LSR-STD-MIB", "mplsInSegmentIndex")) if mibBuilder.loadTexts: mplsInSegmentEntry.setStatus('current') mplsInSegmentIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 4, 1, 1), MplsIndexType()) if mibBuilder.loadTexts: mplsInSegmentIndex.setStatus('current') mplsInSegmentInterface = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 4, 1, 2), InterfaceIndexOrZero()).setMaxAccess("readcreate") if mibBuilder.loadTexts: mplsInSegmentInterface.setStatus('current') mplsInSegmentLabel = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 4, 1, 3), MplsLabel()).setMaxAccess("readcreate") if mibBuilder.loadTexts: mplsInSegmentLabel.setStatus('current') mplsInSegmentLabelPtr = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 4, 1, 4), RowPointer().clone((0, 0))).setMaxAccess("readcreate") if mibBuilder.loadTexts: mplsInSegmentLabelPtr.setStatus('current') mplsInSegmentNPop = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 4, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647)).clone(1)).setMaxAccess("readcreate") if mibBuilder.loadTexts: mplsInSegmentNPop.setStatus('current') mplsInSegmentAddrFamily = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 4, 1, 6), AddressFamilyNumbers().clone('other')).setMaxAccess("readcreate") if mibBuilder.loadTexts: mplsInSegmentAddrFamily.setStatus('current') mplsInSegmentXCIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 4, 1, 7), MplsIndexType()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsInSegmentXCIndex.setStatus('current') mplsInSegmentOwner = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 4, 1, 8), MplsOwner()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsInSegmentOwner.setStatus('current') mplsInSegmentTrafficParamPtr = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 4, 1, 9), RowPointer().clone((0, 0))).setMaxAccess("readcreate") if mibBuilder.loadTexts: mplsInSegmentTrafficParamPtr.setStatus('current') mplsInSegmentRowStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 4, 1, 10), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: mplsInSegmentRowStatus.setStatus('current') mplsInSegmentStorageType = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 4, 1, 11), StorageType().clone('volatile')).setMaxAccess("readcreate") if mibBuilder.loadTexts: mplsInSegmentStorageType.setStatus('current') mplsInSegmentPerfTable = MibTable((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 5), ) if mibBuilder.loadTexts: mplsInSegmentPerfTable.setStatus('current') mplsInSegmentPerfEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 5, 1), ) mplsInSegmentEntry.registerAugmentions(("MPLS-LSR-STD-MIB", "mplsInSegmentPerfEntry")) mplsInSegmentPerfEntry.setIndexNames(*mplsInSegmentEntry.getIndexNames()) if mibBuilder.loadTexts: mplsInSegmentPerfEntry.setStatus('current') mplsInSegmentPerfOctets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 5, 1, 1), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsInSegmentPerfOctets.setStatus('current') mplsInSegmentPerfPackets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 5, 1, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsInSegmentPerfPackets.setStatus('current') mplsInSegmentPerfErrors = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 5, 1, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsInSegmentPerfErrors.setStatus('current') mplsInSegmentPerfDiscards = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 5, 1, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsInSegmentPerfDiscards.setStatus('current') mplsInSegmentPerfHCOctets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 5, 1, 5), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsInSegmentPerfHCOctets.setStatus('current') mplsInSegmentPerfDiscontinuityTime = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 5, 1, 6), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsInSegmentPerfDiscontinuityTime.setStatus('current') mplsOutSegmentIndexNext = MibScalar((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 6), MplsIndexNextType()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsOutSegmentIndexNext.setStatus('current') mplsOutSegmentTable = MibTable((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 7), ) if mibBuilder.loadTexts: mplsOutSegmentTable.setStatus('current') mplsOutSegmentEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 7, 1), ).setIndexNames((0, "MPLS-LSR-STD-MIB", "mplsOutSegmentIndex")) if mibBuilder.loadTexts: mplsOutSegmentEntry.setStatus('current') mplsOutSegmentIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 7, 1, 1), MplsIndexType()) if mibBuilder.loadTexts: mplsOutSegmentIndex.setStatus('current') mplsOutSegmentInterface = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 7, 1, 2), InterfaceIndexOrZero()).setMaxAccess("readcreate") if mibBuilder.loadTexts: mplsOutSegmentInterface.setStatus('current') mplsOutSegmentPushTopLabel = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 7, 1, 3), TruthValue().clone('true')).setMaxAccess("readcreate") if mibBuilder.loadTexts: mplsOutSegmentPushTopLabel.setStatus('current') mplsOutSegmentTopLabel = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 7, 1, 4), MplsLabel()).setMaxAccess("readcreate") if mibBuilder.loadTexts: mplsOutSegmentTopLabel.setStatus('current') mplsOutSegmentTopLabelPtr = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 7, 1, 5), RowPointer().clone((0, 0))).setMaxAccess("readcreate") if mibBuilder.loadTexts: mplsOutSegmentTopLabelPtr.setStatus('current') mplsOutSegmentNextHopAddrType = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 7, 1, 6), InetAddressType()).setMaxAccess("readcreate") if mibBuilder.loadTexts: mplsOutSegmentNextHopAddrType.setStatus('current') mplsOutSegmentNextHopAddr = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 7, 1, 7), InetAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: mplsOutSegmentNextHopAddr.setStatus('current') mplsOutSegmentXCIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 7, 1, 8), MplsIndexType()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsOutSegmentXCIndex.setStatus('current') mplsOutSegmentOwner = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 7, 1, 9), MplsOwner()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsOutSegmentOwner.setStatus('current') mplsOutSegmentTrafficParamPtr = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 7, 1, 10), RowPointer().clone((0, 0))).setMaxAccess("readcreate") if mibBuilder.loadTexts: mplsOutSegmentTrafficParamPtr.setStatus('current') mplsOutSegmentRowStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 7, 1, 11), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: mplsOutSegmentRowStatus.setStatus('current') mplsOutSegmentStorageType = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 7, 1, 12), StorageType().clone('volatile')).setMaxAccess("readcreate") if mibBuilder.loadTexts: mplsOutSegmentStorageType.setStatus('current') mplsOutSegmentPerfTable = MibTable((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 8), ) if mibBuilder.loadTexts: mplsOutSegmentPerfTable.setStatus('current') mplsOutSegmentPerfEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 8, 1), ) mplsOutSegmentEntry.registerAugmentions(("MPLS-LSR-STD-MIB", "mplsOutSegmentPerfEntry")) mplsOutSegmentPerfEntry.setIndexNames(*mplsOutSegmentEntry.getIndexNames()) if mibBuilder.loadTexts: mplsOutSegmentPerfEntry.setStatus('current') mplsOutSegmentPerfOctets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 8, 1, 1), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsOutSegmentPerfOctets.setStatus('current') mplsOutSegmentPerfPackets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 8, 1, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsOutSegmentPerfPackets.setStatus('current') mplsOutSegmentPerfErrors = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 8, 1, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsOutSegmentPerfErrors.setStatus('current') mplsOutSegmentPerfDiscards = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 8, 1, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsOutSegmentPerfDiscards.setStatus('current') mplsOutSegmentPerfHCOctets = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 8, 1, 5), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsOutSegmentPerfHCOctets.setStatus('current') mplsOutSegmentPerfDiscontinuityTime = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 8, 1, 6), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsOutSegmentPerfDiscontinuityTime.setStatus('current') mplsXCIndexNext = MibScalar((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 9), MplsIndexNextType()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsXCIndexNext.setStatus('current') mplsXCTable = MibTable((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 10), ) if mibBuilder.loadTexts: mplsXCTable.setStatus('current') mplsXCEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 10, 1), ).setIndexNames((0, "MPLS-LSR-STD-MIB", "mplsXCIndex"), (0, "MPLS-LSR-STD-MIB", "mplsXCInSegmentIndex"), (0, "MPLS-LSR-STD-MIB", "mplsXCOutSegmentIndex")) if mibBuilder.loadTexts: mplsXCEntry.setStatus('current') mplsXCIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 10, 1, 1), MplsIndexType()) if mibBuilder.loadTexts: mplsXCIndex.setStatus('current') mplsXCInSegmentIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 10, 1, 2), MplsIndexType()) if mibBuilder.loadTexts: mplsXCInSegmentIndex.setStatus('current') mplsXCOutSegmentIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 10, 1, 3), MplsIndexType()) if mibBuilder.loadTexts: mplsXCOutSegmentIndex.setStatus('current') mplsXCLspId = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 10, 1, 4), MplsLSPID()).setMaxAccess("readcreate") if mibBuilder.loadTexts: mplsXCLspId.setStatus('current') mplsXCLabelStackIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 10, 1, 5), MplsIndexType()).setMaxAccess("readcreate") if mibBuilder.loadTexts: mplsXCLabelStackIndex.setStatus('current') mplsXCOwner = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 10, 1, 6), MplsOwner()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsXCOwner.setStatus('current') mplsXCRowStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 10, 1, 7), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: mplsXCRowStatus.setStatus('current') mplsXCStorageType = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 10, 1, 8), StorageType().clone('volatile')).setMaxAccess("readcreate") if mibBuilder.loadTexts: mplsXCStorageType.setStatus('current') mplsXCAdminStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 10, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("up", 1), ("down", 2), ("testing", 3))).clone('up')).setMaxAccess("readcreate") if mibBuilder.loadTexts: mplsXCAdminStatus.setStatus('current') mplsXCOperStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 10, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("up", 1), ("down", 2), ("testing", 3), ("unknown", 4), ("dormant", 5), ("notPresent", 6), ("lowerLayerDown", 7)))).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsXCOperStatus.setStatus('current') mplsMaxLabelStackDepth = MibScalar((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 11), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsMaxLabelStackDepth.setStatus('current') mplsLabelStackIndexNext = MibScalar((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 12), MplsIndexNextType()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsLabelStackIndexNext.setStatus('current') mplsLabelStackTable = MibTable((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 13), ) if mibBuilder.loadTexts: mplsLabelStackTable.setStatus('current') mplsLabelStackEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 13, 1), ).setIndexNames((0, "MPLS-LSR-STD-MIB", "mplsLabelStackIndex"), (0, "MPLS-LSR-STD-MIB", "mplsLabelStackLabelIndex")) if mibBuilder.loadTexts: mplsLabelStackEntry.setStatus('current') mplsLabelStackIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 13, 1, 1), MplsIndexType()) if mibBuilder.loadTexts: mplsLabelStackIndex.setStatus('current') mplsLabelStackLabelIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 13, 1, 2), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))) if mibBuilder.loadTexts: mplsLabelStackLabelIndex.setStatus('current') mplsLabelStackLabel = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 13, 1, 3), MplsLabel()).setMaxAccess("readcreate") if mibBuilder.loadTexts: mplsLabelStackLabel.setStatus('current') mplsLabelStackLabelPtr = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 13, 1, 4), RowPointer().clone((0, 0))).setMaxAccess("readcreate") if mibBuilder.loadTexts: mplsLabelStackLabelPtr.setStatus('current') mplsLabelStackRowStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 13, 1, 5), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: mplsLabelStackRowStatus.setStatus('current') mplsLabelStackStorageType = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 13, 1, 6), StorageType().clone('volatile')).setMaxAccess("readcreate") if mibBuilder.loadTexts: mplsLabelStackStorageType.setStatus('current') mplsInSegmentMapTable = MibTable((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 14), ) if mibBuilder.loadTexts: mplsInSegmentMapTable.setStatus('current') mplsInSegmentMapEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 14, 1), ).setIndexNames((0, "MPLS-LSR-STD-MIB", "mplsInSegmentMapInterface"), (0, "MPLS-LSR-STD-MIB", "mplsInSegmentMapLabel"), (0, "MPLS-LSR-STD-MIB", "mplsInSegmentMapLabelPtrIndex")) if mibBuilder.loadTexts: mplsInSegmentMapEntry.setStatus('current') mplsInSegmentMapInterface = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 14, 1, 1), InterfaceIndexOrZero()) if mibBuilder.loadTexts: mplsInSegmentMapInterface.setStatus('current') mplsInSegmentMapLabel = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 14, 1, 2), MplsLabel()) if mibBuilder.loadTexts: mplsInSegmentMapLabel.setStatus('current') mplsInSegmentMapLabelPtrIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 14, 1, 3), RowPointer()) if mibBuilder.loadTexts: mplsInSegmentMapLabelPtrIndex.setStatus('current') mplsInSegmentMapIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 14, 1, 4), MplsIndexType()).setMaxAccess("readonly") if mibBuilder.loadTexts: mplsInSegmentMapIndex.setStatus('current') mplsXCNotificationsEnable = MibScalar((1, 3, 6, 1, 2, 1, 10, 166, 2, 1, 15), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: mplsXCNotificationsEnable.setStatus('current') mplsXCUp = NotificationType((1, 3, 6, 1, 2, 1, 10, 166, 2, 0, 1)).setObjects(("MPLS-LSR-STD-MIB", "mplsXCOperStatus"), ("MPLS-LSR-STD-MIB", "mplsXCOperStatus")) if mibBuilder.loadTexts: mplsXCUp.setStatus('current') mplsXCDown = NotificationType((1, 3, 6, 1, 2, 1, 10, 166, 2, 0, 2)).setObjects(("MPLS-LSR-STD-MIB", "mplsXCOperStatus"), ("MPLS-LSR-STD-MIB", "mplsXCOperStatus")) if mibBuilder.loadTexts: mplsXCDown.setStatus('current') mplsLsrGroups = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 166, 2, 2, 1)) mplsLsrCompliances = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 166, 2, 2, 2)) mplsLsrModuleFullCompliance = ModuleCompliance((1, 3, 6, 1, 2, 1, 10, 166, 2, 2, 2, 1)).setObjects(("IF-MIB", "ifGeneralInformationGroup"), ("IF-MIB", "ifCounterDiscontinuityGroup"), ("MPLS-LSR-STD-MIB", "mplsInterfaceGroup"), ("MPLS-LSR-STD-MIB", "mplsInSegmentGroup"), ("MPLS-LSR-STD-MIB", "mplsOutSegmentGroup"), ("MPLS-LSR-STD-MIB", "mplsXCGroup"), ("MPLS-LSR-STD-MIB", "mplsPerfGroup"), ("MPLS-LSR-STD-MIB", "mplsLabelStackGroup"), ("MPLS-LSR-STD-MIB", "mplsHCInSegmentPerfGroup"), ("MPLS-LSR-STD-MIB", "mplsHCOutSegmentPerfGroup"), ("MPLS-LSR-STD-MIB", "mplsLsrNotificationGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): mplsLsrModuleFullCompliance = mplsLsrModuleFullCompliance.setStatus('current') mplsLsrModuleReadOnlyCompliance = ModuleCompliance((1, 3, 6, 1, 2, 1, 10, 166, 2, 2, 2, 2)).setObjects(("IF-MIB", "ifGeneralInformationGroup"), ("IF-MIB", "ifCounterDiscontinuityGroup"), ("MPLS-LSR-STD-MIB", "mplsInterfaceGroup"), ("MPLS-LSR-STD-MIB", "mplsInSegmentGroup"), ("MPLS-LSR-STD-MIB", "mplsOutSegmentGroup"), ("MPLS-LSR-STD-MIB", "mplsXCGroup"), ("MPLS-LSR-STD-MIB", "mplsPerfGroup"), ("MPLS-LSR-STD-MIB", "mplsLabelStackGroup"), ("MPLS-LSR-STD-MIB", "mplsHCInSegmentPerfGroup"), ("MPLS-LSR-STD-MIB", "mplsHCOutSegmentPerfGroup"), ("MPLS-LSR-STD-MIB", "mplsLsrNotificationGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): mplsLsrModuleReadOnlyCompliance = mplsLsrModuleReadOnlyCompliance.setStatus('current') mplsInterfaceGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 10, 166, 2, 2, 1, 1)).setObjects(("MPLS-LSR-STD-MIB", "mplsInterfaceLabelMinIn"), ("MPLS-LSR-STD-MIB", "mplsInterfaceLabelMaxIn"), ("MPLS-LSR-STD-MIB", "mplsInterfaceLabelMinOut"), ("MPLS-LSR-STD-MIB", "mplsInterfaceLabelMaxOut"), ("MPLS-LSR-STD-MIB", "mplsInterfaceTotalBandwidth"), ("MPLS-LSR-STD-MIB", "mplsInterfaceAvailableBandwidth"), ("MPLS-LSR-STD-MIB", "mplsInterfaceLabelParticipationType")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): mplsInterfaceGroup = mplsInterfaceGroup.setStatus('current') mplsInSegmentGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 10, 166, 2, 2, 1, 2)).setObjects(("MPLS-LSR-STD-MIB", "mplsInSegmentIndexNext"), ("MPLS-LSR-STD-MIB", "mplsInSegmentInterface"), ("MPLS-LSR-STD-MIB", "mplsInSegmentLabel"), ("MPLS-LSR-STD-MIB", "mplsInSegmentLabelPtr"), ("MPLS-LSR-STD-MIB", "mplsInSegmentNPop"), ("MPLS-LSR-STD-MIB", "mplsInSegmentAddrFamily"), ("MPLS-LSR-STD-MIB", "mplsInSegmentXCIndex"), ("MPLS-LSR-STD-MIB", "mplsInSegmentOwner"), ("MPLS-LSR-STD-MIB", "mplsInSegmentRowStatus"), ("MPLS-LSR-STD-MIB", "mplsInSegmentStorageType"), ("MPLS-LSR-STD-MIB", "mplsInSegmentTrafficParamPtr"), ("MPLS-LSR-STD-MIB", "mplsInSegmentMapIndex")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): mplsInSegmentGroup = mplsInSegmentGroup.setStatus('current') mplsOutSegmentGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 10, 166, 2, 2, 1, 3)).setObjects(("MPLS-LSR-STD-MIB", "mplsOutSegmentIndexNext"), ("MPLS-LSR-STD-MIB", "mplsOutSegmentInterface"), ("MPLS-LSR-STD-MIB", "mplsOutSegmentPushTopLabel"), ("MPLS-LSR-STD-MIB", "mplsOutSegmentTopLabel"), ("MPLS-LSR-STD-MIB", "mplsOutSegmentTopLabelPtr"), ("MPLS-LSR-STD-MIB", "mplsOutSegmentNextHopAddrType"), ("MPLS-LSR-STD-MIB", "mplsOutSegmentNextHopAddr"), ("MPLS-LSR-STD-MIB", "mplsOutSegmentXCIndex"), ("MPLS-LSR-STD-MIB", "mplsOutSegmentOwner"), ("MPLS-LSR-STD-MIB", "mplsOutSegmentPerfOctets"), ("MPLS-LSR-STD-MIB", "mplsOutSegmentPerfDiscards"), ("MPLS-LSR-STD-MIB", "mplsOutSegmentPerfErrors"), ("MPLS-LSR-STD-MIB", "mplsOutSegmentRowStatus"), ("MPLS-LSR-STD-MIB", "mplsOutSegmentStorageType"), ("MPLS-LSR-STD-MIB", "mplsOutSegmentTrafficParamPtr")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): mplsOutSegmentGroup = mplsOutSegmentGroup.setStatus('current') mplsXCGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 10, 166, 2, 2, 1, 4)).setObjects(("MPLS-LSR-STD-MIB", "mplsXCIndexNext"), ("MPLS-LSR-STD-MIB", "mplsXCLspId"), ("MPLS-LSR-STD-MIB", "mplsXCLabelStackIndex"), ("MPLS-LSR-STD-MIB", "mplsXCOwner"), ("MPLS-LSR-STD-MIB", "mplsXCStorageType"), ("MPLS-LSR-STD-MIB", "mplsXCAdminStatus"), ("MPLS-LSR-STD-MIB", "mplsXCOperStatus"), ("MPLS-LSR-STD-MIB", "mplsXCRowStatus"), ("MPLS-LSR-STD-MIB", "mplsXCNotificationsEnable")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): mplsXCGroup = mplsXCGroup.setStatus('current') mplsPerfGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 10, 166, 2, 2, 1, 5)).setObjects(("MPLS-LSR-STD-MIB", "mplsInSegmentPerfOctets"), ("MPLS-LSR-STD-MIB", "mplsInSegmentPerfPackets"), ("MPLS-LSR-STD-MIB", "mplsInSegmentPerfErrors"), ("MPLS-LSR-STD-MIB", "mplsInSegmentPerfDiscards"), ("MPLS-LSR-STD-MIB", "mplsInSegmentPerfDiscontinuityTime"), ("MPLS-LSR-STD-MIB", "mplsOutSegmentPerfOctets"), ("MPLS-LSR-STD-MIB", "mplsOutSegmentPerfPackets"), ("MPLS-LSR-STD-MIB", "mplsOutSegmentPerfDiscards"), ("MPLS-LSR-STD-MIB", "mplsOutSegmentPerfDiscontinuityTime"), ("MPLS-LSR-STD-MIB", "mplsInterfacePerfInLabelsInUse"), ("MPLS-LSR-STD-MIB", "mplsInterfacePerfInLabelLookupFailures"), ("MPLS-LSR-STD-MIB", "mplsInterfacePerfOutFragmentedPkts"), ("MPLS-LSR-STD-MIB", "mplsInterfacePerfOutLabelsInUse")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): mplsPerfGroup = mplsPerfGroup.setStatus('current') mplsHCInSegmentPerfGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 10, 166, 2, 2, 1, 6)).setObjects(("MPLS-LSR-STD-MIB", "mplsInSegmentPerfHCOctets")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): mplsHCInSegmentPerfGroup = mplsHCInSegmentPerfGroup.setStatus('current') mplsHCOutSegmentPerfGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 10, 166, 2, 2, 1, 7)).setObjects(("MPLS-LSR-STD-MIB", "mplsOutSegmentPerfHCOctets")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): mplsHCOutSegmentPerfGroup = mplsHCOutSegmentPerfGroup.setStatus('current') mplsLabelStackGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 10, 166, 2, 2, 1, 8)).setObjects(("MPLS-LSR-STD-MIB", "mplsLabelStackLabel"), ("MPLS-LSR-STD-MIB", "mplsLabelStackLabelPtr"), ("MPLS-LSR-STD-MIB", "mplsLabelStackRowStatus"), ("MPLS-LSR-STD-MIB", "mplsLabelStackStorageType"), ("MPLS-LSR-STD-MIB", "mplsMaxLabelStackDepth"), ("MPLS-LSR-STD-MIB", "mplsLabelStackIndexNext")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): mplsLabelStackGroup = mplsLabelStackGroup.setStatus('current') mplsLsrNotificationGroup = NotificationGroup((1, 3, 6, 1, 2, 1, 10, 166, 2, 2, 1, 9)).setObjects(("MPLS-LSR-STD-MIB", "mplsXCUp"), ("MPLS-LSR-STD-MIB", "mplsXCDown")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): mplsLsrNotificationGroup = mplsLsrNotificationGroup.setStatus('current') mibBuilder.exportSymbols("MPLS-LSR-STD-MIB", mplsInterfaceAvailableBandwidth=mplsInterfaceAvailableBandwidth, mplsLabelStackGroup=mplsLabelStackGroup, mplsInterfaceLabelMaxOut=mplsInterfaceLabelMaxOut, mplsXCTable=mplsXCTable, mplsInSegmentPerfDiscards=mplsInSegmentPerfDiscards, mplsLsrGroups=mplsLsrGroups, mplsXCEntry=mplsXCEntry, mplsInterfaceTotalBandwidth=mplsInterfaceTotalBandwidth, mplsLsrConformance=mplsLsrConformance, mplsOutSegmentPerfHCOctets=mplsOutSegmentPerfHCOctets, mplsInSegmentMapIndex=mplsInSegmentMapIndex, mplsInterfaceEntry=mplsInterfaceEntry, mplsOutSegmentOwner=mplsOutSegmentOwner, mplsLsrStdMIB=mplsLsrStdMIB, mplsXCLspId=mplsXCLspId, mplsLabelStackRowStatus=mplsLabelStackRowStatus, mplsInSegmentPerfPackets=mplsInSegmentPerfPackets, mplsInterfacePerfOutFragmentedPkts=mplsInterfacePerfOutFragmentedPkts, mplsLsrNotifications=mplsLsrNotifications, mplsOutSegmentTrafficParamPtr=mplsOutSegmentTrafficParamPtr, mplsXCDown=mplsXCDown, mplsInSegmentEntry=mplsInSegmentEntry, mplsOutSegmentStorageType=mplsOutSegmentStorageType, mplsInterfacePerfInLabelLookupFailures=mplsInterfacePerfInLabelLookupFailures, mplsInSegmentPerfErrors=mplsInSegmentPerfErrors, mplsLsrObjects=mplsLsrObjects, mplsInSegmentXCIndex=mplsInSegmentXCIndex, mplsInSegmentMapLabel=mplsInSegmentMapLabel, mplsInterfaceGroup=mplsInterfaceGroup, mplsXCIndex=mplsXCIndex, mplsInSegmentIndexNext=mplsInSegmentIndexNext, mplsInSegmentMapEntry=mplsInSegmentMapEntry, mplsOutSegmentPerfErrors=mplsOutSegmentPerfErrors, mplsLabelStackIndex=mplsLabelStackIndex, mplsLsrModuleReadOnlyCompliance=mplsLsrModuleReadOnlyCompliance, mplsInSegmentStorageType=mplsInSegmentStorageType, mplsLabelStackLabelPtr=mplsLabelStackLabelPtr, mplsLabelStackTable=mplsLabelStackTable, mplsInSegmentTrafficParamPtr=mplsInSegmentTrafficParamPtr, mplsPerfGroup=mplsPerfGroup, mplsHCInSegmentPerfGroup=mplsHCInSegmentPerfGroup, mplsInterfacePerfTable=mplsInterfacePerfTable, mplsOutSegmentNextHopAddrType=mplsOutSegmentNextHopAddrType, mplsXCIndexNext=mplsXCIndexNext, mplsXCOwner=mplsXCOwner, mplsInterfacePerfOutLabelsInUse=mplsInterfacePerfOutLabelsInUse, mplsOutSegmentPerfTable=mplsOutSegmentPerfTable, mplsInterfaceLabelMinIn=mplsInterfaceLabelMinIn, mplsOutSegmentGroup=mplsOutSegmentGroup, mplsOutSegmentTopLabelPtr=mplsOutSegmentTopLabelPtr, mplsInSegmentMapTable=mplsInSegmentMapTable, mplsInSegmentIndex=mplsInSegmentIndex, mplsXCOutSegmentIndex=mplsXCOutSegmentIndex, mplsInSegmentPerfTable=mplsInSegmentPerfTable, mplsInSegmentLabel=mplsInSegmentLabel, mplsOutSegmentPerfDiscontinuityTime=mplsOutSegmentPerfDiscontinuityTime, mplsXCGroup=mplsXCGroup, mplsOutSegmentIndex=mplsOutSegmentIndex, mplsLabelStackLabelIndex=mplsLabelStackLabelIndex, mplsInterfaceTable=mplsInterfaceTable, mplsOutSegmentPerfEntry=mplsOutSegmentPerfEntry, MplsIndexType=MplsIndexType, mplsXCInSegmentIndex=mplsXCInSegmentIndex, mplsOutSegmentEntry=mplsOutSegmentEntry, mplsInterfacePerfEntry=mplsInterfacePerfEntry, mplsXCStorageType=mplsXCStorageType, mplsLabelStackLabel=mplsLabelStackLabel, mplsOutSegmentPerfDiscards=mplsOutSegmentPerfDiscards, mplsInSegmentPerfDiscontinuityTime=mplsInSegmentPerfDiscontinuityTime, mplsXCAdminStatus=mplsXCAdminStatus, mplsInterfaceLabelMinOut=mplsInterfaceLabelMinOut, mplsLabelStackStorageType=mplsLabelStackStorageType, mplsInterfacePerfInLabelsInUse=mplsInterfacePerfInLabelsInUse, mplsXCRowStatus=mplsXCRowStatus, mplsOutSegmentIndexNext=mplsOutSegmentIndexNext, mplsOutSegmentTable=mplsOutSegmentTable, mplsLsrNotificationGroup=mplsLsrNotificationGroup, mplsOutSegmentPerfOctets=mplsOutSegmentPerfOctets, mplsLabelStackEntry=mplsLabelStackEntry, mplsMaxLabelStackDepth=mplsMaxLabelStackDepth, mplsInSegmentAddrFamily=mplsInSegmentAddrFamily, mplsInSegmentInterface=mplsInSegmentInterface, mplsInterfaceLabelMaxIn=mplsInterfaceLabelMaxIn, mplsInterfaceIndex=mplsInterfaceIndex, mplsInSegmentPerfHCOctets=mplsInSegmentPerfHCOctets, mplsXCOperStatus=mplsXCOperStatus, mplsOutSegmentNextHopAddr=mplsOutSegmentNextHopAddr, mplsLsrCompliances=mplsLsrCompliances, mplsInSegmentTable=mplsInSegmentTable, mplsOutSegmentRowStatus=mplsOutSegmentRowStatus, mplsXCUp=mplsXCUp, mplsInSegmentLabelPtr=mplsInSegmentLabelPtr, mplsXCNotificationsEnable=mplsXCNotificationsEnable, mplsInSegmentMapInterface=mplsInSegmentMapInterface, mplsOutSegmentTopLabel=mplsOutSegmentTopLabel, MplsIndexNextType=MplsIndexNextType, mplsInterfaceLabelParticipationType=mplsInterfaceLabelParticipationType, mplsInSegmentMapLabelPtrIndex=mplsInSegmentMapLabelPtrIndex, mplsInSegmentRowStatus=mplsInSegmentRowStatus, mplsInSegmentOwner=mplsInSegmentOwner, mplsInSegmentNPop=mplsInSegmentNPop, mplsInSegmentPerfEntry=mplsInSegmentPerfEntry, mplsHCOutSegmentPerfGroup=mplsHCOutSegmentPerfGroup, mplsLabelStackIndexNext=mplsLabelStackIndexNext, mplsOutSegmentPerfPackets=mplsOutSegmentPerfPackets, mplsInSegmentGroup=mplsInSegmentGroup, mplsInSegmentPerfOctets=mplsInSegmentPerfOctets, mplsOutSegmentPushTopLabel=mplsOutSegmentPushTopLabel, PYSNMP_MODULE_ID=mplsLsrStdMIB, mplsOutSegmentXCIndex=mplsOutSegmentXCIndex, mplsOutSegmentInterface=mplsOutSegmentInterface, mplsLsrModuleFullCompliance=mplsLsrModuleFullCompliance, mplsXCLabelStackIndex=mplsXCLabelStackIndex)
n = int(input('How many sides the convex polygon have: ')) nd = (n * (n - 3)) / 2 print(f'The convex polygon have {nd} sides.')
""" PSEUDO CODE: function mergesort(m) var list left, right if length(m) ≤ 1 return m else middle = length(m) / 2 for each x in m up to middle add x to left for each x in m after middle add x to right left = mergesort(left) right = mergesort(right) result = merge(left, right) return result """ def mergeSort(alist): print("Splitting: ",alist) if len(alist)>1: mid = len(alist)//2 lefthalf = alist[:mid] righthalf = alist[mid:] mergeSort(lefthalf) mergeSort(righthalf) i=0 j=0 k=0 while i<len(lefthalf) and j<len(righthalf): if lefthalf[i]<righthalf[j]: alist[k]=lefthalf[i] i=i+1 else: alist[k]=righthalf[j] j=j+1 k=k+1 while i<len(lefthalf): alist[k]=lefthalf[i] i=i+1 k=k+1 while j<len(righthalf): alist[k]=righthalf[j] j=j+1 k=k+1 print("Merging ",alist) alist = [54,26,93,17,77,31,44,55,20] mergeSort(alist) print(alist)
# Minimal django settings to run tests DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = () MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': './sqlite3.db', } } SECRET_KEY = 'alksjdf93jqpijsdaklfjq;3lejqklejlakefjas' TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) MIDDLEWARE_CLASSES = ( 'django_seo_js.middleware.HashBangMiddleware', 'django_seo_js.middleware.UserAgentMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) INSTALLED_APPS += ('django_seo_js',) CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'django_seo_js' } } SEO_JS_PRERENDER_TOKEN = "123456789"
#!/usr/bin/env python TOOL = "tool" PRECISION = "precision" RECALL = "recall" AVG_PRECISION = "avg_precision" STD_DEV_PRECISION = "std_dev_precision" SEM_PRECISION = "sem_precision" AVG_RECALL = "avg_recall" STD_DEV_RECALL = "std_dev_recall" SEM_RECALL = "sem_recall" RI_BY_BP = "rand_index_by_bp" RI_BY_SEQ = "rand_index_by_seq" ARI_BY_BP = "a_rand_index_by_bp" ARI_BY_SEQ = "a_rand_index_by_seq" PERCENTAGE_ASSIGNED_BPS = "percent_assigned_bps" abbreviations = {'avg_precision': 'precision averaged over genome bins', 'std_dev_precision': 'standard deviation of precision averaged over genome bins', 'sem_precision': 'standard error of the mean of precision averaged over genome bins', 'avg_recall': 'recall averaged over genome bins', 'std_dev_recall': 'standard deviation of recall averaged over genome bins', 'sem_recall': 'standard error of the mean of recall averaged over genome bins', 'precision': 'precision weighed by base pairs', 'recall': 'recall weighed by base pairs', 'rand_index_by_bp': 'Rand index weighed by base pairs', 'rand_index_by_seq': 'Rand index weighed by sequence counts', 'a_rand_index_by_bp': 'adjusted Rand index weighed by base pairs', 'a_rand_index_by_seq': 'adjusted Rand index weighed by sequence counts', 'percent_assigned_bps': 'percentage of base pairs that were assigned to bins', '>0.5compl<0.1cont': 'number of genomes with more than 50% completeness and less than 10% contamination', '>0.7compl<0.1cont': 'number of genomes with more than 70% completeness and less than 10% contamination', '>0.9compl<0.1cont': 'number of genomes with more than 90% completeness and less than 10% contamination', '>0.5compl<0.05cont': 'number of genomes with more than 50% completeness and less than 5% contamination', '>0.7compl<0.05cont': 'number of genomes with more than 70% completeness and less than 5% contamination', '>0.9compl<0.05cont': 'number of genomes with more than 90% completeness and less than 5% contamination'}
# parameters used in experiment # ============================================================================== # optitrack communication ip (win10 is the server, the ubuntu receiving data is client) # ============================================================================== ip_win10 = '192.168.1.5' ip_ubuntu_pc = '192.168.1.3' # ============================================================================== # Local lidar ports # ============================================================================== LIDAR_PORT1 = '/dev/ttyUSB0' LIDAR_PORT2 = '/dev/ttyUSB1' LIDAR_PORT3 = '/dev/ttyUSB2' LIDAR_PORT4 = '/dev/ttyUSB3' LIDAR_PORTs = [LIDAR_PORT1, LIDAR_PORT2, LIDAR_PORT3] # ============================================================================== # Parameters used in calibration # ============================================================================== # [t1, t2], rmax: car is in the lidar field of view [t1,t2] within range of rmax # where the lidar measurements is in [0, 360 deg] CarToLidar1FoV = dict(FoVs=[[0,40], [320, 360]], rmax=1400) CarToLidar2FoV = dict(FoVs=[[0,40], [320, 360]], rmax=1400) CarToLidar3FoV = dict(FoVs=[[0,40], [320, 360]], rmax=1400) CarToLidarFoVs = [CarToLidar1FoV, CarToLidar2FoV, CarToLidar3FoV] DistanceThreshold = [[0.2, 0.22], [0.11,0.14], [0.0, 0.06]] #range of l2 error between lidar and optitrack estimation in [meter] HardErrBound = [0.1, 10] # hard max error bound
Vocales = ("a","e","i","o","u", " ") texto = input("Ingresar el texto: ") texto_nuevo = 0 for letters in texto: if letters not in Vocales: texto_nuevo = texto_nuevo + 1 print("El numero de consonantes es: ", texto_nuevo)
FILE_PATH = "data/cows.mp4" MODEL_PATH = "model/mobilenet_v2_ssd_coco_frozen_graph.pb" CONFIG_PATH = "model/mobilenet_v2_ssd_coco_config.pbtxt" LABEL_PATH = "model/coco_class_labels.txt" WINDOW_NAME = "detection" MIN_CONF = 0.4 MAX_IOU = 0.5
''' data structures that used executive architecture ''' class Command(object): def __init__(self, Name, Payload): self.Name = Name self.Payload = Payload class Gesture(object): def __init__(self, ID, NAME, LastTimeSync, IterableGesture, NumberOfGestureRepetitions, NumberOfMotions, ListActions): self.ID = ID self.NAME = NAME self.LastTimeSync = LastTimeSync self.IterableGesture = IterableGesture self.NumberOfGestureRepetitions = NumberOfGestureRepetitions self.NumberOfMotions = NumberOfMotions self.ListActions = ListActions class GestureAction(object): def __init__(self, PointerFingerPosition, MiddleFingerPosition, RingFinderPosition, LittleFingerPosition, ThumbFingerPosition, Delay): self.PointerFingerPosition = PointerFingerPosition self.MiddleFingerPosition = MiddleFingerPosition self.RingFinderPosition = RingFinderPosition self.LittleFingerPosition = LittleFingerPosition self.ThumbFingerPosition = ThumbFingerPosition self.Delay = Delay
#!/usr/bin/env python # -*- coding: utf-8 -*- # author: Olivier Noguès DSC = { } class JsBillboard(object): """ :category: RecordSet to Billboard Object :rubric: JS :type: Data Transformation :dsc: Function to convert an AReS recordSet to a valid object for Billboard. """ alias = "Billboard" params = ("seriesNames", "xAxis") value = ''' var temp = {}; var labels = []; var uniqLabels = {}; seriesNames.forEach(function(series){temp[series] = {}}) ; data.forEach(function(rec) { seriesNames.forEach(function(name){ if(rec[name] !== undefined) { if (!(rec[xAxis] in uniqLabels)){labels.push(rec[xAxis]); uniqLabels[rec[xAxis]] = true}; temp[name][rec[xAxis]] = rec[name]}}) }); result = []; result.push(['x'].concat(labels)); seriesNames.forEach(function(series){ dataSet = [series]; labels.forEach(function(x){ if (temp[series][x] == undefined) {dataSet.push(null)} else {dataSet.push(temp[series][x])} }); result.push(dataSet)}); ''' class JsC3Pie(object): """ :category: RecordSet to Billboard Object :rubric: JS :type: Data Transformation :dsc: """ alias = "Billboard" chartTypes = ['pie', 'donut'] params = ("seriesNames", "xAxis") value = ''' var temp = {} ; var labels = {}; data.forEach(function(rec) { if (!(rec[xAxis] in temp)) {temp[rec[xAxis]] = {}}; seriesNames.forEach(function(name){ labels[name] = true; if(rec[name] !== undefined) {if (!(name in temp[rec[xAxis]])) {temp[rec[xAxis]][name] = rec[name]} else {temp[rec[xAxis]][name] += rec[name]}} }) ; }); result = []; result.push(['x'].concat(labels)); var labels = Object.keys(labels); for(var series in temp) { var values = [series]; labels.forEach(function(label) { if(temp[series][label] !== undefined ) { values.push(temp[series][label]) } else { values.push(null) }}); result.push(values);}; '''
timezone_translation = { '国际日期变更线西': {'en': ' Intern. Date Line West'}, '萨摩亚群岛': {'en': ' Samoa'}, '协调世界时': {'en': ' Coordinated Universal Time'}, '夏威夷': {'en': ' Hawaii'}, '马克萨斯群岛标准时间': {'en': ' Marquesas Standard Time'}, '阿拉斯加': {'en': ' Alaska'}, '太平洋时间(美国和加拿大)': {'en': ' Pacific Time (US and Canada)'}, '下加利福尼亚州': {'en': ' Baja California'}, '奇瓦瓦,拉巴斯,马萨特兰': {'en': ' Chihuahua, La Paz, Mazatlan'}, '山地时间(美国和加拿大)': {'en': ' Mountain Time (US and Canada)'}, '亚利桑那': {'en': ' Arizona'}, '瓜达拉哈拉,墨西哥城,蒙特雷': {'en': ' Guadalajara, Mexico City, Monterrey'}, '萨斯克彻温': {'en': ' Saskatchewan'}, '中部时间(美国和加拿大)': {'en': ' Central Time (US and Canada)'}, '中美洲': {'en': ' Central America'}, '波哥大,利马,基多': {'en': ' Bogota, Lima, Quito'}, '东部时间(美国和加拿大)': {'en': ' Eastern Time (US and Canada)'}, '印第安纳州(东部)': {'en': ' Indiana (East)'}, '加拉加斯': {'en': ' Caracas'}, '大西洋时间(加拿大)': {'en': ' Atlantic Time (Canada)'}, '库亚巴': {'en': ' Cuiaba'}, '乔治敦,拉巴斯,马瑙斯,圣湖安': {'en': ' Georgetown, La Paz, Manaus, Saint Lake Ann'}, '圣地亚哥': {'en': ' San Diego'}, '亚松森': {'en': ' Asuncion'}, '纽芬兰': {'en': ' Newfoundland'}, '巴西利亚': {'en': ' Brasilia'}, '布宜诺斯艾利斯': {'en': ' Buenos Aires'}, '格陵兰': {'en': ' Greenland'}, '卡宴,福塔雷萨': {'en': ' Cayenne, Fortaleza'}, '蒙得维的亚': {'en': ' Montevideo'}, '佛得角群岛': {'en': ' Cape Verde Islands'}, '中大西洋': {'en': ' Mid-Atlantic'}, '亚速尔群岛': {'en': ' Azores'}, '都柏林,爱丁堡,里斯本,伦敦': {'en': ' Dublin, Edinburgh, Lisbon, London'}, '卡萨布兰卡': {'en': ' Casablanca'}, '蒙罗维亚,雷克雅未克': {'en': ' Monrovia, Reykjavik'}, '阿姆斯特丹,柏林,伯尔尼,罗马,斯德歌尔摩,维也纳': {'en': ' Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna'}, '贝尔格莱德,布拉迪斯拉发,布达佩斯,卢布尔雅那': {'en': ' Belgrade, Bratislava, Budapest, Ljubljana'}, '布鲁塞尔,哥本哈根,马德里,巴黎': {'en': ' Brussels, Copenhagen, Madrid, Paris'}, '萨拉热窝,斯科普里,华沙,萨格勒布': {'en': ' Sarajevo, Skopje, Warsaw, Zagreb'}, '温得和克': {'en': ' Windhoek'}, '中非西部': {'en': ' West Central Africa'}, '安曼': {'en': ' Amman'}, '贝鲁特': {'en': ' Beirut'}, '大马士革': {'en': ' Damascus'}, '哈拉雷,比勒陀利亚': {'en': ' Harare, Pretoria'}, '赫尔辛基,基辅,里加,索非亚,塔林,维尔纽斯': { 'en': ' Helsinki, Kiev, Riga, Sofia, Tallinn, Vilnius', 'ru': ' Хельсинки, Киев, Рига, София, Таллинн, Вильнюс' }, '开罗': {'en': ' Cairo'}, '明斯克': {'en': ' Minsk', 'ru': ' Минск'}, '雅典,布加勒斯特': {'en': ' Athens, Bucharest'}, '耶路撒冷': {'en': ' Jerusalem'}, '伊斯坦布尔': {'en': ' Istanbul'}, '巴格达': {'en': ' Baghdad'}, '加里宁格勒': {'en': ' Kaliningrad', 'ru': ' Калининград'}, '科威特,利雅得': {'en': ' Kuwait, Riyadh'}, '内罗毕': {'en': ' Nairobi'}, '德黑兰': {'en': ' Tehran'}, '阿布扎比,马斯喀特': {'en': ' Abu Dhabi, Muscat'}, '埃里温': {'en': ' Yerevan', 'ru': ' Ереван'}, '巴库': {'en': ' Baku', 'ru': ' Баку'}, '第比利斯': {'en': ' Tbilisi', 'ru': ' Тбилиси'}, '路易港': {'en': ' Port Louis'}, '莫斯科,圣彼得堡,伏尔加格勒': {'en': ' Moscow, St. Petersburg, Volgograd', 'ru': ' Москва, Санкт-Петербург, Волгоград'}, '喀布尔': {'en': ' Kabul'}, '塔什干': {'en': ' Tashkent', 'ru': ' Ташкент'}, '伊斯兰堡,卡拉奇': {'en': ' Islamabad, Karachi'}, '钦奈,加尔各答,孟买,新德里': {'en': ' Chennai, Kolkata, Mumbai, New Delhi'}, '斯里加亚渥登普拉': {'en': ' Sri Jaya Wodenpura'}, '加德满都': {'en': ' Kathmandu'}, '阿斯塔纳': {'en': ' Astana', 'ru': ' Астана'}, '达卡': {'en': ' Dhaka'}, '叶卡捷琳堡': {'en': ' Yekaterinburg', 'ru': ' Екатеринбург'}, '仰光': {'en': ' Yangon'}, '曼谷,河内,雅加达': {'en': ' Bangkok, Hanoi, Jakarta'}, '新西伯利亚': {'en': ' Novosibirsk', 'ru': ' Новосибирск'}, '北京,重庆,香港特别行政区,乌鲁木齐': {'en': ' Beijing, Chongqing, Hong Kong, Urumqi'}, '吉隆坡,新加坡': {'en': ' Kuala Lumpur, Singapore'}, '克拉斯诺亚尔斯克': {'en': ' Krasnoyarsk', 'ru': ' Красноярск'}, '珀斯': {'en': ' Perth'}, '台北': {'en': ' Taipei'}, '乌兰巴托': {'en': ' Ulaanbaatar'}, '朝鲜标准时间': {'en': ' North Korea Standard Time'}, '大阪,札幌,东': {'en': ' Osaka, Sapporo, East'}, '首尔': {'en': ' Seoul'}, '伊尔库茨克': {'en': ' Irkutsk', 'ru': ' Иркутск'}, '阿德莱德': {'en': ' Adelaide'}, '达尔文': {'en': ' Darwin'}, '布里斯班': {'en': ' Brisbane'}, '关岛,莫尔兹比港': {'en': ' Guam, Port Moresby'}, '霍巴特': {'en': ' Hobart'}, '堪培拉,墨尔本,悉尼': {'en': ' Canberra, Melbourne, Sydney'}, '雅库茨克': {'en': ' Yakutsk', 'ru': ' Якутск'}, '澳大利亚远东标准时间': {'en': ' Australian Eastern Standard Time'}, '符拉迪沃斯托克': {'en': ' Vladivostok', 'ru': ' Владивосток'}, '所罗门群岛,新喀里多尼亚': {'en': ' Solomon Islands, New Caledonia'}, '诺福克岛标准时间': {'en': ' Norfolk Island Standard Time'}, '奥克兰,惠灵顿': {'en': ' Auckland, Wellington'}, '斐济': {'en': ' Fiji'}, '马加丹': {'en': ' Magadan'}, '努库阿洛法': {'en': ' Nuku\\\'alofa'}, '查塔姆群岛标准时间': {'en': ' Chatham Islands Standard Time'}, '基里巴斯': {'en': ' Kiribati'}, '大阪,札幌,东京': {'en': ' Osaka, Sapporo, Tokyo'} } timezone_translation_keys_sorted = sorted(timezone_translation, key=len, reverse=True)
class Pattern: """ This class is used for N:M conversions. """ def __init__(self, name=""): """ Patterns are described by the components which make up the pattern and the connections between those components. """ # # Pattern name is used in the conversion rules # # Example: *Boost => Boost # pattern name => Typhoon component type self.name = name.strip() # Components dict holds the type names of the # components which will be converted, under a # key which the user defines. This key is to be # used later on in the conversion to reference # exactly that one component which is being # consumed for this pattern conversion. # Example: # {"M":"MOSFET", # "D":"DIODE"} self.components = {} # Connections list holds the connections # between components which must exist in order # for the components to be matched with this pattern self.connections = [] def __str__(self): return f"{self.name}" def __repr__(self): return self.__str__() class Rule: """ This class defines the conversion rules. """ def __init__(self, source_type: str = "", typhoon_type: str = "", pattern_match: bool = False): self.source_type = source_type.strip() self.typhoon_type = typhoon_type.strip() self.pattern_match = pattern_match self.properties = [] # components = {"handle":{"type":"type_name1". # "properties":["name":"value"], # "} # "connections":[{"start_handle":"terminal", "end_handle":"terminal"}, # {"start_handle":"terminal", "end_handle":"terminal"}], # "ports":} self.components = {} self.connections = [] self.ports = {} self.terminals = {} self.predicates = [] def __str__(self): return f"{self.source_type} -> {self.typhoon_type}" def __repr__(self): return self.__str__() class Connection: """ This class is used to describe the connections between components in pattern matches """ def __init__(self, start_handle: str, start_terminal: str, end_handle: str, end_terminal: str): """ Connection objects contain start and end terminals, described by dicts. The keys are the user defined names of component types in the pattern, and the values are terminal keys of the matched component objects. If both start and end terminals are in the same node, the parent components of these terminals are matched to the pattern. Args: start_handle (str): handle of the component - the user defined name of the component type defined in the pattern start_terminal (str): actual terminal key of the component object's terminal end_handle (str): handle of the component - the user defined name of the component type defined in the pattern end_terminal (str): actual terminal key of the component object's terminal """ self.start_handle = start_handle self.start_terminal = start_terminal self.end_handle = end_handle self.end_terminal = end_terminal def __str__(self): return f"{self.start_handle}:{self.start_terminal} -> " \ f"{self.end_handle}:{self.end_terminal}" def __repr__(self): return self.__str__() class Property: """ This class is used for describing properties within conversion rules. These are the valid use cases: 1.) The property is a string value 2.) The property is a numeric value 3.) The property is a reference to another Component's property 4.) The property is the return value of a user defined function """ def __init__(self, prop_type="str", name="", value=None): """ Args: type (str): type of the property - str/float/ref/func name (str): name of the property of the Typhoon component value: value of the property - either a string or a float """ self.name = name.strip() self.prop_type = prop_type self.value = value self.params = {} def __str__(self): return f"{self.name} ({self.prop_type}) = {self.value} ({self.params})" def __repr__(self): return self.__str__() class Predicate: """ This class is used to describe additional conditions of component conversion, and is instantiated when a conversion rule is annotated in the rule file. A comparison of the component's property (property_name) is done with the condition value, via the operator (greater, lesser, equal, and their combinations). """ def __init__(self, property_name: str, operator: str, condition_value: (str, float, int)): self.property_name = property_name.strip() condition_value = condition_value.strip() if operator == ">": self.operator = "gt" elif operator == "<": self.operator = "lt" elif operator == "==": self.operator = "eq" elif operator == ">=": self.operator = "gteq" elif operator == "<=": self.operator = "lteq" else: raise Exception("Predicate operators must be " "either >, <, ==, >= or <= .") try: self.condition_value = float(condition_value) except ValueError: if self.operator == "eq": self.condition_value = condition_value.strip("\"") else: raise Exception("Predicate operator must be '==' " "for correct string comparison.") def evaluate(self, component): if component is None: raise Exception("Cannot evaluate predicate on None type object.") component_property_value = component.properties.get(self.property_name, None) if component_property_value is None: return False try: if self.operator == "gt": return component_property_value > self.condition_value elif self.operator == "lt": return component_property_value < self.condition_value elif self.operator == "eq": return component_property_value == self.condition_value elif self.operator == "gteq": return component_property_value >= self.condition_value elif self.operator == "ltgt": return component_property_value <= self.condition_value except TypeError as e: return False
# Description: Count number of *.mtz files in current directory. # Source: placeHolder """ cmd.do('print("Count the number of mtz structure factor files in current directory.");') cmd.do('print("Usage: cntmtzs");') cmd.do('myPath = os.getcwd();') cmd.do('mtzCounter = len(glob.glob1(myPath,"*.mtz"));') cmd.do('print("Number of number of mtz structure factor files in the current directory: ", mtzCounter);') """ cmd.do('print("Count the number of mtz structure factor files in current directory.");') cmd.do('print("Usage: cntmtzs");') cmd.do('myPath = os.getcwd();') cmd.do('mtzCounter = len(glob.glob1(myPath,"*.mtz"));') cmd.do('print("Number of number of mtz structure factor files in the current directory: ", mtzCounter);')
'''FreeProxy exceptions module''' class FreeProxyException(Exception): '''Exception class with message as a required parameter''' def __init__(self, message) -> None: self.message = message super().__init__(self.message)
__all__ = ["SENTINEL1_COLLECTION_ID", "VV", "VH", "IW", "ASCENDING", "DESCENDING"] SENTINEL1_COLLECTION_ID = "COPERNICUS/S1_GRD_FLOAT" VV = "VV" VH = "VH" IW = "IW" ASCENDING = "ASCENDING" DESCENDING = "DESCENDING" GEE_PROPERTIES = [ "system:id", "sliceNumber", "system:time_start", "relativeOrbitNumber_start", "relativeOrbitNumber_stop", "orbitNumber_start", "orbitNumber_stop", "instrumentConfigurationID", "system:asset_size", "cycleNumber", ]
def problem303(): """ # This function computes and returns the smallest positive multiple of n such that the result # uses only the digits 0, 1, 2 in base 10. For example, fmm(2) = 2, fmm(3) = 12, fmm(5) = 10. As an overview, the algorithm has two phases: # 0. Determine whether a k-digit solution is possible, for increasing values of k. # 1. Knowing that a k-digit solution exists, construct the minimum solution. Let n >= 1 be an arbitrary integer that will remain constant for the rest of the explanation. When we look at the set of all k-digit numbers using only the digits {0, 1, 2} # (with possible leading zeros), each number will have a particular remainder modulo n. # For example, the set of 3-digit numbers is {000, 001, 002, 010, ..., 120, ..., 221, 222} (having 3^3 = 27 elements). # If one of these numbers is congruent to 0 mod n, then a solution to the original problem exists. # If not, then we prepend the digits 0, 1, 2 to all the numbers to get the set of all 4-digit numbers. The size of the set of k-digit numbers grows exponentially with the length k, but we can avoid constructing and # working with the explicit set of numbers. Instead, we only need to keep track of whether each remainder modulo n has # a number that generates it or not. But we also need to exclude 0 as a solution, even though it is a multiple of n. For 0-digit numbers, the only possible remainder is 0. All other remainders modulo n are impossible. # For 1-digit numbers, we look at all the possible 0-digit number remainders. If a remainder m is possible, then: # - By prepending the digit 0, a remainder of (m + 0*1 mod n) is possible for 1-digit numbers. # - By prepending the digit 1, a remainder of (m + 1*1 mod n) is possible for 1-digit numbers. # - By prepending the digit 2, a remainder of (m + 2*1 mod n) is possible for 1-digit numbers. # We keep iterating this process of tracking possible remainders for k-digit # numbers until the remainder of 0 mod n is possible in a non-zero number. Now we know that a k-digit solution exists, such that the k-digit number consists of only {0, 1, 2}, # and the number is congruent to 0 modulo n. To construct the minimum solution, we start at the most significant # digit of the result, choose the lowest possible value, and work backward toward the least significant digit. The leading digit must be 1 or 2, because if it were 0 then it would contradict the fact that # no solution shorter than k digits exists. All subsequent digits can possibly be 0, 1, or 2. At each value place, we choose the lowest digit value out of {0, 1, 2} such that there still # exists a solution for the remaining suffix of the number. When we choose a value at a certain # digit position, say 2 at the 8th place, we subtract 2 * 10^8 mod n from the ongoing remainder. """ def find_minimum_multiple(n): # feasible[i][j] indicates whether there exists an i-digit number that consists of # only the digits {0, 1, 2} (with possible leading zeros) having a remainder of j modulo n: # - 0: No i-digit number can form this remainder # - 1: Only zero can form this remainder # - 2: Some non-zero number can form this remainder # Initialization and base case feasible = [[1] + [0] * (n - 1)] # Add digits on the left side until a solution exists, using dynamic programming i = 0 while feasible[i][0] != 2: # Unbounded loop assert i == len(feasible) - 1 prev = feasible[i] cur = list(prev) # Clone digitmod = pow(10, i, n) for j in range(n): # Run time of O(n) if prev[j] > 0: cur[(j + digitmod * 1) % n] = 2 cur[(j + digitmod * 2) % n] = 2 feasible.append(cur) i += 1 # Construct the smallest solution using the Memoized table # Run time of O(len(feasible)) bigint operations result = 0 remainder = 0 # Modulo n # Pick digit values from left (most significant) to right for i in reversed(range(len(feasible) - 1)): digitmod = pow(10, i, n) # Leading digit must start searching at 1; subsequent digits start searching at 0 for j in range((1 if (i == len(feasible) - 2) else 0), 3): newrem = (remainder - digitmod * j) % n if feasible[i][newrem] > 0: result = result * 10 + j remainder = newrem break else: raise AssertionError() return result ans = sum(find_minimum_multiple(n) // n for n in range(1, 10001)) return ans if __name__ == "__main__": print(problem303())
start = 1 end = 100 for x in range(start,end): if (x % 2 == 0): continue print(x)
'''12、 统计不同类型的字符 【问题描述】 输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。 【输入】 一行字符。 【输出】 分别输出英文字母、空格、数字和其它字符的个数,具体格式见输出样例。 【输入样例】 123runoobc kdf235*(dfl 【输出样例】 char = 13,space = 2,digit = 6,others = 2''' str = input() alphaNum=0 numbers=0 spaceNum=0 otherNum=0 for i in str: if i.isalpha(): alphaNum +=1 elif i.isnumeric(): numbers +=1 elif i.isspace(): spaceNum +=1 else: otherNum +=1 print('char = %d,'%alphaNum,'space = %d,'%spaceNum,'digit = %d,'%numbers,'others %d'%otherNum)
""" You are given an n x n 2D matrix representing an image. Rotate the matrix 90 degrees clockwise in-place. Example 1: [[1, 2, 3], [[7, 4, 1], [4, 5, 6], -> [8, 5, 2], [7, 8, 9]], [9, 6, 3]] Example 2: [[ 5, 1, 9, 11], [[15, 13, 2, 5], [ 2, 4, 8, 10], -> [14, 3, 4, 1], [13, 3, 6, 7], [12, 6, 8, 9], [15, 14, 12, 16]], [16, 7, 10, 11]] """ """ We work our way through one side of concentrically smaller squares, shifting every side of the square clockwise. """ def rotate(matrix): n = len(matrix) for row_idx in range(n//2): for col_idx in range(row_idx, square_size := n-row_idx-1): diff = col_idx - row_idx top = matrix[row_idx][col_idx] matrix[row_idx][col_idx] = matrix[square_size - diff][row_idx] # top from left matrix[square_size - diff][row_idx] = matrix[square_size][square_size - diff] # left from bottom matrix[square_size][square_size - diff] = matrix[row_idx + diff][square_size] # bottom from right matrix[row_idx + diff][square_size] = top # right from top matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] rotate(matrix) assert matrix == [[7, 4, 1], [8, 5, 2], [9, 6, 3]] matrix = [[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]] rotate(matrix) assert matrix == [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]] matrix = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]] rotate(matrix) assert matrix == [[21, 16, 11, 6, 1], [22, 17, 12, 7, 2], [23, 18, 13, 8, 3], [24, 19, 14, 9, 4], [25, 20, 15, 10, 5]]
""" 1356. Sort Integers by The Number of 1 Bits Given an integer array arr. You have to sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order. Return the sorted array. Example 1: Input: arr = [0,1,2,3,4,5,6,7,8] Output: [0,1,2,4,8,3,5,6,7] Explantion: [0] is the only integer with 0 bits. [1,2,4,8] all have 1 bit. [3,5,6] have 2 bits. [7] has 3 bits. The sorted array by bits is [0,1,2,4,8,3,5,6,7] Example 2: Input: arr = [1024,512,256,128,64,32,16,8,4,2,1] Output: [1,2,4,8,16,32,64,128,256,512,1024] Explantion: All integers have 1 bit in the binary representation, you should just sort them in ascending order. Example 3: Input: arr = [10000,10000] Output: [10000,10000] Example 4: Input: arr = [2,3,5,7,11,13,17,19] Output: [2,3,5,17,7,11,13,19] Example 5: Input: arr = [10,100,1000,10000] Output: [10,100,10000,1000] Constraints: 1 <= arr.length <= 500 0 <= arr[i] <= 10^4 """ class Solution: def sortByBits(self, arr: List[int]) -> List[int]: return sorted(arr, key = lambda x: (bin(x).count('1'), x))
class AggResult: def __init__(self, agg_key, result=None, return_counts=True): self.return_counts = return_counts if result is None: self.total = 0 self._hits = [] else: self.total = result['hits']['total']['value'] self._hits = result['aggregations'][agg_key]['buckets'] def __repr__(self): return "hits {}, total: {}".format(self._hits, self.total) def __iter__(self): for hit in self._hits: row = hit['key'] if self.return_counts: count = hit['doc_count'] yield {row: count} else: yield row def dict(self): return { "total": self.total, "result": list(self) }
input = """ a(1). a(2). b(1,2). c(2). c(3). q(X,Y) :- a(X), c(Y). p(X,Y,Z) :- a(X), q(Y,Z), m(X,Z). m(X,Y) :- a(Z), p(Z,X,Y). m(X,Y) :- b(X,Y), not n(X,Y). n(X,Y) :- q(X,Y). n(X,Y) :- b(X,Y), m(X,Y). """ output = """ a(1). a(2). b(1,2). c(2). c(3). q(X,Y) :- a(X), c(Y). p(X,Y,Z) :- a(X), q(Y,Z), m(X,Z). m(X,Y) :- a(Z), p(Z,X,Y). m(X,Y) :- b(X,Y), not n(X,Y). n(X,Y) :- q(X,Y). n(X,Y) :- b(X,Y), m(X,Y). """
# -*- coding: utf-8 -*- """ Created on 2018/10/31 @author: gaoan """ class HourTrading(object): def __init__(self): self.trading_session = None # 盘前/盘后 self.latest_price = None # 最新价 self.prev_close = None # 昨日收盘价 self.latest_time = None # 最后交易时间 self.volume = None # 成交量 self.open_price = None # 开盘价 self.high_price = None # 最高价 self.low_price = None # 最低价 self.change = None # 涨跌额 def __repr__(self): """ String representation for this object. """ return "HourTrading(%s)" % self.__dict__ class QuoteBrief(object): def __init__(self): # contract info self.symbol = None # 股票代号 self.market = None # 市场代号 self.name = None # 股票名称 self.sec_type = None # STK 股票, OPT 期权,WAR窝轮,IOPT牛熊证, FUT期货 self.latest_price = None # 最新价 self.prev_close = None # 昨日收盘价 self.latest_time = None # 最后交易时间 self.volume = None # 成交量 self.open_price = None # 开盘价 self.high_price = None # 最高价 self.low_price = None # 最低价 self.change = None # 涨跌额 self.bid_price = None # 卖盘价 self.bid_size = None # 卖盘数量 self.ask_price = None # 买盘价 self.ask_size = None # 买盘数量 self.halted = None # 是否停牌 0: 正常,3: 停牌,4: 退市 self.delay = None # 延时分钟 self.auction = None # 是否竞价时段(仅港股) self.expiry = None # 到期时间(仅港股) self.hour_trading = None # 盘前盘后数据,可能为空(仅美股 def __repr__(self): return "QuoteBrief(%s)" % self.__dict__
""" 백준 14623번 : 감정이입 """ B1 = int(input(), 2) B2 = int(input(), 2) print(bin(B1 * B2)[2:])
class Solution: def destCity(self, paths: List[List[str]]) -> str: s = set() for path in paths: s.add(path[0]) s.add(path[1]) for path in paths: s.remove(path[0]) return list(s).pop()
class Solution: def checkString(self, s: str) -> bool: flag = 0 for ch in s: if flag == 0 and ch == 'b': flag = 1 elif flag == 1 and ch == 'a': return False return True
class Node: def __init__(self, data=None) -> None: self.data = data self.next = None self.prev = None class DoublyList: def __init__(self) -> None: self.front = None self.back = None self.size = 0 def add_back(self, data: int) -> None: node = Node(data) if self.is_empty(): self.front = node self.back = node else: self.back.next = node node.prev = self.back self.back = node self.size += 1 def add_front(self, data: int) -> None: node = Node(data) if self.is_empty(): self.front = node self.back = node else: node.next = self.front self.front.prev = node self.front = node self.size += 1 def remove(self, data: int) -> None: if self.is_empty(): raise Exception("Error: list is aleady empty.") else: ptr = self.front while ptr.next is not None: if (ptr.data == data): ptr.prev = ptr.prev.prev ptr.next = ptr.next.next self.size -= 1 return ptr = ptr.next raise Exception("Error: element is not found on the list") def remove_front(self)->None: if self.is_empty(): return else: self.front = self.front.next self.size -= 1 def remove_back(self)->None: if self.is_empty(): return else: self.back = self.back.prev self.size -= 1 def display(self) -> None: ptr = self.front while ptr.next is not None: print(ptr.data) ptr = ptr.next def is_empty(self) -> bool: return self.front is None and self.back is None def display_reverse(self) -> None: pass
class AlmostPrimeNumbers: def getNext(self, m): sieve = [True]*(10**6+2) for i in xrange(2, 10**6+2): if sieve[i]: for j in xrange(2*i, 10**6+2, i): sieve[j] = False def is_almost(n): return not sieve[n] and not any(n%i == 0 for i in xrange(2, 11)) i = m+1 while not is_almost(i): i += 1 return i
class LandingType(object): # For choosing what the main landing page displays KICKOFF = 1 BUILDSEASON = 2 COMPETITIONSEASON = 3 OFFSEASON = 4 INSIGHTS = 5 CHAMPS = 6 NAMES = { KICKOFF: 'Kickoff', BUILDSEASON: 'Build Season', COMPETITIONSEASON: 'Competition Season', OFFSEASON: 'Offseason', INSIGHTS: 'Insights', CHAMPS: 'Championship', }
#!/usr/bin/env python polymer = input() letters = [ord(c) for c in set(polymer.upper())] polymer = [ord(c) for c in polymer] def react(polymer, forbidden=set()): stack = [] for unit in polymer: if unit not in forbidden: if stack and abs(unit - stack[-1]) == 32: stack.pop() else: stack.append(unit) return len(stack) assert react(polymer) == 9172 lowest = min([react(polymer, {c, c + 32}) for c in letters]) assert lowest == 6550
HANGMAN_ASCII_ART = (""" _ _ | | | | | |__| | __ _ _ __ __ _ _ __ ___ __ _ _ __ | __ |/ _` | '_ \ / _` | '_ ` _ \ / _` | '_ \ | | | | (_| | | | | (_| | | | | | | (_| | | | | |_| |_|\__,_|_| |_|\__, |_| |_| |_|\__,_|_| |_| __/ | |___/ \n""") MAX_TRIES = 6 print(HANGMAN_ASCII_ART, MAX_TRIES) """ HANGMAN GAME ASCII LOGO AND MAX TRIES """
#!/usr/bin/env python3 class colors: GREEN = '\033[92m' YELLOW = '\033[93m' BLUE = '\033[94m' RED = '\033[91m' BOLD = '\033[1m' RESET = '\033[0m'
nombre_usuario = input("Introduce tu nombre de usuario: ") print("El nombre es:", nombre_usuario) print("El nombre es:", nombre_usuario.upper()) print("El nombre es:", nombre_usuario.lower()) print("El nombre es:", nombre_usuario.capitalize())
class Node: def __init__(self, value=None): self.value = value self.next = None def __str__(self): return str(self.value) class LinkedList: def __init__(self): self.head = None self.tail = None def __iter__(self): node = self.head while node != None: yield node node = node.next class Queue: def __init__(self): self.linkedList = LinkedList() def __str__(self): values = [str(x) for x in self.linkedList] return ' '.join(values) def enqueue(self, value): newNode = Node(value) if self.linkedList.head == None: self.linkedList.head = newNode self.linkedList.tail = newNode else: self.linkedList.tail.next = newNode self.linkedList.tail = newNode def isEmpty(self): if self.linkedList.head == None: return True else: return False def dequeue(self): if self.isEmpty() == True: return "There is not any node in the Queue" else: tempNode = self.linkedList.head if self.linkedList.head == self.linkedList.tail: self.linkedList.head = None self.linkedList.tail = None else: self.linkedList.head = self.linkedList.head.next return tempNode def peek(self): if self.isEmpty() == True: return "There is not any node in the Queue" else: return self.linkedList.head.value def delete(self): if self.isEmpty() == True: return "There is not any node in the Queue" else: self.linkedList.head = None self.linkedList.tail = None
RELEVANT_COLUMNS = [ "HONG KONG", "JAPAN", "CANADA", "FINLAND", "DENMARK", "ESTONIA", "POLAND", "CZECH REPUBLIC", "SLOVENIA and BALKANs", "ITALY", "SPAIN", "SWITZERLAND", "BENELUX", "UK", "ISLAND", "USA Wholesale", "Germany/ Austria", "Sweden/ Norway", "Store", "Marketplaces (AZ+ ZA)", "Webshop (INK US, CAN, FIN)", ] def forecasts_handler(iterator): for row in iterator: if row["Article number "] == "": continue else: for col in RELEVANT_COLUMNS: try: row[col] = int(row[col].replace(" ", "")) except: row[col] = 0 yield { "Article_number": row["Article number "], "Distribution_ID": col, "Quantity": row[col], }
''' Author : MiKueen Level : Hard Company : Stripe Problem Statement : First Missing Positive Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3. You can modify the input array in-place. ''' def firstMissingPositive(nums): """ :type nums: List[int] :rtype: int """ # Method 1: Changing array values # mark those elements who aren't in the range of [1, n] n = len(nums) for i in range(n): if nums[i] <= 0 or nums[i] > n: nums[i] = n + 1 # mark visited elements as negative for i in range(n): if (abs(nums[i]) - 1 < n and nums[abs(nums[i]) - 1] > 0): nums[abs(nums[i]) - 1] = -nums[abs(nums[i]) - 1] # find first positive/unmarked element and return its index for i in range(n): if (nums[i] > 0): return i + 1 # if all elements are negative/marked means all elements are in the range of [1, n] return n + 1 ''' # Method 2: Changing position of elements n = len(nums) for i in range(n): pos = nums[i] - 1 while 1 <= nums[i] <= n and nums[i] != nums[pos]: nums[i], nums[pos] = nums[pos], nums[i] pos = nums[i] - 1 for i in range(n): if nums[i] != i + 1: return i + 1 return n + 1 '''
#*****************************************************************************# #* Copyright (c) 2004-2008, SRI International. *# #* All rights reserved. *# #* *# #* Redistribution and use in source and binary forms, with or without *# #* modification, are permitted provided that the following conditions are *# #* met: *# #* * Redistributions of source code must retain the above copyright *# #* notice, this list of conditions and the following disclaimer. *# #* * Redistributions in binary form must reproduce the above copyright *# #* notice, this list of conditions and the following disclaimer in the *# #* documentation and/or other materials provided with the distribution. *# #* * Neither the name of SRI International nor the names of its *# #* contributors may be used to endorse or promote products derived from *# #* this software without specific prior written permission. *# #* *# #* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *# #* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *# #* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR *# #* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT *# #* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, *# #* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT *# #* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, *# #* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY *# #* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *# #* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE *# #* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *# #*****************************************************************************# #* "$Revision:: 26 $" *# #* "$HeadURL:: https://svn.ai.sri.com/projects/spark/trunk/spark/src/spar#$" *# #*****************************************************************************# def computeCycles(root, successors): finished = [] companions = {} path = [] _process(successors, [], companions, path, root) return companions def _process(successors, complete, companions, path, node): #print "Processing", companions, path, node if node in path: # we have found a cycle pos = path.index(node) #print "Found new cycle", path[pos:] group = None for cnode in path[pos:]: # for every other node in this cycle, merge the companions group = _merge_group(group, companions, cnode) elif node in complete and _subset(companions.get(node,()), complete): # every node in the companion group is complete #print "Pruning search under", node pass else: path.append(node) #print "successors", node, successors(node) for next in successors(node): _process(successors, complete, companions, path, next) path.pop() complete.append(node) def _subset(seq1, seq2): for elt in seq1: if elt not in seq2: return False return True def _merge_group(group, companions, cnode): """Merge group with the previously known companions of cnode, return the group (which should now be the companion list for everything in group) """ # precondition: if group then forall x in group companions[x]==group if group is not None and cnode in group: return group #print "_merge_group", group, companions, cnode othergroup = companions.get(cnode) if group is None: if othergroup is None: group = [cnode] companions[cnode] = group else: group = othergroup elif othergroup is None: group.append(cnode) companions[cnode] = group elif group is not othergroup: for onode in othergroup: if onode not in group: #print " adding", onode group.append(onode) companions[onode] = group return group TEST1 = {1:[2,3], 2:[1,4,5], 3:[6,7,8], 4:[1], 5:[], 6:[2], 7:[], 8:[8]} ANSWER1 = {1: [1, 2, 4, 3, 6], 2: [1, 2, 4, 3, 6], 3: [1, 2, 4, 3, 6], 4: [1, 2, 4, 3, 6], 6: [1, 2, 4, 3, 6], 8:[8]} def test(): result = computeCycles(1, TEST1.get) if (result != ANSWER1): raise AssertionError
API = "api" API_DEFAULT_DESCRIPTOR = "default" API_ERROR_MESSAGES = "errorMessages" API_QUERY_STRING = "query_string" API_RESOURCE = "resource_name" API_RETURN = "on_return" COLUMN_FORMATING = "column_formating" COLUMN_CLEANING = "column_cleaning" COLUMN_EXPANDING = "column_expending" DEFAULT_COLUMNS_TO_EXPAND = ["changelog", "fields", "renderedFields", "names", "schema", "operations", "editmeta", "versionedRepresentations"] ENDPOINTS = "endpoints" ITEM_VALUE = "{item_value}" JIRA_BOARD_ID_404 = "Board {item_value} does not exists or the user does not have permission to view it." JIRA_CORE_PAGINATION = { "skip_key": "startAt", "limit_key": "maxResults", "total_key": "total" } JIRA_CORE_URL = "{site_url}rest/api/3/{resource_name}" JIRA_IS_LAST_PAGE = "isLastPage" JIRA_LICENSE_403 = "The user does not a have valid license" JIRA_NEXT = "next" JIRA_OPSGENIE_402 = "The account cannot do this action because of subscription plan" JIRA_OPSGENIE_PAGING = "paging" JIRA_OPSGENIE_URL = "api.opsgenie.com/{resource_name}" JIRA_PAGING = "_links" JIRA_SERVICE_DESK_ID_404 = "Service Desk ID {item_value} does not exists" JIRA_SERVICE_DESK_PAGINATION = { "next_page_key": ["_links", "next"] } JIRA_SERVICE_DESK_URL = "{site_url}rest/servicedeskapi/{resource_name}" JIRA_SOFTWARE_URL = "{site_url}rest/agile/1.0/{resource_name}" PAGINATION = "pagination" endpoint_descriptors = { API_DEFAULT_DESCRIPTOR: { API_RESOURCE: "{endpoint_name}/{item_value}", API: JIRA_CORE_URL, API_RETURN: { 200: None, 401: "The user is not logged in", 403: "The user does not have permission to complete this request", 404: "Item {item_value} not found", 500: "Jira Internal Server Error" }, COLUMN_EXPANDING: DEFAULT_COLUMNS_TO_EXPAND, PAGINATION: JIRA_CORE_PAGINATION }, ENDPOINTS: { "dashboard": {API_RETURN: {200: ["dashboards", None]}}, "dashboard/search": {API_RETURN: {200: "values"}}, "field": { API_RESOURCE: "{endpoint_name}", }, "group": { API_RESOURCE: "{endpoint_name}/member", API_QUERY_STRING: {"groupname": ITEM_VALUE}, API_RETURN: {200: "values"} }, "issue": { API_QUERY_STRING: {"expand": "{expand}"} }, "issue/createmeta": { API_RESOURCE: "{endpoint_name}", API_RETURN: { 200: "projects" } }, "issue(Filter)": { API_RESOURCE: "search", API_QUERY_STRING: {"jql": "filter={}".format(ITEM_VALUE), "expand": "{expand}"}, API_RETURN: { 200: "issues" } }, "issue(JQL)": { API_RESOURCE: "search", API_QUERY_STRING: {"jql": ITEM_VALUE, "expand": "{expand}"}, API_RETURN: { 200: "issues" } }, "project/components": { API_RESOURCE: "project/{item_value}/components" }, "project/search": { API_RESOURCE: "{endpoint_name}", API_QUERY_STRING: {"expand": "{expand}"}, # expand: description, projectKeyrs, lead, issueTypes, url, insight API_RETURN: { 200: "values", 404: "Item not found" } }, "project/versions": { API_RESOURCE: "project/{item_value}/versions", API_QUERY_STRING: {"expand": "{expand}"} # expand: issuesstatus, operations }, "search": { API_RESOURCE: "search", API_QUERY_STRING: {"jql": ITEM_VALUE, "expand": "{expand}"}, API_RETURN: { 200: "issues" } }, "worklog/deleted": {}, "worklog/list": { API_RESOURCE: "issue/{item_value}/worklog", }, "organization": { API: JIRA_SERVICE_DESK_URL, API_RESOURCE: "organization/{item_value}", API_RETURN: { 200: ["values", None], 404: "Organization ID {item_value} does not exists" }, PAGINATION: JIRA_SERVICE_DESK_PAGINATION }, "organization/user": { API: JIRA_SERVICE_DESK_URL, API_RESOURCE: "organization/{item_value}/user", API_RETURN: { 200: "values", 404: "Organization ID {item_value} does not exists" }, PAGINATION: JIRA_SERVICE_DESK_PAGINATION }, "request": { API: JIRA_SERVICE_DESK_URL, API_RETURN: { 200: ["values", None] }, PAGINATION: JIRA_SERVICE_DESK_PAGINATION }, "servicedesk": { API: JIRA_SERVICE_DESK_URL, API_RESOURCE: "{endpoint_name}/{item_value}", API_RETURN: { 200: ["values", None], 404: JIRA_SERVICE_DESK_ID_404 }, PAGINATION: JIRA_SERVICE_DESK_PAGINATION }, "servicedesk/customer": { API: JIRA_SERVICE_DESK_URL, API_RESOURCE: "servicedesk/{item_value}/customer", API_RETURN: { 200: "values", 404: JIRA_SERVICE_DESK_ID_404 }, PAGINATION: JIRA_SERVICE_DESK_PAGINATION }, "servicedesk/organization": { API: JIRA_SERVICE_DESK_URL, API_RESOURCE: "servicedesk/{item_value}/organization", API_RETURN: { 200: "values", 404: JIRA_SERVICE_DESK_ID_404 }, PAGINATION: JIRA_SERVICE_DESK_PAGINATION }, "servicedesk/queue": { API: JIRA_SERVICE_DESK_URL, API_RESOURCE: "servicedesk/{item_value}/queue", API_RETURN: { 200: "values", 404: JIRA_SERVICE_DESK_ID_404 }, PAGINATION: JIRA_SERVICE_DESK_PAGINATION }, "servicedesk/queue/issue": { API: JIRA_SERVICE_DESK_URL, API_RESOURCE: "servicedesk/{item_value}/queue/{queue_id}/issue", API_RETURN: { 200: "values", 404: "Service Desk ID {item_value} or queue ID {queue_id} do not exist" }, PAGINATION: JIRA_SERVICE_DESK_PAGINATION }, "board": { API: JIRA_SOFTWARE_URL, API_RESOURCE: "board", API_RETURN: { 200: "values", 404: JIRA_BOARD_ID_404 } }, "board/backlog": { API: JIRA_SOFTWARE_URL, API_RESOURCE: "board/{item_value}/backlog", API_RETURN: { 200: "issues", 404: JIRA_BOARD_ID_404 } }, "board/epic": { API: JIRA_SOFTWARE_URL, API_RESOURCE: "board/{item_value}/epic", API_RETURN: { 200: "values", 404: JIRA_BOARD_ID_404 } }, "board/epic/none/issue": { API: JIRA_SOFTWARE_URL, API_RESOURCE: "board/{item_value}/epic/none/issue", API_RETURN: { 200: "issues", 404: JIRA_BOARD_ID_404 } }, "board/issue": { API: JIRA_SOFTWARE_URL, API_RESOURCE: "board/{item_value}/issue", API_RETURN: { 200: "issues", 404: JIRA_BOARD_ID_404 } }, "board/project": { API: JIRA_SOFTWARE_URL, API_RESOURCE: "board/{item_value}/project", API_RETURN: { 200: "values" } }, "board/project/full": { API: JIRA_SOFTWARE_URL, API_RESOURCE: "board/{item_value}/project/full", API_RETURN: { 200: "values", 403: JIRA_LICENSE_403 } }, "board/sprint": { API: JIRA_SOFTWARE_URL, API_RESOURCE: "board/{item_value}/sprint", API_RETURN: { 200: "values", 403: JIRA_LICENSE_403 } }, "board/version": { API: JIRA_SOFTWARE_URL, API_RESOURCE: "board/{item_value}/version", API_RETURN: { 200: "values", 403: JIRA_LICENSE_403 } }, "epic/none/issue": { API: JIRA_SOFTWARE_URL, API_RESOURCE: "epic/none/issue", API_RETURN: { 200: "issues" } }, "alerts": { API: JIRA_OPSGENIE_URL, API_RESOURCE: "v2/alerts", API_QUERY_STRING: { "query": ITEM_VALUE }, API_RETURN: { 200: "data", 402: JIRA_OPSGENIE_402 }, COLUMN_FORMATING: { "integration_type": ["integration", "type"], "integration_id": ["integration", "id"], "integration_name": ["integration", "name"] }, COLUMN_CLEANING: ["integration"] }, "incidents": { API: JIRA_OPSGENIE_URL, API_RESOURCE: "v1/incidents", API_QUERY_STRING: { "query": ITEM_VALUE }, API_RETURN: { 200: "data", 402: JIRA_OPSGENIE_402 } }, "users": { API: JIRA_OPSGENIE_URL, API_RESOURCE: "v2/users", API_QUERY_STRING: { "query": ITEM_VALUE }, API_RETURN: { 200: "data", 402: JIRA_OPSGENIE_402 }, COLUMN_FORMATING: { "country": ["userAddress", "country"], "state": ["userAddress", "state"], "line": ["userAddress", "line"], "zip_code": ["userAddress", "zipCode"], "city": ["userAddress", "city"], "role": ["role", "id"] }, COLUMN_CLEANING: ["userAddress"] }, "teams": { API: JIRA_OPSGENIE_URL, API_RESOURCE: "v2/teams", API_QUERY_STRING: { "query": ITEM_VALUE }, API_RETURN: { 200: "data", 402: JIRA_OPSGENIE_402 }, COLUMN_EXPANDING: DEFAULT_COLUMNS_TO_EXPAND.append("links") }, "schedules": { API: JIRA_OPSGENIE_URL, API_RESOURCE: "v2/schedules", API_QUERY_STRING: { "query": ITEM_VALUE }, API_RETURN: { 200: "data", 402: JIRA_OPSGENIE_402 } }, "escalations": { API: JIRA_OPSGENIE_URL, API_RESOURCE: "v2/escalations", API_RETURN: { 200: "data", 402: JIRA_OPSGENIE_402 } }, "services": { API: JIRA_OPSGENIE_URL, API_RESOURCE: "v1/services", API_QUERY_STRING: {"query": ITEM_VALUE}, API_RETURN: { 200: "data", 402: JIRA_OPSGENIE_402 } } } }
region = 'us-west-2' default_vpc = dict( enable_dns_hostnames=True, cidr_block='10.0.0.0/16', tags={'Name': 'default'}, ) default_gateway = dict(vpc_id='${aws_vpc.default.id}') internet_access_route = dict( route_table_id='${aws_vpc.default.main_route_table_id}', destination_cidr_block='0.0.0.0/0', gateway_id='${aws_internet_gateway.default.id}' ) config = dict( provider=dict( aws=dict(region=region) ), resource=dict( aws_vpc=dict(default=default_vpc), aws_internet_gateway=dict(default=default_gateway), aws_route=dict(internet_access=internet_access_route), ) )
ants_picture = """ .` / `:` .-` ` -- `-` `-`.-` `-. --..o `..` .:. `y. --` `-/-` `/+` -o` `...` `-/-` `s+ ```-+` ..-````` /s `-+: -/ossyyys+/- `-:://///:-.` `yh -o/` :dmmmdhhhhyo+` ```......:+so- :m/ oy/+o+:/yNNNmdhyhdo+o ``...........+hs. .h.`.+dhmmhyydddNNddyshhhs/ `.....-:/+/++++/os---+hhdmmddmdddmd/dmyyssyys+ ``.-:/ohdhmdhhhhdy:dmmNmdddhyyysys+. sdyso+:. /- `.-+hhhmmmmmdhydmmNdmyhsos//ss/--` ` o: .+ydmdmmmmNmdddddd.-s+``o -+++//-. `/-``` .+sdmmmddddhoosyy+ s: o/ ``..//-` ``.......` ./shdhhyyssyoo/. `d- `y: `-:-.`` `... .-/+++//:-` +s .y. `.-. ` :s` -+ `:-` o- `::` -+` `-:. `-. .-` .-` .` `: `-` .` `. """ ants_picture2 = \ """ ___ _ _____________ / | / | / /_ __/ ___/ / /| | / |/ / / / \__ \ / ___ |/ /| / / / ___/ / /_/ |_/_/ |_/ /_/ /____/ """ print(ants_picture) ants = 'Accelerated Neutron Transport Solution'
class BlackjackWinner: def winnings(self, bet, dealer, dealerBlackjack, player, blackjack): if player > 21 or (player < dealer and dealer <= 21): return -bet if dealerBlackjack and blackjack: return 0 if dealerBlackjack and not blackjack: return -bet if not dealerBlackjack and blackjack: return 1.5 * bet if dealer > 21 or player > dealer: return bet return 0