content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
centerX = 0 centerY = 0 angle = 0 fsize = 0 weight = 0 counter = 0 centerX= 500/2 centerY= 500/2 angle= 0 fsize= 150 weight = 1 class MyEllipse(): cX = centerX cY = centerY cA = angle eS = fsize Ew = weight def render(self, fsize): fill(200, fsize/20) x1 = centerX - cos(angle)*fsize/2 y1 = centerY + sin(angle)*fsize/2 stroke(250, 100) strokeWeight(weight) ellipse(x1, y1,fsize,fsize) ell = MyEllipse() def setup(): size(500,500) smooth() background(10) def draw(): global counter counter += 0.01 if counter > TWO_PI: sounter = 0 ell.render(sin(counter*4)*mouseX)
center_x = 0 center_y = 0 angle = 0 fsize = 0 weight = 0 counter = 0 center_x = 500 / 2 center_y = 500 / 2 angle = 0 fsize = 150 weight = 1 class Myellipse: c_x = centerX c_y = centerY c_a = angle e_s = fsize ew = weight def render(self, fsize): fill(200, fsize / 20) x1 = centerX - cos(angle) * fsize / 2 y1 = centerY + sin(angle) * fsize / 2 stroke(250, 100) stroke_weight(weight) ellipse(x1, y1, fsize, fsize) ell = my_ellipse() def setup(): size(500, 500) smooth() background(10) def draw(): global counter counter += 0.01 if counter > TWO_PI: sounter = 0 ell.render(sin(counter * 4) * mouseX)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # x = int(input()) y = int(input()) day = 1 while y - x > 0: x = x + (x * 0.1) day += 1 print(day)
x = int(input()) y = int(input()) day = 1 while y - x > 0: x = x + x * 0.1 day += 1 print(day)
TELEGRAM_API_TOKEN = 'Tel Bot Token By @BotFather' UPLOADER = { 'uploader': 'reverse_image_search_bot.uploaders.ssh.SSHUploader', 'url': 'Host Domain Name', 'configuration': { 'host': 'Host IP (PUBLIC)', 'user': 'Yourname', 'password': 'Password', 'upload_dir': '/path/to/ReVot/', 'key_filename': '/path/to/.ssh/rsakey.pub (Public key)', } }
telegram_api_token = 'Tel Bot Token By @BotFather' uploader = {'uploader': 'reverse_image_search_bot.uploaders.ssh.SSHUploader', 'url': 'Host Domain Name', 'configuration': {'host': 'Host IP (PUBLIC)', 'user': 'Yourname', 'password': 'Password', 'upload_dir': '/path/to/ReVot/', 'key_filename': '/path/to/.ssh/rsakey.pub (Public key)'}}
# https://www.geeksforgeeks.org/basic/cryptography/ # SGVP387900|14:43 27F19 # Hill Cipher implementation keyMatrix = [[0] * 3 for i in range(3)] # Genrate vector for the message messageVector = [[0] for i in range(3)] # Genrate vector for the cipher cipherMatrix = [[0] for i in range(3)] # Following function generates the # key matrix for the key string def getKeyMatrix(key): k = 0 for i in range(3): for j in range(3): keyMatrix[i][j] = ord(key[k]) % 65 k += 1 # Function encrypts the message def encrypt(messageVector): for i in range(3): for j in range(1): cipherMatrix[i][j] = 0 for x in range(3): cipherMatrix[i][j] += (keyMatrix[i][x] * messageVector[x][j]) cipherMatrix[i][j] = cipherMatrix[i][j] % 26 # https://www.geeksforgeeks.org/hill-cipher/ # HillCipher def HillCipher(message, key): # Get key matrix from the key string getKeyMatrix(key) # Generate vector for the message for i in range(3): messageVector[i][0] = ord(message[i]) % 65 # Function genrates # the encrypted vector encrypt(messageVector) # Generate the encrypted text # from the encrypted vector CipherText = [] for i in range(3): CipherText.append(chr(cipherMatrix[i][0] + 65)) # Print the cipherText print("Ciphertext: ", "".join(CipherText)) # Driver Code def main(): # Get the message to be encrypted message = "ACT" # Get the key key = "GYBNQKURP" HillCipher(message, key) if __name__ == "__main__": main()
key_matrix = [[0] * 3 for i in range(3)] message_vector = [[0] for i in range(3)] cipher_matrix = [[0] for i in range(3)] def get_key_matrix(key): k = 0 for i in range(3): for j in range(3): keyMatrix[i][j] = ord(key[k]) % 65 k += 1 def encrypt(messageVector): for i in range(3): for j in range(1): cipherMatrix[i][j] = 0 for x in range(3): cipherMatrix[i][j] += keyMatrix[i][x] * messageVector[x][j] cipherMatrix[i][j] = cipherMatrix[i][j] % 26 def hill_cipher(message, key): get_key_matrix(key) for i in range(3): messageVector[i][0] = ord(message[i]) % 65 encrypt(messageVector) cipher_text = [] for i in range(3): CipherText.append(chr(cipherMatrix[i][0] + 65)) print('Ciphertext: ', ''.join(CipherText)) def main(): message = 'ACT' key = 'GYBNQKURP' hill_cipher(message, key) if __name__ == '__main__': main()
def weakNumbers(n): all_factors = [count_factors(num) for num in range(1, n + 1)] weaknesses = [] for num, num_factors in enumerate(all_factors, 1): weakness = 0 for factor in all_factors[:num]: if factor > num_factors: weakness += 1 weaknesses.append(weakness) weakest = max(weaknesses) return [weakest, weaknesses.count(weakest)] def count_factors(n): factors = 0 for i in range(1, n + 1): if n % i == 0: factors += 1 return factors print(weakNumbers(500))
def weak_numbers(n): all_factors = [count_factors(num) for num in range(1, n + 1)] weaknesses = [] for (num, num_factors) in enumerate(all_factors, 1): weakness = 0 for factor in all_factors[:num]: if factor > num_factors: weakness += 1 weaknesses.append(weakness) weakest = max(weaknesses) return [weakest, weaknesses.count(weakest)] def count_factors(n): factors = 0 for i in range(1, n + 1): if n % i == 0: factors += 1 return factors print(weak_numbers(500))
##Config file for lifetime_spyrelet.py in spyre/spyre/spyrelet/ # Device List devices = { 'analyzer':[ 'lantz.drivers.spectrum.MS2721B', ['USB0::0x0B5B::0xFFF9::1118010_150_11::INSTR'], {} ], 'source':[ 'lantz.drivers.mwsource.SynthNVPro', ['ASRL16::INSTR'], {} ] } # Experiment List spyrelets = { 'freqSweep':[ 'spyre.spyrelets.freqSweep_spyrelet_test.Sweep', {'analyzer': 'analyzer','source': 'source'}, {} ], }
devices = {'analyzer': ['lantz.drivers.spectrum.MS2721B', ['USB0::0x0B5B::0xFFF9::1118010_150_11::INSTR'], {}], 'source': ['lantz.drivers.mwsource.SynthNVPro', ['ASRL16::INSTR'], {}]} spyrelets = {'freqSweep': ['spyre.spyrelets.freqSweep_spyrelet_test.Sweep', {'analyzer': 'analyzer', 'source': 'source'}, {}]}
class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return f'({self.x}, {self.y})'
class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return f'({self.x}, {self.y})'
class BST(): def __init__(self,data): self.key = data self.lch = None self.rch = None def Print(self): if self is None or self.key is None: return if self.lch: self.lch.Print() if self.rch: self.rch.Print() print(self.key,end=" ") def insert(self,data): if self.key is None: self.key = data if data <= self.key: if self.lch: self.lch.insert(data) else: self.lch = BST(data) if data > self.key: if self.rch: self.rch.insert(data) else: self.rch = BST(data) def countNodes(root,low,high): global count temp = list(range(low,high+1)) if root is None: return 0 if root: if root.key in temp: count+=1 if root.lch: countNodes(root.lch,low,high) if root.rch: countNodes(root.rch,low,high) count = 0 root = BST(15) root.insert(10) root.insert(25) root.insert(8) root.insert(12) root.insert(20) root.insert(30) root.insert(0) root.insert(-1) root.insert(21) root.insert(22) countNodes(root,-1,10) print(count) root.Print()
class Bst: def __init__(self, data): self.key = data self.lch = None self.rch = None def print(self): if self is None or self.key is None: return if self.lch: self.lch.Print() if self.rch: self.rch.Print() print(self.key, end=' ') def insert(self, data): if self.key is None: self.key = data if data <= self.key: if self.lch: self.lch.insert(data) else: self.lch = bst(data) if data > self.key: if self.rch: self.rch.insert(data) else: self.rch = bst(data) def count_nodes(root, low, high): global count temp = list(range(low, high + 1)) if root is None: return 0 if root: if root.key in temp: count += 1 if root.lch: count_nodes(root.lch, low, high) if root.rch: count_nodes(root.rch, low, high) count = 0 root = bst(15) root.insert(10) root.insert(25) root.insert(8) root.insert(12) root.insert(20) root.insert(30) root.insert(0) root.insert(-1) root.insert(21) root.insert(22) count_nodes(root, -1, 10) print(count) root.Print()
i = 0 while True: print(i) i+=1
i = 0 while True: print(i) i += 1
def bbox_normalize(bbox, image_size): return tuple(v / image_size[0] if i % 2 == 0 else v / image_size[1] for i, v in enumerate(bbox)) def bbox_denormalize(bbox, image_size): return tuple(v * image_size[0] if i % 2 == 0 else v * image_size[1] for i, v in enumerate(bbox))
def bbox_normalize(bbox, image_size): return tuple((v / image_size[0] if i % 2 == 0 else v / image_size[1] for (i, v) in enumerate(bbox))) def bbox_denormalize(bbox, image_size): return tuple((v * image_size[0] if i % 2 == 0 else v * image_size[1] for (i, v) in enumerate(bbox)))
def calculateStats(numbers): if len(numbers) == 0: stat_dict = {"avg": "nan", "max": "nan", "min": "nan"} else: max_value = max(numbers) min_value = min(numbers) avg_value = round(sum(numbers) / len(numbers), 3) stat_dict = {"avg": avg_value, "max": max_value, "min": min_value} return stat_dict
def calculate_stats(numbers): if len(numbers) == 0: stat_dict = {'avg': 'nan', 'max': 'nan', 'min': 'nan'} else: max_value = max(numbers) min_value = min(numbers) avg_value = round(sum(numbers) / len(numbers), 3) stat_dict = {'avg': avg_value, 'max': max_value, 'min': min_value} return stat_dict
data = ( None, # 0x00 None, # 0x01 None, # 0x02 None, # 0x03 None, # 0x04 'B', # 0x05 'P', # 0x06 'M', # 0x07 'F', # 0x08 'D', # 0x09 'T', # 0x0a 'N', # 0x0b 'L', # 0x0c 'G', # 0x0d 'K', # 0x0e 'H', # 0x0f 'J', # 0x10 'Q', # 0x11 'X', # 0x12 'ZH', # 0x13 'CH', # 0x14 'SH', # 0x15 'R', # 0x16 'Z', # 0x17 'C', # 0x18 'S', # 0x19 'A', # 0x1a 'O', # 0x1b 'E', # 0x1c 'EH', # 0x1d 'AI', # 0x1e 'EI', # 0x1f 'AU', # 0x20 'OU', # 0x21 'AN', # 0x22 'EN', # 0x23 'ANG', # 0x24 'ENG', # 0x25 'ER', # 0x26 'I', # 0x27 'U', # 0x28 'IU', # 0x29 'V', # 0x2a 'NG', # 0x2b 'GN', # 0x2c None, # 0x2d None, # 0x2e None, # 0x2f None, # 0x30 'g', # 0x31 'gg', # 0x32 'gs', # 0x33 'n', # 0x34 'nj', # 0x35 'nh', # 0x36 'd', # 0x37 'dd', # 0x38 'r', # 0x39 'lg', # 0x3a 'lm', # 0x3b 'lb', # 0x3c 'ls', # 0x3d 'lt', # 0x3e 'lp', # 0x3f 'rh', # 0x40 'm', # 0x41 'b', # 0x42 'bb', # 0x43 'bs', # 0x44 's', # 0x45 'ss', # 0x46 '', # 0x47 'j', # 0x48 'jj', # 0x49 'c', # 0x4a 'k', # 0x4b 't', # 0x4c 'p', # 0x4d 'h', # 0x4e 'a', # 0x4f 'ae', # 0x50 'ya', # 0x51 'yae', # 0x52 'eo', # 0x53 'e', # 0x54 'yeo', # 0x55 'ye', # 0x56 'o', # 0x57 'wa', # 0x58 'wae', # 0x59 'oe', # 0x5a 'yo', # 0x5b 'u', # 0x5c 'weo', # 0x5d 'we', # 0x5e 'wi', # 0x5f 'yu', # 0x60 'eu', # 0x61 'yi', # 0x62 'i', # 0x63 '', # 0x64 'nn', # 0x65 'nd', # 0x66 'ns', # 0x67 'nZ', # 0x68 'lgs', # 0x69 'ld', # 0x6a 'lbs', # 0x6b 'lZ', # 0x6c 'lQ', # 0x6d 'mb', # 0x6e 'ms', # 0x6f 'mZ', # 0x70 'mN', # 0x71 'bg', # 0x72 '', # 0x73 'bsg', # 0x74 'bst', # 0x75 'bj', # 0x76 'bt', # 0x77 'bN', # 0x78 'bbN', # 0x79 'sg', # 0x7a 'sn', # 0x7b 'sd', # 0x7c 'sb', # 0x7d 'sj', # 0x7e 'Z', # 0x7f '', # 0x80 'N', # 0x81 'Ns', # 0x82 'NZ', # 0x83 'pN', # 0x84 'hh', # 0x85 'Q', # 0x86 'yo-ya', # 0x87 'yo-yae', # 0x88 'yo-i', # 0x89 'yu-yeo', # 0x8a 'yu-ye', # 0x8b 'yu-i', # 0x8c 'U', # 0x8d 'U-i', # 0x8e None, # 0x8f '', # 0x90 '', # 0x91 '', # 0x92 '', # 0x93 '', # 0x94 '', # 0x95 '', # 0x96 '', # 0x97 '', # 0x98 '', # 0x99 '', # 0x9a '', # 0x9b '', # 0x9c '', # 0x9d '', # 0x9e '', # 0x9f 'BU', # 0xa0 'ZI', # 0xa1 'JI', # 0xa2 'GU', # 0xa3 'EE', # 0xa4 'ENN', # 0xa5 'OO', # 0xa6 'ONN', # 0xa7 'IR', # 0xa8 'ANN', # 0xa9 'INN', # 0xaa 'UNN', # 0xab 'IM', # 0xac 'NGG', # 0xad 'AINN', # 0xae 'AUNN', # 0xaf 'AM', # 0xb0 'OM', # 0xb1 'ONG', # 0xb2 'INNN', # 0xb3 'P', # 0xb4 'T', # 0xb5 'K', # 0xb6 'H', # 0xb7 None, # 0xb8 None, # 0xb9 None, # 0xba None, # 0xbb None, # 0xbc None, # 0xbd None, # 0xbe None, # 0xbf None, # 0xc0 None, # 0xc1 None, # 0xc2 None, # 0xc3 None, # 0xc4 None, # 0xc5 None, # 0xc6 None, # 0xc7 None, # 0xc8 None, # 0xc9 None, # 0xca None, # 0xcb None, # 0xcc None, # 0xcd None, # 0xce None, # 0xcf None, # 0xd0 None, # 0xd1 None, # 0xd2 None, # 0xd3 None, # 0xd4 None, # 0xd5 None, # 0xd6 None, # 0xd7 None, # 0xd8 None, # 0xd9 None, # 0xda None, # 0xdb None, # 0xdc None, # 0xdd None, # 0xde None, # 0xdf None, # 0xe0 None, # 0xe1 None, # 0xe2 None, # 0xe3 None, # 0xe4 None, # 0xe5 None, # 0xe6 None, # 0xe7 None, # 0xe8 None, # 0xe9 None, # 0xea None, # 0xeb None, # 0xec None, # 0xed None, # 0xee None, # 0xef None, # 0xf0 None, # 0xf1 None, # 0xf2 None, # 0xf3 None, # 0xf4 None, # 0xf5 None, # 0xf6 None, # 0xf7 None, # 0xf8 None, # 0xf9 None, # 0xfa None, # 0xfb None, # 0xfc None, # 0xfd None, # 0xfe )
data = (None, None, None, None, None, 'B', 'P', 'M', 'F', 'D', 'T', 'N', 'L', 'G', 'K', 'H', 'J', 'Q', 'X', 'ZH', 'CH', 'SH', 'R', 'Z', 'C', 'S', 'A', 'O', 'E', 'EH', 'AI', 'EI', 'AU', 'OU', 'AN', 'EN', 'ANG', 'ENG', 'ER', 'I', 'U', 'IU', 'V', 'NG', 'GN', None, None, None, None, 'g', 'gg', 'gs', 'n', 'nj', 'nh', 'd', 'dd', 'r', 'lg', 'lm', 'lb', 'ls', 'lt', 'lp', 'rh', 'm', 'b', 'bb', 'bs', 's', 'ss', '', 'j', 'jj', 'c', 'k', 't', 'p', 'h', 'a', 'ae', 'ya', 'yae', 'eo', 'e', 'yeo', 'ye', 'o', 'wa', 'wae', 'oe', 'yo', 'u', 'weo', 'we', 'wi', 'yu', 'eu', 'yi', 'i', '', 'nn', 'nd', 'ns', 'nZ', 'lgs', 'ld', 'lbs', 'lZ', 'lQ', 'mb', 'ms', 'mZ', 'mN', 'bg', '', 'bsg', 'bst', 'bj', 'bt', 'bN', 'bbN', 'sg', 'sn', 'sd', 'sb', 'sj', 'Z', '', 'N', 'Ns', 'NZ', 'pN', 'hh', 'Q', 'yo-ya', 'yo-yae', 'yo-i', 'yu-yeo', 'yu-ye', 'yu-i', 'U', 'U-i', None, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'BU', 'ZI', 'JI', 'GU', 'EE', 'ENN', 'OO', 'ONN', 'IR', 'ANN', 'INN', 'UNN', 'IM', 'NGG', 'AINN', 'AUNN', 'AM', 'OM', 'ONG', 'INNN', 'P', 'T', 'K', 'H', None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None)
jibunno = "red" kimino = "green" kari = jibunno jibunno = kimino kimino = kari print(jibunno, kimino)
jibunno = 'red' kimino = 'green' kari = jibunno jibunno = kimino kimino = kari print(jibunno, kimino)
class LinkedStack: class _Node: __slots__ = '_element', '_next' def __init__(self, element, next): self._element = element self._next = next def __init__(self): self._head = None self._size = 0 def __len__(self): return self._size def is_empty(self): return self._size == 0 def push(self, e): self._head = self._Node(e, self._head) self._size += 1 def top(self): if self.is_empty(): raise Empty('Stack is empty') return self._head._element def pop(self): if self.is_empty(): raise Empty('Stack is empty') answer = self._head._element self._head = self._head._next self._size -= 1 return answer
class Linkedstack: class _Node: __slots__ = ('_element', '_next') def __init__(self, element, next): self._element = element self._next = next def __init__(self): self._head = None self._size = 0 def __len__(self): return self._size def is_empty(self): return self._size == 0 def push(self, e): self._head = self._Node(e, self._head) self._size += 1 def top(self): if self.is_empty(): raise empty('Stack is empty') return self._head._element def pop(self): if self.is_empty(): raise empty('Stack is empty') answer = self._head._element self._head = self._head._next self._size -= 1 return answer
#!/usr/bin/env python # -*- coding: utf-8 -*- dice = [] for d1 in range(1, 7): for d2 in range(1, 7): dice.append((d1, d2)) n = 0 comb = [] for d1, d2 in dice: if d1 + d2 == 7: n += 1 comb.append((d1,d2)) print('%d combinations results in the sum 7' % n) print(comb)
dice = [] for d1 in range(1, 7): for d2 in range(1, 7): dice.append((d1, d2)) n = 0 comb = [] for (d1, d2) in dice: if d1 + d2 == 7: n += 1 comb.append((d1, d2)) print('%d combinations results in the sum 7' % n) print(comb)
def selectionsort(L): n = len(L) for i in range(n-1): max_index=0 for index in range(n - i): if L[index] > L[max_index]: max_index = index L[n-i-1], L[max_index] = L[max_index], L[n-i-1]
def selectionsort(L): n = len(L) for i in range(n - 1): max_index = 0 for index in range(n - i): if L[index] > L[max_index]: max_index = index (L[n - i - 1], L[max_index]) = (L[max_index], L[n - i - 1])
class Constants: WINDOW_BACKGROUND_RGB: str = '#393939' # this needs to be the same as in windowstyle.py GREY_180_RGB: str = '#b4b3b3' # Text color GREY_127_RGB: str = '#7f7f7f' # 127, 127, 127 disabled GREY_90_RGB: str = '#5a5a5a' # 90, 90, 90 midlight GREY_5C_RGB: str = '#026fb2' # button GREY_80_RGB: str = '#505050' # 80, 80, 80 # Visited link GREY_66_RGB: str = '#424242' # 66, 66, 66 alternatebase GREY_53_RGB: str = '#353535' # 53, 53, 53 window GREY_42_RGB: str = '#2a2a2a' # 42, 42, 42 base GREY_35_RGB: str = '#232323' # 35, 35, 35 dark GREY_20_RGB: str = '#141414' # 20, 20, 20 shadow HIGHLIGHT_RGB: str = '#2a82da' # 42, 130, 218 highlight HYPERLINK_RGB: str = '#2a82da' # 42, 130, 218 hyperlink
class Constants: window_background_rgb: str = '#393939' grey_180_rgb: str = '#b4b3b3' grey_127_rgb: str = '#7f7f7f' grey_90_rgb: str = '#5a5a5a' grey_5_c_rgb: str = '#026fb2' grey_80_rgb: str = '#505050' grey_66_rgb: str = '#424242' grey_53_rgb: str = '#353535' grey_42_rgb: str = '#2a2a2a' grey_35_rgb: str = '#232323' grey_20_rgb: str = '#141414' highlight_rgb: str = '#2a82da' hyperlink_rgb: str = '#2a82da'
# ************************ compare_object_with_info.py ****************************** # # # # compare_object_with_info.py - # # # # Description: # # # # This component, is able to compare any two object, nested and # # not nested, and gives a simple result == True or False and information. # # # # # # *********************************************************************************** # success_message = "Objects are equal!" def compare_objects_with_info(a, b, indention=''): if not isinstance(a, type(b)): return False elif isinstance(a, dict): return compare_dict_with_info(dict(sorted(a.items())), dict(sorted(b.items())), indention) elif isinstance(a, list) or isinstance(a, tuple): return compare_list_with_info(a, b, indention) else: comparison = (a == b) if not comparison: comparison = (False, f"{indention}mismatch between {a} != {b}") else: comparison = True, f"{a} and {b} are equal!" return comparison # *************** NESTED COMPLEX OBJECTS ******************** # def is_complex_with_info(item): return isinstance(item, dict) or isinstance(item, list) or isinstance(item, tuple) or isinstance(item, set) # dict nested in other objects def dict_in_dict_of_dicts_with_info(parent_key, elem, dict_of_elem, indention): for k, v in dict_of_elem.items(): if isinstance(elem, type(v)) and sorted(elem.keys()) == sorted(v.keys()) and parent_key == k: result = compare_objects_with_info(elem, v, f"{indention} ") if not result[0]: return result else: return True, success_message return False, f"Element {elem}, is not appear correctly in dict {dict_of_elem}" def dict_in_list_with_info(elem, list_of_elem, indention): collect_info = "" counter = 1 for j in range(len(list_of_elem)): if isinstance(elem, type(list_of_elem[j])): if sorted(elem.keys()) == sorted(list_of_elem[j].keys()): result, info = compare_objects_with_info(elem, list_of_elem[j], f"{indention} ") if result: return True, success_message else: collect_info += f"{indention}{counter} : {info}\n" counter += 1 else: info = f'Origin Element keys {sorted(elem.keys())} and current object keys {sorted(list_of_elem[j].keys())}' collect_info += f"{indention}{counter} : {info}\n" counter += 1 return False, f"Element {elem}, is not exist in list in the exact way.\n\n{indention}Reasons are : \n{collect_info}" # indices objects nested in other objects def list_in_dict_with_info(parent_key, elem, dict_of_elem, indention): for k, v in dict_of_elem.items(): if parent_key == k: if type(elem) != type(v): return False, f"{indention}Elements {elem} and {v}, refer to the same key ``{parent_key}``, with diff types" elif not compare_objects_with_info(elem, v)[0]: return compare_objects_with_info(elem, v, f"{indention} ") else: return True, success_message return False, f"Element {elem}, is not appear correctly in dict {dict_of_elem}." def list_and_tuple_within_list_with_info(elem, list_of_elem, indention): collect_info = "" counter = 1 for j in range(len(list_of_elem)): if isinstance(elem, type(list_of_elem[j])): result, info = compare_objects_with_info(elem, list_of_elem[j], f"{indention} ") if result: return True, success_message else: collect_info += f"{indention}{counter} : {info}\n" counter += 1 return False, f"Element {elem} is not exist in list in the exact way.\n\n{indention}Reasons are : \n{collect_info}" def properties_do_not_fit_with_info(a, b, indention): if len(a) != len(b): return False, f"{indention}{a} length is {len(a)} and {b} length is {len(b)}" if a.keys() != b.keys(): return False, f"{indention}{a} keys are {list(a.keys())} and {b} keys is {list(b.keys())}" return True, success_message def compare_dict_with_info(a, b, indention): result = properties_do_not_fit_with_info(a, b, indention) if not result[0]: return result for key, value in a.items(): if isinstance(value, dict): result = dict_in_dict_of_dicts_with_info(key, value, b, indention) if not result[0]: return result elif is_complex_with_info(value): result = list_in_dict_with_info(key, value, b, indention) if not result[0]: return result else: if value != b[key]: return False, f"Mismatch between values for key ``{key}``, {value} != {b[key]}." return True, success_message def compare_list_with_info(a, b, indention): if len(a) != len(b): return False, f"Mismatch - length of list {a} is {len(a)} and {b} is {len(b)}" for i in range(len(a)): if isinstance(a[i], dict): result = dict_in_list_with_info(a[i], b, f"{indention}") if not result[0]: return result elif is_complex_with_info(a[i]): result = list_and_tuple_within_list_with_info(a[i], b, f"{indention}") if not result[0]: return result else: if not a[i] in b: return False, f"Element {a[i]} is in {a} and not in {b}" return True, success_message
success_message = 'Objects are equal!' def compare_objects_with_info(a, b, indention=''): if not isinstance(a, type(b)): return False elif isinstance(a, dict): return compare_dict_with_info(dict(sorted(a.items())), dict(sorted(b.items())), indention) elif isinstance(a, list) or isinstance(a, tuple): return compare_list_with_info(a, b, indention) else: comparison = a == b if not comparison: comparison = (False, f'{indention}mismatch between {a} != {b}') else: comparison = (True, f'{a} and {b} are equal!') return comparison def is_complex_with_info(item): return isinstance(item, dict) or isinstance(item, list) or isinstance(item, tuple) or isinstance(item, set) def dict_in_dict_of_dicts_with_info(parent_key, elem, dict_of_elem, indention): for (k, v) in dict_of_elem.items(): if isinstance(elem, type(v)) and sorted(elem.keys()) == sorted(v.keys()) and (parent_key == k): result = compare_objects_with_info(elem, v, f'{indention} ') if not result[0]: return result else: return (True, success_message) return (False, f'Element {elem}, is not appear correctly in dict {dict_of_elem}') def dict_in_list_with_info(elem, list_of_elem, indention): collect_info = '' counter = 1 for j in range(len(list_of_elem)): if isinstance(elem, type(list_of_elem[j])): if sorted(elem.keys()) == sorted(list_of_elem[j].keys()): (result, info) = compare_objects_with_info(elem, list_of_elem[j], f'{indention} ') if result: return (True, success_message) else: collect_info += f'{indention}{counter} : {info}\n' counter += 1 else: info = f'Origin Element keys {sorted(elem.keys())} and current object keys {sorted(list_of_elem[j].keys())}' collect_info += f'{indention}{counter} : {info}\n' counter += 1 return (False, f'Element {elem}, is not exist in list in the exact way.\n\n{indention}Reasons are : \n{collect_info}') def list_in_dict_with_info(parent_key, elem, dict_of_elem, indention): for (k, v) in dict_of_elem.items(): if parent_key == k: if type(elem) != type(v): return (False, f'{indention}Elements {elem} and {v}, refer to the same key ``{parent_key}``, with diff types') elif not compare_objects_with_info(elem, v)[0]: return compare_objects_with_info(elem, v, f'{indention} ') else: return (True, success_message) return (False, f'Element {elem}, is not appear correctly in dict {dict_of_elem}.') def list_and_tuple_within_list_with_info(elem, list_of_elem, indention): collect_info = '' counter = 1 for j in range(len(list_of_elem)): if isinstance(elem, type(list_of_elem[j])): (result, info) = compare_objects_with_info(elem, list_of_elem[j], f'{indention} ') if result: return (True, success_message) else: collect_info += f'{indention}{counter} : {info}\n' counter += 1 return (False, f'Element {elem} is not exist in list in the exact way.\n\n{indention}Reasons are : \n{collect_info}') def properties_do_not_fit_with_info(a, b, indention): if len(a) != len(b): return (False, f'{indention}{a} length is {len(a)} and {b} length is {len(b)}') if a.keys() != b.keys(): return (False, f'{indention}{a} keys are {list(a.keys())} and {b} keys is {list(b.keys())}') return (True, success_message) def compare_dict_with_info(a, b, indention): result = properties_do_not_fit_with_info(a, b, indention) if not result[0]: return result for (key, value) in a.items(): if isinstance(value, dict): result = dict_in_dict_of_dicts_with_info(key, value, b, indention) if not result[0]: return result elif is_complex_with_info(value): result = list_in_dict_with_info(key, value, b, indention) if not result[0]: return result elif value != b[key]: return (False, f'Mismatch between values for key ``{key}``, {value} != {b[key]}.') return (True, success_message) def compare_list_with_info(a, b, indention): if len(a) != len(b): return (False, f'Mismatch - length of list {a} is {len(a)} and {b} is {len(b)}') for i in range(len(a)): if isinstance(a[i], dict): result = dict_in_list_with_info(a[i], b, f'{indention}') if not result[0]: return result elif is_complex_with_info(a[i]): result = list_and_tuple_within_list_with_info(a[i], b, f'{indention}') if not result[0]: return result elif not a[i] in b: return (False, f'Element {a[i]} is in {a} and not in {b}') return (True, success_message)
n = int(input()) arr = [int(x) for x in input().split()] distinct = set(arr) print(len(distinct))
n = int(input()) arr = [int(x) for x in input().split()] distinct = set(arr) print(len(distinct))
class ZoneinfoError(Exception): pass class InvalidZoneinfoFile(ZoneinfoError): pass class InvalidTimezone(ZoneinfoError): def __init__(self, name): super(InvalidTimezone, self).__init__( 'Invalid timezone "{}"'.format(name) ) class InvalidPosixSpec(ZoneinfoError): def __init__(self, spec): super(InvalidPosixSpec, self).__init__( 'Invalid POSIX spec: {}'.format(spec) )
class Zoneinfoerror(Exception): pass class Invalidzoneinfofile(ZoneinfoError): pass class Invalidtimezone(ZoneinfoError): def __init__(self, name): super(InvalidTimezone, self).__init__('Invalid timezone "{}"'.format(name)) class Invalidposixspec(ZoneinfoError): def __init__(self, spec): super(InvalidPosixSpec, self).__init__('Invalid POSIX spec: {}'.format(spec))
class RenderQueue: def __init__(self, window): self.window = window self.queue = [] def render(self): if self.queue: self.queue[0]() def next(self): self.queue = self.queue[1:] def add(self, source): self.queue.append(source) def clear(self): self.queue = []
class Renderqueue: def __init__(self, window): self.window = window self.queue = [] def render(self): if self.queue: self.queue[0]() def next(self): self.queue = self.queue[1:] def add(self, source): self.queue.append(source) def clear(self): self.queue = []
def question(text, default=None, resp_type=None): if default is None: default_str = '' else: default_str = f'({default})' resp = input(f'{text}{default_str}: ') if not resp: return default if resp_type: return resp_type(resp) return resp
def question(text, default=None, resp_type=None): if default is None: default_str = '' else: default_str = f'({default})' resp = input(f'{text}{default_str}: ') if not resp: return default if resp_type: return resp_type(resp) return resp
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def __init__(self): self.arrVal = [] self.arrTmp = [] def isSymmetric(self,root): if root == None: return True num = 0 self.arrTmp.append(root) while (len(self.arrTmp) != 0): tempNode = self.arrTmp[0] del self.arrTmp[0] if tempNode == None: self.arrVal.append(None) self.arrTmp.append(None) self.arrTmp.append(None) else: self.arrVal.append(tempNode.val) self.arrTmp.append(tempNode.left) self.arrTmp.append(tempNode.right) if (len(self.arrVal) == pow(2,num)): num+=1 if not self.isHUI(self.arrVal): return False else: del self.arrVal[:] if (self.isNoneList(self.arrTmp)): return True else: continue print(self.arrVal) return True def isHUI(self,lst): i = 0 while (i < len(lst)-i-1): if lst[i] != lst[len(lst)-i-1]: return False i+=1 return True def isNoneList(self,lst): for i in self.arrTmp: if i != None: return False return True if __name__ == "__main__": solution = Solution() leftNode = TreeNode(2) rightNode = TreeNode(2) rootNode = TreeNode(1) rootNode.left = leftNode rootNode.right = rightNode print(solution.isSymmetric(rootNode))
class Treenode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def __init__(self): self.arrVal = [] self.arrTmp = [] def is_symmetric(self, root): if root == None: return True num = 0 self.arrTmp.append(root) while len(self.arrTmp) != 0: temp_node = self.arrTmp[0] del self.arrTmp[0] if tempNode == None: self.arrVal.append(None) self.arrTmp.append(None) self.arrTmp.append(None) else: self.arrVal.append(tempNode.val) self.arrTmp.append(tempNode.left) self.arrTmp.append(tempNode.right) if len(self.arrVal) == pow(2, num): num += 1 if not self.isHUI(self.arrVal): return False else: del self.arrVal[:] if self.isNoneList(self.arrTmp): return True else: continue print(self.arrVal) return True def is_hui(self, lst): i = 0 while i < len(lst) - i - 1: if lst[i] != lst[len(lst) - i - 1]: return False i += 1 return True def is_none_list(self, lst): for i in self.arrTmp: if i != None: return False return True if __name__ == '__main__': solution = solution() left_node = tree_node(2) right_node = tree_node(2) root_node = tree_node(1) rootNode.left = leftNode rootNode.right = rightNode print(solution.isSymmetric(rootNode))
a,b,n,w=list(map(int,input().split())) L = [] for i in range(1,n): if a*i + b*(n-i) == w: L.append(i) if len(L) == 1: print(L[0],n-L[0]) else: print(-1)
(a, b, n, w) = list(map(int, input().split())) l = [] for i in range(1, n): if a * i + b * (n - i) == w: L.append(i) if len(L) == 1: print(L[0], n - L[0]) else: print(-1)
#!/usr/bin/env python3 def is_terminal(battle_data) -> bool: return battle_data["ended"] def get_side_value(side) -> float: return sum(pokemon["hp"] / pokemon["maxhp"] for pokemon in side["pokemon"]) def get_heuristic_value(battle_data): sides = battle_data["sides"] return get_side_value(sides[1]) - get_side_value(sides[0]) def alpha_beta(env, battle, depth, alpha, beta, player_idx, last_move): client = env.client battle_id = battle["id"] battle_data = battle["data"] next_player_idx = (player_idx + 1) % 2 if depth == 0 or is_terminal(battle_data): return get_heuristic_value(battle_data), None best_move_idx = None if player_idx == 0: value = -float("inf") for move_idx in battle["actions"][1]: successor_value, _ = alpha_beta( env, battle, depth, alpha, beta, next_player_idx, env.get_move(move_idx) ) if successor_value > value: value = successor_value best_move_idx = move_idx alpha = max(alpha, value) if alpha >= beta: break return value, best_move_idx else: value = float("inf") for move_idx in battle["actions"][0]: successor = client.do_move(battle_id, env.get_move(move_idx), last_move) successor_value, _ = alpha_beta( env, successor, depth - 1, alpha, beta, next_player_idx, None ) if successor_value < value: value = successor_value best_move_idx = move_idx beta = min(beta, value) if alpha >= beta: break return value, best_move_idx def agent(env, depth=1): _, best_move_idx = alpha_beta( env, env.current_battle, depth, -float("inf"), float("inf"), 0, None ) return best_move_idx
def is_terminal(battle_data) -> bool: return battle_data['ended'] def get_side_value(side) -> float: return sum((pokemon['hp'] / pokemon['maxhp'] for pokemon in side['pokemon'])) def get_heuristic_value(battle_data): sides = battle_data['sides'] return get_side_value(sides[1]) - get_side_value(sides[0]) def alpha_beta(env, battle, depth, alpha, beta, player_idx, last_move): client = env.client battle_id = battle['id'] battle_data = battle['data'] next_player_idx = (player_idx + 1) % 2 if depth == 0 or is_terminal(battle_data): return (get_heuristic_value(battle_data), None) best_move_idx = None if player_idx == 0: value = -float('inf') for move_idx in battle['actions'][1]: (successor_value, _) = alpha_beta(env, battle, depth, alpha, beta, next_player_idx, env.get_move(move_idx)) if successor_value > value: value = successor_value best_move_idx = move_idx alpha = max(alpha, value) if alpha >= beta: break return (value, best_move_idx) else: value = float('inf') for move_idx in battle['actions'][0]: successor = client.do_move(battle_id, env.get_move(move_idx), last_move) (successor_value, _) = alpha_beta(env, successor, depth - 1, alpha, beta, next_player_idx, None) if successor_value < value: value = successor_value best_move_idx = move_idx beta = min(beta, value) if alpha >= beta: break return (value, best_move_idx) def agent(env, depth=1): (_, best_move_idx) = alpha_beta(env, env.current_battle, depth, -float('inf'), float('inf'), 0, None) return best_move_idx
class Cartes: couleur = ("bleu", "vert", "rouge", "jaune") valeur = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "+2", "inversion", "passer", "stop") def __init__(self, coul, val): self.valeur = val self.couleur = coul def validation(self, val, coul): if val > 0 or val < 14: raise Exception("La valeur est comprise entre 0 et 14") if coul > 0 or coul < 4: raise Exception("La couleur est comprise entre 0 et 3") def __str__(self): return str(Cartes.valeur[self.__valeur]) + " de " + (Cartes.couleur[self.__couleur]) def __getValeur(self): return self.__valeur def __setValeur(self, val): self.__valeur = val valeur = property(__getValeur, __setValeur) def __getCouleur(self): return self.__valeur def __setCouleur(self, val): self.__couleur = val couleur = property(__getCouleur, __setCouleur)
class Cartes: couleur = ('bleu', 'vert', 'rouge', 'jaune') valeur = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, '+2', 'inversion', 'passer', 'stop') def __init__(self, coul, val): self.valeur = val self.couleur = coul def validation(self, val, coul): if val > 0 or val < 14: raise exception('La valeur est comprise entre 0 et 14') if coul > 0 or coul < 4: raise exception('La couleur est comprise entre 0 et 3') def __str__(self): return str(Cartes.valeur[self.__valeur]) + ' de ' + Cartes.couleur[self.__couleur] def __get_valeur(self): return self.__valeur def __set_valeur(self, val): self.__valeur = val valeur = property(__getValeur, __setValeur) def __get_couleur(self): return self.__valeur def __set_couleur(self, val): self.__couleur = val couleur = property(__getCouleur, __setCouleur)
inputs = [1,2,3,2.5] weights1 = [0.2,0.8,-0.5,1.0] weights2 = [0.5,-0.91,0.26,-0.5] weights3 = [-0.26, -0.27, 0.17, 0.87] bias1 = 2 bias2 = 3 bias3 = 0.5 output = [inputs[0] * weights1[0] + inputs[1] * weights1[1] + inputs[2] * weights1[2] + inputs[3] * weights1[3] + bias1, inputs[0] * weights2[0] + inputs[1] * weights2[1] + inputs[2] * weights2[2] + inputs[3] * weights2[3] + bias2, inputs[0] * weights3[0] + inputs[1] * weights3[1] + inputs[2] * weights3[2] + inputs[3] * weights3[3] + bias3] print(output)
inputs = [1, 2, 3, 2.5] weights1 = [0.2, 0.8, -0.5, 1.0] weights2 = [0.5, -0.91, 0.26, -0.5] weights3 = [-0.26, -0.27, 0.17, 0.87] bias1 = 2 bias2 = 3 bias3 = 0.5 output = [inputs[0] * weights1[0] + inputs[1] * weights1[1] + inputs[2] * weights1[2] + inputs[3] * weights1[3] + bias1, inputs[0] * weights2[0] + inputs[1] * weights2[1] + inputs[2] * weights2[2] + inputs[3] * weights2[3] + bias2, inputs[0] * weights3[0] + inputs[1] * weights3[1] + inputs[2] * weights3[2] + inputs[3] * weights3[3] + bias3] print(output)
l1 = [1,2,3] l2 = [4,5,6] l3 = [1,2,3] # number of items in list print(f"number of items in l1 : {len(l1)}") # compare lists , == compare the data element wise print(l1 == l1) print(l1 == l3) print(l1 == l2)
l1 = [1, 2, 3] l2 = [4, 5, 6] l3 = [1, 2, 3] print(f'number of items in l1 : {len(l1)}') print(l1 == l1) print(l1 == l3) print(l1 == l2)
class CannotExploit(Exception): pass class CannotExplore(Exception): pass class NoSuchShellcode(Exception): pass
class Cannotexploit(Exception): pass class Cannotexplore(Exception): pass class Nosuchshellcode(Exception): pass
def soma(lista): if len(lista) == 0: return 0 else: return lista[0] +soma(lista[1:]) print(soma([1,2,3,4,5,6,7])) def fib(n): if n==0: return 0 elif n==1: return 1 else: return fib(n-1)+fib(n-2)
def soma(lista): if len(lista) == 0: return 0 else: return lista[0] + soma(lista[1:]) print(soma([1, 2, 3, 4, 5, 6, 7])) def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n - 1) + fib(n - 2)
# # from src/eulerian.c # # Eulerian to eulerianNumber # def eulerianNumber(n, k): if k == 0: return 1 if k < 0 or k >= n: return 0 return (k+1) * eulerianNumber(n-1,k) + (n-k) * eulerianNumber(n-1,k-1)
def eulerian_number(n, k): if k == 0: return 1 if k < 0 or k >= n: return 0 return (k + 1) * eulerian_number(n - 1, k) + (n - k) * eulerian_number(n - 1, k - 1)
# go_board.py class GoBoard: EMPTY = 0 WHITE = 1 BLACK = 2 def __init__( self, size = 0 ): self.size = size if size > 0: self.matrix = [ [ self.EMPTY for j in range( size ) ] for i in range( size ) ] def Serialize( self ): return { 'size' : self.size, 'matrix' : self.matrix } def Deserialize( self, data ): self.size = data[ 'size' ] self.matrix = data[ 'matrix' ] return self def __eq__( self, board ): for i in range( self.size ): for j in range( self.size ): if self.matrix[i][j] != board.matrix[i][j]: return False return True def AllLocationsOfState( self, state ): for i in range( self.size ): for j in range( self.size ): if self.matrix[i][j] == state: yield ( i, j ) def AdjacentLocations( self, location ): for offset in [ ( -1, 0 ), ( 1, 0 ), ( 0, -1 ), ( 0, 1 ) ]: adjacent_location = ( location[0] + offset[0], location[1] + offset[1] ) if adjacent_location[0] < 0 or adjacent_location[1] < 0: continue if adjacent_location[0] >= self.size or adjacent_location[1] >= self.size: continue yield adjacent_location def GetState( self, location ): return self.matrix[ location[0] ][ location[1] ] def SetState( self, location, state ): self.matrix[ location[0] ][ location[1] ] = state def AnalyzeGroups( self, for_who ): location_list = [ location for location in self.AllLocationsOfState( for_who ) ] group_list = [] while len( location_list ) > 0: location = location_list[0] group = { 'location_list' : [], 'liberties' : 0, 'liberty_location_list' : [] } queue = [ location ] while len( queue ) > 0: location = queue.pop() group[ 'location_list' ].append( location ) location_list.remove( location ) for adjacent_location in self.AdjacentLocations( location ): if adjacent_location in group[ 'location_list' ]: continue if adjacent_location in queue: continue if self.GetState( adjacent_location ) == for_who: queue.append( adjacent_location ) if for_who != self.EMPTY: for location in group[ 'location_list' ]: for adjacent_location in self.AdjacentLocations( location ): if self.GetState( adjacent_location ) == self.EMPTY: if not adjacent_location in group[ 'liberty_location_list' ]: group[ 'liberties' ] += 1 group[ 'liberty_location_list' ].append( adjacent_location ) else: del group[ 'liberties' ] del group[ 'liberty_location_list' ] group_list.append( group ) return group_list def CalculateTerritory( self ): territory = { self.WHITE : 0, self.BLACK : 0, } group_list = self.AnalyzeGroups( self.EMPTY ) for group in group_list: location_list = group[ 'location_list' ] touch_map = { self.WHITE : set(), self.BLACK : set(), } for location in location_list: for adjacent_location in self.AdjacentLocations( location ): state = self.GetState( adjacent_location ) if state != self.EMPTY: touch_map[ state ].add( adjacent_location ) white_touch_count = len( touch_map[ self.WHITE ] ) black_touch_count = len( touch_map[ self.BLACK ] ) group[ 'owner' ] = None if white_touch_count > 0 and black_touch_count == 0: group[ 'owner' ] = self.WHITE elif black_touch_count > 0 and white_touch_count == 0: group[ 'owner' ] = self.BLACK else: pass # No one owns the territory. owner = group[ 'owner' ] if owner: territory[ owner ] += len( location_list ) return territory, group_list def Clone( self ): clone = GoBoard( self.size ) for i in range( self.size ): for j in range( self.size ): clone.matrix[i][j] = self.matrix[i][j] return clone def __str__( self ): board_string = '' for i in range( self.size ): for j in range( self.size ): stone = self.matrix[i][j] if stone == self.EMPTY: stone = ' ' elif stone == self.WHITE: stone = 'O' elif stone == self.BLACK: stone = '#' else: stone = '?' board_string += '[' + stone + ']' if j < self.size - 1: board_string += '--' board_string += ' %02d\n' % i if i < self.size - 1: board_string += ' | ' * self.size + '\n' else: for j in range( self.size ): board_string += ' %02d ' % j board_string += '\n' return board_string
class Goboard: empty = 0 white = 1 black = 2 def __init__(self, size=0): self.size = size if size > 0: self.matrix = [[self.EMPTY for j in range(size)] for i in range(size)] def serialize(self): return {'size': self.size, 'matrix': self.matrix} def deserialize(self, data): self.size = data['size'] self.matrix = data['matrix'] return self def __eq__(self, board): for i in range(self.size): for j in range(self.size): if self.matrix[i][j] != board.matrix[i][j]: return False return True def all_locations_of_state(self, state): for i in range(self.size): for j in range(self.size): if self.matrix[i][j] == state: yield (i, j) def adjacent_locations(self, location): for offset in [(-1, 0), (1, 0), (0, -1), (0, 1)]: adjacent_location = (location[0] + offset[0], location[1] + offset[1]) if adjacent_location[0] < 0 or adjacent_location[1] < 0: continue if adjacent_location[0] >= self.size or adjacent_location[1] >= self.size: continue yield adjacent_location def get_state(self, location): return self.matrix[location[0]][location[1]] def set_state(self, location, state): self.matrix[location[0]][location[1]] = state def analyze_groups(self, for_who): location_list = [location for location in self.AllLocationsOfState(for_who)] group_list = [] while len(location_list) > 0: location = location_list[0] group = {'location_list': [], 'liberties': 0, 'liberty_location_list': []} queue = [location] while len(queue) > 0: location = queue.pop() group['location_list'].append(location) location_list.remove(location) for adjacent_location in self.AdjacentLocations(location): if adjacent_location in group['location_list']: continue if adjacent_location in queue: continue if self.GetState(adjacent_location) == for_who: queue.append(adjacent_location) if for_who != self.EMPTY: for location in group['location_list']: for adjacent_location in self.AdjacentLocations(location): if self.GetState(adjacent_location) == self.EMPTY: if not adjacent_location in group['liberty_location_list']: group['liberties'] += 1 group['liberty_location_list'].append(adjacent_location) else: del group['liberties'] del group['liberty_location_list'] group_list.append(group) return group_list def calculate_territory(self): territory = {self.WHITE: 0, self.BLACK: 0} group_list = self.AnalyzeGroups(self.EMPTY) for group in group_list: location_list = group['location_list'] touch_map = {self.WHITE: set(), self.BLACK: set()} for location in location_list: for adjacent_location in self.AdjacentLocations(location): state = self.GetState(adjacent_location) if state != self.EMPTY: touch_map[state].add(adjacent_location) white_touch_count = len(touch_map[self.WHITE]) black_touch_count = len(touch_map[self.BLACK]) group['owner'] = None if white_touch_count > 0 and black_touch_count == 0: group['owner'] = self.WHITE elif black_touch_count > 0 and white_touch_count == 0: group['owner'] = self.BLACK else: pass owner = group['owner'] if owner: territory[owner] += len(location_list) return (territory, group_list) def clone(self): clone = go_board(self.size) for i in range(self.size): for j in range(self.size): clone.matrix[i][j] = self.matrix[i][j] return clone def __str__(self): board_string = '' for i in range(self.size): for j in range(self.size): stone = self.matrix[i][j] if stone == self.EMPTY: stone = ' ' elif stone == self.WHITE: stone = 'O' elif stone == self.BLACK: stone = '#' else: stone = '?' board_string += '[' + stone + ']' if j < self.size - 1: board_string += '--' board_string += ' %02d\n' % i if i < self.size - 1: board_string += ' | ' * self.size + '\n' else: for j in range(self.size): board_string += ' %02d ' % j board_string += '\n' return board_string
class QuoteInfo: def __init__(self): self.symbol = str() self.exchange = str() self.date = None self.time = None self.local_time = None self.price = float() self.volume = int() self.changepct = float() def __repr__(self): d = [] d.append(self.symbol+',') d.append(self.exchange+',') d.append(str(self.time)+',') d.append(str(self.price)+',') d.append(str(self.volume)+',') d.append(str(self.changepct)+'%,') return str().join(d) class QuoteArray: def __init__(self): self.symbol = str() self.exchange = str() self.date = None self.time_arr = [] self.price_arr = [] self.volume_arr = [] def append(self,q): self.symbol = q.symbol self.exchange = q.exchange self.date = q.date self.price_arr.append(q.price) self.time_arr.append(q.time) self.volume_arr.append(q.volume) class MarketDepth: def __init__(self): self.symbol = str() self.exchange = str() self.date = None self.time = None self.local_time = None self.bid_q = [] self.bid_qty_q = [] self.ask_q = [] self.ask_qty_q = [] def __repr__(self): d = [] d.append(self.symbol+',') d.append(self.exchange+',') d.append(str(self.time)+',') for bid in self.bid_q: d.append(str(bid)+',') for bid_qty in self.bid_qty_q: d.append(str(bid_qty)+',') for ask in self.ask_q: d.append(str(ask)+',') for ask_qty in self.ask_qty_q: d.append(str(ask_qty)+',') return str().join(d) class MarketDepthArray: def __init__(self): self.symbol = str() self.exchange = str() self.date = None self.time_arr = [] self.bid_q_arr = [] self.bid_qty_q_arr = [] self.ask_q_arr = [] self.ask_qty_q_arr = []
class Quoteinfo: def __init__(self): self.symbol = str() self.exchange = str() self.date = None self.time = None self.local_time = None self.price = float() self.volume = int() self.changepct = float() def __repr__(self): d = [] d.append(self.symbol + ',') d.append(self.exchange + ',') d.append(str(self.time) + ',') d.append(str(self.price) + ',') d.append(str(self.volume) + ',') d.append(str(self.changepct) + '%,') return str().join(d) class Quotearray: def __init__(self): self.symbol = str() self.exchange = str() self.date = None self.time_arr = [] self.price_arr = [] self.volume_arr = [] def append(self, q): self.symbol = q.symbol self.exchange = q.exchange self.date = q.date self.price_arr.append(q.price) self.time_arr.append(q.time) self.volume_arr.append(q.volume) class Marketdepth: def __init__(self): self.symbol = str() self.exchange = str() self.date = None self.time = None self.local_time = None self.bid_q = [] self.bid_qty_q = [] self.ask_q = [] self.ask_qty_q = [] def __repr__(self): d = [] d.append(self.symbol + ',') d.append(self.exchange + ',') d.append(str(self.time) + ',') for bid in self.bid_q: d.append(str(bid) + ',') for bid_qty in self.bid_qty_q: d.append(str(bid_qty) + ',') for ask in self.ask_q: d.append(str(ask) + ',') for ask_qty in self.ask_qty_q: d.append(str(ask_qty) + ',') return str().join(d) class Marketdeptharray: def __init__(self): self.symbol = str() self.exchange = str() self.date = None self.time_arr = [] self.bid_q_arr = [] self.bid_qty_q_arr = [] self.ask_q_arr = [] self.ask_qty_q_arr = []
class City: def __init__(self, name, lat, lon): self.name=name; self.lat=lat; self.lon=lon;
class City: def __init__(self, name, lat, lon): self.name = name self.lat = lat self.lon = lon
class InvalidInterface(Exception): pass class EmptyInterface(InvalidInterface): pass class NotAFileError(Exception): pass class MissingFileError(Exception): pass
class Invalidinterface(Exception): pass class Emptyinterface(InvalidInterface): pass class Notafileerror(Exception): pass class Missingfileerror(Exception): pass
#! /usr/bin/env python3 a=[1, 4, 3, 53, 2] print("list :", a) print(a.pop()) #poping last element print("pop element from list :", a) a.append(21) #adding element in list print("adding element in list :", a)
a = [1, 4, 3, 53, 2] print('list :', a) print(a.pop()) print('pop element from list :', a) a.append(21) print('adding element in list :', a)
# Distinct powers def koliko_potenc(): sez = [] for a in range(2, 101): for b in range(2, 101): sez.append(a ** b) return sez def izloci_iste(sez): podvojeni = 0 for i in range(len(sez)): if sez[i] in sez[:i] : podvojeni += 1 return len(sez) - podvojeni print(izloci_iste(koliko_potenc()))
def koliko_potenc(): sez = [] for a in range(2, 101): for b in range(2, 101): sez.append(a ** b) return sez def izloci_iste(sez): podvojeni = 0 for i in range(len(sez)): if sez[i] in sez[:i]: podvojeni += 1 return len(sez) - podvojeni print(izloci_iste(koliko_potenc()))
# MIT 6.006 Introduction to Algorithms, Spring 2020 # see: https://www.youtube.com/watch?v=r4-cftqTcdI&list=PLUl4u3cNGP63EdVPNLG3ToM6LaEUuStEY&index=42 def max_score_prefix(in_list: list): dp = [0] * (len(in_list) + 1) in_list.insert(0, 1) for i in range(1, len(in_list)): dp[i - 1] = max(dp[i - 2], dp[i - 2] + in_list[i], dp[i - 3] + in_list[i] * in_list[i - 1]) print(dp[-2]) def max_score_suffix(in_list: list): dp = [0] * (len(in_list) + 2) in_list.append(1) for i in reversed(range(len(in_list) - 1)): dp[i] = max(dp[i + 1], dp[i + 1] + in_list[i], dp[i + 2] + in_list[i] * in_list[i + 1]) print(dp[0]) if __name__ == '__main__': bowling_pins = [1, 1, 9, 9, 2, -5, -5] max_score_suffix(bowling_pins)
def max_score_prefix(in_list: list): dp = [0] * (len(in_list) + 1) in_list.insert(0, 1) for i in range(1, len(in_list)): dp[i - 1] = max(dp[i - 2], dp[i - 2] + in_list[i], dp[i - 3] + in_list[i] * in_list[i - 1]) print(dp[-2]) def max_score_suffix(in_list: list): dp = [0] * (len(in_list) + 2) in_list.append(1) for i in reversed(range(len(in_list) - 1)): dp[i] = max(dp[i + 1], dp[i + 1] + in_list[i], dp[i + 2] + in_list[i] * in_list[i + 1]) print(dp[0]) if __name__ == '__main__': bowling_pins = [1, 1, 9, 9, 2, -5, -5] max_score_suffix(bowling_pins)
def gen_perms_helper(array, current, subsets, index): if index >= len(array): subsets.append(current) return gen_perms_helper(array, current.copy(), subsets, index + 1) current.append(array[index]) gen_perms_helper(array, current.copy(), subsets, index + 1) def gen_perms(array): subsets = [] gen_perms_helper(array, [], subsets, 0) return subsets print(gen_perms([1, 2, 3]))
def gen_perms_helper(array, current, subsets, index): if index >= len(array): subsets.append(current) return gen_perms_helper(array, current.copy(), subsets, index + 1) current.append(array[index]) gen_perms_helper(array, current.copy(), subsets, index + 1) def gen_perms(array): subsets = [] gen_perms_helper(array, [], subsets, 0) return subsets print(gen_perms([1, 2, 3]))
class WireMap: def __init__(self): self.wire_map = {} self.x = 0 self.y = 0 self.step_counter = 0 def move(self, steps, x_dir, y_dir): while steps > 0: self.x += x_dir self.y += y_dir self.step_counter += 1 self.wire_map[(self.x, self.y)] = self.step_counter steps -= 1 def move_up(self, steps): return self.move(steps, 0, -1) def move_down(self, steps): return self.move(steps, 0, 1) def move_left(self, steps): return self.move(steps, -1, 0) def move_right(self, steps): return self.move(steps, 1, 0) def mark_wires(self, movements): for command in movements: direction = command[0] s = int(command[1:]) if direction == "R": self.move_right(s) elif direction == "L": self.move_left(s) elif direction == "U": self.move_up(s) else: self.move_down(s) maps = [line.strip().split(",") for line in open("Day3.txt")] map1 = WireMap() map1.mark_wires(maps[0]) map2 = WireMap() map2.mark_wires(maps[1]) keys1 = set(map1.wire_map.keys()) keys2 = set(map2.wire_map.keys()) keys_intersection = keys1 & keys2 result = [] for key in keys_intersection: result.append(map1.wire_map[key] + map2.wire_map[key]) print(min(result))
class Wiremap: def __init__(self): self.wire_map = {} self.x = 0 self.y = 0 self.step_counter = 0 def move(self, steps, x_dir, y_dir): while steps > 0: self.x += x_dir self.y += y_dir self.step_counter += 1 self.wire_map[self.x, self.y] = self.step_counter steps -= 1 def move_up(self, steps): return self.move(steps, 0, -1) def move_down(self, steps): return self.move(steps, 0, 1) def move_left(self, steps): return self.move(steps, -1, 0) def move_right(self, steps): return self.move(steps, 1, 0) def mark_wires(self, movements): for command in movements: direction = command[0] s = int(command[1:]) if direction == 'R': self.move_right(s) elif direction == 'L': self.move_left(s) elif direction == 'U': self.move_up(s) else: self.move_down(s) maps = [line.strip().split(',') for line in open('Day3.txt')] map1 = wire_map() map1.mark_wires(maps[0]) map2 = wire_map() map2.mark_wires(maps[1]) keys1 = set(map1.wire_map.keys()) keys2 = set(map2.wire_map.keys()) keys_intersection = keys1 & keys2 result = [] for key in keys_intersection: result.append(map1.wire_map[key] + map2.wire_map[key]) print(min(result))
class Solution: def longestPalindrome(self, s: str) -> str: res = "" for i in range(len(s)): res = max(res,self.lp(s,i,i),self.lp(s,i,i+1),key=len) return res def lp(self,s,l,r): while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1 r += 1 return s[l+1:r]
class Solution: def longest_palindrome(self, s: str) -> str: res = '' for i in range(len(s)): res = max(res, self.lp(s, i, i), self.lp(s, i, i + 1), key=len) return res def lp(self, s, l, r): while l >= 0 and r < len(s) and (s[l] == s[r]): l -= 1 r += 1 return s[l + 1:r]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class Priority(object): def __init__(self, nlp, object): self.object = object self.matcher = object.matcher.Matcher(nlp.vocab) self.matcher.add("Priority", None, #important [{'LOWER': 'important'}], #crucial [{'LOWER': 'crucial'}], #key [{'LOWER': 'key'}], #essential [{'LOWER': 'essential'}], #critical [{'LOWER': 'critical'}], #fundamental [{'LOWER': 'fundamental'}], #key [{'LOWER': 'key'}], #major [{'LOWER': 'major'}], #vital [{'LOWER': 'vital'}], #first and foremost [{'LOWER': 'first'}, {'LOWER': 'and'}, {'LOWER': 'foremost'}], #(now )?remember (that)? [{'LOWER': 'now', 'OP':'?'}, {'LOWER': 'remember'}], #keep in mind (that)? [{'LOWER': 'keep'}, {'LOWER': 'in'}, {'LOWER': 'mind'}], #don\'t forget (that)? [{'LOWER': 'do'}, {'LOWER': 'not'}, {'LOWER': 'forget'}], #let\'s not forget [{'LOWER': 'let'}, {'LOWER': 'us'}, {'LOWER': 'not'}, {'LOWER': 'forget'}], #let\'s keep in mind [{'LOWER': 'let'}, {'LOWER': 'us'}, {'LOWER': 'keep'}, {'LOWER': 'in'}, {'LOWER': 'mind'}], #let\'s remember [{'LOWER': 'let'}, {'LOWER': 'us'}, {'LOWER': 'remember'}], ) def __call__(self, doc): matches = self.matcher(doc) for match_id, start, end in matches: sents = self.object.tokens.Span(doc, start, end).sent sent_start, sent_end = sents.start, sents.end opinion = self.object.tokens.Span(doc, sent_start, sent_end, label = "PRIORITY") doc._.opinion.append(opinion,) return doc
class Priority(object): def __init__(self, nlp, object): self.object = object self.matcher = object.matcher.Matcher(nlp.vocab) self.matcher.add('Priority', None, [{'LOWER': 'important'}], [{'LOWER': 'crucial'}], [{'LOWER': 'key'}], [{'LOWER': 'essential'}], [{'LOWER': 'critical'}], [{'LOWER': 'fundamental'}], [{'LOWER': 'key'}], [{'LOWER': 'major'}], [{'LOWER': 'vital'}], [{'LOWER': 'first'}, {'LOWER': 'and'}, {'LOWER': 'foremost'}], [{'LOWER': 'now', 'OP': '?'}, {'LOWER': 'remember'}], [{'LOWER': 'keep'}, {'LOWER': 'in'}, {'LOWER': 'mind'}], [{'LOWER': 'do'}, {'LOWER': 'not'}, {'LOWER': 'forget'}], [{'LOWER': 'let'}, {'LOWER': 'us'}, {'LOWER': 'not'}, {'LOWER': 'forget'}], [{'LOWER': 'let'}, {'LOWER': 'us'}, {'LOWER': 'keep'}, {'LOWER': 'in'}, {'LOWER': 'mind'}], [{'LOWER': 'let'}, {'LOWER': 'us'}, {'LOWER': 'remember'}]) def __call__(self, doc): matches = self.matcher(doc) for (match_id, start, end) in matches: sents = self.object.tokens.Span(doc, start, end).sent (sent_start, sent_end) = (sents.start, sents.end) opinion = self.object.tokens.Span(doc, sent_start, sent_end, label='PRIORITY') doc._.opinion.append(opinion) return doc
class TileData(object): def __init__(self, filename, z, x, y) -> None: self.filename = filename self.z = z self.x = x self.y = y
class Tiledata(object): def __init__(self, filename, z, x, y) -> None: self.filename = filename self.z = z self.x = x self.y = y
#! /usr/bin/env python # coding: utf-8 class Singleton(object): _instance = None def __new__(cls, *args, **kwargs): if cls._instance is not None: return cls._instance o = object.__new__(cls) cls._instance = o return o @classmethod def get_instance(cls): return cls()
class Singleton(object): _instance = None def __new__(cls, *args, **kwargs): if cls._instance is not None: return cls._instance o = object.__new__(cls) cls._instance = o return o @classmethod def get_instance(cls): return cls()
line_input = list(x for x in input()) num_list = list(int(x) for x in line_input if x.isnumeric()) words = list(x for x in line_input if not x.isnumeric()) take = list(num_list[x] for x in range(len(num_list)) if x % 2 == 0) skip = list(num_list[y] for y in range(len(num_list)) if y % 2 == 1) result = [] for i in range(len(take)): result.append(words[:take[i]]) if skip[i] > 0: words = words[take[i] + skip[i]:] for j in range(len(result)): for k in result[j]: print(k, end="") # /home/master/PycharmProjects/pythonProjects/FirstStepsInPython/Fundamentals/Exercise /Lists Advanced/ # More Exercises
line_input = list((x for x in input())) num_list = list((int(x) for x in line_input if x.isnumeric())) words = list((x for x in line_input if not x.isnumeric())) take = list((num_list[x] for x in range(len(num_list)) if x % 2 == 0)) skip = list((num_list[y] for y in range(len(num_list)) if y % 2 == 1)) result = [] for i in range(len(take)): result.append(words[:take[i]]) if skip[i] > 0: words = words[take[i] + skip[i]:] for j in range(len(result)): for k in result[j]: print(k, end='')
class Sampleinfor: def __init__(self, samplename, datafile, fregion, hotspots=list()): self.samplename = samplename self.datafile = datafile self.hotspots = hotspots self.fregion = fregion
class Sampleinfor: def __init__(self, samplename, datafile, fregion, hotspots=list()): self.samplename = samplename self.datafile = datafile self.hotspots = hotspots self.fregion = fregion
a=1 print( not isinstance(a,str)) if __name__ == "__main__": codes = [1,2,3,4,5,6,7,8,9,10] offset = 0 limit = 3 total = len(codes) while offset < total: print("offet:{} limit:{} partial codes:{}".format(offset,limit, codes[offset:offset+limit])) offset += limit
a = 1 print(not isinstance(a, str)) if __name__ == '__main__': codes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] offset = 0 limit = 3 total = len(codes) while offset < total: print('offet:{} limit:{} partial codes:{}'.format(offset, limit, codes[offset:offset + limit])) offset += limit
def func(): nums = [1,3,4,4,3] sum = 0 # Converting nums to a set which gives us s = set(nums) # s = [1,3,4] for i in s: if nums.count(i)==1: sum +=i print(sum) func()
def func(): nums = [1, 3, 4, 4, 3] sum = 0 s = set(nums) for i in s: if nums.count(i) == 1: sum += i print(sum) func()
def test_register_function(fresh_db): @fresh_db.register_function def reverse_string(s): return "".join(reversed(list(s))) result = fresh_db.execute('select reverse_string("hello")').fetchone()[0] assert result == "olleh" def test_register_function_multiple_arguments(fresh_db): @fresh_db.register_function def a_times_b_plus_c(a, b, c): return a * b + c result = fresh_db.execute("select a_times_b_plus_c(2, 3, 4)").fetchone()[0] assert result == 10
def test_register_function(fresh_db): @fresh_db.register_function def reverse_string(s): return ''.join(reversed(list(s))) result = fresh_db.execute('select reverse_string("hello")').fetchone()[0] assert result == 'olleh' def test_register_function_multiple_arguments(fresh_db): @fresh_db.register_function def a_times_b_plus_c(a, b, c): return a * b + c result = fresh_db.execute('select a_times_b_plus_c(2, 3, 4)').fetchone()[0] assert result == 10
#cAssume s is a string of lower case characters. #Write a program that prints the longest substring of s in which the letters occur # in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print #Longest substring in alphabetical order is: beggh #In the case of ties, print the first substring. For example, if s = 'abcbcd', # then your program should print #Longest substring in alphabetical order is: abc s = 'abcdcd' maxLen = 0 current = s[0] long = s[0] for x in range(len(s) - 1): if s[x + 1] >= s[x]: current += s[x + 1] if len(current) > maxLen: maxLen = len(current) long = current else: current = s[x + 1] x += 1 print ('Longest substring in alphabetical order is: ' + long)
s = 'abcdcd' max_len = 0 current = s[0] long = s[0] for x in range(len(s) - 1): if s[x + 1] >= s[x]: current += s[x + 1] if len(current) > maxLen: max_len = len(current) long = current else: current = s[x + 1] x += 1 print('Longest substring in alphabetical order is: ' + long)
class Solution: def combinationSum2(self, candidates, target): if not candidates or not target: return [] result = [] cand = sorted(candidates) N = len(candidates) def dfs(remainder, curr_combo, start): if remainder == 0: result.append(curr_combo) return for i in range(start, N): curr = cand[i] if i > start and curr == cand[i-1]: continue if curr > remainder: break dfs(remainder - curr, curr_combo + [curr], i+1) dfs(target, [], 0) return result
class Solution: def combination_sum2(self, candidates, target): if not candidates or not target: return [] result = [] cand = sorted(candidates) n = len(candidates) def dfs(remainder, curr_combo, start): if remainder == 0: result.append(curr_combo) return for i in range(start, N): curr = cand[i] if i > start and curr == cand[i - 1]: continue if curr > remainder: break dfs(remainder - curr, curr_combo + [curr], i + 1) dfs(target, [], 0) return result
''' 2^100 ''' n = 1 result = 1 while n <= 10: result = result * 2 print(result) n = n + 1 print('The final is', result)
""" 2^100 """ n = 1 result = 1 while n <= 10: result = result * 2 print(result) n = n + 1 print('The final is', result)
# function to create a list (marks) with the content of every line, every item corresponds to a line with the same index def scan(vp): marks = [] for line in vp: # defining positions of last start and end of general information text_start = 0 text_end = 0 for idx, mark in enumerate(marks): if mark == "text_end": text_end = idx elif mark == "text_start": text_start = idx # finding line with the day the vp is made for if "Ausfertigung" in line: marks.append("new_day") continue # finding line with pressure on schedule if " | / " in line: marks.append("pressure") continue # finding blank lines with no information if line == " |": # to prevent index errors this part will only run when there are already at least 3 lines marked if len(marks) > 2: # if there are two blank lines (the current and the last one), # the line before those two will contain the last line of the general information block # text_start > text_end is true when the current line is in the general information block or the end of # this block has not been found yet if line == " |" and marks[-1] == "blank" and text_start > text_end: marks[-2] = "text_end" marks.append("blank") continue # when there are at least 3 lines marked if len(marks) >= 3: # two lines after the "pressure"-line the general information block will start if marks[-2] == "pressure": marks.append("text_start") continue # when the current line is in between text_start and text_end, # (when text_end does not contain the right index of the end of the general information block, # it will be smaller then text_start) # the current line will contain general information if text_start > text_end: marks.append("text") continue # searching for single class information if " | " in line: # when the class name could not be found, the line takes its place group = str(line) for idx, mark in enumerate(marks): if mark == "class_name": # extracting class names group = vp[idx][7:].replace(":", "") marks.append(group) continue if " |" in line: marks.append("class_name") continue # default (something is not right) marks.append("blank") # postprocessing for idx, mark in enumerate(marks): # replacing text_start and text_end marks with text marks # every possible class name at this point: # text; new_day; pressure; blank; class_name; [class name] if mark == "text_start" or mark == "text_end": marks[idx] = "text" return marks # return dictionary with intel for this day def get_intel(day, groups): intel = { # new day info "new_day": "", # pressure on schedule "pressure": "", # info text "text": [], # list with important information for selected groups "groups_intel": [] } # scan plan marks = scan(day) # going through every day for idx, line in enumerate(day): # extract intel from already marked lines if marks[idx] == "new_day": intel["new_day"] = day[idx][8:] elif marks[idx] == "pressure": intel["pressure"] = day[idx][12:] elif marks[idx] == "text": intel["text"].append(day[idx][7:]) elif marks[idx] in groups: intel["groups_intel"].append(day[idx][9:]) return intel
def scan(vp): marks = [] for line in vp: text_start = 0 text_end = 0 for (idx, mark) in enumerate(marks): if mark == 'text_end': text_end = idx elif mark == 'text_start': text_start = idx if 'Ausfertigung' in line: marks.append('new_day') continue if ' | / ' in line: marks.append('pressure') continue if line == ' |': if len(marks) > 2: if line == ' |' and marks[-1] == 'blank' and (text_start > text_end): marks[-2] = 'text_end' marks.append('blank') continue if len(marks) >= 3: if marks[-2] == 'pressure': marks.append('text_start') continue if text_start > text_end: marks.append('text') continue if ' | ' in line: group = str(line) for (idx, mark) in enumerate(marks): if mark == 'class_name': group = vp[idx][7:].replace(':', '') marks.append(group) continue if ' |' in line: marks.append('class_name') continue marks.append('blank') for (idx, mark) in enumerate(marks): if mark == 'text_start' or mark == 'text_end': marks[idx] = 'text' return marks def get_intel(day, groups): intel = {'new_day': '', 'pressure': '', 'text': [], 'groups_intel': []} marks = scan(day) for (idx, line) in enumerate(day): if marks[idx] == 'new_day': intel['new_day'] = day[idx][8:] elif marks[idx] == 'pressure': intel['pressure'] = day[idx][12:] elif marks[idx] == 'text': intel['text'].append(day[idx][7:]) elif marks[idx] in groups: intel['groups_intel'].append(day[idx][9:]) return intel
# __ __ _ __ ____ _ _ # \ \ / / | |/ _| _ \ | (_) # \ \ /\ / /__ | | |_| |_) | ___ | |_ _ __ # \ \/ \/ / _ \| | _| _ < / _ \| | | '_ \ # \ /\ / (_) | | | | |_) | (_) | | | | | | # \/ \/ \___/|_|_| |____/ \___/|_|_|_| |_| VERSION = (0, 1, 3) __version__ = '.'.join(map(str, VERSION))
version = (0, 1, 3) __version__ = '.'.join(map(str, VERSION))
def main(): print(add(1, 3)) def add(a: int, b: int): return a + b
def main(): print(add(1, 3)) def add(a: int, b: int): return a + b
__version__ = "0.29.9" __db_version__ = 7 __author__ = "Kristian Larsson, Lukas Garberg" __author_email__ = "kll@tele2.net, lukas@spritelink.net" __copyright__ = "Copyright 2011-2014, Kristian Larsson, Lukas Garberg" __license__ = "MIT" __status__ = "Development" __url__ = "http://SpriteLink.github.com/NIPAP"
__version__ = '0.29.9' __db_version__ = 7 __author__ = 'Kristian Larsson, Lukas Garberg' __author_email__ = 'kll@tele2.net, lukas@spritelink.net' __copyright__ = 'Copyright 2011-2014, Kristian Larsson, Lukas Garberg' __license__ = 'MIT' __status__ = 'Development' __url__ = 'http://SpriteLink.github.com/NIPAP'
CSV_HEADERS = [ "externalID", "status", "internalID", "rescueID", "name", "type", "priBreed", "secBreed", "mix", "sex", "okwithdogs", "okwithcats", "okwithkids", "declawed", "housebroken", "age", "specialNeeds", "altered", "size", "uptodate", "color", "pattern", "coatLength", "courtesy", "dsc", "found", "foundDate", "foundZipcode", "photo1", "photo2", "photo3", "photo4", "videoUrl", ]
csv_headers = ['externalID', 'status', 'internalID', 'rescueID', 'name', 'type', 'priBreed', 'secBreed', 'mix', 'sex', 'okwithdogs', 'okwithcats', 'okwithkids', 'declawed', 'housebroken', 'age', 'specialNeeds', 'altered', 'size', 'uptodate', 'color', 'pattern', 'coatLength', 'courtesy', 'dsc', 'found', 'foundDate', 'foundZipcode', 'photo1', 'photo2', 'photo3', 'photo4', 'videoUrl']
load( "@io_bazel_rules_scala//scala:providers.bzl", _DepsInfo = "DepsInfo", _ScalacProvider = "ScalacProvider", ) def _compute_strict_deps_mode(input_strict_deps_mode, dependency_mode): if dependency_mode == "direct": return "off" if input_strict_deps_mode == "default": if dependency_mode == "transitive": return "error" else: return "off" return input_strict_deps_mode def _compute_dependency_tracking_method( dependency_mode, input_dependency_tracking_method): if input_dependency_tracking_method == "default": if dependency_mode == "direct": return "high-level" else: return "ast" return input_dependency_tracking_method def _scala_toolchain_impl(ctx): dependency_mode = ctx.attr.dependency_mode strict_deps_mode = _compute_strict_deps_mode( ctx.attr.strict_deps_mode, dependency_mode, ) unused_dependency_checker_mode = ctx.attr.unused_dependency_checker_mode dependency_tracking_method = _compute_dependency_tracking_method( dependency_mode, ctx.attr.dependency_tracking_method, ) # Final quality checks to possibly detect buggy code above if dependency_mode not in ("direct", "plus-one", "transitive"): fail("Internal error: invalid dependency_mode " + dependency_mode) if strict_deps_mode not in ("off", "warn", "error"): fail("Internal error: invalid strict_deps_mode " + strict_deps_mode) if dependency_tracking_method not in ("ast", "high-level"): fail("Internal error: invalid dependency_tracking_method " + dependency_tracking_method) enable_diagnostics_report = ctx.attr.enable_diagnostics_report toolchain = platform_common.ToolchainInfo( scalacopts = ctx.attr.scalacopts, dep_providers = ctx.attr.dep_providers, dependency_mode = dependency_mode, strict_deps_mode = strict_deps_mode, unused_dependency_checker_mode = unused_dependency_checker_mode, dependency_tracking_method = dependency_tracking_method, enable_code_coverage_aspect = ctx.attr.enable_code_coverage_aspect, scalac_jvm_flags = ctx.attr.scalac_jvm_flags, scala_test_jvm_flags = ctx.attr.scala_test_jvm_flags, enable_diagnostics_report = enable_diagnostics_report, ) return [toolchain] scala_toolchain = rule( _scala_toolchain_impl, attrs = { "scalacopts": attr.string_list(), "dep_providers": attr.label_list( default = [ "@io_bazel_rules_scala//scala:scala_xml_provider", "@io_bazel_rules_scala//scala:parser_combinators_provider", "@io_bazel_rules_scala//scala:scala_compile_classpath_provider", "@io_bazel_rules_scala//scala:scala_library_classpath_provider", "@io_bazel_rules_scala//scala:scala_macro_classpath_provider", ], providers = [_DepsInfo], ), "dependency_mode": attr.string( default = "direct", values = ["direct", "plus-one", "transitive"], ), "strict_deps_mode": attr.string( default = "default", values = ["off", "warn", "error", "default"], ), "unused_dependency_checker_mode": attr.string( default = "off", values = ["off", "warn", "error"], ), "dependency_tracking_method": attr.string( default = "default", values = ["ast", "high-level", "default"], ), "enable_code_coverage_aspect": attr.string( default = "off", values = ["off", "on"], ), "scalac_jvm_flags": attr.string_list(), "scala_test_jvm_flags": attr.string_list(), "enable_diagnostics_report": attr.bool( doc = "Enable the output of structured diagnostics through the BEP", ), }, fragments = ["java"], )
load('@io_bazel_rules_scala//scala:providers.bzl', _DepsInfo='DepsInfo', _ScalacProvider='ScalacProvider') def _compute_strict_deps_mode(input_strict_deps_mode, dependency_mode): if dependency_mode == 'direct': return 'off' if input_strict_deps_mode == 'default': if dependency_mode == 'transitive': return 'error' else: return 'off' return input_strict_deps_mode def _compute_dependency_tracking_method(dependency_mode, input_dependency_tracking_method): if input_dependency_tracking_method == 'default': if dependency_mode == 'direct': return 'high-level' else: return 'ast' return input_dependency_tracking_method def _scala_toolchain_impl(ctx): dependency_mode = ctx.attr.dependency_mode strict_deps_mode = _compute_strict_deps_mode(ctx.attr.strict_deps_mode, dependency_mode) unused_dependency_checker_mode = ctx.attr.unused_dependency_checker_mode dependency_tracking_method = _compute_dependency_tracking_method(dependency_mode, ctx.attr.dependency_tracking_method) if dependency_mode not in ('direct', 'plus-one', 'transitive'): fail('Internal error: invalid dependency_mode ' + dependency_mode) if strict_deps_mode not in ('off', 'warn', 'error'): fail('Internal error: invalid strict_deps_mode ' + strict_deps_mode) if dependency_tracking_method not in ('ast', 'high-level'): fail('Internal error: invalid dependency_tracking_method ' + dependency_tracking_method) enable_diagnostics_report = ctx.attr.enable_diagnostics_report toolchain = platform_common.ToolchainInfo(scalacopts=ctx.attr.scalacopts, dep_providers=ctx.attr.dep_providers, dependency_mode=dependency_mode, strict_deps_mode=strict_deps_mode, unused_dependency_checker_mode=unused_dependency_checker_mode, dependency_tracking_method=dependency_tracking_method, enable_code_coverage_aspect=ctx.attr.enable_code_coverage_aspect, scalac_jvm_flags=ctx.attr.scalac_jvm_flags, scala_test_jvm_flags=ctx.attr.scala_test_jvm_flags, enable_diagnostics_report=enable_diagnostics_report) return [toolchain] scala_toolchain = rule(_scala_toolchain_impl, attrs={'scalacopts': attr.string_list(), 'dep_providers': attr.label_list(default=['@io_bazel_rules_scala//scala:scala_xml_provider', '@io_bazel_rules_scala//scala:parser_combinators_provider', '@io_bazel_rules_scala//scala:scala_compile_classpath_provider', '@io_bazel_rules_scala//scala:scala_library_classpath_provider', '@io_bazel_rules_scala//scala:scala_macro_classpath_provider'], providers=[_DepsInfo]), 'dependency_mode': attr.string(default='direct', values=['direct', 'plus-one', 'transitive']), 'strict_deps_mode': attr.string(default='default', values=['off', 'warn', 'error', 'default']), 'unused_dependency_checker_mode': attr.string(default='off', values=['off', 'warn', 'error']), 'dependency_tracking_method': attr.string(default='default', values=['ast', 'high-level', 'default']), 'enable_code_coverage_aspect': attr.string(default='off', values=['off', 'on']), 'scalac_jvm_flags': attr.string_list(), 'scala_test_jvm_flags': attr.string_list(), 'enable_diagnostics_report': attr.bool(doc='Enable the output of structured diagnostics through the BEP')}, fragments=['java'])
# Automatically generated # pylint: disable=all get = [{'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3, 'DefaultVCpus': 16, 'SizeInMiB': 32768, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 8, 'Ipv4AddressesPerInterface': 30, 'Ipv6AddressesPerInterface': 30, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'a1.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3}, 'VCpuInfo': {'DefaultVCpus': 16}, 'MemoryInfo': {'SizeInMiB': 32768}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 8, 'Ipv4AddressesPerInterface': 30, 'Ipv6AddressesPerInterface': 30, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 4.0, 'DefaultVCpus': 48, 'SizeInMiB': 393216, 'TotalSizeInGB': 1800, 'Disks': [{'SizeInGB': 900, 'Count': 2, 'Type': 'ssd'}], 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'z1d.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 4.0}, 'VCpuInfo': {'DefaultVCpus': 48}, 'MemoryInfo': {'SizeInMiB': 393216}, 'InstanceStorageSupported': True, 'InstanceStorageInfo': {'TotalSizeInGB': 1800, 'Disks': [{'SizeInGB': 900, 'Count': 2, 'Type': 'ssd'}]}, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': False}, {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.5, 'DefaultVCpus': 64, 'SizeInMiB': 131072, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'c6g.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.5}, 'VCpuInfo': {'DefaultVCpus': 64}, 'MemoryInfo': {'SizeInMiB': 131072}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.5, 'DefaultVCpus': 64, 'SizeInMiB': 131072, 'TotalSizeInGB': 3800, 'Disks': [{'SizeInGB': 1900, 'Count': 2, 'Type': 'ssd'}], 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'c6gd.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.5}, 'VCpuInfo': {'DefaultVCpus': 64}, 'MemoryInfo': {'SizeInMiB': 131072}, 'InstanceStorageSupported': True, 'InstanceStorageInfo': {'TotalSizeInGB': 3800, 'Disks': [{'SizeInGB': 1900, 'Count': 2, 'Type': 'ssd'}]}, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': False}, {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.5, 'DefaultVCpus': 64, 'SizeInMiB': 262144, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'm6g.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.5}, 'VCpuInfo': {'DefaultVCpus': 64}, 'MemoryInfo': {'SizeInMiB': 262144}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.5, 'DefaultVCpus': 64, 'SizeInMiB': 262144, 'TotalSizeInGB': 3800, 'Disks': [{'SizeInGB': 1900, 'Count': 2, 'Type': 'ssd'}], 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'm6gd.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.5}, 'VCpuInfo': {'DefaultVCpus': 64}, 'MemoryInfo': {'SizeInMiB': 262144}, 'InstanceStorageSupported': True, 'InstanceStorageInfo': {'TotalSizeInGB': 3800, 'Disks': [{'SizeInGB': 1900, 'Count': 2, 'Type': 'ssd'}]}, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': False}, {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.5, 'DefaultVCpus': 64, 'SizeInMiB': 524288, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'r6g.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.5}, 'VCpuInfo': {'DefaultVCpus': 64}, 'MemoryInfo': {'SizeInMiB': 524288}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': False, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.5, 'DefaultVCpus': 64, 'SizeInMiB': 524288, 'TotalSizeInGB': 3800, 'Disks': [{'SizeInGB': 1900, 'Count': 2, 'Type': 'ssd'}], 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'r6gd.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.5}, 'VCpuInfo': {'DefaultVCpus': 64}, 'MemoryInfo': {'SizeInMiB': 524288}, 'InstanceStorageSupported': True, 'InstanceStorageInfo': {'TotalSizeInGB': 3800, 'Disks': [{'SizeInGB': 1900, 'Count': 2, 'Type': 'ssd'}]}, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': False, 'AutoRecoverySupported': False}, {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.4, 'DefaultVCpus': 72, 'SizeInMiB': 196608, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '100 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'c5n.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.4}, 'VCpuInfo': {'DefaultVCpus': 72}, 'MemoryInfo': {'SizeInMiB': 196608}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '100 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 2.3, 'DefaultVCpus': 72, 'SizeInMiB': 524288, 'TotalSizeInGB': 15200, 'Disks': [{'SizeInGB': 1900, 'Count': 8, 'Type': 'ssd'}], 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'i3.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 2.3}, 'VCpuInfo': {'DefaultVCpus': 72}, 'MemoryInfo': {'SizeInMiB': 524288}, 'InstanceStorageSupported': True, 'InstanceStorageInfo': {'TotalSizeInGB': 15200, 'Disks': [{'SizeInGB': 1900, 'Count': 8, 'Type': 'ssd'}]}, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': False}, {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.6, 'DefaultVCpus': 96, 'SizeInMiB': 196608, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'c5.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.6}, 'VCpuInfo': {'DefaultVCpus': 96}, 'MemoryInfo': {'SizeInMiB': 196608}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': False, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.6, 'DefaultVCpus': 96, 'SizeInMiB': 196608, 'TotalSizeInGB': 3600, 'Disks': [{'SizeInGB': 900, 'Count': 4, 'Type': 'ssd'}], 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'c5d.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.6}, 'VCpuInfo': {'DefaultVCpus': 96}, 'MemoryInfo': {'SizeInMiB': 196608}, 'InstanceStorageSupported': True, 'InstanceStorageInfo': {'TotalSizeInGB': 3600, 'Disks': [{'SizeInGB': 900, 'Count': 4, 'Type': 'ssd'}]}, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': False, 'AutoRecoverySupported': False}, {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 2.5, 'DefaultVCpus': 96, 'SizeInMiB': 393216, 'TotalSizeInGB': 1800, 'Disks': [{'SizeInGB': 900, 'Count': 2, 'Type': 'ssd'}], 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '100 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'Gpus': [{'Name': 'T4', 'Manufacturer': 'NVIDIA', 'Count': 8, 'MemoryInfo': {'SizeInMiB': 16384}}], 'TotalGpuMemoryInMiB': 131072, 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'g4dn.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 2.5}, 'VCpuInfo': {'DefaultVCpus': 96}, 'MemoryInfo': {'SizeInMiB': 393216}, 'InstanceStorageSupported': True, 'InstanceStorageInfo': {'TotalSizeInGB': 1800, 'Disks': [{'SizeInGB': 900, 'Count': 2, 'Type': 'ssd'}]}, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '100 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'GpuInfo': {'Gpus': [{'Name': 'T4', 'Manufacturer': 'NVIDIA', 'Count': 8, 'MemoryInfo': {'SizeInMiB': 16384}}], 'TotalGpuMemoryInMiB': 131072}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': False}, {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.1, 'DefaultVCpus': 96, 'SizeInMiB': 786432, 'TotalSizeInGB': 60000, 'Disks': [{'SizeInGB': 7500, 'Count': 8, 'Type': 'ssd'}], 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '100 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'i3en.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.1}, 'VCpuInfo': {'DefaultVCpus': 96}, 'MemoryInfo': {'SizeInMiB': 786432}, 'InstanceStorageSupported': True, 'InstanceStorageInfo': {'TotalSizeInGB': 60000, 'Disks': [{'SizeInGB': 7500, 'Count': 8, 'Type': 'ssd'}]}, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '100 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': False}, {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.1, 'DefaultVCpus': 96, 'SizeInMiB': 393216, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'm5.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.1}, 'VCpuInfo': {'DefaultVCpus': 96}, 'MemoryInfo': {'SizeInMiB': 393216}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.1, 'DefaultVCpus': 96, 'SizeInMiB': 393216, 'TotalSizeInGB': 3600, 'Disks': [{'SizeInGB': 900, 'Count': 4, 'Type': 'ssd'}], 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'm5d.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.1}, 'VCpuInfo': {'DefaultVCpus': 96}, 'MemoryInfo': {'SizeInMiB': 393216}, 'InstanceStorageSupported': True, 'InstanceStorageInfo': {'TotalSizeInGB': 3600, 'Disks': [{'SizeInGB': 900, 'Count': 4, 'Type': 'ssd'}]}, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': False}, {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.1, 'DefaultVCpus': 96, 'SizeInMiB': 786432, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'r5.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.1}, 'VCpuInfo': {'DefaultVCpus': 96}, 'MemoryInfo': {'SizeInMiB': 786432}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.1, 'DefaultVCpus': 96, 'SizeInMiB': 786432, 'TotalSizeInGB': 3600, 'Disks': [{'SizeInGB': 900, 'Count': 4, 'Type': 'ssd'}], 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'r5d.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.1}, 'VCpuInfo': {'DefaultVCpus': 96}, 'MemoryInfo': {'SizeInMiB': 786432}, 'InstanceStorageSupported': True, 'InstanceStorageInfo': {'TotalSizeInGB': 3600, 'Disks': [{'SizeInGB': 900, 'Count': 4, 'Type': 'ssd'}]}, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': False}] # noqa: E501 def get_instances_list() -> list: '''Returns list EC2 instances with BareMetal = True .''' # pylint: disable=all return get
get = [{'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3, 'DefaultVCpus': 16, 'SizeInMiB': 32768, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 8, 'Ipv4AddressesPerInterface': 30, 'Ipv6AddressesPerInterface': 30, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'a1.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3}, 'VCpuInfo': {'DefaultVCpus': 16}, 'MemoryInfo': {'SizeInMiB': 32768}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': 'Up to 10 Gigabit', 'MaximumNetworkInterfaces': 8, 'Ipv4AddressesPerInterface': 30, 'Ipv6AddressesPerInterface': 30, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 4.0, 'DefaultVCpus': 48, 'SizeInMiB': 393216, 'TotalSizeInGB': 1800, 'Disks': [{'SizeInGB': 900, 'Count': 2, 'Type': 'ssd'}], 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'z1d.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 4.0}, 'VCpuInfo': {'DefaultVCpus': 48}, 'MemoryInfo': {'SizeInMiB': 393216}, 'InstanceStorageSupported': True, 'InstanceStorageInfo': {'TotalSizeInGB': 1800, 'Disks': [{'SizeInGB': 900, 'Count': 2, 'Type': 'ssd'}]}, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': False}, {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.5, 'DefaultVCpus': 64, 'SizeInMiB': 131072, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'c6g.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.5}, 'VCpuInfo': {'DefaultVCpus': 64}, 'MemoryInfo': {'SizeInMiB': 131072}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.5, 'DefaultVCpus': 64, 'SizeInMiB': 131072, 'TotalSizeInGB': 3800, 'Disks': [{'SizeInGB': 1900, 'Count': 2, 'Type': 'ssd'}], 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'c6gd.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.5}, 'VCpuInfo': {'DefaultVCpus': 64}, 'MemoryInfo': {'SizeInMiB': 131072}, 'InstanceStorageSupported': True, 'InstanceStorageInfo': {'TotalSizeInGB': 3800, 'Disks': [{'SizeInGB': 1900, 'Count': 2, 'Type': 'ssd'}]}, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': False}, {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.5, 'DefaultVCpus': 64, 'SizeInMiB': 262144, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'm6g.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.5}, 'VCpuInfo': {'DefaultVCpus': 64}, 'MemoryInfo': {'SizeInMiB': 262144}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.5, 'DefaultVCpus': 64, 'SizeInMiB': 262144, 'TotalSizeInGB': 3800, 'Disks': [{'SizeInGB': 1900, 'Count': 2, 'Type': 'ssd'}], 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'm6gd.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.5}, 'VCpuInfo': {'DefaultVCpus': 64}, 'MemoryInfo': {'SizeInMiB': 262144}, 'InstanceStorageSupported': True, 'InstanceStorageInfo': {'TotalSizeInGB': 3800, 'Disks': [{'SizeInGB': 1900, 'Count': 2, 'Type': 'ssd'}]}, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': False}, {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.5, 'DefaultVCpus': 64, 'SizeInMiB': 524288, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'r6g.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.5}, 'VCpuInfo': {'DefaultVCpus': 64}, 'MemoryInfo': {'SizeInMiB': 524288}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': False, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.5, 'DefaultVCpus': 64, 'SizeInMiB': 524288, 'TotalSizeInGB': 3800, 'Disks': [{'SizeInGB': 1900, 'Count': 2, 'Type': 'ssd'}], 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'r6gd.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.5}, 'VCpuInfo': {'DefaultVCpus': 64}, 'MemoryInfo': {'SizeInMiB': 524288}, 'InstanceStorageSupported': True, 'InstanceStorageInfo': {'TotalSizeInGB': 3800, 'Disks': [{'SizeInGB': 1900, 'Count': 2, 'Type': 'ssd'}]}, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': False, 'AutoRecoverySupported': False}, {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.4, 'DefaultVCpus': 72, 'SizeInMiB': 196608, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '100 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'c5n.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.4}, 'VCpuInfo': {'DefaultVCpus': 72}, 'MemoryInfo': {'SizeInMiB': 196608}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '100 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 2.3, 'DefaultVCpus': 72, 'SizeInMiB': 524288, 'TotalSizeInGB': 15200, 'Disks': [{'SizeInGB': 1900, 'Count': 8, 'Type': 'ssd'}], 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'i3.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 2.3}, 'VCpuInfo': {'DefaultVCpus': 72}, 'MemoryInfo': {'SizeInMiB': 524288}, 'InstanceStorageSupported': True, 'InstanceStorageInfo': {'TotalSizeInGB': 15200, 'Disks': [{'SizeInGB': 1900, 'Count': 8, 'Type': 'ssd'}]}, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': False}, {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.6, 'DefaultVCpus': 96, 'SizeInMiB': 196608, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'c5.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.6}, 'VCpuInfo': {'DefaultVCpus': 96}, 'MemoryInfo': {'SizeInMiB': 196608}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': False, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.6, 'DefaultVCpus': 96, 'SizeInMiB': 196608, 'TotalSizeInGB': 3600, 'Disks': [{'SizeInGB': 900, 'Count': 4, 'Type': 'ssd'}], 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'c5d.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.6}, 'VCpuInfo': {'DefaultVCpus': 96}, 'MemoryInfo': {'SizeInMiB': 196608}, 'InstanceStorageSupported': True, 'InstanceStorageInfo': {'TotalSizeInGB': 3600, 'Disks': [{'SizeInGB': 900, 'Count': 4, 'Type': 'ssd'}]}, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': False, 'AutoRecoverySupported': False}, {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 2.5, 'DefaultVCpus': 96, 'SizeInMiB': 393216, 'TotalSizeInGB': 1800, 'Disks': [{'SizeInGB': 900, 'Count': 2, 'Type': 'ssd'}], 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '100 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'Gpus': [{'Name': 'T4', 'Manufacturer': 'NVIDIA', 'Count': 8, 'MemoryInfo': {'SizeInMiB': 16384}}], 'TotalGpuMemoryInMiB': 131072, 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'g4dn.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 2.5}, 'VCpuInfo': {'DefaultVCpus': 96}, 'MemoryInfo': {'SizeInMiB': 393216}, 'InstanceStorageSupported': True, 'InstanceStorageInfo': {'TotalSizeInGB': 1800, 'Disks': [{'SizeInGB': 900, 'Count': 2, 'Type': 'ssd'}]}, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '100 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'GpuInfo': {'Gpus': [{'Name': 'T4', 'Manufacturer': 'NVIDIA', 'Count': 8, 'MemoryInfo': {'SizeInMiB': 16384}}], 'TotalGpuMemoryInMiB': 131072}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': False}, {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.1, 'DefaultVCpus': 96, 'SizeInMiB': 786432, 'TotalSizeInGB': 60000, 'Disks': [{'SizeInGB': 7500, 'Count': 8, 'Type': 'ssd'}], 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '100 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'i3en.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.1}, 'VCpuInfo': {'DefaultVCpus': 96}, 'MemoryInfo': {'SizeInMiB': 786432}, 'InstanceStorageSupported': True, 'InstanceStorageInfo': {'TotalSizeInGB': 60000, 'Disks': [{'SizeInGB': 7500, 'Count': 8, 'Type': 'ssd'}]}, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '100 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': False}, {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.1, 'DefaultVCpus': 96, 'SizeInMiB': 393216, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'm5.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.1}, 'VCpuInfo': {'DefaultVCpus': 96}, 'MemoryInfo': {'SizeInMiB': 393216}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.1, 'DefaultVCpus': 96, 'SizeInMiB': 393216, 'TotalSizeInGB': 3600, 'Disks': [{'SizeInGB': 900, 'Count': 4, 'Type': 'ssd'}], 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'm5d.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.1}, 'VCpuInfo': {'DefaultVCpus': 96}, 'MemoryInfo': {'SizeInMiB': 393216}, 'InstanceStorageSupported': True, 'InstanceStorageInfo': {'TotalSizeInGB': 3600, 'Disks': [{'SizeInGB': 900, 'Count': 4, 'Type': 'ssd'}]}, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': False}, {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.1, 'DefaultVCpus': 96, 'SizeInMiB': 786432, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'r5.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.1}, 'VCpuInfo': {'DefaultVCpus': 96}, 'MemoryInfo': {'SizeInMiB': 786432}, 'InstanceStorageSupported': False, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': True}, {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.1, 'DefaultVCpus': 96, 'SizeInMiB': 786432, 'TotalSizeInGB': 3600, 'Disks': [{'SizeInGB': 900, 'Count': 4, 'Type': 'ssd'}], 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported', 'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required', 'SupportedStrategies': ['cluster', 'partition', 'spread'], 'InstanceType': 'r5d.metal', 'CurrentGeneration': True, 'FreeTierEligible': False, 'SupportedUsageClasses': ['on-demand', 'spot'], 'SupportedRootDeviceTypes': ['ebs'], 'BareMetal': True, 'ProcessorInfo': {'SupportedArchitectures': ['x86_64'], 'SustainedClockSpeedInGhz': 3.1}, 'VCpuInfo': {'DefaultVCpus': 96}, 'MemoryInfo': {'SizeInMiB': 786432}, 'InstanceStorageSupported': True, 'InstanceStorageInfo': {'TotalSizeInGB': 3600, 'Disks': [{'SizeInGB': 900, 'Count': 4, 'Type': 'ssd'}]}, 'EbsInfo': {'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supported'}, 'NetworkInfo': {'NetworkPerformance': '25 Gigabit', 'MaximumNetworkInterfaces': 15, 'Ipv4AddressesPerInterface': 50, 'Ipv6AddressesPerInterface': 50, 'Ipv6Supported': True, 'EnaSupport': 'required'}, 'PlacementGroupInfo': {'SupportedStrategies': ['cluster', 'partition', 'spread']}, 'HibernationSupported': False, 'BurstablePerformanceSupported': False, 'DedicatedHostsSupported': True, 'AutoRecoverySupported': False}] def get_instances_list() -> list: """Returns list EC2 instances with BareMetal = True .""" return get
# 8. With two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155], # write a program to make a list whose elements are intersection of the above given lists. listA = [1, 3, 6, 78, 35, 55] listB = [12, 24, 35, 24, 88, 120, 155] setA = set(listA) setB = set(listB) insersaction_of_AB = setA.intersection(setB) # A&B listA_insersact_B = list(insersaction_of_AB) print(listA_insersact_B)
list_a = [1, 3, 6, 78, 35, 55] list_b = [12, 24, 35, 24, 88, 120, 155] set_a = set(listA) set_b = set(listB) insersaction_of_ab = setA.intersection(setB) list_a_insersact_b = list(insersaction_of_AB) print(listA_insersact_B)
#encoding:utf-8 subreddit = 'WikiLeaks' t_channel = '@r_WikiLeaks' def send_post(submission, r2t): return r2t.send_simple(submission)
subreddit = 'WikiLeaks' t_channel = '@r_WikiLeaks' def send_post(submission, r2t): return r2t.send_simple(submission)
# # PySNMP MIB module WWP-LEOS-PING-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WWP-LEOS-PING-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:38:13 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) # ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ConstraintsUnion, ConstraintsIntersection, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueRangeConstraint", "ValueSizeConstraint") AddressFamilyNumbers, = mibBuilder.importSymbols("IANA-ADDRESS-FAMILY-NUMBERS-MIB", "AddressFamilyNumbers") InetAddressType, = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddressType") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Integer32, NotificationType, ModuleIdentity, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, Counter32, iso, ObjectIdentity, TimeTicks, MibIdentifier, Counter64, Unsigned32, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "NotificationType", "ModuleIdentity", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "Counter32", "iso", "ObjectIdentity", "TimeTicks", "MibIdentifier", "Counter64", "Unsigned32", "IpAddress") DisplayString, TruthValue, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TruthValue", "TextualConvention") wwpModulesLeos, = mibBuilder.importSymbols("WWP-SMI", "wwpModulesLeos") wwpLeosPingMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19)) wwpLeosPingMIB.setRevisions(('2012-04-02 00:00', '2001-07-03 12:57',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: wwpLeosPingMIB.setRevisionsDescriptions(('Add wwpLeosPingInetAddrType to support IP protocol version independent Inet addressing.', 'Initial Creation',)) if mibBuilder.loadTexts: wwpLeosPingMIB.setLastUpdated('201204020000Z') if mibBuilder.loadTexts: wwpLeosPingMIB.setOrganization('Ciena, Inc') if mibBuilder.loadTexts: wwpLeosPingMIB.setContactInfo(' Mib Meister 115 North Sullivan Road Spokane Valley, WA 99037 USA Phone: +1 509 242 9000 Email: support@ciena.com') if mibBuilder.loadTexts: wwpLeosPingMIB.setDescription('The MIB for WWP Ping') class PingFailCause(TextualConvention, Integer32): description = 'The cause of the last ping failure.' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17)) namedValues = NamedValues(("unknownHost", 1), ("socketError", 2), ("bindError", 3), ("connectError", 4), ("missingHost", 5), ("asyncError", 6), ("nonBlockError", 7), ("mcastError", 8), ("ttlError", 9), ("mcastTtlError", 10), ("outputError", 11), ("unreachableError", 12), ("isAlive", 13), ("txRx", 14), ("commandCompleted", 15), ("noStatus", 16), ("sendRecvMismatch", 17)) class PingState(TextualConvention, Integer32): description = 'The state of the last ping request.' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4)) namedValues = NamedValues(("idle", 1), ("pinging", 2), ("pingComplete", 3), ("failed", 4)) wwpLeosPingMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19, 1)) wwpLeosPingDelay = MibScalar((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 100000))).setMaxAccess("readwrite") if mibBuilder.loadTexts: wwpLeosPingDelay.setStatus('current') if mibBuilder.loadTexts: wwpLeosPingDelay.setDescription('The object specifies the minimum amount of time to wait before sending the next packet in a sequence after receiving a response or declaring a timeout for a previous packet.') wwpLeosPingPacketSize = MibScalar((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1464)).clone(56)).setMaxAccess("readwrite") if mibBuilder.loadTexts: wwpLeosPingPacketSize.setStatus('current') if mibBuilder.loadTexts: wwpLeosPingPacketSize.setDescription('The size of the ping packets to send to the target.') wwpLeosPingActivate = MibScalar((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19, 1, 3), TruthValue()).setMaxAccess("readwrite") if mibBuilder.loadTexts: wwpLeosPingActivate.setStatus('current') if mibBuilder.loadTexts: wwpLeosPingActivate.setDescription("Ping can be activated by setting this object to true. Once the ping operation is completed, the object is set to 'false'. This object can be set to 'false' by the Management Station to stop the ping.") wwpLeosPingAddrType = MibScalar((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19, 1, 4), AddressFamilyNumbers()).setMaxAccess("readonly") if mibBuilder.loadTexts: wwpLeosPingAddrType.setStatus('current') if mibBuilder.loadTexts: wwpLeosPingAddrType.setDescription('The address type associated with wwpLeosPingAddr. With the new wwpLeosPingInetAddrType being introduced to support RFC 4001, this OID will only be used when wwpLeosPingAddr is a host name or an IPv4 address. Otherwise, it will be set to other(0).') wwpLeosPingAddr = MibScalar((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19, 1, 5), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: wwpLeosPingAddr.setStatus('current') if mibBuilder.loadTexts: wwpLeosPingAddr.setDescription('The host name or IP address of the device to be pinged. wwpLeosPingAddrType determines if address is host name or IP address.') wwpLeosPingPacketCount = MibScalar((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 100000))).setMaxAccess("readwrite") if mibBuilder.loadTexts: wwpLeosPingPacketCount.setStatus('current') if mibBuilder.loadTexts: wwpLeosPingPacketCount.setDescription('Specifies the number of ICMP requests to send to the target.') wwpLeosPingPacketTimeout = MibScalar((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 100000))).setMaxAccess("readwrite") if mibBuilder.loadTexts: wwpLeosPingPacketTimeout.setStatus('current') if mibBuilder.loadTexts: wwpLeosPingPacketTimeout.setDescription("Specifies the amount of time to wait for a response to a transmitted packet before declaring the packet 'dropped'.") wwpLeosPingSentPackets = MibScalar((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19, 1, 8), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wwpLeosPingSentPackets.setStatus('current') if mibBuilder.loadTexts: wwpLeosPingSentPackets.setDescription('The number of ping packets that have been sent to the target.') wwpLeosPingReceivedPackets = MibScalar((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19, 1, 9), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wwpLeosPingReceivedPackets.setStatus('current') if mibBuilder.loadTexts: wwpLeosPingReceivedPackets.setDescription('The number of ping packets that have been received from the target.') wwpLeosPingFailCause = MibScalar((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19, 1, 10), PingFailCause()).setMaxAccess("readonly") if mibBuilder.loadTexts: wwpLeosPingFailCause.setStatus('current') if mibBuilder.loadTexts: wwpLeosPingFailCause.setDescription('The result of the ping.') wwpLeosPingState = MibScalar((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19, 1, 11), PingState().clone('idle')).setMaxAccess("readonly") if mibBuilder.loadTexts: wwpLeosPingState.setStatus('current') if mibBuilder.loadTexts: wwpLeosPingState.setDescription('The state of the ping process. The possible states include pinging, idle, complete or failed.') wwpLeosPingUntilStopped = MibScalar((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19, 1, 12), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: wwpLeosPingUntilStopped.setStatus('current') if mibBuilder.loadTexts: wwpLeosPingUntilStopped.setDescription("Setting this object to true prior to wwpLeosPingActivate will cause the device to ping the specified host until wwpLeosPingActivate is set to false. The object cannot be modified once the ping is active. The object returns to 'false' once the ping is halted.") wwpLeosPingInetAddrType = MibScalar((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19, 1, 13), InetAddressType()).setMaxAccess("readonly") if mibBuilder.loadTexts: wwpLeosPingInetAddrType.setStatus('current') if mibBuilder.loadTexts: wwpLeosPingInetAddrType.setDescription('The Inet address type associated with wwpLeosPingAddr. When set to: ipv4 : wwpLeosPingAddr should be compliant with InetAddressIPv4 from RFC 4001 ipv6 : wwpLeosPingAddr should be compliant with InetAddressIPv6 from RFC 4001.') mibBuilder.exportSymbols("WWP-LEOS-PING-MIB", wwpLeosPingMIB=wwpLeosPingMIB, wwpLeosPingDelay=wwpLeosPingDelay, wwpLeosPingPacketTimeout=wwpLeosPingPacketTimeout, wwpLeosPingPacketSize=wwpLeosPingPacketSize, wwpLeosPingFailCause=wwpLeosPingFailCause, wwpLeosPingSentPackets=wwpLeosPingSentPackets, PingState=PingState, wwpLeosPingPacketCount=wwpLeosPingPacketCount, wwpLeosPingState=wwpLeosPingState, wwpLeosPingMIBObjects=wwpLeosPingMIBObjects, wwpLeosPingInetAddrType=wwpLeosPingInetAddrType, PingFailCause=PingFailCause, wwpLeosPingReceivedPackets=wwpLeosPingReceivedPackets, PYSNMP_MODULE_ID=wwpLeosPingMIB, wwpLeosPingAddrType=wwpLeosPingAddrType, wwpLeosPingUntilStopped=wwpLeosPingUntilStopped, wwpLeosPingActivate=wwpLeosPingActivate, wwpLeosPingAddr=wwpLeosPingAddr)
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, constraints_union, constraints_intersection, value_range_constraint, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ConstraintsUnion', 'ConstraintsIntersection', 'ValueRangeConstraint', 'ValueSizeConstraint') (address_family_numbers,) = mibBuilder.importSymbols('IANA-ADDRESS-FAMILY-NUMBERS-MIB', 'AddressFamilyNumbers') (inet_address_type,) = mibBuilder.importSymbols('INET-ADDRESS-MIB', 'InetAddressType') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (integer32, notification_type, module_identity, gauge32, mib_scalar, mib_table, mib_table_row, mib_table_column, bits, counter32, iso, object_identity, time_ticks, mib_identifier, counter64, unsigned32, ip_address) = mibBuilder.importSymbols('SNMPv2-SMI', 'Integer32', 'NotificationType', 'ModuleIdentity', 'Gauge32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Bits', 'Counter32', 'iso', 'ObjectIdentity', 'TimeTicks', 'MibIdentifier', 'Counter64', 'Unsigned32', 'IpAddress') (display_string, truth_value, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TruthValue', 'TextualConvention') (wwp_modules_leos,) = mibBuilder.importSymbols('WWP-SMI', 'wwpModulesLeos') wwp_leos_ping_mib = module_identity((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19)) wwpLeosPingMIB.setRevisions(('2012-04-02 00:00', '2001-07-03 12:57')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: wwpLeosPingMIB.setRevisionsDescriptions(('Add wwpLeosPingInetAddrType to support IP protocol version independent Inet addressing.', 'Initial Creation')) if mibBuilder.loadTexts: wwpLeosPingMIB.setLastUpdated('201204020000Z') if mibBuilder.loadTexts: wwpLeosPingMIB.setOrganization('Ciena, Inc') if mibBuilder.loadTexts: wwpLeosPingMIB.setContactInfo(' Mib Meister 115 North Sullivan Road Spokane Valley, WA 99037 USA Phone: +1 509 242 9000 Email: support@ciena.com') if mibBuilder.loadTexts: wwpLeosPingMIB.setDescription('The MIB for WWP Ping') class Pingfailcause(TextualConvention, Integer32): description = 'The cause of the last ping failure.' status = 'current' subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17)) named_values = named_values(('unknownHost', 1), ('socketError', 2), ('bindError', 3), ('connectError', 4), ('missingHost', 5), ('asyncError', 6), ('nonBlockError', 7), ('mcastError', 8), ('ttlError', 9), ('mcastTtlError', 10), ('outputError', 11), ('unreachableError', 12), ('isAlive', 13), ('txRx', 14), ('commandCompleted', 15), ('noStatus', 16), ('sendRecvMismatch', 17)) class Pingstate(TextualConvention, Integer32): description = 'The state of the last ping request.' status = 'current' subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4)) named_values = named_values(('idle', 1), ('pinging', 2), ('pingComplete', 3), ('failed', 4)) wwp_leos_ping_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19, 1)) wwp_leos_ping_delay = mib_scalar((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(0, 100000))).setMaxAccess('readwrite') if mibBuilder.loadTexts: wwpLeosPingDelay.setStatus('current') if mibBuilder.loadTexts: wwpLeosPingDelay.setDescription('The object specifies the minimum amount of time to wait before sending the next packet in a sequence after receiving a response or declaring a timeout for a previous packet.') wwp_leos_ping_packet_size = mib_scalar((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(1, 1464)).clone(56)).setMaxAccess('readwrite') if mibBuilder.loadTexts: wwpLeosPingPacketSize.setStatus('current') if mibBuilder.loadTexts: wwpLeosPingPacketSize.setDescription('The size of the ping packets to send to the target.') wwp_leos_ping_activate = mib_scalar((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19, 1, 3), truth_value()).setMaxAccess('readwrite') if mibBuilder.loadTexts: wwpLeosPingActivate.setStatus('current') if mibBuilder.loadTexts: wwpLeosPingActivate.setDescription("Ping can be activated by setting this object to true. Once the ping operation is completed, the object is set to 'false'. This object can be set to 'false' by the Management Station to stop the ping.") wwp_leos_ping_addr_type = mib_scalar((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19, 1, 4), address_family_numbers()).setMaxAccess('readonly') if mibBuilder.loadTexts: wwpLeosPingAddrType.setStatus('current') if mibBuilder.loadTexts: wwpLeosPingAddrType.setDescription('The address type associated with wwpLeosPingAddr. With the new wwpLeosPingInetAddrType being introduced to support RFC 4001, this OID will only be used when wwpLeosPingAddr is a host name or an IPv4 address. Otherwise, it will be set to other(0).') wwp_leos_ping_addr = mib_scalar((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19, 1, 5), display_string()).setMaxAccess('readwrite') if mibBuilder.loadTexts: wwpLeosPingAddr.setStatus('current') if mibBuilder.loadTexts: wwpLeosPingAddr.setDescription('The host name or IP address of the device to be pinged. wwpLeosPingAddrType determines if address is host name or IP address.') wwp_leos_ping_packet_count = mib_scalar((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19, 1, 6), integer32().subtype(subtypeSpec=value_range_constraint(0, 100000))).setMaxAccess('readwrite') if mibBuilder.loadTexts: wwpLeosPingPacketCount.setStatus('current') if mibBuilder.loadTexts: wwpLeosPingPacketCount.setDescription('Specifies the number of ICMP requests to send to the target.') wwp_leos_ping_packet_timeout = mib_scalar((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19, 1, 7), integer32().subtype(subtypeSpec=value_range_constraint(0, 100000))).setMaxAccess('readwrite') if mibBuilder.loadTexts: wwpLeosPingPacketTimeout.setStatus('current') if mibBuilder.loadTexts: wwpLeosPingPacketTimeout.setDescription("Specifies the amount of time to wait for a response to a transmitted packet before declaring the packet 'dropped'.") wwp_leos_ping_sent_packets = mib_scalar((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19, 1, 8), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wwpLeosPingSentPackets.setStatus('current') if mibBuilder.loadTexts: wwpLeosPingSentPackets.setDescription('The number of ping packets that have been sent to the target.') wwp_leos_ping_received_packets = mib_scalar((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19, 1, 9), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wwpLeosPingReceivedPackets.setStatus('current') if mibBuilder.loadTexts: wwpLeosPingReceivedPackets.setDescription('The number of ping packets that have been received from the target.') wwp_leos_ping_fail_cause = mib_scalar((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19, 1, 10), ping_fail_cause()).setMaxAccess('readonly') if mibBuilder.loadTexts: wwpLeosPingFailCause.setStatus('current') if mibBuilder.loadTexts: wwpLeosPingFailCause.setDescription('The result of the ping.') wwp_leos_ping_state = mib_scalar((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19, 1, 11), ping_state().clone('idle')).setMaxAccess('readonly') if mibBuilder.loadTexts: wwpLeosPingState.setStatus('current') if mibBuilder.loadTexts: wwpLeosPingState.setDescription('The state of the ping process. The possible states include pinging, idle, complete or failed.') wwp_leos_ping_until_stopped = mib_scalar((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19, 1, 12), truth_value().clone('false')).setMaxAccess('readwrite') if mibBuilder.loadTexts: wwpLeosPingUntilStopped.setStatus('current') if mibBuilder.loadTexts: wwpLeosPingUntilStopped.setDescription("Setting this object to true prior to wwpLeosPingActivate will cause the device to ping the specified host until wwpLeosPingActivate is set to false. The object cannot be modified once the ping is active. The object returns to 'false' once the ping is halted.") wwp_leos_ping_inet_addr_type = mib_scalar((1, 3, 6, 1, 4, 1, 6141, 2, 60, 19, 1, 13), inet_address_type()).setMaxAccess('readonly') if mibBuilder.loadTexts: wwpLeosPingInetAddrType.setStatus('current') if mibBuilder.loadTexts: wwpLeosPingInetAddrType.setDescription('The Inet address type associated with wwpLeosPingAddr. When set to: ipv4 : wwpLeosPingAddr should be compliant with InetAddressIPv4 from RFC 4001 ipv6 : wwpLeosPingAddr should be compliant with InetAddressIPv6 from RFC 4001.') mibBuilder.exportSymbols('WWP-LEOS-PING-MIB', wwpLeosPingMIB=wwpLeosPingMIB, wwpLeosPingDelay=wwpLeosPingDelay, wwpLeosPingPacketTimeout=wwpLeosPingPacketTimeout, wwpLeosPingPacketSize=wwpLeosPingPacketSize, wwpLeosPingFailCause=wwpLeosPingFailCause, wwpLeosPingSentPackets=wwpLeosPingSentPackets, PingState=PingState, wwpLeosPingPacketCount=wwpLeosPingPacketCount, wwpLeosPingState=wwpLeosPingState, wwpLeosPingMIBObjects=wwpLeosPingMIBObjects, wwpLeosPingInetAddrType=wwpLeosPingInetAddrType, PingFailCause=PingFailCause, wwpLeosPingReceivedPackets=wwpLeosPingReceivedPackets, PYSNMP_MODULE_ID=wwpLeosPingMIB, wwpLeosPingAddrType=wwpLeosPingAddrType, wwpLeosPingUntilStopped=wwpLeosPingUntilStopped, wwpLeosPingActivate=wwpLeosPingActivate, wwpLeosPingAddr=wwpLeosPingAddr)
# Copyright (c) 2009 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'variables': { 'chromium_code': 1, 'chromium_root': '<(DEPTH)/third_party/chromium/src', }, 'targets': [ { 'target_name': 'instaweb_util', 'type': '<(library)', 'dependencies': [ '<(DEPTH)/base/base.gyp:base', ], 'include_dirs': [ '<(DEPTH)', ], 'export_dependent_settings': [ '<(DEPTH)/base/base.gyp:base', ], 'sources': [ # TODO(mdsteele): Add sources here as we need them. 'instaweb/util/function.cc', ], }, { 'target_name': 'spdy', 'type': '<(library)', 'dependencies': [ '<(DEPTH)/base/base.gyp:base', '<(DEPTH)/third_party/zlib/zlib.gyp:zlib', ], 'export_dependent_settings': [ '<(DEPTH)/base/base.gyp:base', ], 'include_dirs': [ '<(DEPTH)', '<(chromium_root)', ], 'sources': [ '<(chromium_root)/net/spdy/buffered_spdy_framer.cc', '<(chromium_root)/net/spdy/spdy_frame_builder.cc', '<(chromium_root)/net/spdy/spdy_frame_reader.cc', '<(chromium_root)/net/spdy/spdy_framer.cc', ], }, ], }
{'variables': {'chromium_code': 1, 'chromium_root': '<(DEPTH)/third_party/chromium/src'}, 'targets': [{'target_name': 'instaweb_util', 'type': '<(library)', 'dependencies': ['<(DEPTH)/base/base.gyp:base'], 'include_dirs': ['<(DEPTH)'], 'export_dependent_settings': ['<(DEPTH)/base/base.gyp:base'], 'sources': ['instaweb/util/function.cc']}, {'target_name': 'spdy', 'type': '<(library)', 'dependencies': ['<(DEPTH)/base/base.gyp:base', '<(DEPTH)/third_party/zlib/zlib.gyp:zlib'], 'export_dependent_settings': ['<(DEPTH)/base/base.gyp:base'], 'include_dirs': ['<(DEPTH)', '<(chromium_root)'], 'sources': ['<(chromium_root)/net/spdy/buffered_spdy_framer.cc', '<(chromium_root)/net/spdy/spdy_frame_builder.cc', '<(chromium_root)/net/spdy/spdy_frame_reader.cc', '<(chromium_root)/net/spdy/spdy_framer.cc']}]}
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"CoreClass": "00_core.ipynb", "TSDataFrame": "01_TSDataFrame.ipynb"} modules = ["core.py", "TSDataFrame.py"] doc_url = "https://alvaroof.github.io/nbdevtest/" git_url = "https://github.com/alvaroof/nbdevtest/tree/master/" def custom_doc_links(name): return None
__all__ = ['index', 'modules', 'custom_doc_links', 'git_url'] index = {'CoreClass': '00_core.ipynb', 'TSDataFrame': '01_TSDataFrame.ipynb'} modules = ['core.py', 'TSDataFrame.py'] doc_url = 'https://alvaroof.github.io/nbdevtest/' git_url = 'https://github.com/alvaroof/nbdevtest/tree/master/' def custom_doc_links(name): return None
# Time: O(n) # Space: O(1) class ListNode(object): def __init__(self, x): self.val = x self.next = None def __repr__(self): if self: return "{} -> {}".format(self.val, self.next) class Solution(object): # @param a ListNode # @return a ListNode def swapPairs(self, head): dummy = ListNode(0) dummy.next = head current = dummy while current.next and current.next.next: next_one, next_two, next_three = current.next, current.next.next, current.next.next.next current.next = next_two next_two.next = next_one next_one.next = next_three current = next_one return dummy.next
class Listnode(object): def __init__(self, x): self.val = x self.next = None def __repr__(self): if self: return '{} -> {}'.format(self.val, self.next) class Solution(object): def swap_pairs(self, head): dummy = list_node(0) dummy.next = head current = dummy while current.next and current.next.next: (next_one, next_two, next_three) = (current.next, current.next.next, current.next.next.next) current.next = next_two next_two.next = next_one next_one.next = next_three current = next_one return dummy.next
N, K = map(int, input().split()) if K > 1: diff = N-K print(diff) else: print(0)
(n, k) = map(int, input().split()) if K > 1: diff = N - K print(diff) else: print(0)
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. load("@bazel_skylib//lib:shell.bzl", "shell") load("//antlir/bzl:oss_shim.bzl", "buck_genrule") load("//antlir/bzl:shape.bzl", "shape") load(":flavor_helpers.bzl", "flavor_helpers") load(":gpt.shape.bzl", "gpt_partition_t", "gpt_t") load(":image_utils.bzl", "image_utils") def image_gpt_partition(package, is_esp = False, is_bios_boot = False, name = None): return shape.new( gpt_partition_t, package = package, is_esp = is_esp, is_bios_boot = is_bios_boot, name = name, ) def image_gpt( name, table, disk_guid = None, visibility = None, build_appliance = None): visibility = visibility or [] build_appliance = build_appliance or flavor_helpers.default_flavor_build_appliance gpt = shape.new(gpt_t, name = name, table = table, disk_guid = disk_guid) buck_genrule( name = name, bash = image_utils.wrap_bash_build_in_common_boilerplate( self_dependency = "//antlir/bzl:image_gpt", bash = ''' $(exe //antlir:gpt) \ --output-path "$OUT" \ --gpt {opts_quoted} \ --build-appliance $(query_outputs {build_appliance}) \ '''.format( opts_quoted = shell.quote(shape.do_not_cache_me_json(gpt)), build_appliance = build_appliance, ), rule_type = "image_gpt", target_name = name, ), cacheable = False, executable = True, visibility = visibility, antlir_rule = "user-internal", )
load('@bazel_skylib//lib:shell.bzl', 'shell') load('//antlir/bzl:oss_shim.bzl', 'buck_genrule') load('//antlir/bzl:shape.bzl', 'shape') load(':flavor_helpers.bzl', 'flavor_helpers') load(':gpt.shape.bzl', 'gpt_partition_t', 'gpt_t') load(':image_utils.bzl', 'image_utils') def image_gpt_partition(package, is_esp=False, is_bios_boot=False, name=None): return shape.new(gpt_partition_t, package=package, is_esp=is_esp, is_bios_boot=is_bios_boot, name=name) def image_gpt(name, table, disk_guid=None, visibility=None, build_appliance=None): visibility = visibility or [] build_appliance = build_appliance or flavor_helpers.default_flavor_build_appliance gpt = shape.new(gpt_t, name=name, table=table, disk_guid=disk_guid) buck_genrule(name=name, bash=image_utils.wrap_bash_build_in_common_boilerplate(self_dependency='//antlir/bzl:image_gpt', bash='\n $(exe //antlir:gpt) --output-path "$OUT" --gpt {opts_quoted} --build-appliance $(query_outputs {build_appliance}) '.format(opts_quoted=shell.quote(shape.do_not_cache_me_json(gpt)), build_appliance=build_appliance), rule_type='image_gpt', target_name=name), cacheable=False, executable=True, visibility=visibility, antlir_rule='user-internal')
def part1(data): return score(combat(*parse(data))) def parse(data): players = [] for player, cs in enumerate('\n'.join(data).split('\n\n'), 1): cards = [int(c.strip()) for c in cs.split('\n')[1:]] players.append(cards) return players def combat(a, b): if not a: return b elif not b: return a _a = a.pop(0) _b = b.pop(0) if _a > _b: return combat(a + [_a, _b], b) return combat(a, b + [_b, _a]) def score(cards): return sum([i * c for i, c in enumerate(reversed(cards), 1)]) def part2(data): return score(recursive_combat(*parse(data))[1]) def key(a, b): return ','.join([str(i) for i in a]) + '#' + ','.join([str(i) for i in b]) def recursive_combat(a, b): seen = set() while a and b: hands = (tuple(a), tuple(b)) if hands in seen: return 1, a seen.add(hands) _a = a.pop(0) _b = b.pop(0) if len(a) >= _a and len(b) >= _b: winner, _ = recursive_combat(a[:_a].copy(), b[:_b].copy()) if winner == 1: a += [_a, _b] else: b += [_b, _a] else: if _a > _b: a += [_a, _b] else: b += [_b, _a] if len(a) > len(b): return 1, a return 2, b
def part1(data): return score(combat(*parse(data))) def parse(data): players = [] for (player, cs) in enumerate('\n'.join(data).split('\n\n'), 1): cards = [int(c.strip()) for c in cs.split('\n')[1:]] players.append(cards) return players def combat(a, b): if not a: return b elif not b: return a _a = a.pop(0) _b = b.pop(0) if _a > _b: return combat(a + [_a, _b], b) return combat(a, b + [_b, _a]) def score(cards): return sum([i * c for (i, c) in enumerate(reversed(cards), 1)]) def part2(data): return score(recursive_combat(*parse(data))[1]) def key(a, b): return ','.join([str(i) for i in a]) + '#' + ','.join([str(i) for i in b]) def recursive_combat(a, b): seen = set() while a and b: hands = (tuple(a), tuple(b)) if hands in seen: return (1, a) seen.add(hands) _a = a.pop(0) _b = b.pop(0) if len(a) >= _a and len(b) >= _b: (winner, _) = recursive_combat(a[:_a].copy(), b[:_b].copy()) if winner == 1: a += [_a, _b] else: b += [_b, _a] elif _a > _b: a += [_a, _b] else: b += [_b, _a] if len(a) > len(b): return (1, a) return (2, b)
# 2021 June 13 13:48 - 14:06 # 10101 # 01010 # Naturally, the sum would be 11111, which is 100000 - 1. # The essence then is to know the length of its bits representation. class Solution: def findComplement(self, num: int) -> int: cnt = 0 orig = num while num != 0: num >>= 1 cnt += 1 return (1 << cnt) - 1 - orig # Or else, we can certainly flip it bit-by-bit. Speed-wise quite comparable to # the last solution. Since there's no class Solution1: def findComplement(self, num: int) -> int: ans = 0 bit = 0 while num != 0: ans += ((num & 1) ^ 1) << bit bit += 1 num >>= 1 return ans # Now comes the most efficient solution to this problem! # A trick to get the most significant bit: # for any n, # n |= n >> 1 # n |= n >> 2 # n |= n >> 4 # n |= n >> 8 # n |= n >> 16 # Started with a 32 bit int n, it's guranteed that we'd get all 1's with the same # number of bits, after the above operations. And this is because: # 1) The most significant bit (left bit) would always be a set bit. # 2) Oring n and n >> 1 would give us n WITH 2 LEADING SET BITS. # 3) Now when we bitwise or n with n >> 2, we get n with 4 set bits, and it keeps # going. # 4) Since we get at most 32 set bits in 32 bit int, the above 5 ops would # gurantee that n would be all set by the end. # 5) If we don't get to certain shifts, but already has an all-set n, then what # the following operations do would be only oring n with 0, making the result # stays at n. # With this idea, we can solve it as follow: class Solution2: def findComplement(self, num: int) -> int: orig = num num |= num >> 1 num |= num >> 2 num |= num >> 4 num |= num >> 8 num |= num >> 16 return num - orig if __name__ == "__main__": print(Solution2().findComplement(5)) print(Solution2().findComplement(1))
class Solution: def find_complement(self, num: int) -> int: cnt = 0 orig = num while num != 0: num >>= 1 cnt += 1 return (1 << cnt) - 1 - orig class Solution1: def find_complement(self, num: int) -> int: ans = 0 bit = 0 while num != 0: ans += (num & 1 ^ 1) << bit bit += 1 num >>= 1 return ans class Solution2: def find_complement(self, num: int) -> int: orig = num num |= num >> 1 num |= num >> 2 num |= num >> 4 num |= num >> 8 num |= num >> 16 return num - orig if __name__ == '__main__': print(solution2().findComplement(5)) print(solution2().findComplement(1))
class InterfaceError(Exception): def __init__(self, message, human_message=None): super().__init__(message) if human_message is None: self.human_message = message else: self.human_message = human_message
class Interfaceerror(Exception): def __init__(self, message, human_message=None): super().__init__(message) if human_message is None: self.human_message = message else: self.human_message = human_message
class Solution: def compress(self, chars: List[str]) -> int: read = 0 while read < len(chars) - 1: count = 1 read_next = read + 1 while read < len(chars) - 1 and chars[read_next] == chars[read]: del chars[read_next] count += 1 if count > 1: for char in str(count): chars.insert(read_next, char) read_next += 1 read = read_next return len(chars)
class Solution: def compress(self, chars: List[str]) -> int: read = 0 while read < len(chars) - 1: count = 1 read_next = read + 1 while read < len(chars) - 1 and chars[read_next] == chars[read]: del chars[read_next] count += 1 if count > 1: for char in str(count): chars.insert(read_next, char) read_next += 1 read = read_next return len(chars)
class RunnerException(Exception): def __init__(self, message=''): super().__init__() self.message = message class ArgumentError(RunnerException): def __str__(self): return 'ArgumentError: %s' % self.message
class Runnerexception(Exception): def __init__(self, message=''): super().__init__() self.message = message class Argumenterror(RunnerException): def __str__(self): return 'ArgumentError: %s' % self.message
words = "Life is short" def lazy_print(text): return lambda: print(text) task = lazy_print(words) task()
words = 'Life is short' def lazy_print(text): return lambda : print(text) task = lazy_print(words) task()
g = int(input().strip()) for _ in range(g): n = int(input().strip()) s = [int(x) for x in input().strip().split(' ')] x = 0 for i in s: x ^= i if x: print("First") else:#x=0 print("Second")
g = int(input().strip()) for _ in range(g): n = int(input().strip()) s = [int(x) for x in input().strip().split(' ')] x = 0 for i in s: x ^= i if x: print('First') else: print('Second')
# Write your solution here: class SuperHero: def __init__(self, name: str, superpowers: str): self.name = name self.superpowers = superpowers def __str__(self): return f'{self.name}, superpowers: {self.superpowers}' class SuperGroup: def __init__(self, name: str, location: str): self._name = name self._location = location self._members = [] @property def name(self): return self._name @property def location(self): return self._location def add_member(self,hero: SuperHero): self._members.append(hero) def print_group(self): print(f"{self.name}, {self.location}") print("Members:") for member in self._members: print(f"{member.name}, superpowers: {member.superpowers}") if __name__=="__main__": superperson = SuperHero("SuperPerson", "Superspeed, superstrength") invisible = SuperHero("Invisible Inca", "Invisibility") revengers = SuperGroup("Revengers", "Emerald City") revengers.add_member(superperson) revengers.add_member(invisible) revengers.print_group()
class Superhero: def __init__(self, name: str, superpowers: str): self.name = name self.superpowers = superpowers def __str__(self): return f'{self.name}, superpowers: {self.superpowers}' class Supergroup: def __init__(self, name: str, location: str): self._name = name self._location = location self._members = [] @property def name(self): return self._name @property def location(self): return self._location def add_member(self, hero: SuperHero): self._members.append(hero) def print_group(self): print(f'{self.name}, {self.location}') print('Members:') for member in self._members: print(f'{member.name}, superpowers: {member.superpowers}') if __name__ == '__main__': superperson = super_hero('SuperPerson', 'Superspeed, superstrength') invisible = super_hero('Invisible Inca', 'Invisibility') revengers = super_group('Revengers', 'Emerald City') revengers.add_member(superperson) revengers.add_member(invisible) revengers.print_group()
#!/usr/bin/python # list_comprehension.py a = [1, 2, 3, 4, 5, 6, 7, 8, 9] b = [e for e in a if e % 2] print (b)
a = [1, 2, 3, 4, 5, 6, 7, 8, 9] b = [e for e in a if e % 2] print(b)
numbers = list(map(int, input().split())) d = dict() for n in numbers: d[n] = 0 for n in numbers: d[n] += 1 result = "" for n in d: if d[n] == 1: result += f"{n} " print(result)
numbers = list(map(int, input().split())) d = dict() for n in numbers: d[n] = 0 for n in numbers: d[n] += 1 result = '' for n in d: if d[n] == 1: result += f'{n} ' print(result)
def coverDebts(s, debts, interests): items = list(zip(interests, debts)) items.sort(reverse=True) n = len(items) ans = 0 for i in range(len(debts)): items[i] = list(items[i]) while True: amount = s*0.1 isEmpty = True for i in range(n): if items[i][1] > 0: isEmpty = False if items[i][1] > amount: items[i][1] -= amount ans += amount break else: amount -= items[i][1] ans += items[i][1] items[i][1] = 0 if isEmpty: break else: for i in range(n): if items[i][1] > 0: items[i][1] += items[i][1]*(items[i][0]*0.01) return ans def main(): print(coverDebts(50, [2,2,5], [200, 100, 150])) if __name__ == "__main__": main()
def cover_debts(s, debts, interests): items = list(zip(interests, debts)) items.sort(reverse=True) n = len(items) ans = 0 for i in range(len(debts)): items[i] = list(items[i]) while True: amount = s * 0.1 is_empty = True for i in range(n): if items[i][1] > 0: is_empty = False if items[i][1] > amount: items[i][1] -= amount ans += amount break else: amount -= items[i][1] ans += items[i][1] items[i][1] = 0 if isEmpty: break else: for i in range(n): if items[i][1] > 0: items[i][1] += items[i][1] * (items[i][0] * 0.01) return ans def main(): print(cover_debts(50, [2, 2, 5], [200, 100, 150])) if __name__ == '__main__': main()
__author__ = 'shijianliu' host = 'http://223.252.199.7' server_host='127.0.0.1' server_port=9999 username = 'liverliu' password = 'liu90shi12jian21' headers = {} headers['Accept'] = '*/*' headers['Accept-Encoding'] = 'gzip, deflate, sdch' headers['Accept-Language'] = 'zh-CN,zh;q=0.8,en;q=0.6,ja;q=0.4,zh-TW;q=0.2' headers['Host'] = 'music.163.com' headers['Connection'] = 'keep-alive' headers['Content-Type'] = 'application/x-www-form-urlencoded' headers['Referer'] = 'http://music.163.com/' headers['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36' cookies = {'appver': '1.5.2'}
__author__ = 'shijianliu' host = 'http://223.252.199.7' server_host = '127.0.0.1' server_port = 9999 username = 'liverliu' password = 'liu90shi12jian21' headers = {} headers['Accept'] = '*/*' headers['Accept-Encoding'] = 'gzip, deflate, sdch' headers['Accept-Language'] = 'zh-CN,zh;q=0.8,en;q=0.6,ja;q=0.4,zh-TW;q=0.2' headers['Host'] = 'music.163.com' headers['Connection'] = 'keep-alive' headers['Content-Type'] = 'application/x-www-form-urlencoded' headers['Referer'] = 'http://music.163.com/' headers['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36' cookies = {'appver': '1.5.2'}
def df_corr_pearson(data, y, excluded_list=False): '''One-by-One Correlation Based on the input data, returns a dictionary where each column is provided a correlation coefficient and number of unique values. Columns with non-numeric values will have None as their coefficient. data : dataframe A Pandas dataframe with the data y : str The prediction variable excluded_list : bool If True, then also a list will be returned with column labels for non-numeric columns. ''' out = {} category_columns = [] for col in data.columns: try: out[col] = [data[y].corr(data[col]), len(data[col].unique())] except TypeError: out[col] = [None, len(data[col].unique())] category_columns.append(col) if excluded_list: return out, category_columns else: return out
def df_corr_pearson(data, y, excluded_list=False): """One-by-One Correlation Based on the input data, returns a dictionary where each column is provided a correlation coefficient and number of unique values. Columns with non-numeric values will have None as their coefficient. data : dataframe A Pandas dataframe with the data y : str The prediction variable excluded_list : bool If True, then also a list will be returned with column labels for non-numeric columns. """ out = {} category_columns = [] for col in data.columns: try: out[col] = [data[y].corr(data[col]), len(data[col].unique())] except TypeError: out[col] = [None, len(data[col].unique())] category_columns.append(col) if excluded_list: return (out, category_columns) else: return out
# Sem zip a = [17, 28, 30] b = [99, 16, 8] alice = 0 bob = 0 # for i in range(len(a)): # if a[i] > b[i]: # alice += 1 # elif a[i] < b[i]: # bob += 1 # print(alice, bob) #Com Zip for x, y in zip(a, b): if x > y: alice += 1 elif x < y: bob += 1 print(alice, bob)
a = [17, 28, 30] b = [99, 16, 8] alice = 0 bob = 0 for (x, y) in zip(a, b): if x > y: alice += 1 elif x < y: bob += 1 print(alice, bob)
''' Set of functions to provide managed input for Python programs. Uses the input and print standard input functions to read, but provides ranged checked input functions, and also handles CTRL+C input which would normally break a Python application. CTRL+C handling can be turned off by setting DEBUG_MODE to True so that a program can be interrupted. ''' DEBUG_MODE = True def read_text(prompt): ''' Displays a prompt and reads in a string of text. Keyboard interrupts (CTRL+C) are ignored returns a string containing the string input by the user ''' while True: # repeat forever try: result=input(prompt) # read the input # if we get here no exception was raised if result=='': #don't accept empty lines print('Please enter text') else: # break out of the loop break except KeyboardInterrupt: # if we get here the user pressed CTRL+C print('Please enter text') if DEBUG_MODE: raise Exception('Keyboard interrupt') # return the result return result def readme(): print('''Welcome to the BTCInput functions version 1.0 You can use these to read numbers and strings in your programs. The functions are used as follows: text = read_text(prompt) int_value = read_int(prompt) float_falue = read_float(prompt) int_value = read_int_ranged(prompt, max_value, min_value) float_falue = read_float_ranged(prompt, max_value, min_value) Have fun with them. Rob Miles''') if __name__ == '__main__': # Have the BTCInput module introduce itself readme() def read_number(prompt,function): ''' Displays a prompt and reads in a floating point number. Keyboard interrupts (CTRL+C) are ignored Invalid numbers are rejected returns a float containing the value input by the user ''' while True: # repeat forever try: number_text=read_text(prompt) result=function(number_text) # read the input # if we get here no exception was raised # break out of the loop break except ValueError: # if we get here the user entered an invalid number print('Please enter a number') # return the result return result def read_number_ranged(prompt, function, min_value, max_value): ''' Displays a prompt and reads in a number. min_value gives the inclusive minimum value max_value gives the inclusive maximum value Raises an exception if max and min are the wrong way round Keyboard interrupts (CTRL+C) are ignored Invalid numbers are rejected returns a number containing the value input by the user ''' if min_value>max_value: # If we get here the min and the max # are wrong way round raise Exception('Min value is greater than max value') while True: # repeat forever result=read_number(prompt,function) if result<min_value: # Value entered is too low print('That number is too low') print('Minimum value is:',min_value) # Repeat the number reading loop continue if result>max_value: # Value entered is too high print('That number is too high') print('Maximum value is:',max_value) # Repeat the number reading loop continue # If we get here the number is valid # break out of the loop break # return the result return result def read_float(prompt): ''' Displays a prompt and reads in a floating point number. Keyboard interrupts (CTRL+C) are ignored Invalid numbers are rejected returns a float containing the value input by the user ''' return read_number(prompt,float) def read_int(prompt): ''' Displays a prompt and reads in an integer number. Keyboard interrupts (CTRL+C) are ignored Invalid numbers are rejected returns an int containing the value input by the user ''' return read_number(prompt,int) def read_float_ranged(prompt, min_value, max_value): ''' Displays a prompt and reads in a floating point number. min_value gives the inclusive minimum value max_value gives the inclusive maximum value Raises an exception if max and min are the wrong way round Keyboard interrupts (CTRL+C) are ignored Invalid numbers are rejected returns a number containing the value input by the user ''' return read_number_ranged(prompt,float,min_value,max_value) def read_int_ranged(prompt, min_value, max_value): ''' Displays a prompt and reads in an integer point number. min_value gives the inclusive minimum value max_value gives the inclusive maximum value Raises an exception if max and min are the wrong way round Keyboard interrupts (CTRL+C) are ignored Invalid numbers are rejected returns a number containing the value input by the user ''' return read_number_ranged(prompt,int,min_value,max_value)
""" Set of functions to provide managed input for Python programs. Uses the input and print standard input functions to read, but provides ranged checked input functions, and also handles CTRL+C input which would normally break a Python application. CTRL+C handling can be turned off by setting DEBUG_MODE to True so that a program can be interrupted. """ debug_mode = True def read_text(prompt): """ Displays a prompt and reads in a string of text. Keyboard interrupts (CTRL+C) are ignored returns a string containing the string input by the user """ while True: try: result = input(prompt) if result == '': print('Please enter text') else: break except KeyboardInterrupt: print('Please enter text') if DEBUG_MODE: raise exception('Keyboard interrupt') return result def readme(): print('Welcome to the BTCInput functions version 1.0\n\nYou can use these to read numbers and strings in your programs.\nThe functions are used as follows:\ntext = read_text(prompt)\nint_value = read_int(prompt)\nfloat_falue = read_float(prompt)\nint_value = read_int_ranged(prompt, max_value, min_value)\nfloat_falue = read_float_ranged(prompt, max_value, min_value)\n\nHave fun with them.\n\nRob Miles') if __name__ == '__main__': readme() def read_number(prompt, function): """ Displays a prompt and reads in a floating point number. Keyboard interrupts (CTRL+C) are ignored Invalid numbers are rejected returns a float containing the value input by the user """ while True: try: number_text = read_text(prompt) result = function(number_text) break except ValueError: print('Please enter a number') return result def read_number_ranged(prompt, function, min_value, max_value): """ Displays a prompt and reads in a number. min_value gives the inclusive minimum value max_value gives the inclusive maximum value Raises an exception if max and min are the wrong way round Keyboard interrupts (CTRL+C) are ignored Invalid numbers are rejected returns a number containing the value input by the user """ if min_value > max_value: raise exception('Min value is greater than max value') while True: result = read_number(prompt, function) if result < min_value: print('That number is too low') print('Minimum value is:', min_value) continue if result > max_value: print('That number is too high') print('Maximum value is:', max_value) continue break return result def read_float(prompt): """ Displays a prompt and reads in a floating point number. Keyboard interrupts (CTRL+C) are ignored Invalid numbers are rejected returns a float containing the value input by the user """ return read_number(prompt, float) def read_int(prompt): """ Displays a prompt and reads in an integer number. Keyboard interrupts (CTRL+C) are ignored Invalid numbers are rejected returns an int containing the value input by the user """ return read_number(prompt, int) def read_float_ranged(prompt, min_value, max_value): """ Displays a prompt and reads in a floating point number. min_value gives the inclusive minimum value max_value gives the inclusive maximum value Raises an exception if max and min are the wrong way round Keyboard interrupts (CTRL+C) are ignored Invalid numbers are rejected returns a number containing the value input by the user """ return read_number_ranged(prompt, float, min_value, max_value) def read_int_ranged(prompt, min_value, max_value): """ Displays a prompt and reads in an integer point number. min_value gives the inclusive minimum value max_value gives the inclusive maximum value Raises an exception if max and min are the wrong way round Keyboard interrupts (CTRL+C) are ignored Invalid numbers are rejected returns a number containing the value input by the user """ return read_number_ranged(prompt, int, min_value, max_value)
''' This package contains material and attributes class ''' # ---------- # Attributes # ---------- class Attributes(): '''Attributes is the base class for all attributes container. `Environment` and `Material` are attribute container ''' def __init__(self, attributes=None): ''' *Parameters:* - `attributes`: `list` of attributes ot initialize this object ''' self.attributes = {} if attributes: for a in attributes: self.set(a) def set(self, attribute): '''Set a material attribute *Parameters:* - `attribute`: `Attribute` to set ''' self.attributes[attribute.__class__] = attribute def get(self, attribute_class): '''Get an attribute by class *Parameters:* - `attribute_class`: Class of the attribute to retrieve ''' return self.attributes[attribute_class] class Material(Attributes): '''Material is a container for `Attribute` objects Only one object of the same `Attribute` class can be inside the material. If you set an attribute which is already in the `Material`, the old one is replaced by the new one. ''' pass class Environments(Attributes): ''' Environment contains all `Attribute` related to the environment, like lights, fogs... ''' pass # ---------- # Attribute # ---------- class Attribute(): ''' Base class for attribute classes. ''' def __init__(self, value): self.value = value class ColorAttribute(Attribute): pass
""" This package contains material and attributes class """ class Attributes: """Attributes is the base class for all attributes container. `Environment` and `Material` are attribute container """ def __init__(self, attributes=None): """ *Parameters:* - `attributes`: `list` of attributes ot initialize this object """ self.attributes = {} if attributes: for a in attributes: self.set(a) def set(self, attribute): """Set a material attribute *Parameters:* - `attribute`: `Attribute` to set """ self.attributes[attribute.__class__] = attribute def get(self, attribute_class): """Get an attribute by class *Parameters:* - `attribute_class`: Class of the attribute to retrieve """ return self.attributes[attribute_class] class Material(Attributes): """Material is a container for `Attribute` objects Only one object of the same `Attribute` class can be inside the material. If you set an attribute which is already in the `Material`, the old one is replaced by the new one. """ pass class Environments(Attributes): """ Environment contains all `Attribute` related to the environment, like lights, fogs... """ pass class Attribute: """ Base class for attribute classes. """ def __init__(self, value): self.value = value class Colorattribute(Attribute): pass
# ENTER TIME CONTROLLER # This allows a user to enter a time of the day, in hours, minutes, and AM/PM # # INPUTS: # temp_inside # temp_outside # humidity # gas # motion # timestamp # # OUTPUTS: # line1 # line2 # # CONTEXT: # action(start_in_minutes, end_in_minutes) -> function(inputs, state, settings) -> new_state, setting_changes def time_in_minutes(t): hour = t["hour"] minute = t["minute"] pm = t["pm"] hour = hour % 12 + (12 if pm else 0) return 60 * hour + minute # INITIAL STATE def init_state(): return { "start": { "hour": 12, "minute": 0, "pm": False, }, "end": { "hour": 12, "minute": 0, "pm": False, }, "start_selected": True, "selected": "hour" } # EVENT HANDLER def handle_event(event, inputs, state, settings, context): new_state = dict(state) setting_changes = {} log_entries = [] messages = [] done = False launch = None if event[0] == 'press': key = event[1] if key == 'A': if state["selected"] == "hour": new_state["start_selected"] = not state["start_selected"] new_state["selected"] = "pm" elif state["selected"] == "minute": new_state["selected"] = "hour" else: new_state["selected"] = "minute" elif key == 'D': if state["selected"] == "hour": new_state["selected"] = "minute" elif state["selected"] == "minute": new_state["selected"] = "pm" else: new_state["start_selected"] = not state["start_selected"] new_state["selected"] = "hour" elif key == 'C': done = True elif key == 'B': done = True launch = context(time_in_minutes(state["start"]), time_in_minutes(state["end"])) elif str(key).isdigit(): tname = "start" if state["start_selected"] else "end" if state["selected"] == "pm": new_state[tname]["pm"] = int(key) > 1 else: val = state[tname][state["selected"]] new_val_concat = int(str(val) + str(key)) new_val_concat_valid = False if state["selected"] == "hour" and 1 <= new_val_concat <= 12: new_val_concat_valid = True elif state["selected"] == "minute" and 0 <= new_val_concat < 60: new_val_concat_valid = True if new_val_concat_valid: new_state[tname][state["selected"]] = new_val_concat elif int(key) > 0: new_state[tname][state["selected"]] = int(key) return new_state, setting_changes, log_entries, messages, done, launch def get_outputs(inputs, state, settings, context): t = state["start"] if state["start_selected"] else state["end"] hour = t["hour"] minute = t["minute"] pm = t["pm"] hour = ' ' + str(hour) if len(str(hour)) == 1 else str(hour) minute = '0' + str(minute) if len(str(minute)) == 1 else str(minute) if state["selected"] == "hour": line2 = "[" + str(hour) + "]: " + str(minute) + " " + ("PM" if pm else "AM") + " " elif state["selected"] == "minute": line2 = " " + str(hour) + " :[" + str(minute) + "] " + ("PM" if pm else "AM") + " " else: line2 = " " + str(hour) + " : " + str(minute) + " [" + ("PM" if pm else "AM") + "]" return { "line1": "On between..." if state["start_selected"] else "...and", "line2": line2 + "->" if state["start_selected"] else "->" + line2 }
def time_in_minutes(t): hour = t['hour'] minute = t['minute'] pm = t['pm'] hour = hour % 12 + (12 if pm else 0) return 60 * hour + minute def init_state(): return {'start': {'hour': 12, 'minute': 0, 'pm': False}, 'end': {'hour': 12, 'minute': 0, 'pm': False}, 'start_selected': True, 'selected': 'hour'} def handle_event(event, inputs, state, settings, context): new_state = dict(state) setting_changes = {} log_entries = [] messages = [] done = False launch = None if event[0] == 'press': key = event[1] if key == 'A': if state['selected'] == 'hour': new_state['start_selected'] = not state['start_selected'] new_state['selected'] = 'pm' elif state['selected'] == 'minute': new_state['selected'] = 'hour' else: new_state['selected'] = 'minute' elif key == 'D': if state['selected'] == 'hour': new_state['selected'] = 'minute' elif state['selected'] == 'minute': new_state['selected'] = 'pm' else: new_state['start_selected'] = not state['start_selected'] new_state['selected'] = 'hour' elif key == 'C': done = True elif key == 'B': done = True launch = context(time_in_minutes(state['start']), time_in_minutes(state['end'])) elif str(key).isdigit(): tname = 'start' if state['start_selected'] else 'end' if state['selected'] == 'pm': new_state[tname]['pm'] = int(key) > 1 else: val = state[tname][state['selected']] new_val_concat = int(str(val) + str(key)) new_val_concat_valid = False if state['selected'] == 'hour' and 1 <= new_val_concat <= 12: new_val_concat_valid = True elif state['selected'] == 'minute' and 0 <= new_val_concat < 60: new_val_concat_valid = True if new_val_concat_valid: new_state[tname][state['selected']] = new_val_concat elif int(key) > 0: new_state[tname][state['selected']] = int(key) return (new_state, setting_changes, log_entries, messages, done, launch) def get_outputs(inputs, state, settings, context): t = state['start'] if state['start_selected'] else state['end'] hour = t['hour'] minute = t['minute'] pm = t['pm'] hour = ' ' + str(hour) if len(str(hour)) == 1 else str(hour) minute = '0' + str(minute) if len(str(minute)) == 1 else str(minute) if state['selected'] == 'hour': line2 = '[' + str(hour) + ']: ' + str(minute) + ' ' + ('PM' if pm else 'AM') + ' ' elif state['selected'] == 'minute': line2 = ' ' + str(hour) + ' :[' + str(minute) + '] ' + ('PM' if pm else 'AM') + ' ' else: line2 = ' ' + str(hour) + ' : ' + str(minute) + ' [' + ('PM' if pm else 'AM') + ']' return {'line1': 'On between...' if state['start_selected'] else '...and', 'line2': line2 + '->' if state['start_selected'] else '->' + line2}
# Time between two pictures are taken in seconds, Raspberry Pi needs ca. 3 seconds to take one # picture with the current setting, so this value should be at least 3 CAMERA_INTERVAL_SECONDS = 3600 # Settings used for Serial communication with Arduino SERIAL_BAND_RATE = 9600 # times of retry when searing for the correct Serial port SERIAL_ERROR_MAX_RETRY = 10 # when using a serial port which continously having false data but was proven working before before, max waiting # time before abandoning the current connection and go through the port selection process again SERIAL_ERROR_MAX_TIMEOUT = 300 # MQTT base topics used for communication between Raspberry Pi and Cloud, subtopics will # be added after this depending on sensor or device type (these variables should end with '/') TOPIC_PREFIX_SENSOR = "/iot_cloud_solutions/project/db/regensburg/rpi_1/sensor/" TOPIC_PREFIX_CONTROL = "/iot_cloud_solutions/project/control/regensburg/rpi_1/device/"
camera_interval_seconds = 3600 serial_band_rate = 9600 serial_error_max_retry = 10 serial_error_max_timeout = 300 topic_prefix_sensor = '/iot_cloud_solutions/project/db/regensburg/rpi_1/sensor/' topic_prefix_control = '/iot_cloud_solutions/project/control/regensburg/rpi_1/device/'
''' Used by __init__.py to set the MongoDB configuration for the whole app The app can then be references/imported by other script using the __init__.py ''' DEBUG = True TESTING = True # mongo db SECRET_KEY = "vusualyzerrrrrrrr" MONGO_URI = "mongodb://localhost:27017/vus" # debug bar DEBUG_TB_INTERCEPT_REDIRECTS = False DEBUG_TB_PANELS = ( 'flask_debugtoolbar.panels.versions.VersionDebugPanel', 'flask_debugtoolbar.panels.timer.TimerDebugPanel', 'flask_debugtoolbar.panels.headers.HeaderDebugPanel', 'flask_debugtoolbar.panels.request_vars.RequestVarsDebugPanel', 'flask_debugtoolbar.panels.template.TemplateDebugPanel', 'flask_debugtoolbar.panels.logger.LoggingPanel', 'flask_mongoengine.panels.MongoDebugPanel' )
""" Used by __init__.py to set the MongoDB configuration for the whole app The app can then be references/imported by other script using the __init__.py """ debug = True testing = True secret_key = 'vusualyzerrrrrrrr' mongo_uri = 'mongodb://localhost:27017/vus' debug_tb_intercept_redirects = False debug_tb_panels = ('flask_debugtoolbar.panels.versions.VersionDebugPanel', 'flask_debugtoolbar.panels.timer.TimerDebugPanel', 'flask_debugtoolbar.panels.headers.HeaderDebugPanel', 'flask_debugtoolbar.panels.request_vars.RequestVarsDebugPanel', 'flask_debugtoolbar.panels.template.TemplateDebugPanel', 'flask_debugtoolbar.panels.logger.LoggingPanel', 'flask_mongoengine.panels.MongoDebugPanel')
#Contributed by @Hinal-Srivastava def binary_search(list,item): first = 0 last = len(list)-1 flag = False while( first<=last and not flag): mid = (first + last)//2 if list[mid] == item : flag = True print("Element found at ", mid," after sorting the list") else: if (item < list[mid]): last = mid - 1 else: first = mid + 1 if(flag == False): print("Element not part of given list") #Driver Program ele_lst = [] n = int(input("Enter number of elements : ")) #Length of list print("Enter Elements \n") for i in range(n): element = int(input("\t")) ele_lst.append(element) ele_lst.sort() item_=int(input("Enter search element : ")) print(binary_search(ele_lst, item_))
def binary_search(list, item): first = 0 last = len(list) - 1 flag = False while first <= last and (not flag): mid = (first + last) // 2 if list[mid] == item: flag = True print('Element found at ', mid, ' after sorting the list') elif item < list[mid]: last = mid - 1 else: first = mid + 1 if flag == False: print('Element not part of given list') ele_lst = [] n = int(input('Enter number of elements : ')) print('Enter Elements \n') for i in range(n): element = int(input('\t')) ele_lst.append(element) ele_lst.sort() item_ = int(input('Enter search element : ')) print(binary_search(ele_lst, item_))
# compute voltage drops top-bottom of H16, so for black. loops = 100 # iterations of voltage computation # 18 nodes in graph after black capture and dead cell removal Nbrs = [ [1,2,3,4], [0,4,5], [0,5,6], [0,6,7], [0,1,5,10,13], [1,2,4,6,10,13], [2,3,5,7,8], [3,6,8,9], [6,7,9,10,11], [7,8,11,12], [4,5,8,11,13,14], [8,9,10,12,14,15], [9,11,15,16], [4,5,10,17], [10,11,17], [11,12,17], [12,17], [13,14,15,16] ] #Nbrs2 has added the captured cells back in Nbrs2 = [ [1,2,3,4,5,6], [0,6], [0,6], [0,6,7], [0,7,8], [0,8,9], [0,1,2,3,7,12,15], [3,4,6,8,12,15], [4,5,7,9,10], [5,8,10,11], [8,9,11,12,13], [9,10,13,14], [6,7,10,13,15,16], [10,11,12,14,16,17], [11,13,17,18], [6,7,12,19], [12,13,19], [13,14,19], [14,19], [15,16,17,18] ] def update(V,Nbrs): for j in range(1,len(Nbrs)-1): vsum = 0.0 for k in Nbrs[j]: vsum+= V[k] V[j] = vsum/len(Nbrs[j]) def VDrops(V,Nbrs): Drops = [] for j in range(len(Nbrs)-1): delta, v = 0.0, V[j] for k in Nbrs[j]: if V[k] < v: delta += v - V[k] Drops.append(delta) return Drops def initV(n): V = [0.5] * n V[0], V[n-1] = 100.0, 0.0 return V Nb = Nbrs2 print(Nb) print('') Volts = initV(len(Nb)) print(Volts) print('') for t in range(loops): update(Volts, Nb) D = VDrops(Volts,Nb) print(Volts) print('') print(D)
loops = 100 nbrs = [[1, 2, 3, 4], [0, 4, 5], [0, 5, 6], [0, 6, 7], [0, 1, 5, 10, 13], [1, 2, 4, 6, 10, 13], [2, 3, 5, 7, 8], [3, 6, 8, 9], [6, 7, 9, 10, 11], [7, 8, 11, 12], [4, 5, 8, 11, 13, 14], [8, 9, 10, 12, 14, 15], [9, 11, 15, 16], [4, 5, 10, 17], [10, 11, 17], [11, 12, 17], [12, 17], [13, 14, 15, 16]] nbrs2 = [[1, 2, 3, 4, 5, 6], [0, 6], [0, 6], [0, 6, 7], [0, 7, 8], [0, 8, 9], [0, 1, 2, 3, 7, 12, 15], [3, 4, 6, 8, 12, 15], [4, 5, 7, 9, 10], [5, 8, 10, 11], [8, 9, 11, 12, 13], [9, 10, 13, 14], [6, 7, 10, 13, 15, 16], [10, 11, 12, 14, 16, 17], [11, 13, 17, 18], [6, 7, 12, 19], [12, 13, 19], [13, 14, 19], [14, 19], [15, 16, 17, 18]] def update(V, Nbrs): for j in range(1, len(Nbrs) - 1): vsum = 0.0 for k in Nbrs[j]: vsum += V[k] V[j] = vsum / len(Nbrs[j]) def v_drops(V, Nbrs): drops = [] for j in range(len(Nbrs) - 1): (delta, v) = (0.0, V[j]) for k in Nbrs[j]: if V[k] < v: delta += v - V[k] Drops.append(delta) return Drops def init_v(n): v = [0.5] * n (V[0], V[n - 1]) = (100.0, 0.0) return V nb = Nbrs2 print(Nb) print('') volts = init_v(len(Nb)) print(Volts) print('') for t in range(loops): update(Volts, Nb) d = v_drops(Volts, Nb) print(Volts) print('') print(D)
TARGET = 'embox' ARCH = 'x86' CFLAGS = ['-O0', '-g'] CFLAGS += ['-m32', '-march=i386', '-fno-stack-protector', '-Wno-array-bounds'] LDFLAGS = ['-N', '-g', '-m', 'elf_i386' ]
target = 'embox' arch = 'x86' cflags = ['-O0', '-g'] cflags += ['-m32', '-march=i386', '-fno-stack-protector', '-Wno-array-bounds'] ldflags = ['-N', '-g', '-m', 'elf_i386']
TITLE = "DoodleHop" # screen dims WIDTH = 480 HEIGHT = 600 # frames per second FPS = 60 # colors WHITE = (255, 255, 255) BLACK = (0,0,0) REDDISH = (240,55,66) SKY_BLUE = (0, 0, 0) FONT_NAME = 'arial' SPRITESHEET = "spritesheet_jumper.png" # data files HS_FILE = "highscore.txt" # player settings PLAYER_ACC = 0.5 PLAYER_FRICTION = -0.12 PLAYER_GRAV = 0.8 PLAYER_JUMP = 25 PLAYER_SUPERJUMP = 300 # game settings BOOST_POWER = 60 POW_SPAWN_PCT = 7 MOB_FREQ = 5000 PLAYER_LAYER = 2 PLATFORM_LAYER = 1 MLATFORM_LAYER = 1 POW_LAYER = 1 MOB_LAYER = 2 #SPRITES INT HE SAME LAYER CAN INTERACT WITH EACH OTHER (COLISONS) # platform settings ''' old platforms from drawing rectangles''' ''' PLATFORM_LIST = [(0, HEIGHT - 40, WIDTH, 40), (65, HEIGHT - 300, WIDTH-400, 40), (20, HEIGHT - 350, WIDTH-300, 40), (200, HEIGHT - 150, WIDTH-350, 40), (200, HEIGHT - 450, WIDTH-350, 40)] ''' PLATFORM_LIST = [(0, HEIGHT - 40), (65, HEIGHT - 300), (20, HEIGHT - 350), (200, HEIGHT - 150), (200, HEIGHT - 450)] MLATFORM_LIST = [(10, HEIGHT - 20), (30, HEIGHT - 500), (20, HEIGHT - 27)]
title = 'DoodleHop' width = 480 height = 600 fps = 60 white = (255, 255, 255) black = (0, 0, 0) reddish = (240, 55, 66) sky_blue = (0, 0, 0) font_name = 'arial' spritesheet = 'spritesheet_jumper.png' hs_file = 'highscore.txt' player_acc = 0.5 player_friction = -0.12 player_grav = 0.8 player_jump = 25 player_superjump = 300 boost_power = 60 pow_spawn_pct = 7 mob_freq = 5000 player_layer = 2 platform_layer = 1 mlatform_layer = 1 pow_layer = 1 mob_layer = 2 ' old platforms from drawing rectangles' '\nPLATFORM_LIST = [(0, HEIGHT - 40, WIDTH, 40),\n (65, HEIGHT - 300, WIDTH-400, 40),\n (20, HEIGHT - 350, WIDTH-300, 40),\n (200, HEIGHT - 150, WIDTH-350, 40),\n (200, HEIGHT - 450, WIDTH-350, 40)]\n' platform_list = [(0, HEIGHT - 40), (65, HEIGHT - 300), (20, HEIGHT - 350), (200, HEIGHT - 150), (200, HEIGHT - 450)] mlatform_list = [(10, HEIGHT - 20), (30, HEIGHT - 500), (20, HEIGHT - 27)]
height = int(input()) for i in range(1,height+1): for j in range(1,height+1): if(i < height//2+1): print(0,end=" ") else: print(1,end=" ") print() # Sample Input :- 5 # Output :- # 0 0 0 0 0 # 0 0 0 0 0 # 1 1 1 1 1 # 1 1 1 1 1 # 1 1 1 1 1
height = int(input()) for i in range(1, height + 1): for j in range(1, height + 1): if i < height // 2 + 1: print(0, end=' ') else: print(1, end=' ') print()
class FsharpPackage(GitHubTarballPackage): def __init__(self): GitHubTarballPackage.__init__(self, 'fsharp', 'fsharp', '3.0.27', 'f3c8ea8bf4831ce6dc30581558fa4a45a078cd55', configure = '') def build(self): self.sh ('autoreconf') self.sh ('./configure --prefix="%{prefix}"') self.sh ('make') FsharpPackage()
class Fsharppackage(GitHubTarballPackage): def __init__(self): GitHubTarballPackage.__init__(self, 'fsharp', 'fsharp', '3.0.27', 'f3c8ea8bf4831ce6dc30581558fa4a45a078cd55', configure='') def build(self): self.sh('autoreconf') self.sh('./configure --prefix="%{prefix}"') self.sh('make') fsharp_package()
# key: symbol, charge, number of !'s (hypervalent marker) VALENCE = { ("H", 0, 0): 1, ("H", 1, 0): 0, ("He", 0, 0): 0, ("Li", 1, 0): 0, ("Li", 0, 0): 1, ("Be", 2, 0): 0, ("B", 0, 0): 3, ("B", -1, 0): 4, ("C", 0, 0): 4, ("C", -1, 0): 3, ("C", 1, 0): 3, ("N", 0, 0): 3, ("N", 1, 0): 4, ("N", -1, 0): 2, ("O", 0, 0): 2, ("O", -1, 0): 1, ("O", -2, 0): 0, ("O", 1, 0): 3, ("F", 0, 0): 1, ("F", -1, 0): 0, ("F", 1, 0): 2, ("Na", 0, 0): 1, ("Na", 1, 0): 0, ("Mg", 0, 0): 2, ("Mg", 1, 0): 1, ("Mg", 2, 0): 0, ("Al", 0, 0): 3, ("Al", 3, 0): 0, ("Al", -3, 0): 6, ("Xe", 0, 0): 0, ("Si", 0, 0): 4, ("Si", -1, 0): 5, ("P", 0, 0): 3, ("P", 0, 1): 5, ("P", 0, 2): 7, ("P", 1, 0): 4, ("P", -1, 1): 6, ("S", 0, 0): 2, ("S", 0, 1): 4, ("S", 0, 2): 6, ("S", 1, 0): 3, ("S", 1, 1): 5, ("S", -1, 0): 1, ("S", -1, 1): 3, ("S", -2, 0): 0, ("Cl", 0, 0): 1, ("Cl", -1, 0): 0, ("Cl", 1, 0): 2, ("Cl", 2, 0): 3, ("Cl", 3, 0): 4, ("K", 0, 0): 1, ("K", 1, 0): 0, ("Ca", 0, 0): 2, ("Ca", 2, 0): 0, ("Zn", 0, 0): 2, ("Zn", 1, 0): 1, ("Zn", 2, 0): 1, ("Zn", -2, 0): 2, ("Zn", -2, 1): 4, ("As", 0, 0): 3, ("As", 0, 1): 5, ("As", 0, 2): 7, ("As", 1, 0): 4, ("As", -1, 1): 6, ("Se", 0, 0): 2, ("Se", 0, 1): 4, ("Se", 0, 2): 6, ("Se", 1, 0): 3, ("Se", 1, 1): 5, ("Se", -1, 0): 1, ("Se", -2, 0): 0, ("Cs", 1, 0): 0, ("Cs", 0, 0): 1, ("Ba", 0, 0): 2, ("Ba", 2, 0): 0, ("Bi", 0, 0): 3, ("Bi", 3, 0): 0, ("Br", 0, 0): 1, ("Br", -1, 0): 0, ("Br", 2, 0): 3, ("Kr", 0, 0): 0, ("Rb", 0, 0): 1, ("Rb", 1, 0): 0, ("Sr", 0, 0): 2, ("Sr", 2, 0): 0, ("Ag", 0, 0): 2, ("Ag", 1, 0): 0, ("Ag", -4, 0): 3, ("Te", 0, 0): 2, ("Te", 1, 0): 3, ("Te", 0, 1): 4, ("Te", 0, 2): 6, ("Te", -1, 1): 3, ("Te", -1, 2): 5, ("I", 0, 0): 1, ("I", 0, 1): 3, ("I", 0, 2): 5, ("I", -1, 0): 0, ("I", 1, 0): 2, ("I", 2, 1): 3, ("I", 3, 0): 4, ("Ra", 0, 0): 2, ("Ra", 2, 0): 0, } # key: symbol, charge, valence BANGS = { ("S", 0, 4): 1, ("S", 1, 5): 1, ("S", -1, 3): 1, ("S", 0, 6): 2, ("P", 0, 5): 1, ("P", 0, 7): 2, ("P", -1, 6): 1, ("Zn", -2, 4): 1, ("As", 0, 5): 1, ("As", 0, 7): 2, ("As", -1, 6): 1, ("Se", 0, 4): 1, ("Se", 1, 5): 1, ("Se", -1, 3): 1, ("Se", 0, 6): 2, ("Te", 0, 4): 1, ("Te", 0, 6): 2, ("Te", -1, 3): 1, ("Te", -1, 5): 2, ("I", 0, 3): 1, ("I", 0, 5): 2, ("I", 2, 3): 1, }
valence = {('H', 0, 0): 1, ('H', 1, 0): 0, ('He', 0, 0): 0, ('Li', 1, 0): 0, ('Li', 0, 0): 1, ('Be', 2, 0): 0, ('B', 0, 0): 3, ('B', -1, 0): 4, ('C', 0, 0): 4, ('C', -1, 0): 3, ('C', 1, 0): 3, ('N', 0, 0): 3, ('N', 1, 0): 4, ('N', -1, 0): 2, ('O', 0, 0): 2, ('O', -1, 0): 1, ('O', -2, 0): 0, ('O', 1, 0): 3, ('F', 0, 0): 1, ('F', -1, 0): 0, ('F', 1, 0): 2, ('Na', 0, 0): 1, ('Na', 1, 0): 0, ('Mg', 0, 0): 2, ('Mg', 1, 0): 1, ('Mg', 2, 0): 0, ('Al', 0, 0): 3, ('Al', 3, 0): 0, ('Al', -3, 0): 6, ('Xe', 0, 0): 0, ('Si', 0, 0): 4, ('Si', -1, 0): 5, ('P', 0, 0): 3, ('P', 0, 1): 5, ('P', 0, 2): 7, ('P', 1, 0): 4, ('P', -1, 1): 6, ('S', 0, 0): 2, ('S', 0, 1): 4, ('S', 0, 2): 6, ('S', 1, 0): 3, ('S', 1, 1): 5, ('S', -1, 0): 1, ('S', -1, 1): 3, ('S', -2, 0): 0, ('Cl', 0, 0): 1, ('Cl', -1, 0): 0, ('Cl', 1, 0): 2, ('Cl', 2, 0): 3, ('Cl', 3, 0): 4, ('K', 0, 0): 1, ('K', 1, 0): 0, ('Ca', 0, 0): 2, ('Ca', 2, 0): 0, ('Zn', 0, 0): 2, ('Zn', 1, 0): 1, ('Zn', 2, 0): 1, ('Zn', -2, 0): 2, ('Zn', -2, 1): 4, ('As', 0, 0): 3, ('As', 0, 1): 5, ('As', 0, 2): 7, ('As', 1, 0): 4, ('As', -1, 1): 6, ('Se', 0, 0): 2, ('Se', 0, 1): 4, ('Se', 0, 2): 6, ('Se', 1, 0): 3, ('Se', 1, 1): 5, ('Se', -1, 0): 1, ('Se', -2, 0): 0, ('Cs', 1, 0): 0, ('Cs', 0, 0): 1, ('Ba', 0, 0): 2, ('Ba', 2, 0): 0, ('Bi', 0, 0): 3, ('Bi', 3, 0): 0, ('Br', 0, 0): 1, ('Br', -1, 0): 0, ('Br', 2, 0): 3, ('Kr', 0, 0): 0, ('Rb', 0, 0): 1, ('Rb', 1, 0): 0, ('Sr', 0, 0): 2, ('Sr', 2, 0): 0, ('Ag', 0, 0): 2, ('Ag', 1, 0): 0, ('Ag', -4, 0): 3, ('Te', 0, 0): 2, ('Te', 1, 0): 3, ('Te', 0, 1): 4, ('Te', 0, 2): 6, ('Te', -1, 1): 3, ('Te', -1, 2): 5, ('I', 0, 0): 1, ('I', 0, 1): 3, ('I', 0, 2): 5, ('I', -1, 0): 0, ('I', 1, 0): 2, ('I', 2, 1): 3, ('I', 3, 0): 4, ('Ra', 0, 0): 2, ('Ra', 2, 0): 0} bangs = {('S', 0, 4): 1, ('S', 1, 5): 1, ('S', -1, 3): 1, ('S', 0, 6): 2, ('P', 0, 5): 1, ('P', 0, 7): 2, ('P', -1, 6): 1, ('Zn', -2, 4): 1, ('As', 0, 5): 1, ('As', 0, 7): 2, ('As', -1, 6): 1, ('Se', 0, 4): 1, ('Se', 1, 5): 1, ('Se', -1, 3): 1, ('Se', 0, 6): 2, ('Te', 0, 4): 1, ('Te', 0, 6): 2, ('Te', -1, 3): 1, ('Te', -1, 5): 2, ('I', 0, 3): 1, ('I', 0, 5): 2, ('I', 2, 3): 1}
# 235 Lowest Common Ancestor of a Binary Search Tree # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def lowestCommonAncestor(self, root, p, q): if root.val == p.val or root.val == q.val: return root if (p.val < root.val and root.val < q.val) or (p.val > root.val and root.val > q.val): return root if p.val < root.val and q.val < root.val: return self.lowestCommonAncestor(root.left, p, q) return self.lowestCommonAncestor(root.right, p, q) if __name__ == '__main__': pass
class Treenode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def lowest_common_ancestor(self, root, p, q): if root.val == p.val or root.val == q.val: return root if p.val < root.val and root.val < q.val or (p.val > root.val and root.val > q.val): return root if p.val < root.val and q.val < root.val: return self.lowestCommonAncestor(root.left, p, q) return self.lowestCommonAncestor(root.right, p, q) if __name__ == '__main__': pass
def checkout_values(counter_of_items, dict_of_deals): # loops through trying to find best deal on items # does this by subtracting max until it can do no more, pops the max and # loops with second max and so on... value = 0 for item in counter_of_items: if item in dict_of_deals: num = counter_of_items[item] list_of_dict = list(dict_of_deals[item]) result = [] while num > 0: num -= max(list_of_dict) if num == 0: result.append(max(list_of_dict)) break if num > 0: result.append(max(list_of_dict)) if num < 0: num += max(list_of_dict) list_of_dict.pop(list_of_dict.index(max(list_of_dict))) for x in result: value += dict_of_deals[item][x] return value
def checkout_values(counter_of_items, dict_of_deals): value = 0 for item in counter_of_items: if item in dict_of_deals: num = counter_of_items[item] list_of_dict = list(dict_of_deals[item]) result = [] while num > 0: num -= max(list_of_dict) if num == 0: result.append(max(list_of_dict)) break if num > 0: result.append(max(list_of_dict)) if num < 0: num += max(list_of_dict) list_of_dict.pop(list_of_dict.index(max(list_of_dict))) for x in result: value += dict_of_deals[item][x] return value
class DatabaseData: ''' Representation of data read or to write in a no-sql database Attributes: category : str Which document or root element this data belongs to values : dict Data to insert into the document or under the root element ''' def __init__(self, category : str, values): ''' Parameters: category : str What category/document/root this data is from values : dict or list Data read from the category ''' self.category = category self.values = values
class Databasedata: """ Representation of data read or to write in a no-sql database Attributes: category : str Which document or root element this data belongs to values : dict Data to insert into the document or under the root element """ def __init__(self, category: str, values): """ Parameters: category : str What category/document/root this data is from values : dict or list Data read from the category """ self.category = category self.values = values
BLACK = ( 0, 0, 0) WHITE = ( 255, 255, 255) GREEN = ( 0, 255, 0) RED = ( 255, 0, 0) GREY = ( 100, 100, 100) SCREEN_WIDTH = 900 SCREEN_HEIGHT = 600
black = (0, 0, 0) white = (255, 255, 255) green = (0, 255, 0) red = (255, 0, 0) grey = (100, 100, 100) screen_width = 900 screen_height = 600
class check_anagram: def __init__(self,s1,s2): self.s1=s1 self.s2=s2 def check(self): # the sorted strings are checked if(sorted(self.s1)== sorted(self.s2)): print("The strings are anagrams.") else: print("The strings aren't anagrams.") if __name__=='__main__': # driver code s1 =input("Enter the first string") s2 =input("Enter the first string") c_anangram=check_anagram(s1,s2) c_anangram.check()
class Check_Anagram: def __init__(self, s1, s2): self.s1 = s1 self.s2 = s2 def check(self): if sorted(self.s1) == sorted(self.s2): print('The strings are anagrams.') else: print("The strings aren't anagrams.") if __name__ == '__main__': s1 = input('Enter the first string') s2 = input('Enter the first string') c_anangram = check_anagram(s1, s2) c_anangram.check()
class CiphertextMessage(Message): def __init__(self, text): ''' Initializes a CiphertextMessage object text (string): the message's text a CiphertextMessage object has two attributes: self.message_text (string, determined by input text) self.valid_words (list, determined using helper function load_words) ''' self.message_text = text self.valid_words= (load_words(WORDLIST_FILENAME)) def decrypt_message(self): ''' Decrypt self.message_text by trying every possible shift value and find the "best" one. We will define "best" as the shift that creates the maximum number of real words when we use apply_shift(shift) on the message text. If s is the original shift value used to encrypt the message, then we would expect 26 - s to be the best shift value for decrypting it. Note: if multiple shifts are equally good such that they all create the maximum number of you may choose any of those shifts (and their corresponding decrypted messages) to return Returns: a tuple of the best shift value used to decrypt the message and the decrypted message text using that shift value ''' # pass #delete this line and replace with your code here text = self.message_text.split(' ') shift_value = 0 for shifter in range(26): for i in list(super(CiphertextMessage, self).apply_shift(shifter).split(' ')): if is_word(self.valid_words, i): shift_value = shifter listo = super(CiphertextMessage, self).apply_shift(shift_value) return (shift_value, listo)
class Ciphertextmessage(Message): def __init__(self, text): """ Initializes a CiphertextMessage object text (string): the message's text a CiphertextMessage object has two attributes: self.message_text (string, determined by input text) self.valid_words (list, determined using helper function load_words) """ self.message_text = text self.valid_words = load_words(WORDLIST_FILENAME) def decrypt_message(self): """ Decrypt self.message_text by trying every possible shift value and find the "best" one. We will define "best" as the shift that creates the maximum number of real words when we use apply_shift(shift) on the message text. If s is the original shift value used to encrypt the message, then we would expect 26 - s to be the best shift value for decrypting it. Note: if multiple shifts are equally good such that they all create the maximum number of you may choose any of those shifts (and their corresponding decrypted messages) to return Returns: a tuple of the best shift value used to decrypt the message and the decrypted message text using that shift value """ text = self.message_text.split(' ') shift_value = 0 for shifter in range(26): for i in list(super(CiphertextMessage, self).apply_shift(shifter).split(' ')): if is_word(self.valid_words, i): shift_value = shifter listo = super(CiphertextMessage, self).apply_shift(shift_value) return (shift_value, listo)
n = int(input()) p = list(map(int,input().split())) p.sort() sum_ = 0 for i in range(len(p)+1): sum_ += sum(p[:i]) print(sum_)
n = int(input()) p = list(map(int, input().split())) p.sort() sum_ = 0 for i in range(len(p) + 1): sum_ += sum(p[:i]) print(sum_)