content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
LANGUAGES = ['Auto', 'Afrikaans', 'Albanian', 'Amharic', 'Arabic', 'Armenian', 'Azerbaijani', 'Basque', 'Belarusian', 'Bengali', 'Bosnian', 'Bulgarian', 'Catalan', 'Cebuano', 'Chichewa', 'Chinese (Simplified)', 'Chinese (Traditional)', 'Corsican', 'Croatian', 'Czech', 'Danish', 'Dutch', 'English', 'Esperanto', 'Estonian', 'Filipino', 'Finnish', 'French', 'Frisian', 'Galician', 'Georgian', 'German', 'Greek', 'Gujarati', 'Haitian Creole', 'Hausa', 'Hawaiian', 'Hebrew', 'Hindi','hmong', 'Hungarian', 'Icelandic', 'Igbo', 'Indonesian', 'Irish', 'Italian', 'Japanese', 'Javanese', 'Kannada', 'Kazakh', 'Khmer', 'Korean', 'Kurdish (Kurmanji)', 'Kyrgyz', 'Lao', 'Latin', 'Latvian', 'Lithuanian', 'Luxembourgish', 'Macedonian', 'Malagasy', 'Malay', 'Malayalam', 'Maltese', 'Maori', 'Marathi', 'Mongolian', 'Myanmar (Burmese)', 'Nepali', 'Norwegian', 'Odia', 'Pashto', 'Persian', 'Polish', 'Portuguese', 'Punjabi', 'Romanian', 'Russian', 'Samoan', 'Scots Gaelic','Serbian', 'Sesotho', 'Shona', 'Sindhi', 'Sinhala', 'Slovak', 'Slovenian', 'Somali', 'Spanish', 'Sundanese', 'Swahili', 'Swedish', 'Tajik', 'Tamil', 'Telugu', 'Thai', 'Turkish', 'Turkmen', 'Ukrainian', 'Urdu', 'Uyghur', 'Uzbek', 'Vietnamese', 'Welsh', 'Xhosa', 'Yiddish', 'Yoruba', 'Zulu' ]
languages = ['Auto', 'Afrikaans', 'Albanian', 'Amharic', 'Arabic', 'Armenian', 'Azerbaijani', 'Basque', 'Belarusian', 'Bengali', 'Bosnian', 'Bulgarian', 'Catalan', 'Cebuano', 'Chichewa', 'Chinese (Simplified)', 'Chinese (Traditional)', 'Corsican', 'Croatian', 'Czech', 'Danish', 'Dutch', 'English', 'Esperanto', 'Estonian', 'Filipino', 'Finnish', 'French', 'Frisian', 'Galician', 'Georgian', 'German', 'Greek', 'Gujarati', 'Haitian Creole', 'Hausa', 'Hawaiian', 'Hebrew', 'Hindi', 'hmong', 'Hungarian', 'Icelandic', 'Igbo', 'Indonesian', 'Irish', 'Italian', 'Japanese', 'Javanese', 'Kannada', 'Kazakh', 'Khmer', 'Korean', 'Kurdish (Kurmanji)', 'Kyrgyz', 'Lao', 'Latin', 'Latvian', 'Lithuanian', 'Luxembourgish', 'Macedonian', 'Malagasy', 'Malay', 'Malayalam', 'Maltese', 'Maori', 'Marathi', 'Mongolian', 'Myanmar (Burmese)', 'Nepali', 'Norwegian', 'Odia', 'Pashto', 'Persian', 'Polish', 'Portuguese', 'Punjabi', 'Romanian', 'Russian', 'Samoan', 'Scots Gaelic', 'Serbian', 'Sesotho', 'Shona', 'Sindhi', 'Sinhala', 'Slovak', 'Slovenian', 'Somali', 'Spanish', 'Sundanese', 'Swahili', 'Swedish', 'Tajik', 'Tamil', 'Telugu', 'Thai', 'Turkish', 'Turkmen', 'Ukrainian', 'Urdu', 'Uyghur', 'Uzbek', 'Vietnamese', 'Welsh', 'Xhosa', 'Yiddish', 'Yoruba', 'Zulu']
n = int(input()) if n%2!=0: print('Weird') elif 2<n<=5 and n%2==0: print('Not Weird') elif 6<n<=20 and n%2==0: print('Weird') elif n>20 and n%2==0: print('Not Weird')
n = int(input()) if n % 2 != 0: print('Weird') elif 2 < n <= 5 and n % 2 == 0: print('Not Weird') elif 6 < n <= 20 and n % 2 == 0: print('Weird') elif n > 20 and n % 2 == 0: print('Not Weird')
expected_output = { "interface": { "FastEthernet2/1/1.2": { "ethernet_vlan": {2: {"status": "up"}}, "status": "up", "destination_address": { "10.2.2.2": { "default_path": "active", "imposed_label_stack": "{16}", "next_hop": "point2point", "output_interface": "Serial2/0/2", "tunnel_label": "imp-null", "vc_id": {"1002": {"vc_status": "up"}}, "preferred_path": "not configured", } }, "last_status_change_time": "1d00h", "line_protocol_status": "up", "signaling_protocol": { "LDP": { "peer_id": "10.2.2.2:0", "remote_interface_description": "xconnect to PE2", "group_id": {"local": "0", "remote": "0"}, "peer_state": "up", "mtu": {"local": "1500", "remote": "1500"}, "mpls_vc_labels": {"local": "21", "remote": "16"}, } }, "create_time": "1d00h", "statistics": { "bytes": {"received": 4322368, "sent": 5040220}, "packets": {"received": 3466, "sent": 12286}, "packets_drop": {"received": 0, "sent": 0}, }, "sequencing": {"received": "disabled", "sent": "disabled"}, } } }
expected_output = {'interface': {'FastEthernet2/1/1.2': {'ethernet_vlan': {2: {'status': 'up'}}, 'status': 'up', 'destination_address': {'10.2.2.2': {'default_path': 'active', 'imposed_label_stack': '{16}', 'next_hop': 'point2point', 'output_interface': 'Serial2/0/2', 'tunnel_label': 'imp-null', 'vc_id': {'1002': {'vc_status': 'up'}}, 'preferred_path': 'not configured'}}, 'last_status_change_time': '1d00h', 'line_protocol_status': 'up', 'signaling_protocol': {'LDP': {'peer_id': '10.2.2.2:0', 'remote_interface_description': 'xconnect to PE2', 'group_id': {'local': '0', 'remote': '0'}, 'peer_state': 'up', 'mtu': {'local': '1500', 'remote': '1500'}, 'mpls_vc_labels': {'local': '21', 'remote': '16'}}}, 'create_time': '1d00h', 'statistics': {'bytes': {'received': 4322368, 'sent': 5040220}, 'packets': {'received': 3466, 'sent': 12286}, 'packets_drop': {'received': 0, 'sent': 0}}, 'sequencing': {'received': 'disabled', 'sent': 'disabled'}}}}
class InvalidResponseException(Exception): def __init__(self, message): self.message = f'Request was not success: {message}' super()
class Invalidresponseexception(Exception): def __init__(self, message): self.message = f'Request was not success: {message}' super()
# Contents: # Ahoy! (or Should I Say Ahoyay!) # Input! # Check Yourself! # Check Yourself... Some More # Ay B C # Word Up # Move it on Back # Ending Up # Testing, Testing, is This Thing On? print("### Ahoy! (or Should I Say Ahoyay!) ###") print("Pig Latin") print("### Input! ###") original = input("Enter a word: ") print("### Check Yourself! ###") # if len(original) > 0: # print(original) # else: # print("empty") print("### Check Yourself... Some More ###") # if len(original) > 0 and original.isalpha(): # print(original) # else: # print("empty") print("### Ay B C ###") pyg = 'ay' print("### Word Up ###") # if len(original) > 0 and original.isalpha(): # word = original.lower() # first = word[0] # else: # print('empty') print("### Move it on Back ###") # if len(original) > 0 and original.isalpha(): # word = original.lower() # first = word[0] # new_word = word + first + pyg # else: # print('empty') print("### Ending Up ###") # if len(original) > 0 and original.isalpha(): # word = original.lower() # first = word[0] # new_word = word + first + pyg # new_word = new_word[1:len(new_word)] # else: # print('empty') print("### Testing, Testing, is This Thing On? ###") if len(original) > 0 and original.isalpha(): word = original.lower() first = word[0] new_word = word + first + pyg new_word = new_word[1:len(new_word)] print(new_word) else: print('empty')
print('### Ahoy! (or Should I Say Ahoyay!) ###') print('Pig Latin') print('### Input! ###') original = input('Enter a word: ') print('### Check Yourself! ###') print('### Check Yourself... Some More ###') print('### Ay B C ###') pyg = 'ay' print('### Word Up ###') print('### Move it on Back ###') print('### Ending Up ###') print('### Testing, Testing, is This Thing On? ###') if len(original) > 0 and original.isalpha(): word = original.lower() first = word[0] new_word = word + first + pyg new_word = new_word[1:len(new_word)] print(new_word) else: print('empty')
# Write a programme to find sum of cubes of first n natural numbers. n = int(input('Input : ')) sumofcubes = sum([x*x*x for x in [*range(1, n+1)]]) print('Output: ', sumofcubes)
n = int(input('Input : ')) sumofcubes = sum([x * x * x for x in [*range(1, n + 1)]]) print('Output: ', sumofcubes)
Bin_Base=['0','1'] Oct_Base=['0', '1', '2', '3', '4', '5', '6', '7'] Hex_Base=['0', '1', '2', '3', '4', '5', '6', '7','8','9','A','B','C','D','E','F'] def BinTesting(n): n=str(n) for digit in n: if digit in Bin_Base: continue else: return False return True def OctTesting(n): n=str(n) for digit in n: if digit in Oct_Base: continue else: return False return True def HexTesting(n): n=str(n) for digit in n: if digit in Hex_Base: continue else: return False return True def DecToBin(n): n=int(n) if n==0: return 0 else: result=[] while n!=0: result.append(str(n%2)) n = n//2 result.reverse() return "".join(result) def BinToDec(n): if BinTesting(n) == False: return "Base error" n=str(n) x=len(n)-1 result =0 for digit in n: result += int(digit)*2**x x -= 1 return result def DecToHex(n): n=int(n) if n==0: return 0 else: sys={10:'A',11:'B',12:'C',13:'D',14:'E',15:'F'} result=[] while n!=0: a=n%16 if a in sys: result.append(sys[a]) else: result.append(str(a)) n=n//16 result.reverse() return "".join(result) def HexToDec(n): n=str(n) if HexTesting(n) == False: return "Wrong Base" sys={'A':10,'B':11,'C':12,'D':13,'E':14,'F':15} x=len(n)-1 result =0 for digit in n: if digit in sys: a=sys[digit] else: a=digit result += int(a)*16**x x -= 1 return result def DecToOct(n): n=int(n) if n==0: return 0 else: result=[] while n!=0: result.append(str(n%8)) n = n//8 result.reverse() return "".join(result) def OctToDec(n): n=str(n) if OctTesting(n) == False: return "Base error" x=len(n)-1 result =0 for digit in n: result += int(digit)*8**x x -= 1 return result def Filter(result): while result[0]=='0': result = result[1:] return result def HexToBin(n): n=str(n) if HexTesting(n) == False: return "Base error" if n=='0': return 0 else: sys={'A':10,'B':11,'C':12,'D':13,'E':14,'F':15} result=[] for digit in n: if digit in sys: a=DecToBin(sys[digit]) result.append(a) else: a=DecToBin(digit) while len(str(a))<4: a='0'+a result.append(a) return Filter("".join(result)) def BinToHex(n): n=str(n) if BinTesting(n) == False: return "Base error" if n=='0': return 0 else: sys={10:'A',11:'B',12:'C',13:'D',14:'E',15:'F'} while len(n)%4 != 0: n='0'+n value=n result=[] for i in range((len(n)//4)): if i== len(n)//4: num = value else: num=value[0:4] value=value[4:] a=BinToDec(num) if a in sys: result.append(sys[a]) else: result.append(str(a)) return "".join(result) def OctToBin(n): n=str(n) if OctTesting(n) == False: return "Base error" if n =='0': return 0 else: result=[] for digit in n: a=DecToBin(digit) while len(str(a))<3: a='0'+str(a) result.append(a) return Filter("".join(result)) def BinToOct(n): n=str(n) if BinTesting(n) == False: return "Base error" if n=='0': return 0 else: sys={10:'A',11:'B',12:'C',13:'D',14:'E',15:'F'} while len(n)%3 != 0: n='0'+n value=n result=[] for i in range((len(n)//3)): if i== len(n)//3: num = value else: num=value[0:3] value=value[3:] a=BinToDec(num) result.append(str(a)) return "".join(result) def OctToHex(n): a=OctToBin(n) b=BinToHex(a) return b def HexToOct(n): a=HexToBin(n) b=BinToOct(a) return b Operations=[DecToBin,BinToDec,DecToHex,HexToDec,DecToOct,OctToDec,HexToBin,BinToHex,OctToBin,BinToOct,OctToHex,HexToOct] Operations_names=["From decimal to binary is:","From binary to decimal is:", "From decimal to hexadecimal is:","From hexadecimal to decimal is:", "From decimal to octal is:","From octal to decimal is:", "From hexadecimal to binary is:", "From binary to hexadecimal is:","From octal to binary is:", "From binary to octal is:" ,"From octal to hexadecimal is:","From hexadecimal to octal is:"] def opt(): print("Number Systems Conversion") print("Select the operation by enetering its number from the list below then enter the starting number") print("0 From Decimal system to Binary system") print("1 From Binary system to Decimal system") print("2 From Decimal system to Hexadecimal system") print("3 From Hexadecimal system to Deicmal system") print("4 From Decimal system to Octal system") print("5 From Octal system to Decimal system") print("6 From Hexadecimal system to Binary system") print("7 From Binary system to Hexadecimal system") print("8 From Octal system to Binary system") print("9 From Binary system to Octal system") print("10 From Octal system to Hexadecimal system") print("11 From Hexadecimal system to Octal system") opt_ord=int(input("Enter the number of the selected operation: ")) number=input("Enter the number: ") try: print("The Conversion of",number,Operations_names[opt_ord],Operations[opt_ord](number)) except: print("Wrong operation number") count=int(input("Number of operations: ")) for i in range(count): opt()
bin__base = ['0', '1'] oct__base = ['0', '1', '2', '3', '4', '5', '6', '7'] hex__base = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'] def bin_testing(n): n = str(n) for digit in n: if digit in Bin_Base: continue else: return False return True def oct_testing(n): n = str(n) for digit in n: if digit in Oct_Base: continue else: return False return True def hex_testing(n): n = str(n) for digit in n: if digit in Hex_Base: continue else: return False return True def dec_to_bin(n): n = int(n) if n == 0: return 0 else: result = [] while n != 0: result.append(str(n % 2)) n = n // 2 result.reverse() return ''.join(result) def bin_to_dec(n): if bin_testing(n) == False: return 'Base error' n = str(n) x = len(n) - 1 result = 0 for digit in n: result += int(digit) * 2 ** x x -= 1 return result def dec_to_hex(n): n = int(n) if n == 0: return 0 else: sys = {10: 'A', 11: 'B', 12: 'C', 13: 'D', 14: 'E', 15: 'F'} result = [] while n != 0: a = n % 16 if a in sys: result.append(sys[a]) else: result.append(str(a)) n = n // 16 result.reverse() return ''.join(result) def hex_to_dec(n): n = str(n) if hex_testing(n) == False: return 'Wrong Base' sys = {'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15} x = len(n) - 1 result = 0 for digit in n: if digit in sys: a = sys[digit] else: a = digit result += int(a) * 16 ** x x -= 1 return result def dec_to_oct(n): n = int(n) if n == 0: return 0 else: result = [] while n != 0: result.append(str(n % 8)) n = n // 8 result.reverse() return ''.join(result) def oct_to_dec(n): n = str(n) if oct_testing(n) == False: return 'Base error' x = len(n) - 1 result = 0 for digit in n: result += int(digit) * 8 ** x x -= 1 return result def filter(result): while result[0] == '0': result = result[1:] return result def hex_to_bin(n): n = str(n) if hex_testing(n) == False: return 'Base error' if n == '0': return 0 else: sys = {'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15} result = [] for digit in n: if digit in sys: a = dec_to_bin(sys[digit]) result.append(a) else: a = dec_to_bin(digit) while len(str(a)) < 4: a = '0' + a result.append(a) return filter(''.join(result)) def bin_to_hex(n): n = str(n) if bin_testing(n) == False: return 'Base error' if n == '0': return 0 else: sys = {10: 'A', 11: 'B', 12: 'C', 13: 'D', 14: 'E', 15: 'F'} while len(n) % 4 != 0: n = '0' + n value = n result = [] for i in range(len(n) // 4): if i == len(n) // 4: num = value else: num = value[0:4] value = value[4:] a = bin_to_dec(num) if a in sys: result.append(sys[a]) else: result.append(str(a)) return ''.join(result) def oct_to_bin(n): n = str(n) if oct_testing(n) == False: return 'Base error' if n == '0': return 0 else: result = [] for digit in n: a = dec_to_bin(digit) while len(str(a)) < 3: a = '0' + str(a) result.append(a) return filter(''.join(result)) def bin_to_oct(n): n = str(n) if bin_testing(n) == False: return 'Base error' if n == '0': return 0 else: sys = {10: 'A', 11: 'B', 12: 'C', 13: 'D', 14: 'E', 15: 'F'} while len(n) % 3 != 0: n = '0' + n value = n result = [] for i in range(len(n) // 3): if i == len(n) // 3: num = value else: num = value[0:3] value = value[3:] a = bin_to_dec(num) result.append(str(a)) return ''.join(result) def oct_to_hex(n): a = oct_to_bin(n) b = bin_to_hex(a) return b def hex_to_oct(n): a = hex_to_bin(n) b = bin_to_oct(a) return b operations = [DecToBin, BinToDec, DecToHex, HexToDec, DecToOct, OctToDec, HexToBin, BinToHex, OctToBin, BinToOct, OctToHex, HexToOct] operations_names = ['From decimal to binary is:', 'From binary to decimal is:', 'From decimal to hexadecimal is:', 'From hexadecimal to decimal is:', 'From decimal to octal is:', 'From octal to decimal is:', 'From hexadecimal to binary is:', 'From binary to hexadecimal is:', 'From octal to binary is:', 'From binary to octal is:', 'From octal to hexadecimal is:', 'From hexadecimal to octal is:'] def opt(): print('Number Systems Conversion') print('Select the operation by enetering its number from the list below then enter the starting number') print('0 From Decimal system to Binary system') print('1 From Binary system to Decimal system') print('2 From Decimal system to Hexadecimal system') print('3 From Hexadecimal system to Deicmal system') print('4 From Decimal system to Octal system') print('5 From Octal system to Decimal system') print('6 From Hexadecimal system to Binary system') print('7 From Binary system to Hexadecimal system') print('8 From Octal system to Binary system') print('9 From Binary system to Octal system') print('10 From Octal system to Hexadecimal system') print('11 From Hexadecimal system to Octal system') opt_ord = int(input('Enter the number of the selected operation: ')) number = input('Enter the number: ') try: print('The Conversion of', number, Operations_names[opt_ord], Operations[opt_ord](number)) except: print('Wrong operation number') count = int(input('Number of operations: ')) for i in range(count): opt()
### tutorzzz tutorzzzURL = 'https://tutorzzz.com/tutorzzz/orders/assignList' tutorzzzCookie = 'SESSION_TUTOR=581fb89c-88c6-4942-a735-d082bf1a29db' tutorzzzReqBody = {"pageNumber":1,"pageSize":20,"sortField":"id","order":"desc"} openIDList = ['ouZ_Ys2FvyLlOk9o-B8oZOnme5n4', 'ouZ_Ys2uzq8fijTerZziXI69jVVY'] appID = 'wxe7b878e46bcf3e24' appsecret = 'a275853a41bdd2b0518befaab24cb545' getAccessTokenURL = 'https://api.weixin.qq.com/cgi-bin/token' templateID = 'ZTtP2eWz4XkEVtmDBsB8JpwapYfv5mCCKkG5ekx1pDE' templateSendURL = 'https://api.weixin.qq.com/cgi-bin/message/template/send'
tutorzzz_url = 'https://tutorzzz.com/tutorzzz/orders/assignList' tutorzzz_cookie = 'SESSION_TUTOR=581fb89c-88c6-4942-a735-d082bf1a29db' tutorzzz_req_body = {'pageNumber': 1, 'pageSize': 20, 'sortField': 'id', 'order': 'desc'} open_id_list = ['ouZ_Ys2FvyLlOk9o-B8oZOnme5n4', 'ouZ_Ys2uzq8fijTerZziXI69jVVY'] app_id = 'wxe7b878e46bcf3e24' appsecret = 'a275853a41bdd2b0518befaab24cb545' get_access_token_url = 'https://api.weixin.qq.com/cgi-bin/token' template_id = 'ZTtP2eWz4XkEVtmDBsB8JpwapYfv5mCCKkG5ekx1pDE' template_send_url = 'https://api.weixin.qq.com/cgi-bin/message/template/send'
def loadfile(name): numbers = [] f = open(name, "r") for x in f: for number in x.split(","): number = int(number) numbers.append(number) return numbers def caculateTravelLinear(numbers, endpoint): travel = 0 for number in numbers: distance = endpoint - number if (endpoint - number) > 0 else (endpoint - number) * -1 travel = travel + distance return travel def caculateTravelFuel(numbers, endpoint): travel = 0 for number in numbers: distance = endpoint - number if (endpoint - number) > 0 else (endpoint - number) * -1 rangeOfNumber = range(0, distance + 1) fuel = sum(rangeOfNumber) travel = travel + fuel return travel def findLowestTravel(function, numbers): median = int(numbers[int(len(numbers) / 2)] if len(numbers) % 2 == 0 else (numbers[int(len(numbers) / 2 - 1)] + (numbers[int(len(numbers) / 2 + 1)])/2)) average = round(sum(numbers)/len(numbers)) print("Median: " + str(median)) print("Average: " + str(average)) lowestTravel = 99999999999999999999999999999999999999999999999999999999999999999999999999999 rangeOfLoop = range(median, average + 1) if median < average + 1 else range(average - 1, median + 1) for endpoint in rangeOfLoop: travel = function(numbers, endpoint) print("Endpoint: ", str(endpoint) + "Travel: ", str(travel) + "-") if travel < lowestTravel: lowestTravel = travel print("Lowest: ", travel) return lowestTravel numbers = sorted(loadfile("data.txt")) lowestTravelA = findLowestTravel(caculateTravelLinear, numbers) lowestTravelB = findLowestTravel(caculateTravelFuel, numbers) print("solution day7a: " + str(lowestTravelA)) print("solution day7b: " + str(lowestTravelB))
def loadfile(name): numbers = [] f = open(name, 'r') for x in f: for number in x.split(','): number = int(number) numbers.append(number) return numbers def caculate_travel_linear(numbers, endpoint): travel = 0 for number in numbers: distance = endpoint - number if endpoint - number > 0 else (endpoint - number) * -1 travel = travel + distance return travel def caculate_travel_fuel(numbers, endpoint): travel = 0 for number in numbers: distance = endpoint - number if endpoint - number > 0 else (endpoint - number) * -1 range_of_number = range(0, distance + 1) fuel = sum(rangeOfNumber) travel = travel + fuel return travel def find_lowest_travel(function, numbers): median = int(numbers[int(len(numbers) / 2)] if len(numbers) % 2 == 0 else numbers[int(len(numbers) / 2 - 1)] + numbers[int(len(numbers) / 2 + 1)] / 2) average = round(sum(numbers) / len(numbers)) print('Median: ' + str(median)) print('Average: ' + str(average)) lowest_travel = 99999999999999999999999999999999999999999999999999999999999999999999999999999 range_of_loop = range(median, average + 1) if median < average + 1 else range(average - 1, median + 1) for endpoint in rangeOfLoop: travel = function(numbers, endpoint) print('Endpoint: ', str(endpoint) + 'Travel: ', str(travel) + '-') if travel < lowestTravel: lowest_travel = travel print('Lowest: ', travel) return lowestTravel numbers = sorted(loadfile('data.txt')) lowest_travel_a = find_lowest_travel(caculateTravelLinear, numbers) lowest_travel_b = find_lowest_travel(caculateTravelFuel, numbers) print('solution day7a: ' + str(lowestTravelA)) print('solution day7b: ' + str(lowestTravelB))
#!/usr/bin/env python3 def import_input(path): with open(path, encoding='utf-8') as infile: return [int(n) for n in infile.read().split()] banks = import_input("input.txt") class Redistributor: def __init__(self, banks): self._banks = banks def redistribute(self, i): blocks = self._banks[i] self._banks[i] = 0 while blocks > 0: i += 1 i = i % len(self._banks) self._banks[i] += 1 blocks -= 1 def find_biggest_bank(self): return self._banks.index(max(self._banks)) def solve(self): count = 0 records = [] while self._banks not in records: records.append(self._banks.copy()) i = self.find_biggest_bank() self.redistribute(i) count += 1 return count def solve2(self): count = 0 target = self._banks.copy() current = None while current != target: i = self.find_biggest_bank() self.redistribute(i) count += 1 current = self._banks.copy() return count r = Redistributor(banks) print(r.solve()) print(r.solve2())
def import_input(path): with open(path, encoding='utf-8') as infile: return [int(n) for n in infile.read().split()] banks = import_input('input.txt') class Redistributor: def __init__(self, banks): self._banks = banks def redistribute(self, i): blocks = self._banks[i] self._banks[i] = 0 while blocks > 0: i += 1 i = i % len(self._banks) self._banks[i] += 1 blocks -= 1 def find_biggest_bank(self): return self._banks.index(max(self._banks)) def solve(self): count = 0 records = [] while self._banks not in records: records.append(self._banks.copy()) i = self.find_biggest_bank() self.redistribute(i) count += 1 return count def solve2(self): count = 0 target = self._banks.copy() current = None while current != target: i = self.find_biggest_bank() self.redistribute(i) count += 1 current = self._banks.copy() return count r = redistributor(banks) print(r.solve()) print(r.solve2())
# https://leetcode.com/problems/search-a-2d-matrix ''' Runtime Complexity: O(logNM) Space Complexity: O(1) ''' def search_matrix(matrix, target): rows, columns = len(matrix), len(matrix[0]) start, end = 0, rows * columns - 1 while start <= end: middle = (start + end) // 2 number = matrix[middle // columns][middle % columns] if number == target: return True if target < number: end = middle - 1 else: start = middle + 1 return False
""" Runtime Complexity: O(logNM) Space Complexity: O(1) """ def search_matrix(matrix, target): (rows, columns) = (len(matrix), len(matrix[0])) (start, end) = (0, rows * columns - 1) while start <= end: middle = (start + end) // 2 number = matrix[middle // columns][middle % columns] if number == target: return True if target < number: end = middle - 1 else: start = middle + 1 return False
class PaginatorFactory(object): def __init__(self, http_client): self.http_client = http_client def make(self, uri, data=None, union_key=None): return Paginator(self.http_client, uri, data, union_key) class Paginator(object): def __init__(self, http_client, uri, data=None, union_key=None): self.http_client = http_client self.union_key = union_key self.uri = uri # Copy dictionary, defaulting to empty. self.data = dict(data or {}) def page(self, page=0): # Add page_index to the dictionary passed in request. data = dict(self.data) data['page_index'] = page - 1 return self.http_client.request(self.uri, data) def all(self): if not self.union_key: raise ValueError("Union key parameter is missing") union_result = [] data = dict(self.data) page_num = 1 page_index = 0 while page_index < page_num: data['page_index'] = page_index page_result = self.http_client.request(self.uri, data) page_num = page_result.get('page_num') if page_num is None: return page_result.get(self.union_key, []) page_index = page_result.get('page_index') + 1 page_result = page_result.get(self.union_key, []) union_result.extend(page_result) return union_result def __iter__(self): if not self.union_key: raise ValueError("Union key parameter is missing") page_index = 0 data = dict(self.data) while True: data['page_index'] = page_index whole_page_result = self.http_client.request(self.uri, data) interesting_data = whole_page_result.get(self.union_key, []) for entry in interesting_data: yield entry page_num = whole_page_result.get('page_num') # Check if that was the last page. if not page_num or page_index >= page_num - 1: break page_index += 1
class Paginatorfactory(object): def __init__(self, http_client): self.http_client = http_client def make(self, uri, data=None, union_key=None): return paginator(self.http_client, uri, data, union_key) class Paginator(object): def __init__(self, http_client, uri, data=None, union_key=None): self.http_client = http_client self.union_key = union_key self.uri = uri self.data = dict(data or {}) def page(self, page=0): data = dict(self.data) data['page_index'] = page - 1 return self.http_client.request(self.uri, data) def all(self): if not self.union_key: raise value_error('Union key parameter is missing') union_result = [] data = dict(self.data) page_num = 1 page_index = 0 while page_index < page_num: data['page_index'] = page_index page_result = self.http_client.request(self.uri, data) page_num = page_result.get('page_num') if page_num is None: return page_result.get(self.union_key, []) page_index = page_result.get('page_index') + 1 page_result = page_result.get(self.union_key, []) union_result.extend(page_result) return union_result def __iter__(self): if not self.union_key: raise value_error('Union key parameter is missing') page_index = 0 data = dict(self.data) while True: data['page_index'] = page_index whole_page_result = self.http_client.request(self.uri, data) interesting_data = whole_page_result.get(self.union_key, []) for entry in interesting_data: yield entry page_num = whole_page_result.get('page_num') if not page_num or page_index >= page_num - 1: break page_index += 1
# Time: 93 ms # Memory: 12 KB n = int(input()) apy = list(map(int, input().split())) apx = list(map(int, input().split())) apset = set(apy[1:] + apx[1:]) # n*(n+1)//2 is 1 + 2 + 3... n # https://en.wikipedia.org/wiki/1_%2B_2_%2B_3_%2B_4_%2B_%E2%8B%AF if sum(apset) == n*(n+1)//2: print('I become the guy.') else: print('Oh, my keyboard!')
n = int(input()) apy = list(map(int, input().split())) apx = list(map(int, input().split())) apset = set(apy[1:] + apx[1:]) if sum(apset) == n * (n + 1) // 2: print('I become the guy.') else: print('Oh, my keyboard!')
class Solution(object): def isBadVersion(self, num): return True def firstBadVersion(self, n): left, right = 1, n while left <= right: mid = left + (right - left)/2 if self.isBadVersion(mid): right = mid - 1 else: left = mid + 1 return left
class Solution(object): def is_bad_version(self, num): return True def first_bad_version(self, n): (left, right) = (1, n) while left <= right: mid = left + (right - left) / 2 if self.isBadVersion(mid): right = mid - 1 else: left = mid + 1 return left
#mengubah atau konversi tipe data data = 20 print(data) #konversi ke float dataFloat = float(data) print(dataFloat) print(type(dataFloat)) #konversi sting dataStr = str(data) print(dataStr) print(type(dataStr))
data = 20 print(data) data_float = float(data) print(dataFloat) print(type(dataFloat)) data_str = str(data) print(dataStr) print(type(dataStr))
#Solution 1 def search_and_insert(nums, target): for i in range(0, len(nums)): if target == nums[i]: return i elif target <nums[i]: return i return i+1 #Solution 2 def search_and_insert2(nums, target): start_index = 0 half_index = len(nums)//2 end_index = len(nums) while True: if target < nums[half_index]: end_index = half_index half_index = (start_index + half_index)//2 elif target > nums[half_index]: start_index = half_index half_index = (half_index + end_index)//2 if target == nums[half_index]: return half_index if (half_index == end_index or half_index == start_index) and target>nums[half_index]: return half_index +1 if (half_index == end_index or half_index == start_index) and target<nums[half_index]: return half_index #Tests def search_and_insert2_test(): input_nums = [1,3,5,6] input_target1 = 5 input_target2 = 2 input_target3 = 7 input_target4 = 0 actual_output_k1 = search_and_insert2(input_nums, input_target1) actual_output_k2 = search_and_insert2(input_nums, input_target2) actual_output_k3 = search_and_insert2(input_nums, input_target3) actual_output_k4 = search_and_insert2(input_nums, input_target4) return actual_output_k1==2, actual_output_k2 ==1, actual_output_k3==4, actual_output_k4 == 0 print(search_and_insert2_test()) print(search_and_insert2([1,3,5,6], 5)) print(search_and_insert2([1,3,5,6], 2)) print(search_and_insert2([1,3,5,6], 7)) print(search_and_insert2([1,3,5,6], 0)) # #For leetcode #Solution 1 class Solution(object): def removeElement(self, nums, val): holding_pointer = 0 for i in range(0, len(nums)): if nums[i] != val: nums[holding_pointer] = nums[i] holding_pointer = holding_pointer +1 return holding_pointer #Solution 2 class Solution(object): def searchInsert(self, nums, target): start_index = 0 half_index = len(nums)//2 end_index = len(nums) while True: if target < nums[half_index]: end_index = half_index half_index = (start_index + half_index)//2 elif target > nums[half_index]: start_index = half_index half_index = (half_index + end_index)//2 if target == nums[half_index]: return half_index if (half_index == end_index or half_index == start_index) and target>nums[half_index]: return half_index +1 if (half_index == end_index or half_index == start_index) and target<nums[half_index]: return half_index
def search_and_insert(nums, target): for i in range(0, len(nums)): if target == nums[i]: return i elif target < nums[i]: return i return i + 1 def search_and_insert2(nums, target): start_index = 0 half_index = len(nums) // 2 end_index = len(nums) while True: if target < nums[half_index]: end_index = half_index half_index = (start_index + half_index) // 2 elif target > nums[half_index]: start_index = half_index half_index = (half_index + end_index) // 2 if target == nums[half_index]: return half_index if (half_index == end_index or half_index == start_index) and target > nums[half_index]: return half_index + 1 if (half_index == end_index or half_index == start_index) and target < nums[half_index]: return half_index def search_and_insert2_test(): input_nums = [1, 3, 5, 6] input_target1 = 5 input_target2 = 2 input_target3 = 7 input_target4 = 0 actual_output_k1 = search_and_insert2(input_nums, input_target1) actual_output_k2 = search_and_insert2(input_nums, input_target2) actual_output_k3 = search_and_insert2(input_nums, input_target3) actual_output_k4 = search_and_insert2(input_nums, input_target4) return (actual_output_k1 == 2, actual_output_k2 == 1, actual_output_k3 == 4, actual_output_k4 == 0) print(search_and_insert2_test()) print(search_and_insert2([1, 3, 5, 6], 5)) print(search_and_insert2([1, 3, 5, 6], 2)) print(search_and_insert2([1, 3, 5, 6], 7)) print(search_and_insert2([1, 3, 5, 6], 0)) class Solution(object): def remove_element(self, nums, val): holding_pointer = 0 for i in range(0, len(nums)): if nums[i] != val: nums[holding_pointer] = nums[i] holding_pointer = holding_pointer + 1 return holding_pointer class Solution(object): def search_insert(self, nums, target): start_index = 0 half_index = len(nums) // 2 end_index = len(nums) while True: if target < nums[half_index]: end_index = half_index half_index = (start_index + half_index) // 2 elif target > nums[half_index]: start_index = half_index half_index = (half_index + end_index) // 2 if target == nums[half_index]: return half_index if (half_index == end_index or half_index == start_index) and target > nums[half_index]: return half_index + 1 if (half_index == end_index or half_index == start_index) and target < nums[half_index]: return half_index
t = int(input()) answer = [] for a in range(t): n = int(input()) if(n%4 == 0): answer.append("YES") else: answer.append("NO") for b in answer: print(b)
t = int(input()) answer = [] for a in range(t): n = int(input()) if n % 4 == 0: answer.append('YES') else: answer.append('NO') for b in answer: print(b)
# when creating a function it can return nothing or it can return a value like so # the return value can be any data type you wish including custom class you've made (see Object-oriented-programming file 1) #main return nothing def main(): result = sum(1, 5) print(result) # sum returns a inter or float depening on the arguments passed def sum(*argv): total = 0 for arg in argv: total += arg return total if __name__ == "__main__": main()
def main(): result = sum(1, 5) print(result) def sum(*argv): total = 0 for arg in argv: total += arg return total if __name__ == '__main__': main()
class Airport: def __init__(self, code, lat, lng, airportName): self.code = code self.lat = lat self.lng = lng self.name = airportName self.flightCategory = None self.isCalculated = False
class Airport: def __init__(self, code, lat, lng, airportName): self.code = code self.lat = lat self.lng = lng self.name = airportName self.flightCategory = None self.isCalculated = False
def gcd(a,b = None): if b != None: if a % b == 0: return b else: return gcd( b, a % b) else: for i in range(len(a)): a[0] = gcd(a[0],a[i]) return a[0] print(gcd([18,12, 6])) print(gcd(9, 12))
def gcd(a, b=None): if b != None: if a % b == 0: return b else: return gcd(b, a % b) else: for i in range(len(a)): a[0] = gcd(a[0], a[i]) return a[0] print(gcd([18, 12, 6])) print(gcd(9, 12))
#!/usr/bin/env python3 # Copyright 20 # Python provides the open() function for opening file # open() opens the file in read-only default mode. def main(): # open the file - open() returns a file object. It takes the file name and opens that file and returns # a file object. The file object itself is a iterator, and so we can use a for loop and get one line at a time # without having to buffer the entire file in memory f = open('lines.txt', 'w') # opens it in write mode. a: append mode, r: read -only, r+ allows to read and write. # read each line by line, stripping the new lines off the end of each line and display them # rstrip() - each of the line is returned as a string and the string class has an R-strip method # which will strip any white space, incl. new lines from the end of the line. for line in f: print(line.rstrip()) if __name__ == '__main__': main()
def main(): f = open('lines.txt', 'w') for line in f: print(line.rstrip()) if __name__ == '__main__': main()
#{ #Driver Code Starts #Initial Template for Python 3 # } Driver Code Ends #User function Template for python3 # Function to count even and odd # c_e : variable to store even count # c_o : variable to store odd count def count_even_odd(n, arr): c_e = 0 c_o = 0 pair = list() # your code here for i in range(0,n): if(arr[i]%2==0): c_e +=1 else: c_o +=1 pair.append(c_e) pair.append(c_o) return pair #{ #Driver Code Starts. # Driver Code def main(): # Testcase input testcases = int(input()) # Looping through testcases while(testcases > 0): # size of array size_array = int(input()) # array elements input array = input().split() # print (array) arr = list() for i in array: arr.append(int(i)) # print (arr) # calling function to count even odd a = count_even_odd(size_array, arr) print (a[0], a[1]) testcases -= 1 if __name__ == '__main__': main() #} Driver Code Ends
def count_even_odd(n, arr): c_e = 0 c_o = 0 pair = list() for i in range(0, n): if arr[i] % 2 == 0: c_e += 1 else: c_o += 1 pair.append(c_e) pair.append(c_o) return pair def main(): testcases = int(input()) while testcases > 0: size_array = int(input()) array = input().split() arr = list() for i in array: arr.append(int(i)) a = count_even_odd(size_array, arr) print(a[0], a[1]) testcases -= 1 if __name__ == '__main__': main()
print(''' Exponent code Exponent code ''') print(''' def answer2(number, power): result=1 for index in range(power): result=result * number return result print(answer2(3,2)) ''') print(''' ''') def answer2(number, power): result=1 for index in range(power): result=result * number return result print(answer2(3,2))
print('\nExponent code\nExponent code\n') print('\ndef answer2(number, power):\n result=1\n for index in range(power):\n result=result * number\n return result\nprint(answer2(3,2))\n') print('\n\n') def answer2(number, power): result = 1 for index in range(power): result = result * number return result print(answer2(3, 2))
# test output stream only print('begin') for i in range(1, 5): # CHANGED FROM 20 TO 1,5 print('Spam!' * i) print('end')
print('begin') for i in range(1, 5): print('Spam!' * i) print('end')
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") def glm_repository(): maybe( http_archive, name = "glm", urls = [ "https://github.com/g-truc/glm/archive/6ad79aae3eb5bf809c30bf1168171e9e55857e45.zip", ], sha256 = "9a147a2b58df9fc30ec494468f6b974489a72aecbaa9062dd1d375379e011b70", strip_prefix = "glm-6ad79aae3eb5bf809c30bf1168171e9e55857e45/", build_file = "@third_party//glm:package.BUILD", patches = [ "@third_party//glm:0001-Works-around-Visual-Studio-compiler-issue-with-std-c.patch", ], patch_args = ["-p1"], )
load('@bazel_tools//tools/build_defs/repo:utils.bzl', 'maybe') load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive') def glm_repository(): maybe(http_archive, name='glm', urls=['https://github.com/g-truc/glm/archive/6ad79aae3eb5bf809c30bf1168171e9e55857e45.zip'], sha256='9a147a2b58df9fc30ec494468f6b974489a72aecbaa9062dd1d375379e011b70', strip_prefix='glm-6ad79aae3eb5bf809c30bf1168171e9e55857e45/', build_file='@third_party//glm:package.BUILD', patches=['@third_party//glm:0001-Works-around-Visual-Studio-compiler-issue-with-std-c.patch'], patch_args=['-p1'])
min_computer_fish_size = 0.25 max_computer_fish_size = 3.7 min_computer_fish_speed = 100 max_computer_fish_speed = 500 player_fish_speed = 400 player_start_size = min_computer_fish_size*1.2 player_win_size = max_computer_fish_size*1.2 player_start_size_acceleration_time_constant = 0.13 player_final_size_acceleration_time_constant = 0.3
min_computer_fish_size = 0.25 max_computer_fish_size = 3.7 min_computer_fish_speed = 100 max_computer_fish_speed = 500 player_fish_speed = 400 player_start_size = min_computer_fish_size * 1.2 player_win_size = max_computer_fish_size * 1.2 player_start_size_acceleration_time_constant = 0.13 player_final_size_acceleration_time_constant = 0.3
# # PySNMP MIB module CISCO-COMMON-ROLES-EXT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-COMMON-ROLES-EXT-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:36:18 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint") ccrmConfigurationExtGroup, = mibBuilder.importSymbols("CISCO-COMMON-ROLES-MIB", "ccrmConfigurationExtGroup") ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt") SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup") ModuleIdentity, iso, ObjectIdentity, MibIdentifier, Counter64, TimeTicks, Integer32, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, Unsigned32, Bits, NotificationType, Gauge32 = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "iso", "ObjectIdentity", "MibIdentifier", "Counter64", "TimeTicks", "Integer32", "Counter32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "Unsigned32", "Bits", "NotificationType", "Gauge32") DisplayString, TextualConvention, RowStatus, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention", "RowStatus", "TruthValue") ciscoCommonRolesExtMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 651)) ciscoCommonRolesExtMIB.setRevisions(('2008-02-15 00:00',)) if mibBuilder.loadTexts: ciscoCommonRolesExtMIB.setLastUpdated('200802150000Z') if mibBuilder.loadTexts: ciscoCommonRolesExtMIB.setOrganization('Cisco Systems Inc.') ciscoCommonRolesExtNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 651, 0)) ciscoCommonRolesExtMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 651, 1)) ciscoCommonRolesExtMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 651, 2)) ccreInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 1)) ccreRoleConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2)) ccreRuleConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 3)) class CcreOperation(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2)) namedValues = NamedValues(("read", 1), ("readWrite", 2)) class CcreResourceAccess(TextualConvention, Bits): status = 'current' namedValues = NamedValues(("vsan", 0), ("vlan", 1), ("interface", 2)) ccreFeatureElementTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 1, 1), ) if mibBuilder.loadTexts: ccreFeatureElementTable.setStatus('current') ccreFeatureElementEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 1, 1, 1), ).setIndexNames((0, "CISCO-COMMON-ROLES-EXT-MIB", "ccreFeatureName"), (0, "CISCO-COMMON-ROLES-EXT-MIB", "ccreFeatureElementIndex")) if mibBuilder.loadTexts: ccreFeatureElementEntry.setStatus('current') ccreFeatureName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 1, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))) if mibBuilder.loadTexts: ccreFeatureName.setStatus('current') ccreFeatureElementIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 1, 1, 1, 2), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4294967295))) if mibBuilder.loadTexts: ccreFeatureElementIndex.setStatus('current') ccreFeatureElementName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 1, 1, 1, 3), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate") if mibBuilder.loadTexts: ccreFeatureElementName.setStatus('current') ccreFeatureElementType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("command", 1), ("feature", 2), ("none", 3)))).setMaxAccess("readcreate") if mibBuilder.loadTexts: ccreFeatureElementType.setStatus('current') ccreFeatureRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 1, 1, 1, 5), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: ccreFeatureRowStatus.setStatus('current') ccreRoleTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 2), ) if mibBuilder.loadTexts: ccreRoleTable.setStatus('current') ccreRoleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 2, 1), ).setIndexNames((0, "CISCO-COMMON-ROLES-EXT-MIB", "ccreRoleName")) if mibBuilder.loadTexts: ccreRoleEntry.setStatus('current') ccreRoleName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 2, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 16))) if mibBuilder.loadTexts: ccreRoleName.setStatus('current') ccreRoleDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 2, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readcreate") if mibBuilder.loadTexts: ccreRoleDescription.setStatus('current') ccreRoleResourceAccess = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 2, 1, 3), CcreResourceAccess()).setMaxAccess("readcreate") if mibBuilder.loadTexts: ccreRoleResourceAccess.setStatus('current') ccreRoleRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 2, 1, 4), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: ccreRoleRowStatus.setStatus('current') ccreRoleScopeTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 3), ) if mibBuilder.loadTexts: ccreRoleScopeTable.setStatus('current') ccreRoleScopeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 3, 1), ).setIndexNames((0, "CISCO-COMMON-ROLES-EXT-MIB", "ccreRoleName"), (0, "CISCO-COMMON-ROLES-EXT-MIB", "ccreRoleScopeIndex")) if mibBuilder.loadTexts: ccreRoleScopeEntry.setStatus('current') ccreRoleScopeIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 3, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4294967295))) if mibBuilder.loadTexts: ccreRoleScopeIndex.setStatus('current') ccreRoleScopeRestriction = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("vsan", 1), ("vlan", 2), ("interface", 3)))).setMaxAccess("readcreate") if mibBuilder.loadTexts: ccreRoleScopeRestriction.setStatus('current') ccreRoleScopeValue = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 3, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readcreate") if mibBuilder.loadTexts: ccreRoleScopeValue.setStatus('current') ccreRoleScopeRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 3, 1, 4), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: ccreRoleScopeRowStatus.setStatus('current') ccreRuleTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 3, 2), ) if mibBuilder.loadTexts: ccreRuleTable.setStatus('current') ccreRuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 3, 2, 1), ).setIndexNames((0, "CISCO-COMMON-ROLES-EXT-MIB", "ccreRoleName"), (0, "CISCO-COMMON-ROLES-EXT-MIB", "ccreRuleNumber")) if mibBuilder.loadTexts: ccreRuleEntry.setStatus('current') ccreRuleNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 3, 2, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 256))) if mibBuilder.loadTexts: ccreRuleNumber.setStatus('current') ccreRuleFeatureElementName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 3, 2, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32)).clone(hexValue="")).setMaxAccess("readcreate") if mibBuilder.loadTexts: ccreRuleFeatureElementName.setStatus('current') ccreRuleFeatureElementType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 3, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("command", 1), ("feature", 2), ("featureGroup", 3), ("all", 4)))).setMaxAccess("readcreate") if mibBuilder.loadTexts: ccreRuleFeatureElementType.setStatus('current') ccreRuleOperation = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 3, 2, 1, 4), CcreOperation()).setMaxAccess("readcreate") if mibBuilder.loadTexts: ccreRuleOperation.setStatus('current') ccreRuleOperationPermitted = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 3, 2, 1, 5), TruthValue().clone('true')).setMaxAccess("readcreate") if mibBuilder.loadTexts: ccreRuleOperationPermitted.setStatus('current') ccreRuleRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 3, 2, 1, 6), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: ccreRuleRowStatus.setStatus('current') ccreMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 651, 2, 1)) ccreMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 651, 2, 2)) ccreMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 651, 2, 1, 1)).setObjects(("CISCO-COMMON-ROLES-EXT-MIB", "ccreConfigurationGroup"), ("CISCO-COMMON-ROLES-MIB", "ccrmConfigurationExtGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ccreMIBCompliance = ccreMIBCompliance.setStatus('current') ccreConfigurationGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 651, 2, 2, 1)).setObjects(("CISCO-COMMON-ROLES-EXT-MIB", "ccreFeatureElementName"), ("CISCO-COMMON-ROLES-EXT-MIB", "ccreFeatureElementType"), ("CISCO-COMMON-ROLES-EXT-MIB", "ccreFeatureRowStatus"), ("CISCO-COMMON-ROLES-EXT-MIB", "ccreRoleDescription"), ("CISCO-COMMON-ROLES-EXT-MIB", "ccreRoleResourceAccess"), ("CISCO-COMMON-ROLES-EXT-MIB", "ccreRoleRowStatus"), ("CISCO-COMMON-ROLES-EXT-MIB", "ccreRoleScopeRestriction"), ("CISCO-COMMON-ROLES-EXT-MIB", "ccreRoleScopeValue"), ("CISCO-COMMON-ROLES-EXT-MIB", "ccreRoleScopeRowStatus"), ("CISCO-COMMON-ROLES-EXT-MIB", "ccreRuleFeatureElementName"), ("CISCO-COMMON-ROLES-EXT-MIB", "ccreRuleFeatureElementType"), ("CISCO-COMMON-ROLES-EXT-MIB", "ccreRuleOperation"), ("CISCO-COMMON-ROLES-EXT-MIB", "ccreRuleOperationPermitted"), ("CISCO-COMMON-ROLES-EXT-MIB", "ccreRuleRowStatus")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ccreConfigurationGroup = ccreConfigurationGroup.setStatus('current') mibBuilder.exportSymbols("CISCO-COMMON-ROLES-EXT-MIB", ccreRoleName=ccreRoleName, ccreMIBCompliance=ccreMIBCompliance, ccreRoleTable=ccreRoleTable, ccreRuleEntry=ccreRuleEntry, ciscoCommonRolesExtNotifications=ciscoCommonRolesExtNotifications, ccreRoleEntry=ccreRoleEntry, ccreRuleTable=ccreRuleTable, ccreFeatureElementIndex=ccreFeatureElementIndex, ccreRoleConfig=ccreRoleConfig, ccreRuleOperation=ccreRuleOperation, PYSNMP_MODULE_ID=ciscoCommonRolesExtMIB, ccreFeatureElementName=ccreFeatureElementName, ccreFeatureRowStatus=ccreFeatureRowStatus, ccreFeatureElementTable=ccreFeatureElementTable, ccreRuleFeatureElementName=ccreRuleFeatureElementName, ccreRuleRowStatus=ccreRuleRowStatus, ccreInfo=ccreInfo, ccreRuleNumber=ccreRuleNumber, ccreConfigurationGroup=ccreConfigurationGroup, ccreRoleScopeValue=ccreRoleScopeValue, ccreRuleOperationPermitted=ccreRuleOperationPermitted, ccreRoleScopeIndex=ccreRoleScopeIndex, ccreRuleFeatureElementType=ccreRuleFeatureElementType, ccreRoleScopeRestriction=ccreRoleScopeRestriction, ccreRoleScopeTable=ccreRoleScopeTable, ciscoCommonRolesExtMIB=ciscoCommonRolesExtMIB, CcreOperation=CcreOperation, ccreRoleScopeEntry=ccreRoleScopeEntry, ccreRoleDescription=ccreRoleDescription, CcreResourceAccess=CcreResourceAccess, ccreMIBGroups=ccreMIBGroups, ccreFeatureElementType=ccreFeatureElementType, ciscoCommonRolesExtMIBObjects=ciscoCommonRolesExtMIBObjects, ccreMIBCompliances=ccreMIBCompliances, ccreRuleConfig=ccreRuleConfig, ciscoCommonRolesExtMIBConformance=ciscoCommonRolesExtMIBConformance, ccreRoleScopeRowStatus=ccreRoleScopeRowStatus, ccreRoleResourceAccess=ccreRoleResourceAccess, ccreRoleRowStatus=ccreRoleRowStatus, ccreFeatureName=ccreFeatureName, ccreFeatureElementEntry=ccreFeatureElementEntry)
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, single_value_constraint, constraints_union, value_range_constraint, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'SingleValueConstraint', 'ConstraintsUnion', 'ValueRangeConstraint', 'ValueSizeConstraint') (ccrm_configuration_ext_group,) = mibBuilder.importSymbols('CISCO-COMMON-ROLES-MIB', 'ccrmConfigurationExtGroup') (cisco_mgmt,) = mibBuilder.importSymbols('CISCO-SMI', 'ciscoMgmt') (snmp_admin_string,) = mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpAdminString') (module_compliance, notification_group, object_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup', 'ObjectGroup') (module_identity, iso, object_identity, mib_identifier, counter64, time_ticks, integer32, counter32, mib_scalar, mib_table, mib_table_row, mib_table_column, ip_address, unsigned32, bits, notification_type, gauge32) = mibBuilder.importSymbols('SNMPv2-SMI', 'ModuleIdentity', 'iso', 'ObjectIdentity', 'MibIdentifier', 'Counter64', 'TimeTicks', 'Integer32', 'Counter32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'IpAddress', 'Unsigned32', 'Bits', 'NotificationType', 'Gauge32') (display_string, textual_convention, row_status, truth_value) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention', 'RowStatus', 'TruthValue') cisco_common_roles_ext_mib = module_identity((1, 3, 6, 1, 4, 1, 9, 9, 651)) ciscoCommonRolesExtMIB.setRevisions(('2008-02-15 00:00',)) if mibBuilder.loadTexts: ciscoCommonRolesExtMIB.setLastUpdated('200802150000Z') if mibBuilder.loadTexts: ciscoCommonRolesExtMIB.setOrganization('Cisco Systems Inc.') cisco_common_roles_ext_notifications = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 651, 0)) cisco_common_roles_ext_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 651, 1)) cisco_common_roles_ext_mib_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 651, 2)) ccre_info = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 1)) ccre_role_config = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2)) ccre_rule_config = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 3)) class Ccreoperation(TextualConvention, Integer32): status = 'current' subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2)) named_values = named_values(('read', 1), ('readWrite', 2)) class Ccreresourceaccess(TextualConvention, Bits): status = 'current' named_values = named_values(('vsan', 0), ('vlan', 1), ('interface', 2)) ccre_feature_element_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 1, 1)) if mibBuilder.loadTexts: ccreFeatureElementTable.setStatus('current') ccre_feature_element_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 1, 1, 1)).setIndexNames((0, 'CISCO-COMMON-ROLES-EXT-MIB', 'ccreFeatureName'), (0, 'CISCO-COMMON-ROLES-EXT-MIB', 'ccreFeatureElementIndex')) if mibBuilder.loadTexts: ccreFeatureElementEntry.setStatus('current') ccre_feature_name = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 1, 1, 1, 1), snmp_admin_string().subtype(subtypeSpec=value_size_constraint(1, 32))) if mibBuilder.loadTexts: ccreFeatureName.setStatus('current') ccre_feature_element_index = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 1, 1, 1, 2), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 4294967295))) if mibBuilder.loadTexts: ccreFeatureElementIndex.setStatus('current') ccre_feature_element_name = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 1, 1, 1, 3), snmp_admin_string().subtype(subtypeSpec=value_size_constraint(1, 32))).setMaxAccess('readcreate') if mibBuilder.loadTexts: ccreFeatureElementName.setStatus('current') ccre_feature_element_type = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 1, 1, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('command', 1), ('feature', 2), ('none', 3)))).setMaxAccess('readcreate') if mibBuilder.loadTexts: ccreFeatureElementType.setStatus('current') ccre_feature_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 1, 1, 1, 5), row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: ccreFeatureRowStatus.setStatus('current') ccre_role_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 2)) if mibBuilder.loadTexts: ccreRoleTable.setStatus('current') ccre_role_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 2, 1)).setIndexNames((0, 'CISCO-COMMON-ROLES-EXT-MIB', 'ccreRoleName')) if mibBuilder.loadTexts: ccreRoleEntry.setStatus('current') ccre_role_name = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 2, 1, 1), snmp_admin_string().subtype(subtypeSpec=value_size_constraint(1, 16))) if mibBuilder.loadTexts: ccreRoleName.setStatus('current') ccre_role_description = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 2, 1, 2), snmp_admin_string().subtype(subtypeSpec=value_size_constraint(0, 64))).setMaxAccess('readcreate') if mibBuilder.loadTexts: ccreRoleDescription.setStatus('current') ccre_role_resource_access = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 2, 1, 3), ccre_resource_access()).setMaxAccess('readcreate') if mibBuilder.loadTexts: ccreRoleResourceAccess.setStatus('current') ccre_role_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 2, 1, 4), row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: ccreRoleRowStatus.setStatus('current') ccre_role_scope_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 3)) if mibBuilder.loadTexts: ccreRoleScopeTable.setStatus('current') ccre_role_scope_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 3, 1)).setIndexNames((0, 'CISCO-COMMON-ROLES-EXT-MIB', 'ccreRoleName'), (0, 'CISCO-COMMON-ROLES-EXT-MIB', 'ccreRoleScopeIndex')) if mibBuilder.loadTexts: ccreRoleScopeEntry.setStatus('current') ccre_role_scope_index = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 3, 1, 1), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 4294967295))) if mibBuilder.loadTexts: ccreRoleScopeIndex.setStatus('current') ccre_role_scope_restriction = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 3, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('vsan', 1), ('vlan', 2), ('interface', 3)))).setMaxAccess('readcreate') if mibBuilder.loadTexts: ccreRoleScopeRestriction.setStatus('current') ccre_role_scope_value = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 3, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(1, 2147483647))).setMaxAccess('readcreate') if mibBuilder.loadTexts: ccreRoleScopeValue.setStatus('current') ccre_role_scope_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 2, 3, 1, 4), row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: ccreRoleScopeRowStatus.setStatus('current') ccre_rule_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 3, 2)) if mibBuilder.loadTexts: ccreRuleTable.setStatus('current') ccre_rule_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 3, 2, 1)).setIndexNames((0, 'CISCO-COMMON-ROLES-EXT-MIB', 'ccreRoleName'), (0, 'CISCO-COMMON-ROLES-EXT-MIB', 'ccreRuleNumber')) if mibBuilder.loadTexts: ccreRuleEntry.setStatus('current') ccre_rule_number = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 3, 2, 1, 1), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 256))) if mibBuilder.loadTexts: ccreRuleNumber.setStatus('current') ccre_rule_feature_element_name = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 3, 2, 1, 2), snmp_admin_string().subtype(subtypeSpec=value_size_constraint(0, 32)).clone(hexValue='')).setMaxAccess('readcreate') if mibBuilder.loadTexts: ccreRuleFeatureElementName.setStatus('current') ccre_rule_feature_element_type = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 3, 2, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('command', 1), ('feature', 2), ('featureGroup', 3), ('all', 4)))).setMaxAccess('readcreate') if mibBuilder.loadTexts: ccreRuleFeatureElementType.setStatus('current') ccre_rule_operation = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 3, 2, 1, 4), ccre_operation()).setMaxAccess('readcreate') if mibBuilder.loadTexts: ccreRuleOperation.setStatus('current') ccre_rule_operation_permitted = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 3, 2, 1, 5), truth_value().clone('true')).setMaxAccess('readcreate') if mibBuilder.loadTexts: ccreRuleOperationPermitted.setStatus('current') ccre_rule_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 651, 1, 3, 2, 1, 6), row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: ccreRuleRowStatus.setStatus('current') ccre_mib_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 651, 2, 1)) ccre_mib_groups = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 651, 2, 2)) ccre_mib_compliance = module_compliance((1, 3, 6, 1, 4, 1, 9, 9, 651, 2, 1, 1)).setObjects(('CISCO-COMMON-ROLES-EXT-MIB', 'ccreConfigurationGroup'), ('CISCO-COMMON-ROLES-MIB', 'ccrmConfigurationExtGroup')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ccre_mib_compliance = ccreMIBCompliance.setStatus('current') ccre_configuration_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 651, 2, 2, 1)).setObjects(('CISCO-COMMON-ROLES-EXT-MIB', 'ccreFeatureElementName'), ('CISCO-COMMON-ROLES-EXT-MIB', 'ccreFeatureElementType'), ('CISCO-COMMON-ROLES-EXT-MIB', 'ccreFeatureRowStatus'), ('CISCO-COMMON-ROLES-EXT-MIB', 'ccreRoleDescription'), ('CISCO-COMMON-ROLES-EXT-MIB', 'ccreRoleResourceAccess'), ('CISCO-COMMON-ROLES-EXT-MIB', 'ccreRoleRowStatus'), ('CISCO-COMMON-ROLES-EXT-MIB', 'ccreRoleScopeRestriction'), ('CISCO-COMMON-ROLES-EXT-MIB', 'ccreRoleScopeValue'), ('CISCO-COMMON-ROLES-EXT-MIB', 'ccreRoleScopeRowStatus'), ('CISCO-COMMON-ROLES-EXT-MIB', 'ccreRuleFeatureElementName'), ('CISCO-COMMON-ROLES-EXT-MIB', 'ccreRuleFeatureElementType'), ('CISCO-COMMON-ROLES-EXT-MIB', 'ccreRuleOperation'), ('CISCO-COMMON-ROLES-EXT-MIB', 'ccreRuleOperationPermitted'), ('CISCO-COMMON-ROLES-EXT-MIB', 'ccreRuleRowStatus')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ccre_configuration_group = ccreConfigurationGroup.setStatus('current') mibBuilder.exportSymbols('CISCO-COMMON-ROLES-EXT-MIB', ccreRoleName=ccreRoleName, ccreMIBCompliance=ccreMIBCompliance, ccreRoleTable=ccreRoleTable, ccreRuleEntry=ccreRuleEntry, ciscoCommonRolesExtNotifications=ciscoCommonRolesExtNotifications, ccreRoleEntry=ccreRoleEntry, ccreRuleTable=ccreRuleTable, ccreFeatureElementIndex=ccreFeatureElementIndex, ccreRoleConfig=ccreRoleConfig, ccreRuleOperation=ccreRuleOperation, PYSNMP_MODULE_ID=ciscoCommonRolesExtMIB, ccreFeatureElementName=ccreFeatureElementName, ccreFeatureRowStatus=ccreFeatureRowStatus, ccreFeatureElementTable=ccreFeatureElementTable, ccreRuleFeatureElementName=ccreRuleFeatureElementName, ccreRuleRowStatus=ccreRuleRowStatus, ccreInfo=ccreInfo, ccreRuleNumber=ccreRuleNumber, ccreConfigurationGroup=ccreConfigurationGroup, ccreRoleScopeValue=ccreRoleScopeValue, ccreRuleOperationPermitted=ccreRuleOperationPermitted, ccreRoleScopeIndex=ccreRoleScopeIndex, ccreRuleFeatureElementType=ccreRuleFeatureElementType, ccreRoleScopeRestriction=ccreRoleScopeRestriction, ccreRoleScopeTable=ccreRoleScopeTable, ciscoCommonRolesExtMIB=ciscoCommonRolesExtMIB, CcreOperation=CcreOperation, ccreRoleScopeEntry=ccreRoleScopeEntry, ccreRoleDescription=ccreRoleDescription, CcreResourceAccess=CcreResourceAccess, ccreMIBGroups=ccreMIBGroups, ccreFeatureElementType=ccreFeatureElementType, ciscoCommonRolesExtMIBObjects=ciscoCommonRolesExtMIBObjects, ccreMIBCompliances=ccreMIBCompliances, ccreRuleConfig=ccreRuleConfig, ciscoCommonRolesExtMIBConformance=ciscoCommonRolesExtMIBConformance, ccreRoleScopeRowStatus=ccreRoleScopeRowStatus, ccreRoleResourceAccess=ccreRoleResourceAccess, ccreRoleRowStatus=ccreRoleRowStatus, ccreFeatureName=ccreFeatureName, ccreFeatureElementEntry=ccreFeatureElementEntry)
class ServerCommands(dict): def __init__(self): super().__init__() self.update({ '!connect': 'on_client_connect', '!disconnect': 'on_client_disconnect' }) def register_command(self, command, callback_name): self[command] = callback_name def remove_command(self, command): try: del self[command] return True except KeyError: return False def get_command(self, get_command): try: self[get_command] except KeyError: return None
class Servercommands(dict): def __init__(self): super().__init__() self.update({'!connect': 'on_client_connect', '!disconnect': 'on_client_disconnect'}) def register_command(self, command, callback_name): self[command] = callback_name def remove_command(self, command): try: del self[command] return True except KeyError: return False def get_command(self, get_command): try: self[get_command] except KeyError: return None
# Get input N, M = map(int, input().split()) # N - the number of restaurants, M - the number of pho restaurants pho = list(map(int, input().split())) # A list of the pho restaurants phos = [False for x in range(N)] leaves = [True for x in range(N)] paths = [[] for x in range(N)] nodes = [False for x in range(N)] total = 0 # The total of the tree ind = [x for x in range(N)] dists = [1 for x in range(N)] maxdist = 0 # The longest distance in the tree def mark(curr, prev): # goes through each of the nodes recursively, setting it to true if it is a pho restaurant if phos[curr] and not nodes[curr]: # If the current node is a pho restaurant nodes[curr] = True # The current node is included in the subtree global total total += 2 for i in paths[curr]: # For all of the connections of this node if i != prev: # If it was not the previous one mark(i, curr) # We go through the connections of that node as well if nodes[i] and not nodes[curr]: # If it is a pho restaurant and the current one is not nodes[curr] = True # This one must also be included in the subtree global total total += 2 def depthFirstSearch(curr, prev, dist): for i in paths[curr]: if i != prev and nodes[i]: depthFirstSearch(i, curr, dist+1) if dists[i]+1 > dists[curr]: dists[curr] = dists[i]+1 ind[curr] = ind[i] def depthFirstSearch2(curr, prev, dist): global maxdist if dist > maxdist: maxdist = dist for i in paths[curr]: if i != prev and nodes[i]: depthFirstSearch2(i, curr, dist+1) for i in range(M): phos[pho[i]] = True for i in range(N-1): a, b = map(int, input().split()) paths[a].append(b) paths[b].append(a) mark(pho[0], -1) depthFirstSearch(pho[0], -1, 0) depthFirstSearch2(ind[pho[0]], -1, 0) total -= 2 print(total - maxdist)
(n, m) = map(int, input().split()) pho = list(map(int, input().split())) phos = [False for x in range(N)] leaves = [True for x in range(N)] paths = [[] for x in range(N)] nodes = [False for x in range(N)] total = 0 ind = [x for x in range(N)] dists = [1 for x in range(N)] maxdist = 0 def mark(curr, prev): if phos[curr] and (not nodes[curr]): nodes[curr] = True global total total += 2 for i in paths[curr]: if i != prev: mark(i, curr) if nodes[i] and (not nodes[curr]): nodes[curr] = True global total total += 2 def depth_first_search(curr, prev, dist): for i in paths[curr]: if i != prev and nodes[i]: depth_first_search(i, curr, dist + 1) if dists[i] + 1 > dists[curr]: dists[curr] = dists[i] + 1 ind[curr] = ind[i] def depth_first_search2(curr, prev, dist): global maxdist if dist > maxdist: maxdist = dist for i in paths[curr]: if i != prev and nodes[i]: depth_first_search2(i, curr, dist + 1) for i in range(M): phos[pho[i]] = True for i in range(N - 1): (a, b) = map(int, input().split()) paths[a].append(b) paths[b].append(a) mark(pho[0], -1) depth_first_search(pho[0], -1, 0) depth_first_search2(ind[pho[0]], -1, 0) total -= 2 print(total - maxdist)
#entrada while True: n = int(input()) if n == 0: break for i in range(0, n): planeta, anoRecebida, tempo = str(input()).split() anoRecebida = int(anoRecebida) tempo = int(tempo) #processamento if i == 0: primeira = anoRecebida - tempo firstPlanet = planeta if anoRecebida - tempo < primeira: primeira = anoRecebida - tempo firstPlanet = planeta #saida print(firstPlanet)
while True: n = int(input()) if n == 0: break for i in range(0, n): (planeta, ano_recebida, tempo) = str(input()).split() ano_recebida = int(anoRecebida) tempo = int(tempo) if i == 0: primeira = anoRecebida - tempo first_planet = planeta if anoRecebida - tempo < primeira: primeira = anoRecebida - tempo first_planet = planeta print(firstPlanet)
# # PySNMP MIB module CISCO-WAN-CES-PORT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-WAN-CES-PORT-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:20:20 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) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection, ValueRangeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueSizeConstraint", "ConstraintsIntersection", "ValueRangeConstraint", "SingleValueConstraint") circuitEmulation, = mibBuilder.importSymbols("BASIS-MIB", "circuitEmulation") ciscoWan, = mibBuilder.importSymbols("CISCOWAN-SMI", "ciscoWan") ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup") NotificationType, ObjectIdentity, Integer32, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, TimeTicks, Counter64, iso, Counter32, Unsigned32, Gauge32, Bits, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "ObjectIdentity", "Integer32", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "TimeTicks", "Counter64", "iso", "Counter32", "Unsigned32", "Gauge32", "Bits", "IpAddress") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") ciscoWanCesPortMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 351, 150, 40)) ciscoWanCesPortMIB.setRevisions(('2002-11-13 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: ciscoWanCesPortMIB.setRevisionsDescriptions(('Initial version of the MIB. The content of this MIB was originally available in CISCO-WAN-AXIPOP-MIB defined using SMIv1. The applicable objects from CISCO-WAN-AXIPOP-MIB are defined using SMIv2 in this MIB. Also the descriptions of some of the objects have been modified.',)) if mibBuilder.loadTexts: ciscoWanCesPortMIB.setLastUpdated('200211130000Z') if mibBuilder.loadTexts: ciscoWanCesPortMIB.setOrganization('Cisco Systems, Inc.') if mibBuilder.loadTexts: ciscoWanCesPortMIB.setContactInfo(' Cisco Systems Customer Service Postal: 170 W Tasman Drive San Jose, CA 95134 USA Tel: +1 800 553-NETS E-mail: cs-wanatm@cisco.com') if mibBuilder.loadTexts: ciscoWanCesPortMIB.setDescription('The MIB module to configure the Circuit Emulation Service(CES) ports.') cesmPort = MibIdentifier((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1)) cesmPortCnfGrp = MibIdentifier((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1)) cesmPortCnfGrpTable = MibTable((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1), ) if mibBuilder.loadTexts: cesmPortCnfGrpTable.setStatus('current') if mibBuilder.loadTexts: cesmPortCnfGrpTable.setDescription('The config table is for CES logical port. This is used for configuring the port type and number of DS0s and number of Subcircuits in DS0 on the CES port.') cesmPortCnfGrpEntry = MibTableRow((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1), ).setIndexNames((0, "CISCO-WAN-CES-PORT-MIB", "cesPortNum")) if mibBuilder.loadTexts: cesmPortCnfGrpEntry.setStatus('current') if mibBuilder.loadTexts: cesmPortCnfGrpEntry.setDescription('An entry for each logical port. Each entry contains information on the port type, DS0s configured and number of DS0 subcircuits.') cesPortNum = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2048))).setMaxAccess("readonly") if mibBuilder.loadTexts: cesPortNum.setStatus('current') if mibBuilder.loadTexts: cesPortNum.setDescription('This object identifies the logical port number. The range support depends upon the type of the service module(Card). - 8 port T1 Card, range is 1..192. - 8 port E1 Card, range is 1..248. - 1 port T3 Card, range is 1..1. Range is caclulated as follows. This can be used for calculating the range for other type of cards. For T1 Card: (24 * Number of T1 Ports) For E1 Card: (31 * Number of E1 Ports).') cesPortRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("add", 1), ("del", 2), ("mod", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: cesPortRowStatus.setStatus('current') if mibBuilder.loadTexts: cesPortRowStatus.setDescription('This variable enables or modifies the port 1 - add : Add a logical port 2 - del : Delete a logical port 3 - mod : Modify a logical port.') cesPortLineNum = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 128))).setMaxAccess("readwrite") if mibBuilder.loadTexts: cesPortLineNum.setStatus('current') if mibBuilder.loadTexts: cesPortLineNum.setDescription('This object represents the line number to which this port is associated. The supported range depends upon the type of service module(card).') cesPortType = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("structured", 1), ("unstructured", 2), ("framingOnVcDisconnect", 3), ("strau", 4)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: cesPortType.setStatus('current') if mibBuilder.loadTexts: cesPortType.setDescription('This object represents port type whether it is carrying subrate circuits. structured : This is for SDT(Structured Data Transfer). This type of port supports following features: * intended to emulate point-to-point fractional DS1 or E1 circuit. * Synchronous timing * Fractional(Nx64 Kbps)DS1/E1 service (Contiguous timeslots only).You can map an Nx64 Kbps channel to any Virtual Channel(VC). unstructured : This is for unstructured data transfer(UDT) All the DS0 time slots are allocated. This type of port supports following features: * intended to emulate point-to-point DS1 or E1 circuit. * Synchronous and Asynchronous timing framingOnVcDisconnect : similar to unstructured during normal operation. In case of channel failure line data will be looped back towards line. strau : only one DS0 time slot is allocated. The value strau(4) value is not supported in CESM-8T1/E1 or CESM-T3E3. CESM-T3E3 card supports value unstructured(2) only.') cesPortDs0ConfigBitMap = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 16777215))).setMaxAccess("readwrite") if mibBuilder.loadTexts: cesPortDs0ConfigBitMap.setStatus('current') if mibBuilder.loadTexts: cesPortDs0ConfigBitMap.setDescription('This represents bit map of DS0s for a line which are used to form this logical port. Bit 0 represents DS0-1.') cesPortNumOfDs0Slot = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 32))).setMaxAccess("readwrite") if mibBuilder.loadTexts: cesPortNumOfDs0Slot.setStatus('current') if mibBuilder.loadTexts: cesPortNumOfDs0Slot.setDescription('This represents number of DS0 time slots configured to this Port. If the cesPortType is strau(4), then this can not have more than 1 DS0 time slot.') cesPortNumOfSCIPerDS0 = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 8)).clone(4)).setMaxAccess("readwrite") if mibBuilder.loadTexts: cesPortNumOfSCIPerDS0.setStatus('current') if mibBuilder.loadTexts: cesPortNumOfSCIPerDS0.setDescription('This object represents number of subcircuit in the DS0 time slot. This is applicable only when cesPortType is strau(4). 8 = there are 8 no .of 8kbps links (1 bit) 4 = there are 4 no .of 16kbps links (2 bit) 2 = there are 2 no .of 32kbps links (4 bit) Currently not supported in CESM-8.') cesPortSpeed = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 44736))).setUnits('kbps').setMaxAccess("readonly") if mibBuilder.loadTexts: cesPortSpeed.setStatus('current') if mibBuilder.loadTexts: cesPortSpeed.setDescription('This object identifies the configured speed of port. Max speed for T1 = 1544 Max speed for E1 = 2038 Max speed for T3 = 44736 Max speed for E3 = 34368.') cesPortState = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=NamedValues(("notConfigured", 1), ("active", 2), ("remoteLoopback", 3), ("failedDueToLine", 4), ("failedDueToSignalling", 5), ("inactive", 6), ("inBert", 7), ("farEndRemoteLoopback", 8))).clone('notConfigured')).setMaxAccess("readonly") if mibBuilder.loadTexts: cesPortState.setStatus('current') if mibBuilder.loadTexts: cesPortState.setDescription('This variable indicates the state of the logical port. The possible values are : notConfigured (1) : Port is not configured active (2) : Port is in active state remoteLoopback (3) : Remote Loopback is set failedDueToLine(4) : Port failed due to some failure in physical line failedDueToSignalling(5) : Port failed due to some Signalling issues. inactive (6) : Port is not active inBert (7) : Bit Error Rate Test(BERT) in progress. farEndRemoteLoopback(8): Far End is in loopback.') cesPortBERTEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disable", 1), ("enable", 2))).clone('disable')).setMaxAccess("readwrite") if mibBuilder.loadTexts: cesPortBERTEnable.setStatus('current') if mibBuilder.loadTexts: cesPortBERTEnable.setDescription('This variable enables/disables BERT. This object is not supported in CESM-T3E3.') cesPortNextAvailable = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2048))).setMaxAccess("readonly") if mibBuilder.loadTexts: cesPortNextAvailable.setStatus('current') if mibBuilder.loadTexts: cesPortNextAvailable.setDescription("This variable contains the next UNUSED logical port number of the possible 32 DS0s * n ports. This number can be used in channel config table, the cesportNextAvailable gets updated if the number gets used to create a logical port. A '0' indicates that no more ports are available.") cesPortsUsedLine1 = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 16777215))).setMaxAccess("readonly") if mibBuilder.loadTexts: cesPortsUsedLine1.setStatus('current') if mibBuilder.loadTexts: cesPortsUsedLine1.setDescription('Each bits set represents a DS0 that is used by all the logical ports defined so far for that DS1, the most significant byte is invalid for DS1 This is for line 1') cesPortsUsedLine2 = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 16777215))).setMaxAccess("readonly") if mibBuilder.loadTexts: cesPortsUsedLine2.setStatus('current') if mibBuilder.loadTexts: cesPortsUsedLine2.setDescription('Each bits set represents a DS0 that is used by all the logical ports defined so far for that DS1, the most significant byte is invalid for DS1 This is for line 2.') cesPortsUsedLine3 = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 16777215))).setMaxAccess("readonly") if mibBuilder.loadTexts: cesPortsUsedLine3.setStatus('current') if mibBuilder.loadTexts: cesPortsUsedLine3.setDescription('Each bits set represents a DS0 that is used by all the logical ports defined so far for that DS1, the most significant byte is invalid for DS1 This is for line 3') cesPortsUsedLine4 = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 16777215))).setMaxAccess("readonly") if mibBuilder.loadTexts: cesPortsUsedLine4.setStatus('current') if mibBuilder.loadTexts: cesPortsUsedLine4.setDescription('Each bits set represents a DS0 that is used by all the logical ports defined so far for that DS1, the most significant byte is invalid for DS1. This is for line 4') cesPortsUsedLine5 = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 16777215))).setMaxAccess("readonly") if mibBuilder.loadTexts: cesPortsUsedLine5.setStatus('current') if mibBuilder.loadTexts: cesPortsUsedLine5.setDescription('Each bits set represents a DS0 that is used by all the logical ports defined so far for that DS1, the most significant byte is invalid for DS1 This is for line 5') cesPortsUsedLine6 = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 16777215))).setMaxAccess("readonly") if mibBuilder.loadTexts: cesPortsUsedLine6.setStatus('current') if mibBuilder.loadTexts: cesPortsUsedLine6.setDescription('Each bits set represents a DS0 that is used by all the logical ports defined so far for that DS1, the most significant byte is invalid for DS1 This is for line 6') cesPortsUsedLine7 = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 16777215))).setMaxAccess("readonly") if mibBuilder.loadTexts: cesPortsUsedLine7.setStatus('current') if mibBuilder.loadTexts: cesPortsUsedLine7.setDescription('Each bits set represents a DS0 that is used by all the logical ports defined so far for that DS1, the most significant byte is invalid for DS1 This is for line 7') cesPortsUsedLine8 = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 16777215))).setMaxAccess("readonly") if mibBuilder.loadTexts: cesPortsUsedLine8.setStatus('current') if mibBuilder.loadTexts: cesPortsUsedLine8.setDescription('Each bits set represents a DS0 that is used by all the logical ports defined so far for that DS1, the most significant byte is invalid for DS1 This is for line 8') ciscoWanCesPortMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 351, 150, 40, 2)) ciscoWanCesPortMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 351, 150, 40, 2, 1)) ciscoWanCesPortMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 351, 150, 40, 2, 2)) ciscoWanCesPortCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 351, 150, 40, 2, 2, 1)).setObjects(("CISCO-WAN-CES-PORT-MIB", "ciscoWanCesPortConfGroup"), ("CISCO-WAN-CES-PORT-MIB", "ciscoWanCesPortDs0InDs1Group"), ("CISCO-WAN-CES-PORT-MIB", "ciscoWanCesPortsUsedGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoWanCesPortCompliance = ciscoWanCesPortCompliance.setStatus('current') if mibBuilder.loadTexts: ciscoWanCesPortCompliance.setDescription('The compliance statement for objects related to CES Logical Ports.') ciscoWanCesPortsUsedGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 351, 150, 40, 2, 1, 1)).setObjects(("CISCO-WAN-CES-PORT-MIB", "cesPortNextAvailable")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoWanCesPortsUsedGroup = ciscoWanCesPortsUsedGroup.setStatus('current') if mibBuilder.loadTexts: ciscoWanCesPortsUsedGroup.setDescription('The collection of objects which are applicable for general information about logical ports.') ciscoWanCesPortConfGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 351, 150, 40, 2, 1, 2)).setObjects(("CISCO-WAN-CES-PORT-MIB", "cesPortNum"), ("CISCO-WAN-CES-PORT-MIB", "cesPortRowStatus"), ("CISCO-WAN-CES-PORT-MIB", "cesPortLineNum"), ("CISCO-WAN-CES-PORT-MIB", "cesPortType"), ("CISCO-WAN-CES-PORT-MIB", "cesPortDs0ConfigBitMap"), ("CISCO-WAN-CES-PORT-MIB", "cesPortNumOfDs0Slot"), ("CISCO-WAN-CES-PORT-MIB", "cesPortNumOfSCIPerDS0"), ("CISCO-WAN-CES-PORT-MIB", "cesPortSpeed"), ("CISCO-WAN-CES-PORT-MIB", "cesPortState"), ("CISCO-WAN-CES-PORT-MIB", "cesPortBERTEnable")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoWanCesPortConfGroup = ciscoWanCesPortConfGroup.setStatus('current') if mibBuilder.loadTexts: ciscoWanCesPortConfGroup.setDescription('The collection of objects which are used to represent Circuit Emulation Service Port information.') ciscoWanCesPortDs0InDs1Group = ObjectGroup((1, 3, 6, 1, 4, 1, 351, 150, 40, 2, 1, 3)).setObjects(("CISCO-WAN-CES-PORT-MIB", "cesPortsUsedLine1"), ("CISCO-WAN-CES-PORT-MIB", "cesPortsUsedLine2"), ("CISCO-WAN-CES-PORT-MIB", "cesPortsUsedLine3"), ("CISCO-WAN-CES-PORT-MIB", "cesPortsUsedLine4"), ("CISCO-WAN-CES-PORT-MIB", "cesPortsUsedLine5"), ("CISCO-WAN-CES-PORT-MIB", "cesPortsUsedLine6"), ("CISCO-WAN-CES-PORT-MIB", "cesPortsUsedLine7"), ("CISCO-WAN-CES-PORT-MIB", "cesPortsUsedLine8")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoWanCesPortDs0InDs1Group = ciscoWanCesPortDs0InDs1Group.setStatus('current') if mibBuilder.loadTexts: ciscoWanCesPortDs0InDs1Group.setDescription('The collection of objects related to information on DS0 time slots used in each DS1 line.') mibBuilder.exportSymbols("CISCO-WAN-CES-PORT-MIB", cesPortNum=cesPortNum, ciscoWanCesPortCompliance=ciscoWanCesPortCompliance, PYSNMP_MODULE_ID=ciscoWanCesPortMIB, cesPortDs0ConfigBitMap=cesPortDs0ConfigBitMap, cesmPort=cesmPort, cesPortsUsedLine8=cesPortsUsedLine8, ciscoWanCesPortsUsedGroup=ciscoWanCesPortsUsedGroup, cesmPortCnfGrpTable=cesmPortCnfGrpTable, cesmPortCnfGrp=cesmPortCnfGrp, cesPortNextAvailable=cesPortNextAvailable, cesPortsUsedLine5=cesPortsUsedLine5, ciscoWanCesPortMIBConformance=ciscoWanCesPortMIBConformance, ciscoWanCesPortConfGroup=ciscoWanCesPortConfGroup, cesPortsUsedLine6=cesPortsUsedLine6, ciscoWanCesPortMIBGroups=ciscoWanCesPortMIBGroups, cesPortState=cesPortState, cesPortsUsedLine3=cesPortsUsedLine3, cesPortBERTEnable=cesPortBERTEnable, cesPortSpeed=cesPortSpeed, cesmPortCnfGrpEntry=cesmPortCnfGrpEntry, cesPortsUsedLine4=cesPortsUsedLine4, cesPortsUsedLine7=cesPortsUsedLine7, cesPortType=cesPortType, cesPortNumOfDs0Slot=cesPortNumOfDs0Slot, cesPortLineNum=cesPortLineNum, cesPortRowStatus=cesPortRowStatus, cesPortsUsedLine1=cesPortsUsedLine1, ciscoWanCesPortMIBCompliances=ciscoWanCesPortMIBCompliances, ciscoWanCesPortDs0InDs1Group=ciscoWanCesPortDs0InDs1Group, ciscoWanCesPortMIB=ciscoWanCesPortMIB, cesPortsUsedLine2=cesPortsUsedLine2, cesPortNumOfSCIPerDS0=cesPortNumOfSCIPerDS0)
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, value_size_constraint, constraints_intersection, value_range_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'ValueSizeConstraint', 'ConstraintsIntersection', 'ValueRangeConstraint', 'SingleValueConstraint') (circuit_emulation,) = mibBuilder.importSymbols('BASIS-MIB', 'circuitEmulation') (cisco_wan,) = mibBuilder.importSymbols('CISCOWAN-SMI', 'ciscoWan') (module_compliance, notification_group, object_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup', 'ObjectGroup') (notification_type, object_identity, integer32, mib_identifier, mib_scalar, mib_table, mib_table_row, mib_table_column, module_identity, time_ticks, counter64, iso, counter32, unsigned32, gauge32, bits, ip_address) = mibBuilder.importSymbols('SNMPv2-SMI', 'NotificationType', 'ObjectIdentity', 'Integer32', 'MibIdentifier', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ModuleIdentity', 'TimeTicks', 'Counter64', 'iso', 'Counter32', 'Unsigned32', 'Gauge32', 'Bits', 'IpAddress') (textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString') cisco_wan_ces_port_mib = module_identity((1, 3, 6, 1, 4, 1, 351, 150, 40)) ciscoWanCesPortMIB.setRevisions(('2002-11-13 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: ciscoWanCesPortMIB.setRevisionsDescriptions(('Initial version of the MIB. The content of this MIB was originally available in CISCO-WAN-AXIPOP-MIB defined using SMIv1. The applicable objects from CISCO-WAN-AXIPOP-MIB are defined using SMIv2 in this MIB. Also the descriptions of some of the objects have been modified.',)) if mibBuilder.loadTexts: ciscoWanCesPortMIB.setLastUpdated('200211130000Z') if mibBuilder.loadTexts: ciscoWanCesPortMIB.setOrganization('Cisco Systems, Inc.') if mibBuilder.loadTexts: ciscoWanCesPortMIB.setContactInfo(' Cisco Systems Customer Service Postal: 170 W Tasman Drive San Jose, CA 95134 USA Tel: +1 800 553-NETS E-mail: cs-wanatm@cisco.com') if mibBuilder.loadTexts: ciscoWanCesPortMIB.setDescription('The MIB module to configure the Circuit Emulation Service(CES) ports.') cesm_port = mib_identifier((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1)) cesm_port_cnf_grp = mib_identifier((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1)) cesm_port_cnf_grp_table = mib_table((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1)) if mibBuilder.loadTexts: cesmPortCnfGrpTable.setStatus('current') if mibBuilder.loadTexts: cesmPortCnfGrpTable.setDescription('The config table is for CES logical port. This is used for configuring the port type and number of DS0s and number of Subcircuits in DS0 on the CES port.') cesm_port_cnf_grp_entry = mib_table_row((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1)).setIndexNames((0, 'CISCO-WAN-CES-PORT-MIB', 'cesPortNum')) if mibBuilder.loadTexts: cesmPortCnfGrpEntry.setStatus('current') if mibBuilder.loadTexts: cesmPortCnfGrpEntry.setDescription('An entry for each logical port. Each entry contains information on the port type, DS0s configured and number of DS0 subcircuits.') ces_port_num = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 2048))).setMaxAccess('readonly') if mibBuilder.loadTexts: cesPortNum.setStatus('current') if mibBuilder.loadTexts: cesPortNum.setDescription('This object identifies the logical port number. The range support depends upon the type of the service module(Card). - 8 port T1 Card, range is 1..192. - 8 port E1 Card, range is 1..248. - 1 port T3 Card, range is 1..1. Range is caclulated as follows. This can be used for calculating the range for other type of cards. For T1 Card: (24 * Number of T1 Ports) For E1 Card: (31 * Number of E1 Ports).') ces_port_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('add', 1), ('del', 2), ('mod', 3)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: cesPortRowStatus.setStatus('current') if mibBuilder.loadTexts: cesPortRowStatus.setDescription('This variable enables or modifies the port 1 - add : Add a logical port 2 - del : Delete a logical port 3 - mod : Modify a logical port.') ces_port_line_num = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(1, 128))).setMaxAccess('readwrite') if mibBuilder.loadTexts: cesPortLineNum.setStatus('current') if mibBuilder.loadTexts: cesPortLineNum.setDescription('This object represents the line number to which this port is associated. The supported range depends upon the type of service module(card).') ces_port_type = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('structured', 1), ('unstructured', 2), ('framingOnVcDisconnect', 3), ('strau', 4)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: cesPortType.setStatus('current') if mibBuilder.loadTexts: cesPortType.setDescription('This object represents port type whether it is carrying subrate circuits. structured : This is for SDT(Structured Data Transfer). This type of port supports following features: * intended to emulate point-to-point fractional DS1 or E1 circuit. * Synchronous timing * Fractional(Nx64 Kbps)DS1/E1 service (Contiguous timeslots only).You can map an Nx64 Kbps channel to any Virtual Channel(VC). unstructured : This is for unstructured data transfer(UDT) All the DS0 time slots are allocated. This type of port supports following features: * intended to emulate point-to-point DS1 or E1 circuit. * Synchronous and Asynchronous timing framingOnVcDisconnect : similar to unstructured during normal operation. In case of channel failure line data will be looped back towards line. strau : only one DS0 time slot is allocated. The value strau(4) value is not supported in CESM-8T1/E1 or CESM-T3E3. CESM-T3E3 card supports value unstructured(2) only.') ces_port_ds0_config_bit_map = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 5), integer32().subtype(subtypeSpec=value_range_constraint(0, 16777215))).setMaxAccess('readwrite') if mibBuilder.loadTexts: cesPortDs0ConfigBitMap.setStatus('current') if mibBuilder.loadTexts: cesPortDs0ConfigBitMap.setDescription('This represents bit map of DS0s for a line which are used to form this logical port. Bit 0 represents DS0-1.') ces_port_num_of_ds0_slot = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 6), integer32().subtype(subtypeSpec=value_range_constraint(1, 32))).setMaxAccess('readwrite') if mibBuilder.loadTexts: cesPortNumOfDs0Slot.setStatus('current') if mibBuilder.loadTexts: cesPortNumOfDs0Slot.setDescription('This represents number of DS0 time slots configured to this Port. If the cesPortType is strau(4), then this can not have more than 1 DS0 time slot.') ces_port_num_of_sci_per_ds0 = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 7), integer32().subtype(subtypeSpec=value_range_constraint(1, 8)).clone(4)).setMaxAccess('readwrite') if mibBuilder.loadTexts: cesPortNumOfSCIPerDS0.setStatus('current') if mibBuilder.loadTexts: cesPortNumOfSCIPerDS0.setDescription('This object represents number of subcircuit in the DS0 time slot. This is applicable only when cesPortType is strau(4). 8 = there are 8 no .of 8kbps links (1 bit) 4 = there are 4 no .of 16kbps links (2 bit) 2 = there are 2 no .of 32kbps links (4 bit) Currently not supported in CESM-8.') ces_port_speed = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 8), integer32().subtype(subtypeSpec=value_range_constraint(0, 44736))).setUnits('kbps').setMaxAccess('readonly') if mibBuilder.loadTexts: cesPortSpeed.setStatus('current') if mibBuilder.loadTexts: cesPortSpeed.setDescription('This object identifies the configured speed of port. Max speed for T1 = 1544 Max speed for E1 = 2038 Max speed for T3 = 44736 Max speed for E3 = 34368.') ces_port_state = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 9), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=named_values(('notConfigured', 1), ('active', 2), ('remoteLoopback', 3), ('failedDueToLine', 4), ('failedDueToSignalling', 5), ('inactive', 6), ('inBert', 7), ('farEndRemoteLoopback', 8))).clone('notConfigured')).setMaxAccess('readonly') if mibBuilder.loadTexts: cesPortState.setStatus('current') if mibBuilder.loadTexts: cesPortState.setDescription('This variable indicates the state of the logical port. The possible values are : notConfigured (1) : Port is not configured active (2) : Port is in active state remoteLoopback (3) : Remote Loopback is set failedDueToLine(4) : Port failed due to some failure in physical line failedDueToSignalling(5) : Port failed due to some Signalling issues. inactive (6) : Port is not active inBert (7) : Bit Error Rate Test(BERT) in progress. farEndRemoteLoopback(8): Far End is in loopback.') ces_port_bert_enable = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 1, 1, 10), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('disable', 1), ('enable', 2))).clone('disable')).setMaxAccess('readwrite') if mibBuilder.loadTexts: cesPortBERTEnable.setStatus('current') if mibBuilder.loadTexts: cesPortBERTEnable.setDescription('This variable enables/disables BERT. This object is not supported in CESM-T3E3.') ces_port_next_available = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(0, 2048))).setMaxAccess('readonly') if mibBuilder.loadTexts: cesPortNextAvailable.setStatus('current') if mibBuilder.loadTexts: cesPortNextAvailable.setDescription("This variable contains the next UNUSED logical port number of the possible 32 DS0s * n ports. This number can be used in channel config table, the cesportNextAvailable gets updated if the number gets used to create a logical port. A '0' indicates that no more ports are available.") ces_ports_used_line1 = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(0, 16777215))).setMaxAccess('readonly') if mibBuilder.loadTexts: cesPortsUsedLine1.setStatus('current') if mibBuilder.loadTexts: cesPortsUsedLine1.setDescription('Each bits set represents a DS0 that is used by all the logical ports defined so far for that DS1, the most significant byte is invalid for DS1 This is for line 1') ces_ports_used_line2 = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 4), integer32().subtype(subtypeSpec=value_range_constraint(0, 16777215))).setMaxAccess('readonly') if mibBuilder.loadTexts: cesPortsUsedLine2.setStatus('current') if mibBuilder.loadTexts: cesPortsUsedLine2.setDescription('Each bits set represents a DS0 that is used by all the logical ports defined so far for that DS1, the most significant byte is invalid for DS1 This is for line 2.') ces_ports_used_line3 = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 5), integer32().subtype(subtypeSpec=value_range_constraint(0, 16777215))).setMaxAccess('readonly') if mibBuilder.loadTexts: cesPortsUsedLine3.setStatus('current') if mibBuilder.loadTexts: cesPortsUsedLine3.setDescription('Each bits set represents a DS0 that is used by all the logical ports defined so far for that DS1, the most significant byte is invalid for DS1 This is for line 3') ces_ports_used_line4 = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 6), integer32().subtype(subtypeSpec=value_range_constraint(0, 16777215))).setMaxAccess('readonly') if mibBuilder.loadTexts: cesPortsUsedLine4.setStatus('current') if mibBuilder.loadTexts: cesPortsUsedLine4.setDescription('Each bits set represents a DS0 that is used by all the logical ports defined so far for that DS1, the most significant byte is invalid for DS1. This is for line 4') ces_ports_used_line5 = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 7), integer32().subtype(subtypeSpec=value_range_constraint(0, 16777215))).setMaxAccess('readonly') if mibBuilder.loadTexts: cesPortsUsedLine5.setStatus('current') if mibBuilder.loadTexts: cesPortsUsedLine5.setDescription('Each bits set represents a DS0 that is used by all the logical ports defined so far for that DS1, the most significant byte is invalid for DS1 This is for line 5') ces_ports_used_line6 = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 8), integer32().subtype(subtypeSpec=value_range_constraint(0, 16777215))).setMaxAccess('readonly') if mibBuilder.loadTexts: cesPortsUsedLine6.setStatus('current') if mibBuilder.loadTexts: cesPortsUsedLine6.setDescription('Each bits set represents a DS0 that is used by all the logical ports defined so far for that DS1, the most significant byte is invalid for DS1 This is for line 6') ces_ports_used_line7 = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 9), integer32().subtype(subtypeSpec=value_range_constraint(0, 16777215))).setMaxAccess('readonly') if mibBuilder.loadTexts: cesPortsUsedLine7.setStatus('current') if mibBuilder.loadTexts: cesPortsUsedLine7.setDescription('Each bits set represents a DS0 that is used by all the logical ports defined so far for that DS1, the most significant byte is invalid for DS1 This is for line 7') ces_ports_used_line8 = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 5, 3, 1, 1, 10), integer32().subtype(subtypeSpec=value_range_constraint(0, 16777215))).setMaxAccess('readonly') if mibBuilder.loadTexts: cesPortsUsedLine8.setStatus('current') if mibBuilder.loadTexts: cesPortsUsedLine8.setDescription('Each bits set represents a DS0 that is used by all the logical ports defined so far for that DS1, the most significant byte is invalid for DS1 This is for line 8') cisco_wan_ces_port_mib_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 351, 150, 40, 2)) cisco_wan_ces_port_mib_groups = mib_identifier((1, 3, 6, 1, 4, 1, 351, 150, 40, 2, 1)) cisco_wan_ces_port_mib_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 351, 150, 40, 2, 2)) cisco_wan_ces_port_compliance = module_compliance((1, 3, 6, 1, 4, 1, 351, 150, 40, 2, 2, 1)).setObjects(('CISCO-WAN-CES-PORT-MIB', 'ciscoWanCesPortConfGroup'), ('CISCO-WAN-CES-PORT-MIB', 'ciscoWanCesPortDs0InDs1Group'), ('CISCO-WAN-CES-PORT-MIB', 'ciscoWanCesPortsUsedGroup')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_wan_ces_port_compliance = ciscoWanCesPortCompliance.setStatus('current') if mibBuilder.loadTexts: ciscoWanCesPortCompliance.setDescription('The compliance statement for objects related to CES Logical Ports.') cisco_wan_ces_ports_used_group = object_group((1, 3, 6, 1, 4, 1, 351, 150, 40, 2, 1, 1)).setObjects(('CISCO-WAN-CES-PORT-MIB', 'cesPortNextAvailable')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_wan_ces_ports_used_group = ciscoWanCesPortsUsedGroup.setStatus('current') if mibBuilder.loadTexts: ciscoWanCesPortsUsedGroup.setDescription('The collection of objects which are applicable for general information about logical ports.') cisco_wan_ces_port_conf_group = object_group((1, 3, 6, 1, 4, 1, 351, 150, 40, 2, 1, 2)).setObjects(('CISCO-WAN-CES-PORT-MIB', 'cesPortNum'), ('CISCO-WAN-CES-PORT-MIB', 'cesPortRowStatus'), ('CISCO-WAN-CES-PORT-MIB', 'cesPortLineNum'), ('CISCO-WAN-CES-PORT-MIB', 'cesPortType'), ('CISCO-WAN-CES-PORT-MIB', 'cesPortDs0ConfigBitMap'), ('CISCO-WAN-CES-PORT-MIB', 'cesPortNumOfDs0Slot'), ('CISCO-WAN-CES-PORT-MIB', 'cesPortNumOfSCIPerDS0'), ('CISCO-WAN-CES-PORT-MIB', 'cesPortSpeed'), ('CISCO-WAN-CES-PORT-MIB', 'cesPortState'), ('CISCO-WAN-CES-PORT-MIB', 'cesPortBERTEnable')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_wan_ces_port_conf_group = ciscoWanCesPortConfGroup.setStatus('current') if mibBuilder.loadTexts: ciscoWanCesPortConfGroup.setDescription('The collection of objects which are used to represent Circuit Emulation Service Port information.') cisco_wan_ces_port_ds0_in_ds1_group = object_group((1, 3, 6, 1, 4, 1, 351, 150, 40, 2, 1, 3)).setObjects(('CISCO-WAN-CES-PORT-MIB', 'cesPortsUsedLine1'), ('CISCO-WAN-CES-PORT-MIB', 'cesPortsUsedLine2'), ('CISCO-WAN-CES-PORT-MIB', 'cesPortsUsedLine3'), ('CISCO-WAN-CES-PORT-MIB', 'cesPortsUsedLine4'), ('CISCO-WAN-CES-PORT-MIB', 'cesPortsUsedLine5'), ('CISCO-WAN-CES-PORT-MIB', 'cesPortsUsedLine6'), ('CISCO-WAN-CES-PORT-MIB', 'cesPortsUsedLine7'), ('CISCO-WAN-CES-PORT-MIB', 'cesPortsUsedLine8')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_wan_ces_port_ds0_in_ds1_group = ciscoWanCesPortDs0InDs1Group.setStatus('current') if mibBuilder.loadTexts: ciscoWanCesPortDs0InDs1Group.setDescription('The collection of objects related to information on DS0 time slots used in each DS1 line.') mibBuilder.exportSymbols('CISCO-WAN-CES-PORT-MIB', cesPortNum=cesPortNum, ciscoWanCesPortCompliance=ciscoWanCesPortCompliance, PYSNMP_MODULE_ID=ciscoWanCesPortMIB, cesPortDs0ConfigBitMap=cesPortDs0ConfigBitMap, cesmPort=cesmPort, cesPortsUsedLine8=cesPortsUsedLine8, ciscoWanCesPortsUsedGroup=ciscoWanCesPortsUsedGroup, cesmPortCnfGrpTable=cesmPortCnfGrpTable, cesmPortCnfGrp=cesmPortCnfGrp, cesPortNextAvailable=cesPortNextAvailable, cesPortsUsedLine5=cesPortsUsedLine5, ciscoWanCesPortMIBConformance=ciscoWanCesPortMIBConformance, ciscoWanCesPortConfGroup=ciscoWanCesPortConfGroup, cesPortsUsedLine6=cesPortsUsedLine6, ciscoWanCesPortMIBGroups=ciscoWanCesPortMIBGroups, cesPortState=cesPortState, cesPortsUsedLine3=cesPortsUsedLine3, cesPortBERTEnable=cesPortBERTEnable, cesPortSpeed=cesPortSpeed, cesmPortCnfGrpEntry=cesmPortCnfGrpEntry, cesPortsUsedLine4=cesPortsUsedLine4, cesPortsUsedLine7=cesPortsUsedLine7, cesPortType=cesPortType, cesPortNumOfDs0Slot=cesPortNumOfDs0Slot, cesPortLineNum=cesPortLineNum, cesPortRowStatus=cesPortRowStatus, cesPortsUsedLine1=cesPortsUsedLine1, ciscoWanCesPortMIBCompliances=ciscoWanCesPortMIBCompliances, ciscoWanCesPortDs0InDs1Group=ciscoWanCesPortDs0InDs1Group, ciscoWanCesPortMIB=ciscoWanCesPortMIB, cesPortsUsedLine2=cesPortsUsedLine2, cesPortNumOfSCIPerDS0=cesPortNumOfSCIPerDS0)
class Frame: def __init__(self, resume: int, store: int, locals_: list, arguments: list): self.stack = [] self.locals = [] for i in range(len(locals_)): self.locals.append(locals_[i]) if len(arguments) > i: self.locals[i] == arguments[i] self.arg_count = len(arguments) self.resume = resume self.store = store def empty(self): self.stack = [] self.locals = [] self.arg_count = 0 self.resume = 0 self.store = None @classmethod def from_bytes(cls, bytes_: bytearray) -> cls: resume = 0 resume += (bytes_[0] << 16) resume += (bytes_[1] << 8) resume += bytes_[2] flags = bytes_[3] has_store = (flags & 0b0001_0000) == 0 num_locals = flags & 0b0000_1111 store = bytes_[4] if has_store else None mask = bytes_[5] arg_count = 0 for bit in range(7): if (mask & (1 << bit)) != 0: arg_count += 1 stack_length = 0 stack_length += bytes_[6] << 8 stack_length += bytes_[7] locals_ = [] stack = [] index = 8 for offset in range(num_locals): word = 0 word += bytes_[index + offset * 2] << 8 word += bytes_[index + offset * 2 + 1] locals_.append(word) index += num_locals * 2 for offset in range(stack_length): word = 0 word += bytes_[index + offset * 2] << 8 word += bytes_[index + offset * 2 + 1] stack.append(word) new_frame = cls(resume, store, locals_, []) new_frame.arg_count = arg_count return new_frame def read_local(self, index: int) -> int: return self.locals[index] def write_local(self, index: int, value: int): self.locals[index] = value def stack_push(self, value: int): self.stack.append(value) def stack_pop(self) -> int: return self.stack.pop() def stack_peek(self) -> int: return self.stack[-1] def to_string(self) -> str: return "--- to do ---" def to_list(self) -> list: bytes_ = [] bytes_.append((self.resume & 0xFF_0000) >> 16) bytes_.append((self.resume & 0x00_FF00) >> 8) bytes_.append(self.resume & 0x00_00FF) flags = len(self.locals) if self.store: flags += 0b0001_0000 args_supplied = 0 for bit in range(self.arg_count): args_supplied |= 1 << bit bytes_.append(flags) bytes_.append(self.store or 0) bytes_.append(args_supplied) stack_length = len(self.stack) bytes_.append((stack_length & 0xFF00) >> 8) bytes_.append(stack_length & 0x00FF) for local in self.locals: bytes_.append((local & 0xFF00) >> 8) bytes_.append(local & 0x00FF) for var in self.stack: bytes_.append((var & 0xFF00) >> 8) bytes_.append(var & 0x00FF) return bytes_
class Frame: def __init__(self, resume: int, store: int, locals_: list, arguments: list): self.stack = [] self.locals = [] for i in range(len(locals_)): self.locals.append(locals_[i]) if len(arguments) > i: self.locals[i] == arguments[i] self.arg_count = len(arguments) self.resume = resume self.store = store def empty(self): self.stack = [] self.locals = [] self.arg_count = 0 self.resume = 0 self.store = None @classmethod def from_bytes(cls, bytes_: bytearray) -> cls: resume = 0 resume += bytes_[0] << 16 resume += bytes_[1] << 8 resume += bytes_[2] flags = bytes_[3] has_store = flags & 16 == 0 num_locals = flags & 15 store = bytes_[4] if has_store else None mask = bytes_[5] arg_count = 0 for bit in range(7): if mask & 1 << bit != 0: arg_count += 1 stack_length = 0 stack_length += bytes_[6] << 8 stack_length += bytes_[7] locals_ = [] stack = [] index = 8 for offset in range(num_locals): word = 0 word += bytes_[index + offset * 2] << 8 word += bytes_[index + offset * 2 + 1] locals_.append(word) index += num_locals * 2 for offset in range(stack_length): word = 0 word += bytes_[index + offset * 2] << 8 word += bytes_[index + offset * 2 + 1] stack.append(word) new_frame = cls(resume, store, locals_, []) new_frame.arg_count = arg_count return new_frame def read_local(self, index: int) -> int: return self.locals[index] def write_local(self, index: int, value: int): self.locals[index] = value def stack_push(self, value: int): self.stack.append(value) def stack_pop(self) -> int: return self.stack.pop() def stack_peek(self) -> int: return self.stack[-1] def to_string(self) -> str: return '--- to do ---' def to_list(self) -> list: bytes_ = [] bytes_.append((self.resume & 16711680) >> 16) bytes_.append((self.resume & 65280) >> 8) bytes_.append(self.resume & 255) flags = len(self.locals) if self.store: flags += 16 args_supplied = 0 for bit in range(self.arg_count): args_supplied |= 1 << bit bytes_.append(flags) bytes_.append(self.store or 0) bytes_.append(args_supplied) stack_length = len(self.stack) bytes_.append((stack_length & 65280) >> 8) bytes_.append(stack_length & 255) for local in self.locals: bytes_.append((local & 65280) >> 8) bytes_.append(local & 255) for var in self.stack: bytes_.append((var & 65280) >> 8) bytes_.append(var & 255) return bytes_
#will ask the user for their age and then it will #tell them how many months that age equals to user_age = input("Enter your age : ") years = int(user_age) months = years * 12 print(f"Your age, {years}, equals to {months} months.")
user_age = input('Enter your age : ') years = int(user_age) months = years * 12 print(f'Your age, {years}, equals to {months} months.')
a = [_.split('\t') for _ in open('a.txt', 'r').read().split('\n')] b = [_.split('\t') for _ in open('b.txt', 'r').read().split('\n')] for _ in range(len(a)): for a_, b_ in zip(a[_], b[_]): print(a_, b_, end='\t', sep='\t') print('')
a = [_.split('\t') for _ in open('a.txt', 'r').read().split('\n')] b = [_.split('\t') for _ in open('b.txt', 'r').read().split('\n')] for _ in range(len(a)): for (a_, b_) in zip(a[_], b[_]): print(a_, b_, end='\t', sep='\t') print('')
#function -->mehgiclude sebuah nilai didalam fungsi def input_barang(nama,harga): print("Nama Barang:", nama) print("Harga Barang", harga) a=input("masukan nama barang:") b=input("masukan harga barang") input_barang(a,b)
def input_barang(nama, harga): print('Nama Barang:', nama) print('Harga Barang', harga) a = input('masukan nama barang:') b = input('masukan harga barang') input_barang(a, b)
#!/usr/bin/python3 class Bash_DB: def __init(self, Parent): self.Controller = Parent def Create_DB(self, DB_Type): if DB_Type.DB_Stack == "LAMP": self.Controller.Bash_Script.subprocess.call("./Sensor_Database/LAMP_Server/LAMP_Setup.sh")
class Bash_Db: def __init(self, Parent): self.Controller = Parent def create_db(self, DB_Type): if DB_Type.DB_Stack == 'LAMP': self.Controller.Bash_Script.subprocess.call('./Sensor_Database/LAMP_Server/LAMP_Setup.sh')
# @desc This is a code that determines whether a number is positive, negative, or just 0 # @desc by Merrick '23 def positive_negative(x): if x > 0: return "pos" elif x == 0: return "0" else: return "neg" def main(): print(positive_negative(5)) print(positive_negative(-1)) print(positive_negative(0)) print(positive_negative(21)) print(positive_negative(-100)) if __name__ == '__main__': main()
def positive_negative(x): if x > 0: return 'pos' elif x == 0: return '0' else: return 'neg' def main(): print(positive_negative(5)) print(positive_negative(-1)) print(positive_negative(0)) print(positive_negative(21)) print(positive_negative(-100)) if __name__ == '__main__': main()
__all__ = [ 'resp', 'user' ]
__all__ = ['resp', 'user']
# ------------------------------------------------ EASTER EGG ------------------------------------------------ # Congratulations on finding this file! Please use the following methods below to decrypt the given cipher. def decrypt(cipher, multiple): text = "" for idx, ch in enumerate(cipher): if ch.isalpha(): shift = multiple * idx % 26 newChar = ord(ch) + shift if newChar > ord('z'): newChar -= 26 text += chr(newChar) return text def encrypt(text, multiple): cipher = "" for idx, ch in enumerate(text): if ch.isalpha(): shift = multiple * idx % 26 newChar = ord(ch) - shift if newChar < ord('a'): newChar += 26 cipher += chr(newChar) return cipher
def decrypt(cipher, multiple): text = '' for (idx, ch) in enumerate(cipher): if ch.isalpha(): shift = multiple * idx % 26 new_char = ord(ch) + shift if newChar > ord('z'): new_char -= 26 text += chr(newChar) return text def encrypt(text, multiple): cipher = '' for (idx, ch) in enumerate(text): if ch.isalpha(): shift = multiple * idx % 26 new_char = ord(ch) - shift if newChar < ord('a'): new_char += 26 cipher += chr(newChar) return cipher
while True: n = int(input()) if n == -1: break s = 0 last = 0 for i in range(n): a,b=map(int,input().split()) s += a*(b-last) last = b print(s,"miles")
while True: n = int(input()) if n == -1: break s = 0 last = 0 for i in range(n): (a, b) = map(int, input().split()) s += a * (b - last) last = b print(s, 'miles')
no_of_adults = float(input()) no_of_childrens = float(input()) total_passenger_cost = 0 service_tax = 7/100 discount = 10/100 rate_per_adult = no_of_adults * 37550.0 + service_tax rate_per_children = no_of_childrens * (37550.0/3.0) + service_tax total_passenger_cost = (rate_per_adult + rate_per_children) - discount print(round(total_passenger_cost, 2))
no_of_adults = float(input()) no_of_childrens = float(input()) total_passenger_cost = 0 service_tax = 7 / 100 discount = 10 / 100 rate_per_adult = no_of_adults * 37550.0 + service_tax rate_per_children = no_of_childrens * (37550.0 / 3.0) + service_tax total_passenger_cost = rate_per_adult + rate_per_children - discount print(round(total_passenger_cost, 2))
class Status(object): SHUTTING_DOWN = 'Shutting Down' RUNNING = 'Running' class __State(object): def __init__(self): self._shutting_down = False def set_to_shutting_down(self): self._shutting_down = True def is_shutting_down(self): return self._shutting_down @property def status(self): return Status.SHUTTING_DOWN if self.is_shutting_down() else Status.RUNNING runtime_state = __State()
class Status(object): shutting_down = 'Shutting Down' running = 'Running' class __State(object): def __init__(self): self._shutting_down = False def set_to_shutting_down(self): self._shutting_down = True def is_shutting_down(self): return self._shutting_down @property def status(self): return Status.SHUTTING_DOWN if self.is_shutting_down() else Status.RUNNING runtime_state = ___state()
class DynGraph(): def node_presence(self, nbunch=None): raise NotImplementedError("Not implemented") def add_interaction(self,u_of_edge,v_of_edge,time): raise NotImplementedError("Not implemented") def add_interactions_from(self, nodePairs, times): raise NotImplementedError("Not implemented") def add_node_presence(self,node,time): raise NotImplementedError("Not implemented") def add_nodes_presence_from(self, nodes, times): raise NotImplementedError("Not implemented") def remove_node_presence(self,node,time): raise NotImplementedError("Not implemented") def graph_at_time(self,t): raise NotImplementedError("Not implemented") def remove_interaction(self,u_of_edge,v_of_edge,time): raise NotImplementedError("Not implemented") def remove_interactions_from(self, nodePairs, periods): raise NotImplementedError("Not implemented") def cumulated_graph(self,times=None): raise NotImplementedError("Not implemented")
class Dyngraph: def node_presence(self, nbunch=None): raise not_implemented_error('Not implemented') def add_interaction(self, u_of_edge, v_of_edge, time): raise not_implemented_error('Not implemented') def add_interactions_from(self, nodePairs, times): raise not_implemented_error('Not implemented') def add_node_presence(self, node, time): raise not_implemented_error('Not implemented') def add_nodes_presence_from(self, nodes, times): raise not_implemented_error('Not implemented') def remove_node_presence(self, node, time): raise not_implemented_error('Not implemented') def graph_at_time(self, t): raise not_implemented_error('Not implemented') def remove_interaction(self, u_of_edge, v_of_edge, time): raise not_implemented_error('Not implemented') def remove_interactions_from(self, nodePairs, periods): raise not_implemented_error('Not implemented') def cumulated_graph(self, times=None): raise not_implemented_error('Not implemented')
def get_sql(company, conn, gl_code, start_date, end_date, step): # start_date = '2018-02-28' # end_date = '2018-03-01' # step = 1 sql = ( "WITH RECURSIVE dates AS " f"(SELECT CAST('{start_date}' AS {conn.constants.date_cast}) AS op_date, " f"{conn.constants.func_prefix}date_add('{start_date}', {step-1}) AS cl_date " f"UNION ALL SELECT {conn.constants.func_prefix}date_add(cl_date, 1) AS op_date, " f"{conn.constants.func_prefix}date_add(cl_date, {step}) AS cl_date " f"FROM dates WHERE {conn.constants.func_prefix}date_add(cl_date, {step}) <= '{end_date}') " "SELECT " # "a.op_row_id, a.cl_row_id" # ", a.op_date, a.cl_date" "a.op_date AS \"[DATE]\", a.cl_date AS \"[DATE]\"" # ", c.location_row_id, c.function_row_id, c.source_code_id" ", SUM(COALESCE(b.tran_tot, 0)) AS \"[REAL2]\"" ", SUM(COALESCE(c.tran_tot, 0) - COALESCE(b.tran_tot, 0)) AS \"[REAL2]\"" ", SUM(COALESCE(c.tran_tot, 0)) AS \"[REAL2]\"" # ", COALESCE(c.tran_tot, 0) AS \"[REAL2]\", COALESCE(b.tran_tot, 0) AS \"[REAL2]\"" " FROM " "(SELECT dates.op_date, dates.cl_date, (" "SELECT c.row_id FROM {0}.gl_totals c " "JOIN {0}.gl_codes f on f.row_id = c.gl_code_id " "WHERE c.tran_date < dates.op_date " "AND c.location_row_id = d.row_id " "AND c.function_row_id = e.row_id " "AND c.source_code_id = g.row_id " f"AND f.gl_code = '{gl_code}' " "ORDER BY c.tran_date DESC LIMIT 1" ") AS op_row_id, (" "SELECT c.row_id FROM {0}.gl_totals c " "JOIN {0}.gl_codes f on f.row_id = c.gl_code_id " "WHERE c.tran_date <= dates.cl_date " "AND c.location_row_id = d.row_id " "AND c.function_row_id = e.row_id " "AND c.source_code_id = g.row_id " f"AND f.gl_code = '{gl_code}' " "ORDER BY c.tran_date DESC LIMIT 1" ") AS cl_row_id " "FROM dates, {0}.adm_locations d, {0}.adm_functions e, {0}.gl_source_codes g " "WHERE d.location_type = 'location' " "AND e.function_type = 'function' " ") AS a " "LEFT JOIN {0}.gl_totals b on b.row_id = a.op_row_id " "LEFT JOIN {0}.gl_totals c on c.row_id = a.cl_row_id " "GROUP BY a.op_date, a.cl_date " # "WHERE c.location_row_id IS NOT NULL " .format(company) ) params = () fmt = '{:%d-%m} - {:%d-%m} : {:>12}{:>12}{:>12}' return sql, params, fmt # cur = await conn.exec_sql(sql) # async for row in cur: # print(fmt.format(*row)) # # print(row)
def get_sql(company, conn, gl_code, start_date, end_date, step): sql = f"""WITH RECURSIVE dates AS (SELECT CAST('{start_date}' AS {conn.constants.date_cast}) AS op_date, {conn.constants.func_prefix}date_add('{start_date}', {step - 1}) AS cl_date UNION ALL SELECT {conn.constants.func_prefix}date_add(cl_date, 1) AS op_date, {conn.constants.func_prefix}date_add(cl_date, {step}) AS cl_date FROM dates WHERE {conn.constants.func_prefix}date_add(cl_date, {step}) <= '{end_date}') SELECT a.op_date AS "[DATE]", a.cl_date AS "[DATE]", SUM(COALESCE(b.tran_tot, 0)) AS "[REAL2]", SUM(COALESCE(c.tran_tot, 0) - COALESCE(b.tran_tot, 0)) AS "[REAL2]", SUM(COALESCE(c.tran_tot, 0)) AS "[REAL2]" FROM (SELECT dates.op_date, dates.cl_date, (SELECT c.row_id FROM {{0}}.gl_totals c JOIN {{0}}.gl_codes f on f.row_id = c.gl_code_id WHERE c.tran_date < dates.op_date AND c.location_row_id = d.row_id AND c.function_row_id = e.row_id AND c.source_code_id = g.row_id AND f.gl_code = '{gl_code}' ORDER BY c.tran_date DESC LIMIT 1) AS op_row_id, (SELECT c.row_id FROM {{0}}.gl_totals c JOIN {{0}}.gl_codes f on f.row_id = c.gl_code_id WHERE c.tran_date <= dates.cl_date AND c.location_row_id = d.row_id AND c.function_row_id = e.row_id AND c.source_code_id = g.row_id AND f.gl_code = '{gl_code}' ORDER BY c.tran_date DESC LIMIT 1) AS cl_row_id FROM dates, {{0}}.adm_locations d, {{0}}.adm_functions e, {{0}}.gl_source_codes g WHERE d.location_type = 'location' AND e.function_type = 'function' ) AS a LEFT JOIN {{0}}.gl_totals b on b.row_id = a.op_row_id LEFT JOIN {{0}}.gl_totals c on c.row_id = a.cl_row_id GROUP BY a.op_date, a.cl_date """.format(company) params = () fmt = '{:%d-%m} - {:%d-%m} : {:>12}{:>12}{:>12}' return (sql, params, fmt)
class ListNode: def __init__(self, x): self.val = x self.next = None def __str__(self): curr = self vals = [] while curr: vals.append(curr.val) curr = curr.next return str(vals) @classmethod def from_list(cls, vals): head = None curr = None for i in vals: node = ListNode(i) if not head: head = node curr = node else: curr.next = node curr = node return head class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None self.next = None def __str__(self): queue = [self] s = '' while len(queue) > 0: next_queue = [] for node in queue: s += node.val.__str__() + '\t' if node.left: next_queue.append(node.left) if node.right: next_queue.append(node.right) s += '\n' queue = next_queue return s @classmethod def from_list(cls, vals): n = len(vals) if n == 0: return None head = TreeNode(vals[0]) level = [head] i = 1 while i < n: next_level = [] for node in level: v = vals[i] if v != '#': left = TreeNode(v) node.left = left next_level.append(left) i += 1 if i >= n: break v = vals[i] if v != '#': right = TreeNode(v) node.right = right next_level.append(right) i += 1 if i >= n: break level = next_level return head
class Listnode: def __init__(self, x): self.val = x self.next = None def __str__(self): curr = self vals = [] while curr: vals.append(curr.val) curr = curr.next return str(vals) @classmethod def from_list(cls, vals): head = None curr = None for i in vals: node = list_node(i) if not head: head = node curr = node else: curr.next = node curr = node return head class Treenode: def __init__(self, x): self.val = x self.left = None self.right = None self.next = None def __str__(self): queue = [self] s = '' while len(queue) > 0: next_queue = [] for node in queue: s += node.val.__str__() + '\t' if node.left: next_queue.append(node.left) if node.right: next_queue.append(node.right) s += '\n' queue = next_queue return s @classmethod def from_list(cls, vals): n = len(vals) if n == 0: return None head = tree_node(vals[0]) level = [head] i = 1 while i < n: next_level = [] for node in level: v = vals[i] if v != '#': left = tree_node(v) node.left = left next_level.append(left) i += 1 if i >= n: break v = vals[i] if v != '#': right = tree_node(v) node.right = right next_level.append(right) i += 1 if i >= n: break level = next_level return head
num1 = int(input()) num2 = int(input()) num3 = int(input()) if num1 == num2 and num2 == num3: print("yes") else: print("no") print("let's see", end="") print("?")
num1 = int(input()) num2 = int(input()) num3 = int(input()) if num1 == num2 and num2 == num3: print('yes') else: print('no') print("let's see", end='') print('?')
# Copyright (c) 2012-2018 SoftBank Robotics. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the COPYING file. def test_simple(qipy_action, record_messages): qipy_action.add_test_project("a_lib") qipy_action.add_test_project("big_project") qipy_action.add_test_project("foomodules") qipy_action("list") assert record_messages.find(r"\*\s+a") assert record_messages.find(r"\*\s+big_project")
def test_simple(qipy_action, record_messages): qipy_action.add_test_project('a_lib') qipy_action.add_test_project('big_project') qipy_action.add_test_project('foomodules') qipy_action('list') assert record_messages.find('\\*\\s+a') assert record_messages.find('\\*\\s+big_project')
# Copyright Alexander Baranin 2016 Logging = None EngineCore = None def onLoad(core): global EngineCore EngineCore = core global Logging Logging = EngineCore.loaded_modules['engine.Logging'] Logging.logMessage('TestFIFOModule1.onLoad()') EngineCore.schedule_FIFO(run1, 10) EngineCore.schedule_FIFO(run2, 30) def onUnload(): Logging.logMessage('TestFIFOModule1.onUnload()') EngineCore.unschedule_FIFO(10) EngineCore.unschedule_FIFO(30) def run1(): Logging.logMessage('dummy print from Module1') def run2(): Logging.logMessage('another dummy print from Module1') raise ArithmeticError()
logging = None engine_core = None def on_load(core): global EngineCore engine_core = core global Logging logging = EngineCore.loaded_modules['engine.Logging'] Logging.logMessage('TestFIFOModule1.onLoad()') EngineCore.schedule_FIFO(run1, 10) EngineCore.schedule_FIFO(run2, 30) def on_unload(): Logging.logMessage('TestFIFOModule1.onUnload()') EngineCore.unschedule_FIFO(10) EngineCore.unschedule_FIFO(30) def run1(): Logging.logMessage('dummy print from Module1') def run2(): Logging.logMessage('another dummy print from Module1') raise arithmetic_error()
''' Find the greatest product of five consecutive digits in the 1000-digit number. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 ''' number = '7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450' maxResultArrayLength = 5 resultProduct = 0 resultArrayLength = 0 resultArray = [] loopIndex = 0 digitsCount = len(number) tempDigit = 0 while loopIndex < digitsCount: tempDigit = int(number[loopIndex]) if tempDigit == 0: loopIndex = loopIndex + maxResultArrayLength resultArray = [] resultArrayLength = 0 continue else : if resultArrayLength < maxResultArrayLength: resultArray.append(tempDigit) resultArrayLength = resultArrayLength + 1 if resultArrayLength == maxResultArrayLength: tempResultProduct = 1 for x in resultArray: tempResultProduct = tempResultProduct * x if tempResultProduct > resultProduct: resultProduct = tempResultProduct resultArray.pop(0) resultArrayLength = resultArrayLength - 1 loopIndex = loopIndex + 1 print(resultProduct)
""" Find the greatest product of five consecutive digits in the 1000-digit number. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 """ number = '7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450' max_result_array_length = 5 result_product = 0 result_array_length = 0 result_array = [] loop_index = 0 digits_count = len(number) temp_digit = 0 while loopIndex < digitsCount: temp_digit = int(number[loopIndex]) if tempDigit == 0: loop_index = loopIndex + maxResultArrayLength result_array = [] result_array_length = 0 continue else: if resultArrayLength < maxResultArrayLength: resultArray.append(tempDigit) result_array_length = resultArrayLength + 1 if resultArrayLength == maxResultArrayLength: temp_result_product = 1 for x in resultArray: temp_result_product = tempResultProduct * x if tempResultProduct > resultProduct: result_product = tempResultProduct resultArray.pop(0) result_array_length = resultArrayLength - 1 loop_index = loopIndex + 1 print(resultProduct)
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # Copyright (C) 2020 Daniel Rodriguez # Use of this source code is governed by the MIT License ############################################################################### __all__ = [] def _generate(cls, bases, dct, **kwargs): # Try to find a group definition in the directory of the class and it not # possible, get the attribute which will have been inherited from the class # Add the final attribute in tuple form, to support many grps = dct.get('group', ()) or getattr(cls, 'group', ()) if isinstance(grps, str): grps = (grps,) # if only str, simulate iterable cls.group = grps # set it in the instance, let others process
__all__ = [] def _generate(cls, bases, dct, **kwargs): grps = dct.get('group', ()) or getattr(cls, 'group', ()) if isinstance(grps, str): grps = (grps,) cls.group = grps
#! /usr/bin/python3 # product.py -- This script prints out a product and it's price. # Author -- Prince Oppong Boamah<regioths@gmail.com> # Date -- 10th September, 2015 class Product: def __init__(self, name): self.name = name def __str__(self): return self.name # The program starts running here. p = Product("Lenovo") p.price = "2000gh cedis or 400 pounds or 600 dollars to be precise." print("p is a %s" % (p.__class__)) print("This is a Laptop called %s and the price is %s" % (p.name, p.price))
class Product: def __init__(self, name): self.name = name def __str__(self): return self.name p = product('Lenovo') p.price = '2000gh cedis or 400 pounds or 600 dollars to be precise.' print('p is a %s' % p.__class__) print('This is a Laptop called %s and the price is %s' % (p.name, p.price))
# constantly ask the user for new names and phone numbers # to add to the phone book, then save them phone_book = {}
phone_book = {}
key_words = ["Trending", "Fact", "Reason", "Side Effect", "Index", "Stock", "ETF"] knowledge_graph_dict = { "Value Investing": {}, "Risk Management": {}, "Joe Biden": { "Tax Increase Policy": { "Tech Company": { "Trending": "Negative", }, "Corporate Tax": { "Trending": "Negative", }, "Capital Gain Tax": { "Trending": "Negative", }, }, "Economic Stimulus Package": { "Trending": "Positive", "Reason": "buy the rumor sell the news.", "Fact": "Negative", "Side Effect": { "Consumption Discretionary Sector": { "ETF": [ "PEJ Leisure & entertainment etf", "XLY Consumer discretionary select sector SPDR fund", ], "Trending": "Positive", "Reason": "Covid recover and stimulus package delivered.", }, }, }, }, "New Type of Inflation": { "Phenomenon": "Fed release money -> core CPI not increasing fast, but asset bull", "Result": "New Type of Inflation, fool people and rich richest all the time", "Reason": "This is so call new type of inflation. " "Traditional CPI index already out of style, because the necessity in the modern world is not food but asset." "Fed blindly or intend to blindly use old world index as CPI to fool people." "Then, the asset increase fast, and the gap between rich and poor split more." "The side effect would show the result sooner or later.", }, } investment_principle = { "principle1": { "Principle": "Other investors haven't go into the underlying but will plan to.", "Trending": "Positive", "Reason": "Newly long position crowd would push the price to go high and squeeze short." }, "principle2": { "Principle": "Does all the potential investors go into the trading? Yes, then leave it", "Trending": "Negative", "Reason": "Picked like leek", }, "principle3": { "Principle": "Find the frontier and the edger of the world who being laughed at.", "Trending": "Positive", "Reason": "Margin cost lowest but margin reward highest in the uncultivated land to lead the world." "Being laughed at by the crowd means less people realize the real value and underestimated but already obtain attention." "Truth is in the hands of a few", }, "principle4": { "Principle": "The highest risk is not long the position but is sell then buy again risk.", "Reason": "long time experience", } } target_assets = [ { "Name": "Asana", "Symbol": "ASAN", "Type": "Equity", "Positive": [], "Negative": [], }, { "Name": "Nano Dimension", "Symbol": "NNDM", "Type": "Equity", "Positive": [], "Negative": [], }, { "Name": "Lockheed", "Symbol": "LMT", "Type": "Equity", "Positive": [], "Negative": [], }, { "Name": "Lockheed", "Symbol": "LMT", "Type": "Equity", "Positive": [], "Negative": [], }, { "Name": "Bitcoin", "Symbol": "BTC", "Type": "Cryptocurrencies", "Positive": [], "Negative": [], }, { "Name": "Uber", "Symbol": "Uber", "Type": "Equity", "Positive": [ "SP500 target stock", ], "Negative": [], } ] todo_list = ["https://en.wikipedia.org/wiki/Ronald_S._Baron"] class Investment2021: def __init__(self): self.knowledge_graph_dict = knowledge_graph_dict if __name__ == "__main__": print("Investment Jan. Plan")
key_words = ['Trending', 'Fact', 'Reason', 'Side Effect', 'Index', 'Stock', 'ETF'] knowledge_graph_dict = {'Value Investing': {}, 'Risk Management': {}, 'Joe Biden': {'Tax Increase Policy': {'Tech Company': {'Trending': 'Negative'}, 'Corporate Tax': {'Trending': 'Negative'}, 'Capital Gain Tax': {'Trending': 'Negative'}}, 'Economic Stimulus Package': {'Trending': 'Positive', 'Reason': 'buy the rumor sell the news.', 'Fact': 'Negative', 'Side Effect': {'Consumption Discretionary Sector': {'ETF': ['PEJ Leisure & entertainment etf', 'XLY Consumer discretionary select sector SPDR fund'], 'Trending': 'Positive', 'Reason': 'Covid recover and stimulus package delivered.'}}}}, 'New Type of Inflation': {'Phenomenon': 'Fed release money -> core CPI not increasing fast, but asset bull', 'Result': 'New Type of Inflation, fool people and rich richest all the time', 'Reason': 'This is so call new type of inflation. Traditional CPI index already out of style, because the necessity in the modern world is not food but asset.Fed blindly or intend to blindly use old world index as CPI to fool people.Then, the asset increase fast, and the gap between rich and poor split more.The side effect would show the result sooner or later.'}} investment_principle = {'principle1': {'Principle': "Other investors haven't go into the underlying but will plan to.", 'Trending': 'Positive', 'Reason': 'Newly long position crowd would push the price to go high and squeeze short.'}, 'principle2': {'Principle': 'Does all the potential investors go into the trading? Yes, then leave it', 'Trending': 'Negative', 'Reason': 'Picked like leek'}, 'principle3': {'Principle': 'Find the frontier and the edger of the world who being laughed at.', 'Trending': 'Positive', 'Reason': 'Margin cost lowest but margin reward highest in the uncultivated land to lead the world.Being laughed at by the crowd means less people realize the real value and underestimated but already obtain attention.Truth is in the hands of a few'}, 'principle4': {'Principle': 'The highest risk is not long the position but is sell then buy again risk.', 'Reason': 'long time experience'}} target_assets = [{'Name': 'Asana', 'Symbol': 'ASAN', 'Type': 'Equity', 'Positive': [], 'Negative': []}, {'Name': 'Nano Dimension', 'Symbol': 'NNDM', 'Type': 'Equity', 'Positive': [], 'Negative': []}, {'Name': 'Lockheed', 'Symbol': 'LMT', 'Type': 'Equity', 'Positive': [], 'Negative': []}, {'Name': 'Lockheed', 'Symbol': 'LMT', 'Type': 'Equity', 'Positive': [], 'Negative': []}, {'Name': 'Bitcoin', 'Symbol': 'BTC', 'Type': 'Cryptocurrencies', 'Positive': [], 'Negative': []}, {'Name': 'Uber', 'Symbol': 'Uber', 'Type': 'Equity', 'Positive': ['SP500 target stock'], 'Negative': []}] todo_list = ['https://en.wikipedia.org/wiki/Ronald_S._Baron'] class Investment2021: def __init__(self): self.knowledge_graph_dict = knowledge_graph_dict if __name__ == '__main__': print('Investment Jan. Plan')
# encoding: utf-8 ''' @author: developer @software: python @file: run8.py @time: 2021/7/28 22:35 @desc: ''' str1 = input() str2 = input() output_str1 = str2[0:2] + str1[2:] output_str2 = str1[0:2] + str2[2:] print(output_str1) print(output_str2)
""" @author: developer @software: python @file: run8.py @time: 2021/7/28 22:35 @desc: """ str1 = input() str2 = input() output_str1 = str2[0:2] + str1[2:] output_str2 = str1[0:2] + str2[2:] print(output_str1) print(output_str2)
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") def tomlplusplus_repository(): maybe( http_archive, name = "tomlplusplus", urls = [ "https://github.com/marzer/tomlplusplus/archive/v2.5.0.zip", ], sha256 = "887dfb7025d532a3485e1269ce5102d9e628ddce8dd055af1020c7b10ee14248", strip_prefix = "tomlplusplus-2.5.0/", build_file = "@third_party//tomlplusplus:package.BUILD", )
load('@bazel_tools//tools/build_defs/repo:utils.bzl', 'maybe') load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive') def tomlplusplus_repository(): maybe(http_archive, name='tomlplusplus', urls=['https://github.com/marzer/tomlplusplus/archive/v2.5.0.zip'], sha256='887dfb7025d532a3485e1269ce5102d9e628ddce8dd055af1020c7b10ee14248', strip_prefix='tomlplusplus-2.5.0/', build_file='@third_party//tomlplusplus:package.BUILD')
#! /usr/bin/env python3 # hjjs.py - write some HJ J-sequences EXTENSION = ".hjjs.txt" MODE = "w" J_MAX = 2 ** 32 - 1 def i22a(f, m): n = 0 js = [] while True: j = 2 ** (2 * n + m) - 2 ** n if j > J_MAX: break js.append(j) n += 1 print(*js, file = f) for m in range(10): with open("i22a" + str(m) + EXTENSION, MODE) as f: i22a(f, m)
extension = '.hjjs.txt' mode = 'w' j_max = 2 ** 32 - 1 def i22a(f, m): n = 0 js = [] while True: j = 2 ** (2 * n + m) - 2 ** n if j > J_MAX: break js.append(j) n += 1 print(*js, file=f) for m in range(10): with open('i22a' + str(m) + EXTENSION, MODE) as f: i22a(f, m)
# This should be subclassed within each # class that gets registered with the API class BaseContext: def __init__(self, instance=None, serial=None): pass def serialized(self): return () def instance(self, global_context): return None # This is actually very different from a context. # Meh. It just holds the things we need it to. class GlobalContext: def __init__(self, universes, network): self.universes = universes self.network = network # ** Function Decorator ** def expose(func, label=None): if not label: label = func.__name__ setattr(func, "__api_exposed__", True) setattr(func, "__api_label__", label) return func def readable(*attrs): def decorator(cls): if not hasattr(cls, "__api_readable__"): setattr(cls, "__api_readable__", []) cls.__api_readable__.extend([attr for attr in attrs if attr not in cls.__api_readable__]) return cls return decorator def writable(*attrs): def decorator(cls): if not hasattr(cls, "__api_readable__"): setattr(cls, "__api_readable__", []) if not hasattr(cls, "__api_writable__"): setattr(cls, "__api_writable__", []) cls.__api_readable__.extend(attrs) cls.__api_writable__.extend(attrs) return cls return decorator # There are two parts to this: # # One is a decorator which, applied to a function, # marks it as registerable through the Client API. # # The other is a method in the ClientAPI, which gets # passed a Class Name and searches through it for any # applicable classes, as well as a Context class. If # the class does not have a context, then the call # will fail. # # Also, each Context will have a constructor that # accepts a global context and either its object, or # a tuple which represents its serialized value. It # should also have an 'object' method which returns # the object to which the context refers. And finally # there should be a 'serialized' method which returns # a tuple that uniquely identifies the context within # the global context. class ClientAPI: def __init__(self, globalContext): self.classes = {} self.globalContext = globalContext def onGet(self, name, ctx): cls, attr = name.split(".") classInfo = self.classes[cls] if attr not in classInfo["readable"]: raise AttributeError("Attribute {} is not readable -- did you @readable it?".format(attr)) context = classInfo["context"] instance = context(serial=ctx).instance(self.globalContext) result = getattr(instance, attr, None) if hasattr(result, 'Context'): return {"result": result, "context": result.Context(instance=result)} return {"result": result} def onSet(self, name, ctx, value): cls, attr = name.split(".") classInfo = self.classes[cls] if attr not in classInfo["writable"]: raise AttributeError("Attribute {} is not writable -- did you @writable it?".format(attr)) context = classInfo["context"] instance = context(serial=ctx).instance(self.globalContext) setattr(instance, attr, value) if attr in classInfo["readable"]: result = getattr(instance, attr) else: result = None if hasattr(result, 'Context'): return {"result": result, "context": result.Context(instance=result)} return {"result": result} def onCall(self, name, ctx, *args, **kwargs): cls, func = name.split(".") classInfo = self.classes[cls] if func not in classInfo["methods"]: raise AttributeError("Method {} is not available -- did you @expose it?".format(func)) context = classInfo["context"] instance = context(serial=ctx).instance(self.globalContext) method = classInfo["methods"][func]["callable"] result = method(instance, *args, **kwargs) if hasattr(result, 'Context'): return {"result": result, "context": result.Context(instance=result)} return {"result": result} def getTable(self): return self.classes def register(self, cls): if not hasattr(cls, "Context"): raise AttributeError("Cannot register class {}; must have Context.".format(cls.__name__)) if not issubclass(cls.Context, BaseContext): raise AttributeError("Cannot register class {}; Invalid Context.".format(cls.__name__)) methods = {} for methname in dir(cls): method = getattr(cls, methname) if hasattr(method, "__api_exposed__") and hasattr(method, "__api_label__"): methods[method.__api_label__] = {"callable": method} readable = [] writable = [] if hasattr(cls, "__api_readable__"): for attrName in cls.__api_readable__: readable.append(attrName) if hasattr(cls, "__api_writable__"): for attrName in cls.__api_writable__: writable.append(attrName) if attrName not in readable: readable.append(attrName) self.classes[cls.__name__] = { "class": cls, "context": cls.Context, "methods": methods, "readable": readable, "writable": writable }
class Basecontext: def __init__(self, instance=None, serial=None): pass def serialized(self): return () def instance(self, global_context): return None class Globalcontext: def __init__(self, universes, network): self.universes = universes self.network = network def expose(func, label=None): if not label: label = func.__name__ setattr(func, '__api_exposed__', True) setattr(func, '__api_label__', label) return func def readable(*attrs): def decorator(cls): if not hasattr(cls, '__api_readable__'): setattr(cls, '__api_readable__', []) cls.__api_readable__.extend([attr for attr in attrs if attr not in cls.__api_readable__]) return cls return decorator def writable(*attrs): def decorator(cls): if not hasattr(cls, '__api_readable__'): setattr(cls, '__api_readable__', []) if not hasattr(cls, '__api_writable__'): setattr(cls, '__api_writable__', []) cls.__api_readable__.extend(attrs) cls.__api_writable__.extend(attrs) return cls return decorator class Clientapi: def __init__(self, globalContext): self.classes = {} self.globalContext = globalContext def on_get(self, name, ctx): (cls, attr) = name.split('.') class_info = self.classes[cls] if attr not in classInfo['readable']: raise attribute_error('Attribute {} is not readable -- did you @readable it?'.format(attr)) context = classInfo['context'] instance = context(serial=ctx).instance(self.globalContext) result = getattr(instance, attr, None) if hasattr(result, 'Context'): return {'result': result, 'context': result.Context(instance=result)} return {'result': result} def on_set(self, name, ctx, value): (cls, attr) = name.split('.') class_info = self.classes[cls] if attr not in classInfo['writable']: raise attribute_error('Attribute {} is not writable -- did you @writable it?'.format(attr)) context = classInfo['context'] instance = context(serial=ctx).instance(self.globalContext) setattr(instance, attr, value) if attr in classInfo['readable']: result = getattr(instance, attr) else: result = None if hasattr(result, 'Context'): return {'result': result, 'context': result.Context(instance=result)} return {'result': result} def on_call(self, name, ctx, *args, **kwargs): (cls, func) = name.split('.') class_info = self.classes[cls] if func not in classInfo['methods']: raise attribute_error('Method {} is not available -- did you @expose it?'.format(func)) context = classInfo['context'] instance = context(serial=ctx).instance(self.globalContext) method = classInfo['methods'][func]['callable'] result = method(instance, *args, **kwargs) if hasattr(result, 'Context'): return {'result': result, 'context': result.Context(instance=result)} return {'result': result} def get_table(self): return self.classes def register(self, cls): if not hasattr(cls, 'Context'): raise attribute_error('Cannot register class {}; must have Context.'.format(cls.__name__)) if not issubclass(cls.Context, BaseContext): raise attribute_error('Cannot register class {}; Invalid Context.'.format(cls.__name__)) methods = {} for methname in dir(cls): method = getattr(cls, methname) if hasattr(method, '__api_exposed__') and hasattr(method, '__api_label__'): methods[method.__api_label__] = {'callable': method} readable = [] writable = [] if hasattr(cls, '__api_readable__'): for attr_name in cls.__api_readable__: readable.append(attrName) if hasattr(cls, '__api_writable__'): for attr_name in cls.__api_writable__: writable.append(attrName) if attrName not in readable: readable.append(attrName) self.classes[cls.__name__] = {'class': cls, 'context': cls.Context, 'methods': methods, 'readable': readable, 'writable': writable}
def pageCount(n, p): print(min(p//2,n//2-p//2)) if __name__ == '__main__': n = int(input()) p = int(input()) pageCount(n, p)
def page_count(n, p): print(min(p // 2, n // 2 - p // 2)) if __name__ == '__main__': n = int(input()) p = int(input()) page_count(n, p)
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def pseudoPalindromicPaths (self, root: TreeNode) -> int: self.a = [0] * 10 self.count = 0 self.dfs(root, []) return self.count; def dfs(self, root, path): if root is None: return self.a[root.val]+=1 if root.left is None and root.right is None: md = 0 for i in range(10): if self.a[i] % 2 != 0 and self.a[i] != 0: md +=1 print(self.a) if md < 2: self.count +=1 if root.left: self.dfs(root.left, path) if root.right: self.dfs(root.right, path) self.a[root.val] -=1
class Solution: def pseudo_palindromic_paths(self, root: TreeNode) -> int: self.a = [0] * 10 self.count = 0 self.dfs(root, []) return self.count def dfs(self, root, path): if root is None: return self.a[root.val] += 1 if root.left is None and root.right is None: md = 0 for i in range(10): if self.a[i] % 2 != 0 and self.a[i] != 0: md += 1 print(self.a) if md < 2: self.count += 1 if root.left: self.dfs(root.left, path) if root.right: self.dfs(root.right, path) self.a[root.val] -= 1
class FLAGS: data_url = "" data_dir = None background_volume = 0.1 background_frequency = 0 silence_percentage = 10.0 unknown_percentage = 10.0 time_shift_ms = 0 use_custom_augs = False testing_percentage = 10 validation_percentage = 10 sample_rate = 16000 clip_duration_ms = 1000 window_size_ms = 30 window_stride_ms = 10 dct_coefficient_count = 40 model_architecture = "ds_cnn" model_size_info = [128, 128, 128] start_checkpoint = "" eval_step_interval = 400 how_many_training_steps = [5000, 5000] learning_rate = [0.001, 0.0001] batch_size = 100 wanted_words = "" excluded_words = "" summaries_dir = None train_dir = None save_step_interval = 100 check_nans = False
class Flags: data_url = '' data_dir = None background_volume = 0.1 background_frequency = 0 silence_percentage = 10.0 unknown_percentage = 10.0 time_shift_ms = 0 use_custom_augs = False testing_percentage = 10 validation_percentage = 10 sample_rate = 16000 clip_duration_ms = 1000 window_size_ms = 30 window_stride_ms = 10 dct_coefficient_count = 40 model_architecture = 'ds_cnn' model_size_info = [128, 128, 128] start_checkpoint = '' eval_step_interval = 400 how_many_training_steps = [5000, 5000] learning_rate = [0.001, 0.0001] batch_size = 100 wanted_words = '' excluded_words = '' summaries_dir = None train_dir = None save_step_interval = 100 check_nans = False
class Solution: def shuffle(self, nums: List[int], n: int) -> List[int]: returnList = [0] * len(nums) temp = 0 for i in range(0,n): returnList[temp] = nums[i] returnList[temp+1] = nums[n] n+=1 temp+=2 return returnList
class Solution: def shuffle(self, nums: List[int], n: int) -> List[int]: return_list = [0] * len(nums) temp = 0 for i in range(0, n): returnList[temp] = nums[i] returnList[temp + 1] = nums[n] n += 1 temp += 2 return returnList
def get_player_score(): score = [] for i in range(0, 5): while True: try: s = float(input('Enter golf scores between 78 and 100: ')) if 78 <= s <= 100: score.append(s) break raise ValueError except ValueError: print("Invalid Input!") return score print(get_player_score())
def get_player_score(): score = [] for i in range(0, 5): while True: try: s = float(input('Enter golf scores between 78 and 100: ')) if 78 <= s <= 100: score.append(s) break raise ValueError except ValueError: print('Invalid Input!') return score print(get_player_score())
# Unneeded charting code that was removed from a jupyter notebook. Stored here as an example for later # Draws a chart with the total area of multiple protin receptors at each time step tmpdf = totals65.loc[(totals65['Receptor'].isin(['M1', 'M5', 'M7', 'M22', 'M26'])) & (totals65['Experiment Step'] == '-nl-post')] pal = ['black', 'blue', 'red', 'orange', 'green'] g = sns.FacetGrid(tmpdf, col='Time Point', col_wrap=3, size=5, ylim=(0,100), xlim=(0,100), palette=pal, hue='Receptor', hue_order=['M1', 'M5', 'M7', 'M22', 'M26'], hue_kws=dict(marker=['^', 'v', '*', '+', 'x'])) g.map(plt.scatter, 'Total Number Scaled', 'Total Area Scaled') g.add_legend() g.savefig('mutants_by_time_nl-post.png')
tmpdf = totals65.loc[totals65['Receptor'].isin(['M1', 'M5', 'M7', 'M22', 'M26']) & (totals65['Experiment Step'] == '-nl-post')] pal = ['black', 'blue', 'red', 'orange', 'green'] g = sns.FacetGrid(tmpdf, col='Time Point', col_wrap=3, size=5, ylim=(0, 100), xlim=(0, 100), palette=pal, hue='Receptor', hue_order=['M1', 'M5', 'M7', 'M22', 'M26'], hue_kws=dict(marker=['^', 'v', '*', '+', 'x'])) g.map(plt.scatter, 'Total Number Scaled', 'Total Area Scaled') g.add_legend() g.savefig('mutants_by_time_nl-post.png')
with open("pattern.txt") as file: inputs = file.readlines() BUFFER = 10 ITERATIONS = 50_000_000_000 state = '.' * BUFFER + "..##.#######...##.###...#..#.#.#..#.##.#.##....####..........#..#.######..####.#.#..###.##..##..#..#" + '.' * 102 gives_empty = {line[:5] for line in inputs if line[-2] == '.'} pattern_iterations = 99 for i in range(pattern_iterations): next_gen = "" for i in range(2, len(state) - 2): if state[i-2:i+3] in gives_empty: next_gen += '.' else: next_gen += '#' next_gen = ".." + next_gen + ".." #print(next_gen[next_gen.index('#'):-next_gen[::-1].index('#')]) state = next_gen pots = state.count('#') final_sum = 0 for i, pot in enumerate(state): if pot == '#': final_sum += i - BUFFER final_sum += pots * (ITERATIONS - pattern_iterations) print(final_sum)
with open('pattern.txt') as file: inputs = file.readlines() buffer = 10 iterations = 50000000000 state = '.' * BUFFER + '..##.#######...##.###...#..#.#.#..#.##.#.##....####..........#..#.######..####.#.#..###.##..##..#..#' + '.' * 102 gives_empty = {line[:5] for line in inputs if line[-2] == '.'} pattern_iterations = 99 for i in range(pattern_iterations): next_gen = '' for i in range(2, len(state) - 2): if state[i - 2:i + 3] in gives_empty: next_gen += '.' else: next_gen += '#' next_gen = '..' + next_gen + '..' state = next_gen pots = state.count('#') final_sum = 0 for (i, pot) in enumerate(state): if pot == '#': final_sum += i - BUFFER final_sum += pots * (ITERATIONS - pattern_iterations) print(final_sum)
all_sales = dict() try: with open(".\\.\\sales.csv") as file: for line in file: string_args = line.split() string_date = string_args[0] string_price = string_args[1].split(",") price = all_sales[string_date] all_sales[string_date] = price + string_price[1] key, value = max(all_sales.iteritems(), key=lambda x: x[1]) except FileNotFoundError: print("File is not found")
all_sales = dict() try: with open('.\\.\\sales.csv') as file: for line in file: string_args = line.split() string_date = string_args[0] string_price = string_args[1].split(',') price = all_sales[string_date] all_sales[string_date] = price + string_price[1] (key, value) = max(all_sales.iteritems(), key=lambda x: x[1]) except FileNotFoundError: print('File is not found')
# Copyright (c) 2017, 2018 Jae-jun Kang # See the file LICENSE for details. class Config(object): heartbeat_interval = 5 # in seconds class Coroutine(object): default_timeout = 60 # in seconds
class Config(object): heartbeat_interval = 5 class Coroutine(object): default_timeout = 60
__all__ = ( "__title__", "__summary__", "__uri__", "__download_url__", "__version__", "__author__", "__email__", "__license__",) __title__ = "gpxconverter" __summary__ = ("gpx to csv converter. it supports waypoint elements except " "extensions. Values in extensions will be ignored.") __uri__ = "https://github.com/linusyoung/GPXConverter" __version__ = "0.8" __download_url__ = ("https://github.com/linusyoung/GPXConverter/archive/" + __version__ + ".tar.gz") __author__ = "Linus Yang" __email__ = "linusyoungrice@gmail.com" __license__ = "MIT"
__all__ = ('__title__', '__summary__', '__uri__', '__download_url__', '__version__', '__author__', '__email__', '__license__') __title__ = 'gpxconverter' __summary__ = 'gpx to csv converter. it supports waypoint elements except extensions. Values in extensions will be ignored.' __uri__ = 'https://github.com/linusyoung/GPXConverter' __version__ = '0.8' __download_url__ = 'https://github.com/linusyoung/GPXConverter/archive/' + __version__ + '.tar.gz' __author__ = 'Linus Yang' __email__ = 'linusyoungrice@gmail.com' __license__ = 'MIT'
def count(s, t, loc, lst): return sum([(loc + dist) >= s and (loc + dist) <= t for dist in lst]) def countApplesAndOranges(s, t, a, b, apples, oranges): print(count(s, t, a, apples)) print(count(s, t, b, oranges))
def count(s, t, loc, lst): return sum([loc + dist >= s and loc + dist <= t for dist in lst]) def count_apples_and_oranges(s, t, a, b, apples, oranges): print(count(s, t, a, apples)) print(count(s, t, b, oranges))
# Ticket numbers usually consist of an even number of digits. # A ticket number is considered lucky if the sum of the first # half of the digits is equal to the sum of the second half. # # Given a ticket number n, determine if it's lucky or not. # # Example # # For n = 1230, the output should be # isLucky(n) = true; # For n = 239017, the output should be # isLucky(n) = false. n = 239017 firstpart, secondpart = str(n)[:len(str(n))//2], str(n)[len(str(n))//2:] n1 = sum(map(int, firstpart)) n2 = sum(map(int, secondpart)) print(n1, n2)
n = 239017 (firstpart, secondpart) = (str(n)[:len(str(n)) // 2], str(n)[len(str(n)) // 2:]) n1 = sum(map(int, firstpart)) n2 = sum(map(int, secondpart)) print(n1, n2)
f = open('input.txt') data = [int(num) for num in f.read().split("\n")[:-1]] for i, num1 in enumerate(data): for num2 in data[i+1:]: if num1 + num2 == 2020: print(num1 * num2)
f = open('input.txt') data = [int(num) for num in f.read().split('\n')[:-1]] for (i, num1) in enumerate(data): for num2 in data[i + 1:]: if num1 + num2 == 2020: print(num1 * num2)
print("Welcome to Alexander's Tic-Tac-Toe Game", "\n") board = [" "for i in range(9)] def cls(): print('\n'*20) def printBoard(): row1 = "|{}|{}|{}|".format(board[0], board[1], board[2]) row2 = "|{}|{}|{}|".format(board[3], board[4], board[5]) row3 = "|{}|{}|{}|".format(board[6], board[7], board[8]) print() print(row1) print(row2) print(row3) print() def playerMove(icon): if icon == "X": number = 1 elif icon == "O": number = 2 choice = int(input("Player {}: Enter your move: ".format(number)).strip()) if board[choice-1] == " ": board[choice-1] = icon else: print("Sorry Player {}!, that space is Taken. ".format(number)) def victory(icon): if (board[0] == icon and board[1] == icon and board[2] == icon) or \ (board[3] == icon and board[4] == icon and board[5] == icon) or \ (board[6] == icon and board[7] == icon and board[8] == icon) or \ (board[0] == icon and board[4] == icon and board[8] == icon) or \ (board[2] == icon and board[4] == icon and board[6] == icon) or \ (board[0] == icon and board[3] == icon and board[6] == icon) or \ (board[1] == icon and board[4] == icon and board[7] == icon) or \ (board[2] == icon and board[5] == icon and board[8] == icon): return True else: return False def isDraw(): if " " not in board: return True else: return False while True: printBoard() playerMove("X") if victory("X"): cls() printBoard() print("Congratulations Player 1! You've won the game.") break if isDraw(): cls() printBoard() print("It's draw!") break printBoard() playerMove("O") if victory("O"): cls() printBoard() print("Congratulations Player 2! you've won the game.") break
print("Welcome to Alexander's Tic-Tac-Toe Game", '\n') board = [' ' for i in range(9)] def cls(): print('\n' * 20) def print_board(): row1 = '|{}|{}|{}|'.format(board[0], board[1], board[2]) row2 = '|{}|{}|{}|'.format(board[3], board[4], board[5]) row3 = '|{}|{}|{}|'.format(board[6], board[7], board[8]) print() print(row1) print(row2) print(row3) print() def player_move(icon): if icon == 'X': number = 1 elif icon == 'O': number = 2 choice = int(input('Player {}: Enter your move: '.format(number)).strip()) if board[choice - 1] == ' ': board[choice - 1] = icon else: print('Sorry Player {}!, that space is Taken. '.format(number)) def victory(icon): if board[0] == icon and board[1] == icon and (board[2] == icon) or (board[3] == icon and board[4] == icon and (board[5] == icon)) or (board[6] == icon and board[7] == icon and (board[8] == icon)) or (board[0] == icon and board[4] == icon and (board[8] == icon)) or (board[2] == icon and board[4] == icon and (board[6] == icon)) or (board[0] == icon and board[3] == icon and (board[6] == icon)) or (board[1] == icon and board[4] == icon and (board[7] == icon)) or (board[2] == icon and board[5] == icon and (board[8] == icon)): return True else: return False def is_draw(): if ' ' not in board: return True else: return False while True: print_board() player_move('X') if victory('X'): cls() print_board() print("Congratulations Player 1! You've won the game.") break if is_draw(): cls() print_board() print("It's draw!") break print_board() player_move('O') if victory('O'): cls() print_board() print("Congratulations Player 2! you've won the game.") break
# We want to make a row of bricks that is goal inches long. We have a number # of small bricks (1 inch each) and big bricks (5 inches each). Return True # if it is possible to make the goal by choosing from the given bricks. # This is a little harder than it looks and can be done without any loops. # make_bricks(3, 1, 8) --> True # make_bricks(3, 1, 9) --> False # make_bricks(3, 2, 10) --> True def make_bricks(small, big, goal): num_fives = goal // 5 num_ones = goal - (5 * num_fives) if num_fives <= big and num_ones <= small: return True elif (num_fives >= big) and ((goal - (5 * big)) <= small): return True else: return False print(make_bricks(3, 1, 8)) print(make_bricks(3, 1, 9)) print(make_bricks(3, 2, 10))
def make_bricks(small, big, goal): num_fives = goal // 5 num_ones = goal - 5 * num_fives if num_fives <= big and num_ones <= small: return True elif num_fives >= big and goal - 5 * big <= small: return True else: return False print(make_bricks(3, 1, 8)) print(make_bricks(3, 1, 9)) print(make_bricks(3, 2, 10))
burgers=[] quan=[] def PrintHead(): print(" ABC Burgers") print(" Pakistan Road,Karachi") print("=====================================") # Data Entry: rates = {"cheese": 110, "zinger": 160, "abc special": 250, "chicken": 120} # Front-End: def TakeInputs(): b = input("Burger Type:").lower() if b not in rates.keys(): print("Burger Type Not Recognized") print("Kindly try again, or add the new burger in Rates list") TakeInputs() return q = int(input("Quantity:")) burgers.append(b) quan.append(q) yn = input("Y to add another burger:") if yn == "y" or yn=="Y" : TakeInputs() else: print("Data Collection Complete!") def receipt(): total = 0 print("{0:13} {1} {2:9} {3:9}".format("Burger","Rate"," Quantity"," Price")) for index,each_burger in enumerate(burgers): print("{0:13}".format(burgers[index].title()), rates[burgers[index]], "{0:9}".format(quan[index]), "{0:9}".format(rates[burgers[index]] * quan[index])) total += (rates[burgers[index]] * quan[index]) print("-------------------------------------") print(" Total:", total) PrintHead() TakeInputs() PrintHead() receipt()
burgers = [] quan = [] def print_head(): print(' ABC Burgers') print(' Pakistan Road,Karachi') print('=====================================') rates = {'cheese': 110, 'zinger': 160, 'abc special': 250, 'chicken': 120} def take_inputs(): b = input('Burger Type:').lower() if b not in rates.keys(): print('Burger Type Not Recognized') print('Kindly try again, or add the new burger in Rates list') take_inputs() return q = int(input('Quantity:')) burgers.append(b) quan.append(q) yn = input('Y to add another burger:') if yn == 'y' or yn == 'Y': take_inputs() else: print('Data Collection Complete!') def receipt(): total = 0 print('{0:13} {1} {2:9} {3:9}'.format('Burger', 'Rate', ' Quantity', ' Price')) for (index, each_burger) in enumerate(burgers): print('{0:13}'.format(burgers[index].title()), rates[burgers[index]], '{0:9}'.format(quan[index]), '{0:9}'.format(rates[burgers[index]] * quan[index])) total += rates[burgers[index]] * quan[index] print('-------------------------------------') print(' Total:', total) print_head() take_inputs() print_head() receipt()
cql = { "and": [ {"lte": [{"property": "eo:cloud_cover"}, "10"]}, {"gte": [{"property": "datetime"}, "2021-04-08T04:39:23Z"]}, { "or": [ {"eq": [{"property": "collection"}, "landsat"]}, {"lte": [{"property": "gsd"}, "10"]}, ] }, {"lte": [{"property": "id"}, "l8_12345"]}, ] } cql_multi = { "and": [ {"lte": [{"property": "eo:cloud_cover"}, "10"]}, {"gte": [{"property": "datetime"}, "2021-04-08T04:39:23Z"]}, { "or": [ {"eq": [{"property": "collection"}, ["landsat", "sentinel"]]}, {"lte": [{"property": "gsd"}, "10"]}, ] }, ] } cql2 = { "op": "or", "args": [ {"op": ">=", "args": [{"property": "sentinel:data_coverage"}, 50]}, {"op": "=", "args": [{"property": "collection"}, "landsat"]}, { "op": "and", "args": [ {"op": "isNull", "args": {"property": "sentinel:data_coverage"}}, {"op": "isNull", "args": {"property": "landsat:coverage_percent"}}, ], }, ], } cql2_nested = { "op": "or", "args": [ {"op": ">=", "args": [{"property": "sentinel:data_coverage"}, 50]}, { "op": "and", "args": [ {"op": "isNull", "args": {"property": "sentinel:data_coverage"}}, { "op": "=", "args": [ {"property": "collection"}, ["landsat", "sentinel"], ], }, {"op": "in", "args": [{"property": "id"}, ["l8_12345", "s2_12345"]]}, ], }, ], } cql2_no_collection = { "op": "or", "args": [{"op": ">=", "args": [{"property": "sentinel:data_coverage"}, 50]}], }
cql = {'and': [{'lte': [{'property': 'eo:cloud_cover'}, '10']}, {'gte': [{'property': 'datetime'}, '2021-04-08T04:39:23Z']}, {'or': [{'eq': [{'property': 'collection'}, 'landsat']}, {'lte': [{'property': 'gsd'}, '10']}]}, {'lte': [{'property': 'id'}, 'l8_12345']}]} cql_multi = {'and': [{'lte': [{'property': 'eo:cloud_cover'}, '10']}, {'gte': [{'property': 'datetime'}, '2021-04-08T04:39:23Z']}, {'or': [{'eq': [{'property': 'collection'}, ['landsat', 'sentinel']]}, {'lte': [{'property': 'gsd'}, '10']}]}]} cql2 = {'op': 'or', 'args': [{'op': '>=', 'args': [{'property': 'sentinel:data_coverage'}, 50]}, {'op': '=', 'args': [{'property': 'collection'}, 'landsat']}, {'op': 'and', 'args': [{'op': 'isNull', 'args': {'property': 'sentinel:data_coverage'}}, {'op': 'isNull', 'args': {'property': 'landsat:coverage_percent'}}]}]} cql2_nested = {'op': 'or', 'args': [{'op': '>=', 'args': [{'property': 'sentinel:data_coverage'}, 50]}, {'op': 'and', 'args': [{'op': 'isNull', 'args': {'property': 'sentinel:data_coverage'}}, {'op': '=', 'args': [{'property': 'collection'}, ['landsat', 'sentinel']]}, {'op': 'in', 'args': [{'property': 'id'}, ['l8_12345', 's2_12345']]}]}]} cql2_no_collection = {'op': 'or', 'args': [{'op': '>=', 'args': [{'property': 'sentinel:data_coverage'}, 50]}]}
class AnnotaVO: def __init__(self): self._entry = None self._label = None self._points = None self._kind = None @property def points(self): return self._points @points.setter def points(self, value): self._points = value @property def entry(self): return self._entry @entry.setter def entry(self, value): self._entry = value @property def label(self): return self._label @label.setter def label(self, value): self._label = value @property def kind(self): return self._kind @kind.setter def kind(self, value): self._kind = value
class Annotavo: def __init__(self): self._entry = None self._label = None self._points = None self._kind = None @property def points(self): return self._points @points.setter def points(self, value): self._points = value @property def entry(self): return self._entry @entry.setter def entry(self, value): self._entry = value @property def label(self): return self._label @label.setter def label(self, value): self._label = value @property def kind(self): return self._kind @kind.setter def kind(self, value): self._kind = value
# Accounts USER_DOES_NOT_EXIST = 1000 INCORRECT_PASSWORD = 1001 USER_INACTIVE = 1002 INVALID_SIGN_UP_CODE = 1030 SOCIAL_DOES_NOT_EXIST = 1100 INCORRECT_TOKEN = 1101 TOKEN_ALREADY_IN_USE = 1102 SAME_PASSWORD = 1200 # Common FORM_ERROR = 9000
user_does_not_exist = 1000 incorrect_password = 1001 user_inactive = 1002 invalid_sign_up_code = 1030 social_does_not_exist = 1100 incorrect_token = 1101 token_already_in_use = 1102 same_password = 1200 form_error = 9000
names = ["kara", "jackie", "Theophilus"] for name in names: print(names) print("\n") for index in range(len(names)): print(names[index])
names = ['kara', 'jackie', 'Theophilus'] for name in names: print(names) print('\n') for index in range(len(names)): print(names[index])
''' Python name attribute Every module in Python has a special variable called name. The value of the nsme attribute is set '''
""" Python name attribute Every module in Python has a special variable called name. The value of the nsme attribute is set """
people = [ ('Alice', 32), # one tuple ('Bob', 51), # another tuple ('Carol', 15), ('Dylan', 5), ('Erin', 25), ('Frank', 48) ] i= 0 yuanzu = (' ', 999) while i < len(people): if people[i][1] <= yuanzu[1]: yuanzu = people[i] i += 1 print('Youngest person: {}, {} years old. '.format(yuanzu[0], yuanzu[1])) print(people(people[i][1] == 5))
people = [('Alice', 32), ('Bob', 51), ('Carol', 15), ('Dylan', 5), ('Erin', 25), ('Frank', 48)] i = 0 yuanzu = (' ', 999) while i < len(people): if people[i][1] <= yuanzu[1]: yuanzu = people[i] i += 1 print('Youngest person: {}, {} years old. '.format(yuanzu[0], yuanzu[1])) print(people(people[i][1] == 5))
#!/usr/bin/env python ''' Description: these are the default parameters to use for processing secrets data Author: Rachel Kalmar ''' # ------------------------------------ # # Set defaults for parameters to be used in secretReaderPollyVoices datapath_base = '/Users/kalmar/Documents/code/secrets/secrets_data/' # Where the secrets data is kept mp3path_base = '/Users/kalmar/Documents/code/secrets/audio/' # Where to store the audio output shuffleSecrets = False # Shuffle the order of the secrets? speak = True # Speak secrets? ssml = True # Use speech synthesis markup language? whisperFreq = 0.15 # What percentage of the secrets should be whispered? mp3_padding = 1500 # Buffer between mp3 files, for concatenated mp3 concatSecretMp3s = True # Concatenate the individual mp3 files in a group datapath = '/Users/kalmar/Documents/code/secrets/secrets_data/secrets_edit_rk.json' # ------------------------------------ # # Set language and translation params translate_lang = False language = 'en' # language = 'it' # language = 'de' target_lang = 'en' # target_lang = 'it' # target_lang = 'de' englishVoiceIds = ['Joanna', 'Kendra', 'Amy', 'Joey', 'Brian'] italianVoiceIds = ['Carla', 'Giorgio'] germanVoiceIds = ['Vicki', 'Marlene', 'Hans'] if language=='en': # voiceIds = ['Joanna', 'Salli', 'Kimberly', 'Kendra', 'Amy', 'Ivy', 'Justin', 'Joey', 'Brian'] voiceIds = englishVoiceIds elif language=='it': voiceIds = italianVoiceIds elif language=='de': voiceIds = germanVoiceIds voice = voiceIds[0] # ------------------------------------ # # Set params based on options chosen above if language == 'en': datapath = datapath_base + 'secrets_edit_edit.json' elif language == 'it': datapath = datapath_base + 'secrets_edit_italian_temp.json' elif language == 'de': datapath = datapath_base + 'secrets_edit_german.json' if ssml: textType = 'ssml' else: textType = 'text'
""" Description: these are the default parameters to use for processing secrets data Author: Rachel Kalmar """ datapath_base = '/Users/kalmar/Documents/code/secrets/secrets_data/' mp3path_base = '/Users/kalmar/Documents/code/secrets/audio/' shuffle_secrets = False speak = True ssml = True whisper_freq = 0.15 mp3_padding = 1500 concat_secret_mp3s = True datapath = '/Users/kalmar/Documents/code/secrets/secrets_data/secrets_edit_rk.json' translate_lang = False language = 'en' target_lang = 'en' english_voice_ids = ['Joanna', 'Kendra', 'Amy', 'Joey', 'Brian'] italian_voice_ids = ['Carla', 'Giorgio'] german_voice_ids = ['Vicki', 'Marlene', 'Hans'] if language == 'en': voice_ids = englishVoiceIds elif language == 'it': voice_ids = italianVoiceIds elif language == 'de': voice_ids = germanVoiceIds voice = voiceIds[0] if language == 'en': datapath = datapath_base + 'secrets_edit_edit.json' elif language == 'it': datapath = datapath_base + 'secrets_edit_italian_temp.json' elif language == 'de': datapath = datapath_base + 'secrets_edit_german.json' if ssml: text_type = 'ssml' else: text_type = 'text'
a = "0,0,0,0,0,0" b = "0,-1,-2,0" c = "-1,-3,-4,-1,-2" d = "qwerty" e = ",,3,,4" f = "1,2,v,b,3" g = "0,7,0,2,-12,3,0,2" h = "1,3,-2,1,2" def sum_earnings(str_earn): next_value = 0 total = 0 neg_sum = 0 if any(char.isalpha() for char in str_earn): return 0 for s in str_earn.split(','): if not s: return 0 lst = [int(s) for s in str_earn.split(',')] print(lst) if all(x <= 0 for x in lst): return 0 for idx, val in enumerate(lst): total +=val if idx < len(lst)-1: next_value = lst[idx + 1] neg_sum = total + next_value if neg_sum <= 0: total = 0 neg_sum = 0 return total print(sum_earnings(h))
a = '0,0,0,0,0,0' b = '0,-1,-2,0' c = '-1,-3,-4,-1,-2' d = 'qwerty' e = ',,3,,4' f = '1,2,v,b,3' g = '0,7,0,2,-12,3,0,2' h = '1,3,-2,1,2' def sum_earnings(str_earn): next_value = 0 total = 0 neg_sum = 0 if any((char.isalpha() for char in str_earn)): return 0 for s in str_earn.split(','): if not s: return 0 lst = [int(s) for s in str_earn.split(',')] print(lst) if all((x <= 0 for x in lst)): return 0 for (idx, val) in enumerate(lst): total += val if idx < len(lst) - 1: next_value = lst[idx + 1] neg_sum = total + next_value if neg_sum <= 0: total = 0 neg_sum = 0 return total print(sum_earnings(h))
def main(): n, k = map(int, input().split()) l = [] for i in range(n): a, b = map(int, input().split()) l.append((a, b)) l.sort() prev = 0 for i in range(n): prev += l[i][1] if k <= prev: print(l[i][0]) break if __name__ == '__main__': main()
def main(): (n, k) = map(int, input().split()) l = [] for i in range(n): (a, b) = map(int, input().split()) l.append((a, b)) l.sort() prev = 0 for i in range(n): prev += l[i][1] if k <= prev: print(l[i][0]) break if __name__ == '__main__': main()
class Solution: def minimumLength(self, s: str) -> int: if len(s)==1: return 1 i=0 j=len(s)-1 while i<j: if s[i]!=s[j]: break temp = s[i] while i<=j and s[i]==temp: i+=1 while j>=i and s[j]==temp: j-=1 return j-i+1
class Solution: def minimum_length(self, s: str) -> int: if len(s) == 1: return 1 i = 0 j = len(s) - 1 while i < j: if s[i] != s[j]: break temp = s[i] while i <= j and s[i] == temp: i += 1 while j >= i and s[j] == temp: j -= 1 return j - i + 1
# set declaration myfruits = {"Apple", "Banana", "Grapes", "Litchi", "Mango"} mynums = {1, 2, 3, 4, 5} # Set printing before removing print("Before remove() method...") print("fruits: ", myfruits) print("numbers: ", mynums) # Removing the elements from the sets elerem = myfruits.remove('Apple') elerem = myfruits.remove('Litchi') elerem = myfruits.remove('Mango') elerem = mynums.remove(1) elerem = mynums.remove(3) elerem = mynums.remove(4) print("After remove() method...") print("fruits: ", myfruits) print("numbers: ", mynums)
myfruits = {'Apple', 'Banana', 'Grapes', 'Litchi', 'Mango'} mynums = {1, 2, 3, 4, 5} print('Before remove() method...') print('fruits: ', myfruits) print('numbers: ', mynums) elerem = myfruits.remove('Apple') elerem = myfruits.remove('Litchi') elerem = myfruits.remove('Mango') elerem = mynums.remove(1) elerem = mynums.remove(3) elerem = mynums.remove(4) print('After remove() method...') print('fruits: ', myfruits) print('numbers: ', mynums)
# CPU: 0.05 s amounts = list(map(int, input().split())) ratios = list(map(int, input().split())) n = min(amounts[x] / ratios[x] for x in range(3)) for amount, ratio in zip(amounts, ratios): print(amount - ratio * n, end=" ")
amounts = list(map(int, input().split())) ratios = list(map(int, input().split())) n = min((amounts[x] / ratios[x] for x in range(3))) for (amount, ratio) in zip(amounts, ratios): print(amount - ratio * n, end=' ')
COUNTRIES = [ "US", "IL", "IN", "UA", "CA", "AR", "SG", "TW", "GB", "AT", "BE", "BG", "HR", "CY", "CZ", "DK", "EE", "FI", "FR", "DE", "GR", "HU", "IE", "IT", "LK", "LV", "LT", "LU", "MT", "NL", "PL", "PT", "RO", "SK", "SI", "ES", "SE", "NZ", "AU", "BF", "BO", "BR", "BZ", "CI", "CL", "CO", "DO", "EC", "GE", "GH", "GY", "ID", "IS", "JP", "KG", "MD", "ME", "MK", "ML", "MM", "MN", "MX", "MY", "PH", "PW", "RS", "SC", "SR", "TR", "TZ", "VC", ]
countries = ['US', 'IL', 'IN', 'UA', 'CA', 'AR', 'SG', 'TW', 'GB', 'AT', 'BE', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'HU', 'IE', 'IT', 'LK', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE', 'NZ', 'AU', 'BF', 'BO', 'BR', 'BZ', 'CI', 'CL', 'CO', 'DO', 'EC', 'GE', 'GH', 'GY', 'ID', 'IS', 'JP', 'KG', 'MD', 'ME', 'MK', 'ML', 'MM', 'MN', 'MX', 'MY', 'PH', 'PW', 'RS', 'SC', 'SR', 'TR', 'TZ', 'VC']
x = 1 y = 10 # Checks if one value is equal to another if x == 1: print("x is equal to 1") # Checks if one value is NOT equal to another if y != 1: print("y is not equal to 1") # Checks if one value is less than another if x < y: print("x is less than y") # Checks if one value is greater than another if y > x: print("y is greater than x") # Checks if a value is less than or equal to another if x >= 1: print("x is greater than or equal to 1") # Checks for two conditions to be met using "and" if x == 1 and y == 10: print("Both values returned true") # Checks if either of two conditions is met if x < 45 or y < 5: print("One or the other statements were true") # Nested if statements if x < 10: if y < 5: print("x is less than 10 and y is less than 5") elif y == 5: print("x is less than 10 and y is equal to 5") else: print("x is less than 10 and y is greater than 5")
x = 1 y = 10 if x == 1: print('x is equal to 1') if y != 1: print('y is not equal to 1') if x < y: print('x is less than y') if y > x: print('y is greater than x') if x >= 1: print('x is greater than or equal to 1') if x == 1 and y == 10: print('Both values returned true') if x < 45 or y < 5: print('One or the other statements were true') if x < 10: if y < 5: print('x is less than 10 and y is less than 5') elif y == 5: print('x is less than 10 and y is equal to 5') else: print('x is less than 10 and y is greater than 5')
# general configuration LOCAL_OTP_PORT = 8088 # port for OTP to use, HTTPS will be served on +1 TEMP_DIRECTORY = "mara-ptm-temp" PROGRESS_WATCHER_INTERVAL = 5 * 60 * 1000 # milliseconds JVM_PARAMETERS = "-Xmx8G" # 6-8GB of RAM is good for bigger graphs # itinerary filter parameters CAR_KMH = 50 CAR_TRAVEL_FACTOR = 1.4 # as the crow flies vs street, how much longer is realistic # note: the factor that public transport may take longer is configured in the GUI # itinerary parameters ALLOWED_TRANSIT_MODES = ["WALK", "BUS", "TRAM", "SUBWAY", "RAIL"] MAX_WALK_DISTANCE = 1000 # meters OTP_PARAMETERS_TEMPLATE = "&".join([ "fromPlace=1:{origin}", "toPlace=1:{destination}", "time=00%3A00", "date={date}", "mode=TRANSIT%2CWALK", "maxWalkDistance={max_walk_distance}", "arriveBy=false", "searchWindow=86400", "numOfItineraries=99999", "keepNumOfItineraries=99999", "showIntermediateStops=true", ])
local_otp_port = 8088 temp_directory = 'mara-ptm-temp' progress_watcher_interval = 5 * 60 * 1000 jvm_parameters = '-Xmx8G' car_kmh = 50 car_travel_factor = 1.4 allowed_transit_modes = ['WALK', 'BUS', 'TRAM', 'SUBWAY', 'RAIL'] max_walk_distance = 1000 otp_parameters_template = '&'.join(['fromPlace=1:{origin}', 'toPlace=1:{destination}', 'time=00%3A00', 'date={date}', 'mode=TRANSIT%2CWALK', 'maxWalkDistance={max_walk_distance}', 'arriveBy=false', 'searchWindow=86400', 'numOfItineraries=99999', 'keepNumOfItineraries=99999', 'showIntermediateStops=true'])
class Solution: # @param s, a string # @param dict, a set of string # @return a boolean def wordBreak(self, s, dict): if not dict: return False n = len(s) res = [False] * n for i in xrange(0, n): if s[:i+1] in dict: res[i] = True if not True in res: return False i = 0 while i < n: if res[i]: i += 1 continue for k in xrange(0, i+1): if res[i-k] and s[i-k+1:i+1] in dict: res[i] = True break i += 1 return res[-1]
class Solution: def word_break(self, s, dict): if not dict: return False n = len(s) res = [False] * n for i in xrange(0, n): if s[:i + 1] in dict: res[i] = True if not True in res: return False i = 0 while i < n: if res[i]: i += 1 continue for k in xrange(0, i + 1): if res[i - k] and s[i - k + 1:i + 1] in dict: res[i] = True break i += 1 return res[-1]
diccionario= {91: 95} a=91 if a==91: a=diccionario.get(91) print(a)
diccionario = {91: 95} a = 91 if a == 91: a = diccionario.get(91) print(a)
arquivo = open('linguagens.txt', 'r') num = int(input("Numero de linguagens: ")) count=0 for linha in arquivo: if count<num: print(linha.rstrip('\n')) count += 1 else: break arquivo.close()
arquivo = open('linguagens.txt', 'r') num = int(input('Numero de linguagens: ')) count = 0 for linha in arquivo: if count < num: print(linha.rstrip('\n')) count += 1 else: break arquivo.close()
#!/usr/bin/env python3 # coding:utf-8 class Solution: def StrToInt(self, s): if s == '': return 0 string = s.strip() num = 0 start = 0 symbol = 1 if string[0] == '+': start += 1 elif string[0] == '-': start += 1 symbol = -1 for i in range(start, len(string)): if '0' <= string[i] <= '9': num = num * 10 + ord(string[i]) - 48 else: return 0 return num * symbol if __name__ == "__main__": string = " -1234 " s = Solution() ans = s.StrToInt(string) print(ans)
class Solution: def str_to_int(self, s): if s == '': return 0 string = s.strip() num = 0 start = 0 symbol = 1 if string[0] == '+': start += 1 elif string[0] == '-': start += 1 symbol = -1 for i in range(start, len(string)): if '0' <= string[i] <= '9': num = num * 10 + ord(string[i]) - 48 else: return 0 return num * symbol if __name__ == '__main__': string = ' -1234 ' s = solution() ans = s.StrToInt(string) print(ans)
fit2_lm = sm.ols(formula="y ~ age + np.power(age, 2) + np.power(age, 3)",data=diab).fit() poly_predictions = fit2_lm.get_prediction(predict_df).summary_frame() poly_predictions.head()
fit2_lm = sm.ols(formula='y ~ age + np.power(age, 2) + np.power(age, 3)', data=diab).fit() poly_predictions = fit2_lm.get_prediction(predict_df).summary_frame() poly_predictions.head()
scores = [("Rodney Dangerfield", -1), ("Marlon Brando", 1), ("You", 100)] # list of tuples for person in scores: name = person[0] score = person[1] print("Hello {}. Your score is {}.".format(name, score)) origPrice = float(input('Enter the original price: $')) discount = float(input('Enter discount percentage: ')) newPrice = (1 - discount/100)*origPrice calculation = '${:.2f} discounted by {}% is ${:.2f}.'.format(origPrice, discount, newPrice) print(calculation)
scores = [('Rodney Dangerfield', -1), ('Marlon Brando', 1), ('You', 100)] for person in scores: name = person[0] score = person[1] print('Hello {}. Your score is {}.'.format(name, score)) orig_price = float(input('Enter the original price: $')) discount = float(input('Enter discount percentage: ')) new_price = (1 - discount / 100) * origPrice calculation = '${:.2f} discounted by {}% is ${:.2f}.'.format(origPrice, discount, newPrice) print(calculation)
def find_loop(root): S = root F = root # set up first meeting while True: # if there is no loop, we will detect it if S is None or F is None: return None # advance slow and fast pointers S = S.next_node F = F.next_node.next_node if S is F: break # reset S to beginning S = root # set up second meeting while True: # advance pointers at same speed S = S.next_node F = F.next_node if S is F: break return S
def find_loop(root): s = root f = root while True: if S is None or F is None: return None s = S.next_node f = F.next_node.next_node if S is F: break s = root while True: s = S.next_node f = F.next_node if S is F: break return S
''' Assume that two variables, varA and varB, are assigned values, either numbers or strings. Write a piece of Python code that evaluates varA and varB, and then prints out one of the following messages: "string involved" if either varA or varB are strings "bigger" if varA is larger than varB "equal" if varA is equal to varB "smaller" if varA is smaller than varB ''' if type(varA) == str or type(varB) == str: print ("string involved") elif varA > varB: print("bigger") elif varA == varB: print("equal") elif varA < varB: print("smaller")
""" Assume that two variables, varA and varB, are assigned values, either numbers or strings. Write a piece of Python code that evaluates varA and varB, and then prints out one of the following messages: "string involved" if either varA or varB are strings "bigger" if varA is larger than varB "equal" if varA is equal to varB "smaller" if varA is smaller than varB """ if type(varA) == str or type(varB) == str: print('string involved') elif varA > varB: print('bigger') elif varA == varB: print('equal') elif varA < varB: print('smaller')
def __create_snap_entry(marker, entry_no, l): # use parse_roll() to create search entry node = [] x = [] for i in range(len(l)-1): if len(l) == 2 and abs(l[i] - l[i+1]) == 2: # if only two balls on the row x += [[l[i], 1]] elif abs(l[i] - l[i+1]) > 1: # only those distance>1 can move x += [[l[i], 1]] x += [[l[i+1], -1]] # record two directions for item in x: node.append([marker, entry_no, item[0], item[1]]) return node def __find_corner(t1, t2, incline=1): if incline == 1: start = 0 end = len(t1) else: start = len(t1)-1 end = -1 for i1 in range(start, end, incline): if len(t1[i1]) > 0: if incline == 1: i2 = t1[i1][0] else: i2 = t1[i1][-1] # print(t1[i1]) # print(t2[i2]) # print(incline) if len(t1[i1]) == 1 and len(t2[i2]) == 1: # single ball at the corner if incline == 1: if i2 == 0: # print('db1') return False, None, None flag = True # True only ball [1, i2) for k in range(0, i2): if len(t2[k]) > 0: flag = False break else: if i2 == len(t2) - 1: # print('db2') return False, None, None flag = True for k in range(i2+1, len(t2)): if len(t2[k]) > 0: flag = False break if flag: # print('db3') return False, None, None if incline == 1: return True, i1, t1[i1][0] return True, i1, t1[i1][-1] def snap(row, col): # row and col and dicts # create [True/False (row/col), row_no., b1 (first ball to move), b2 (ball to be hit)] # to reduce possible solutions, all solutions with unmovable corner balls should be eliminated node = [] n1 = [] n2 = [] n_row = len(row.keys()) n_col = len(col.keys()) for i in row.keys(): n1 += __create_snap_entry(True, i, row[i]) for j in col.keys(): n2 += __create_snap_entry(False, j, col[j]) node = n1 + n2 # corner balls are those closest to the corners # [0, 0], [0, n_col-1] # [n_row-1, 0], [n_row-1, n_col-1] corner = [] c1, b1x, b1y = __find_corner(row, col, 1) c2, b2x, b2y = __find_corner(row, col, -1) c3, b3y, b3x = __find_corner(col, row, 1) c4, b4y, b4x = __find_corner(col, row, -1) if c1 and c2 and c3 and c4: l = [[b1x, b1y], [b2x, b2y], [b3y, b3x], [b4y, b4x]] else: return [] corner.append(l[0]) for i in l[1:]: if i not in corner: corner.append(i) # print(corner) for i in corner: # find corner balls and put them in front for j in range(len(node)): if node[j][0]: # row content if node[j][1] == i[0]: # same row as the corner b = node.pop(j) # take it out node.insert(0, b) # put it in the front else: if node[j][1] == i[1]: # same col as the corner b = node.pop(j) node.insert(0, b) # print(node) return node def __transpose(table, length): assert isinstance(table, dict) result = dict() for i in range(length): result[i] = [] for k in table.keys(): if len(table[k]) != 0: for j in table[k]: result[j].append(k) return result if __name__ == '__main__': row = dict() for i in range(9): row[i] = [] row[0] = [2] row[1] = [5, 6] row[2] = [1] row[3] = [4, 5] row[4] = [5] row[5] = [3] row[6] = [4] col = __transpose(row, 7) node = snap(row, col) print(node)
def __create_snap_entry(marker, entry_no, l): node = [] x = [] for i in range(len(l) - 1): if len(l) == 2 and abs(l[i] - l[i + 1]) == 2: x += [[l[i], 1]] elif abs(l[i] - l[i + 1]) > 1: x += [[l[i], 1]] x += [[l[i + 1], -1]] for item in x: node.append([marker, entry_no, item[0], item[1]]) return node def __find_corner(t1, t2, incline=1): if incline == 1: start = 0 end = len(t1) else: start = len(t1) - 1 end = -1 for i1 in range(start, end, incline): if len(t1[i1]) > 0: if incline == 1: i2 = t1[i1][0] else: i2 = t1[i1][-1] if len(t1[i1]) == 1 and len(t2[i2]) == 1: if incline == 1: if i2 == 0: return (False, None, None) flag = True for k in range(0, i2): if len(t2[k]) > 0: flag = False break else: if i2 == len(t2) - 1: return (False, None, None) flag = True for k in range(i2 + 1, len(t2)): if len(t2[k]) > 0: flag = False break if flag: return (False, None, None) if incline == 1: return (True, i1, t1[i1][0]) return (True, i1, t1[i1][-1]) def snap(row, col): node = [] n1 = [] n2 = [] n_row = len(row.keys()) n_col = len(col.keys()) for i in row.keys(): n1 += __create_snap_entry(True, i, row[i]) for j in col.keys(): n2 += __create_snap_entry(False, j, col[j]) node = n1 + n2 corner = [] (c1, b1x, b1y) = __find_corner(row, col, 1) (c2, b2x, b2y) = __find_corner(row, col, -1) (c3, b3y, b3x) = __find_corner(col, row, 1) (c4, b4y, b4x) = __find_corner(col, row, -1) if c1 and c2 and c3 and c4: l = [[b1x, b1y], [b2x, b2y], [b3y, b3x], [b4y, b4x]] else: return [] corner.append(l[0]) for i in l[1:]: if i not in corner: corner.append(i) for i in corner: for j in range(len(node)): if node[j][0]: if node[j][1] == i[0]: b = node.pop(j) node.insert(0, b) elif node[j][1] == i[1]: b = node.pop(j) node.insert(0, b) return node def __transpose(table, length): assert isinstance(table, dict) result = dict() for i in range(length): result[i] = [] for k in table.keys(): if len(table[k]) != 0: for j in table[k]: result[j].append(k) return result if __name__ == '__main__': row = dict() for i in range(9): row[i] = [] row[0] = [2] row[1] = [5, 6] row[2] = [1] row[3] = [4, 5] row[4] = [5] row[5] = [3] row[6] = [4] col = __transpose(row, 7) node = snap(row, col) print(node)
ls = list() for _ in range(5): ls.append(input()) res = list() for i in range(len(ls)): if 'FBI' in ls[i]: res.append(str(i + 1)) if len(res) == 0: print('HE GOT AWAY!') else: print(' '.join(res))
ls = list() for _ in range(5): ls.append(input()) res = list() for i in range(len(ls)): if 'FBI' in ls[i]: res.append(str(i + 1)) if len(res) == 0: print('HE GOT AWAY!') else: print(' '.join(res))
matriz = [[], [], []] for c in range(0, 3): linha0 = matriz[0].append(int(input(f'Digite um valor para [0, {c}]: '))) for c in range(0, 3): linha1 = matriz[1].append(int(input(f'Digite um valor para [1, {c}]: '))) for c in range(0, 3): linha2 = matriz[2]. append(int(input(f'Digite um valor para [2, {c}]: '))) for c in range(0, len(matriz[0])): print(f'[ {matriz[0][c]} ]', end='') print() for c in range(0, len(matriz[1])): print(f'[ {matriz[1][c]} ]', end='') print() for c in range(0, len(matriz[2])): print(f'[ {matriz[2][c]} ]', end='')
matriz = [[], [], []] for c in range(0, 3): linha0 = matriz[0].append(int(input(f'Digite um valor para [0, {c}]: '))) for c in range(0, 3): linha1 = matriz[1].append(int(input(f'Digite um valor para [1, {c}]: '))) for c in range(0, 3): linha2 = matriz[2].append(int(input(f'Digite um valor para [2, {c}]: '))) for c in range(0, len(matriz[0])): print(f'[ {matriz[0][c]} ]', end='') print() for c in range(0, len(matriz[1])): print(f'[ {matriz[1][c]} ]', end='') print() for c in range(0, len(matriz[2])): print(f'[ {matriz[2][c]} ]', end='')
class NCSBase: def train(self, X, y): pass def scores(self, X, y, cp): pass def score(self, x, labels): pass class NCSBaseRegressor: def train(self, X, y): pass def coeffs(self, X, y, cp): pass def coeffs_n(self, x): pass
class Ncsbase: def train(self, X, y): pass def scores(self, X, y, cp): pass def score(self, x, labels): pass class Ncsbaseregressor: def train(self, X, y): pass def coeffs(self, X, y, cp): pass def coeffs_n(self, x): pass