content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
""" Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). Find the minimum element. You may assume no duplicate exists in the array. Example 1: Input: [3,4,5,1,2] Output: 1 Example 2: Input: [4,5,6,7,0,1,2] Output: 0 """ class Solution(object): def findMin(self, nums): """ Strategy is to use binary search. For a given element, if the previous value is greater than it, the current element must be the minimum. If the current element is not the minimum value to find the next range to search check 1. If current element is greater than or equal to left value and greater than right value then minimum value must be on right side. The GTE for left value is to handle case for two values where first value is > second value but minimum index calculation rounds down (to 0). 2. Else minimum value is on left side :type nums: List[int] :rtype: int """ if nums is None: return 0 if len(nums) == 1: return nums[0] start_index = 0 end_index = len(nums) - 1 while start_index < end_index: middle_index = (start_index + end_index) // 2 start_value = nums[start_index] end_value = nums[end_index] middle_value = nums[middle_index] if middle_index >= 1: previous_index = middle_index - 1 previous_value = nums[previous_index] if previous_value > middle_value: return middle_value if middle_value >= start_value and middle_value > end_value: start_index = middle_index + 1 else: end_index = middle_index - 1 return nums[start_index]
""" Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). Find the minimum element. You may assume no duplicate exists in the array. Example 1: Input: [3,4,5,1,2] Output: 1 Example 2: Input: [4,5,6,7,0,1,2] Output: 0 """ class Solution(object): def find_min(self, nums): """ Strategy is to use binary search. For a given element, if the previous value is greater than it, the current element must be the minimum. If the current element is not the minimum value to find the next range to search check 1. If current element is greater than or equal to left value and greater than right value then minimum value must be on right side. The GTE for left value is to handle case for two values where first value is > second value but minimum index calculation rounds down (to 0). 2. Else minimum value is on left side :type nums: List[int] :rtype: int """ if nums is None: return 0 if len(nums) == 1: return nums[0] start_index = 0 end_index = len(nums) - 1 while start_index < end_index: middle_index = (start_index + end_index) // 2 start_value = nums[start_index] end_value = nums[end_index] middle_value = nums[middle_index] if middle_index >= 1: previous_index = middle_index - 1 previous_value = nums[previous_index] if previous_value > middle_value: return middle_value if middle_value >= start_value and middle_value > end_value: start_index = middle_index + 1 else: end_index = middle_index - 1 return nums[start_index]
class Solution: ops = ['*', '/', '+', '-'] def clumsy(self, N: int) -> int: answer = [N] i = N - 1 j = 0 while i > 0: op = self.ops[j % 4] j += 1 if op == '*': n = answer.pop(-1) val = n * i answer.append(val) i -= 1 continue if op == '/': n = answer.pop(-1) val = int(n / i) answer.append(val) i -= 1 continue if op == '+': answer.append(i) i -= 1 continue if op == '-': answer.append(-i) i -= 1 continue answer = sum(answer) if answer < -2 ** 31: return -2 ** 31 if answer > 2 ** 31 - 1: return 2 ** 31 - 1 return answer
class Solution: ops = ['*', '/', '+', '-'] def clumsy(self, N: int) -> int: answer = [N] i = N - 1 j = 0 while i > 0: op = self.ops[j % 4] j += 1 if op == '*': n = answer.pop(-1) val = n * i answer.append(val) i -= 1 continue if op == '/': n = answer.pop(-1) val = int(n / i) answer.append(val) i -= 1 continue if op == '+': answer.append(i) i -= 1 continue if op == '-': answer.append(-i) i -= 1 continue answer = sum(answer) if answer < -2 ** 31: return -2 ** 31 if answer > 2 ** 31 - 1: return 2 ** 31 - 1 return answer
s = input() s = s[::-1] ans = 0 b = 0 for i in range(len(s)): if s[i] == "B": ans += i ans -= b b += 1 print(ans)
s = input() s = s[::-1] ans = 0 b = 0 for i in range(len(s)): if s[i] == 'B': ans += i ans -= b b += 1 print(ans)
"""This py describe the class the could be accessed by other.""" __author__ = "Gustavo Figueiredo" __copyright__ = "CASA" __version__ = "1.0.1" __maintainer__ = "Gustavo Figueiredo" __email__ = "gustavodsf1@gmail.com" __status__ = "Development"
"""This py describe the class the could be accessed by other.""" __author__ = 'Gustavo Figueiredo' __copyright__ = 'CASA' __version__ = '1.0.1' __maintainer__ = 'Gustavo Figueiredo' __email__ = 'gustavodsf1@gmail.com' __status__ = 'Development'
class PongError(Exception): pass class RoomError(PongError): def __init__(self, room, msg, **kwargs): err_msg = '{} room info : {}'.format(msg, room) super().__init__(err_msg, **kwargs) class PlayerError(PongError): def __init__(self, player, msg, **kwargs): err_msg = '{} player info : {}'.format(msg, player) super().__init__(err_msg, **kwargs) class LobbyError(PongError): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class ProtocolError(PongError): def __init__(self, payload, msg, **kwargs): err_msg = '{} message: {}'.format(msg, payload) super().__init__(err_msg, **kwargs) class UnexpectedProtocolError(ProtocolError): def __init__(self, payload, expected, **kwargs): err_msg = 'Unexpected payload type {}'.format(expected) super().__init__(payload, err_msg, **kwargs)
class Pongerror(Exception): pass class Roomerror(PongError): def __init__(self, room, msg, **kwargs): err_msg = '{} room info : {}'.format(msg, room) super().__init__(err_msg, **kwargs) class Playererror(PongError): def __init__(self, player, msg, **kwargs): err_msg = '{} player info : {}'.format(msg, player) super().__init__(err_msg, **kwargs) class Lobbyerror(PongError): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Protocolerror(PongError): def __init__(self, payload, msg, **kwargs): err_msg = '{} message: {}'.format(msg, payload) super().__init__(err_msg, **kwargs) class Unexpectedprotocolerror(ProtocolError): def __init__(self, payload, expected, **kwargs): err_msg = 'Unexpected payload type {}'.format(expected) super().__init__(payload, err_msg, **kwargs)
BASE_HELIX_URL = "https://api.twitch.tv/helix/" # token url will return a 404 if trailing slash is added BASE_AUTH_URL = "https://id.twitch.tv/oauth2/token" TOKEN_VALIDATION_URL = "https://id.twitch.tv/oauth2/validate" WEBHOOKS_HUB_URL = "https://api.twitch.tv/helix/webhooks/hub"
base_helix_url = 'https://api.twitch.tv/helix/' base_auth_url = 'https://id.twitch.tv/oauth2/token' token_validation_url = 'https://id.twitch.tv/oauth2/validate' webhooks_hub_url = 'https://api.twitch.tv/helix/webhooks/hub'
def main(): t = int(input()) # t = 1 for _ in range(t): n, m = sorted(map(int, input().split())) # n, m = 5, 7 if n % 3 == 0 or m % 3 == 0: print(n * m // 3) continue if n % 3 == 1 and m % 3 == 1: print((m // 3) * n + n // 3 + 1) continue if n % 3 == 2 and m % 3 == 2: print((m // 3) * n + 2 * (n // 3 + 1)) continue if n % 3 == 2: print((m // 3) * n + n // 3 + 1) continue print((m // 3) * n + 2 * (n // 3 + 1) - 1) main()
def main(): t = int(input()) for _ in range(t): (n, m) = sorted(map(int, input().split())) if n % 3 == 0 or m % 3 == 0: print(n * m // 3) continue if n % 3 == 1 and m % 3 == 1: print(m // 3 * n + n // 3 + 1) continue if n % 3 == 2 and m % 3 == 2: print(m // 3 * n + 2 * (n // 3 + 1)) continue if n % 3 == 2: print(m // 3 * n + n // 3 + 1) continue print(m // 3 * n + 2 * (n // 3 + 1) - 1) main()
numbers = range(1, 10) for number in numbers: if number == 1: print (str(number) + 'st') elif number == 2: print (str(number) + 'nd') elif number == 3: print (str(number) + 'rd') else: print (str(number) + 'th')
numbers = range(1, 10) for number in numbers: if number == 1: print(str(number) + 'st') elif number == 2: print(str(number) + 'nd') elif number == 3: print(str(number) + 'rd') else: print(str(number) + 'th')
# 107 # Open the Names.txt file and display the data in Python. with open('Names.txt', 'r') as f: names = f.readlines() for index, name in enumerate(names): # To remove /n names[index] = name[:-1] print(names)
with open('Names.txt', 'r') as f: names = f.readlines() for (index, name) in enumerate(names): names[index] = name[:-1] print(names)
__all__ = ['jazBegin', 'jazEnd', 'jazReturn', 'jazCall', 'jazStackInfo'] class jazBegin: def __init__(self): self.command = "begin"; def call(self, interpreter, arg): interpreter.BeginSubroutine() return None class jazEnd: def __init__(self): self.command = "end"; def call(self, interpreter, arg): interpreter.EndSubroutine() return None class jazReturn: def __init__(self): self.command = "return"; def call(self, interpreter, arg): interpreter.ReturnSubroutine() return None class jazCall: def __init__(self): self.command = "call"; def call(self, interpreter, arg): interpreter.CallSubroutine(arg) return None class jazStackInfo: def __init__(self): self.command = "stackinfo" def call(self, interpreter, arg): if arg is not None and len(arg) > 0: try: scope = interpreter.scopes[int(arg)] info = "Scope: "+str(scope.name)+"\n" info += "* PC : " + str(scope.pc) + "\n" info += "* Labels : " + str(interpreter.labels) + "\n" info += "* Vars : " + str(scope.variables) + "\n" info += "* Stack: " + str(scope.stack) + "\n" if scope.name == scope.lvalue.name: info += "* LScope : self\n" else: info += "* LScope : " + str(scope.lvalue.name) + "\n" if scope.name == scope.rvalue.name: info += "* RScope : self\n" else: info += "* RScope : " + str(scope.rvalue.name) + "\n" except Exception as e: print(e) return "Index is not valid" else: info = "Scopes: ("+str(len(interpreter.scopes))+")\n" i = 0 for s in interpreter.scopes: info = info + "["+str(i)+"] : "+ str(s.name)+"\n" i = i+1; return info # A dictionary of the classes in this file # used to autoload the functions Functions = {'jazBegin': jazBegin,'jazEnd': jazEnd, 'jazReturn': jazReturn, 'jazCall':jazCall,'jazStackInfo': jazStackInfo}
__all__ = ['jazBegin', 'jazEnd', 'jazReturn', 'jazCall', 'jazStackInfo'] class Jazbegin: def __init__(self): self.command = 'begin' def call(self, interpreter, arg): interpreter.BeginSubroutine() return None class Jazend: def __init__(self): self.command = 'end' def call(self, interpreter, arg): interpreter.EndSubroutine() return None class Jazreturn: def __init__(self): self.command = 'return' def call(self, interpreter, arg): interpreter.ReturnSubroutine() return None class Jazcall: def __init__(self): self.command = 'call' def call(self, interpreter, arg): interpreter.CallSubroutine(arg) return None class Jazstackinfo: def __init__(self): self.command = 'stackinfo' def call(self, interpreter, arg): if arg is not None and len(arg) > 0: try: scope = interpreter.scopes[int(arg)] info = 'Scope: ' + str(scope.name) + '\n' info += '* PC : ' + str(scope.pc) + '\n' info += '* Labels : ' + str(interpreter.labels) + '\n' info += '* Vars : ' + str(scope.variables) + '\n' info += '* Stack: ' + str(scope.stack) + '\n' if scope.name == scope.lvalue.name: info += '* LScope : self\n' else: info += '* LScope : ' + str(scope.lvalue.name) + '\n' if scope.name == scope.rvalue.name: info += '* RScope : self\n' else: info += '* RScope : ' + str(scope.rvalue.name) + '\n' except Exception as e: print(e) return 'Index is not valid' else: info = 'Scopes: (' + str(len(interpreter.scopes)) + ')\n' i = 0 for s in interpreter.scopes: info = info + '[' + str(i) + '] : ' + str(s.name) + '\n' i = i + 1 return info functions = {'jazBegin': jazBegin, 'jazEnd': jazEnd, 'jazReturn': jazReturn, 'jazCall': jazCall, 'jazStackInfo': jazStackInfo}
# New tokens can be found at https://archive.org/account/s3.php DOI_FORMAT = '10.70102/fk2osf.io/{guid}' DATACITE_USERNAME = '' DATACITE_PASSWORD = '' DATACITE_URL = 'https://doi.test.datacite.org/' DATACITE_PREFIX = '10.70102' # Datacite's test DOI prefix -- update in production CHUNK_SIZE = 1000 PAGE_SIZE = 100 OSF_COLLECTION_NAME = 'cos-dev-sandbox' OSF_BEARER_TOKEN = '' IA_ACCESS_KEY = '' IA_SECRET_KEY = '' OSF_API_URL = 'http://localhost:8000/' OSF_FILES_URL = 'http://localhost:7777/' OSF_LOGS_URL = 'v2/registrations/{}/logs/?page[size]={}' IA_URL = 's3.us.archive.org'
doi_format = '10.70102/fk2osf.io/{guid}' datacite_username = '' datacite_password = '' datacite_url = 'https://doi.test.datacite.org/' datacite_prefix = '10.70102' chunk_size = 1000 page_size = 100 osf_collection_name = 'cos-dev-sandbox' osf_bearer_token = '' ia_access_key = '' ia_secret_key = '' osf_api_url = 'http://localhost:8000/' osf_files_url = 'http://localhost:7777/' osf_logs_url = 'v2/registrations/{}/logs/?page[size]={}' ia_url = 's3.us.archive.org'
b, br, bs, a, ass = map(int, input().split()) bobMoney = (br - b) * bs aliceMoney = 0 while aliceMoney <= bobMoney: aliceMoney += ass a += 1 print(a)
(b, br, bs, a, ass) = map(int, input().split()) bob_money = (br - b) * bs alice_money = 0 while aliceMoney <= bobMoney: alice_money += ass a += 1 print(a)
# This is a config file for CCI data and CMIP5 sea surface temperature diagnostics # generell flags regionalization = True shape = "Seas_v" shapeNames = 1 #column of the name values # flags for basic diagnostics globmeants = False mima_globmeants=[255,305] cmap_globmeants='jet' mima_ts=[288,292] mima_mts=[270,310] portrait = True globmeandiff =True mima_globmeandiff=[-10,10] mima_globmeandiff_r=[-0.03,0.03] trend = False# True anomalytrend =False#True trend_p=False # flags for specific diagnostics percentile = False#True mima_percentile=[255,305] # percentile parameters percentile_pars = [0,1,0.25] #start,stop,increment #plotting parameters projection={'projection': 'robin', 'lon_0': 180., 'lat_0': 0.}
regionalization = True shape = 'Seas_v' shape_names = 1 globmeants = False mima_globmeants = [255, 305] cmap_globmeants = 'jet' mima_ts = [288, 292] mima_mts = [270, 310] portrait = True globmeandiff = True mima_globmeandiff = [-10, 10] mima_globmeandiff_r = [-0.03, 0.03] trend = False anomalytrend = False trend_p = False percentile = False mima_percentile = [255, 305] percentile_pars = [0, 1, 0.25] projection = {'projection': 'robin', 'lon_0': 180.0, 'lat_0': 0.0}
# # Created on Fri Apr 10 2020 # # Title: Leetcode - Middle of the Linked List # # Author: Vatsal Mistry # Web: mistryvatsal.github.io # # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def middleNode(self, head: ListNode) -> ListNode: p1 = p2 = head while p1 != None and p1.next != None: p1, p2 = p1.next.next, p2.next return p2
class Solution: def middle_node(self, head: ListNode) -> ListNode: p1 = p2 = head while p1 != None and p1.next != None: (p1, p2) = (p1.next.next, p2.next) return p2
async def f(): return 0 def f(): return 0 async for x in test: print(x) for x in test: print(x) for (x, y, z) in test: print(x) with test as f: print(x) async with test as f: print(x) if (x): print(x) x = [1, 2, 3] try: raise x except D: print(x) except C: print(x) except B: print(x) x = [x, y, z] (x, y, z) x x, (1) (1,) [x for (x, y, z) in test if x > 0 for (a, b, c) in test2] def main(): if (x > 1): print(x) else: print(y) [(x, y, z) for (x, y, z) in test] x = {"test" : 1} x = {1, 2, 3} x = {x for x in test} x = {**x, **y} x = {1} x ={1, 2} call(x, y, *varargs, x=3, y=3, **kwargs) class Test: def __init__(self): pass def fun(x, y, *varargs, a, b, c, **kwargs): return 0 (yield x) x = lambda a: a + 1 b"test" b"test" "test"
async def f(): return 0 def f(): return 0 async for x in test: print(x) for x in test: print(x) for (x, y, z) in test: print(x) with test as f: print(x) async with test as f: print(x) if x: print(x) x = [1, 2, 3] try: raise x except D: print(x) except C: print(x) except B: print(x) x = [x, y, z] (x, y, z) x (x,) 1 (1,) [x for (x, y, z) in test if x > 0 for (a, b, c) in test2] def main(): if x > 1: print(x) else: print(y) [(x, y, z) for (x, y, z) in test] x = {'test': 1} x = {1, 2, 3} x = {x for x in test} x = {**x, **y} x = {1} x = {1, 2} call(x, y, *varargs, x=3, y=3, **kwargs) class Test: def __init__(self): pass def fun(x, y, *varargs, a, b, c, **kwargs): return 0 yield x x = lambda a: a + 1 b'testtest' 'test'
tabs = int(input()) salary = float(input()) for tab in range(tabs): current_tab = input() if current_tab == "Facebook": salary -= 150 elif current_tab == "Instagram": salary -= 100 elif current_tab == "Reddit": salary -= 50 if salary <= 0: print("You have lost your salary.") break if salary > 0: print(int(salary))
tabs = int(input()) salary = float(input()) for tab in range(tabs): current_tab = input() if current_tab == 'Facebook': salary -= 150 elif current_tab == 'Instagram': salary -= 100 elif current_tab == 'Reddit': salary -= 50 if salary <= 0: print('You have lost your salary.') break if salary > 0: print(int(salary))
while True: try: a=input() except: break while "BUG" in a: a=a.replace("BUG","") print(a)
while True: try: a = input() except: break while 'BUG' in a: a = a.replace('BUG', '') print(a)
class Solution: """ @param a: The first integer @param b: The second integer @return: The sum of a and b """ # Actually both of these methods fail to work in Python # because Python supports infinite integer # Non-recursive def aplusb(self, a, b): # write your code here, try to do it without arithmetic operators. while b != 0: carry = a & b a = a ^ b b = carry << 1 return a # Recursive def aplusb(self, a, b): carry = a & b result = a ^ b return result if carry == 0 else self.aplusb(result, carry << 1)
class Solution: """ @param a: The first integer @param b: The second integer @return: The sum of a and b """ def aplusb(self, a, b): while b != 0: carry = a & b a = a ^ b b = carry << 1 return a def aplusb(self, a, b): carry = a & b result = a ^ b return result if carry == 0 else self.aplusb(result, carry << 1)
class Stack: def __init__(self): self.items = [] self.head = -1 def push(self, x): self.head+=1 self.items.insert(self.head, x) def pop(self): if self.isEmpty(): print("Stack is empty !!!") else: x = self.items[self.head] self.items.pop(self.head) self.head-=1 return x def size(self): return len(self.items) def isEmpty(self): return self.head == -1 s = Stack() x = s.pop() for i in range(1,6): s.push(i) print(s.items, s.head) x = s.pop() print(s.items) print(s.isEmpty()) print(s.size())
class Stack: def __init__(self): self.items = [] self.head = -1 def push(self, x): self.head += 1 self.items.insert(self.head, x) def pop(self): if self.isEmpty(): print('Stack is empty !!!') else: x = self.items[self.head] self.items.pop(self.head) self.head -= 1 return x def size(self): return len(self.items) def is_empty(self): return self.head == -1 s = stack() x = s.pop() for i in range(1, 6): s.push(i) print(s.items, s.head) x = s.pop() print(s.items) print(s.isEmpty()) print(s.size())
class AttribDesc: def __init__(self, name, default, datatype = 'string', params = {}): self.name = name self.default = default self.datatype = datatype self.params = params def getName(self): return self.name def getDefaultValue(self): return self.default def getDatatype(self): return self.datatype def getParams(self): return self.params def __str__(self): return self.name def __repr__(self): return 'AttribDesc(%s, %s, %s, %s)' % (repr(self.name), repr(self.default), repr(self.datatype), repr(self.params))
class Attribdesc: def __init__(self, name, default, datatype='string', params={}): self.name = name self.default = default self.datatype = datatype self.params = params def get_name(self): return self.name def get_default_value(self): return self.default def get_datatype(self): return self.datatype def get_params(self): return self.params def __str__(self): return self.name def __repr__(self): return 'AttribDesc(%s, %s, %s, %s)' % (repr(self.name), repr(self.default), repr(self.datatype), repr(self.params))
print ("Em que classe o seu terreno se encaixa?") largura = float (input("Insira aqui a largura do seu terreno :")) comprimento = float (input("Insira aqui o comprimento do seu terreno :")) m2 = largura*comprimento if m2 <=100: print ("Terreno Popular") elif m2 <= 500: print ("Terreno Master") if m2 >= 500: print ("Terreno VIP")
print('Em que classe o seu terreno se encaixa?') largura = float(input('Insira aqui a largura do seu terreno :')) comprimento = float(input('Insira aqui o comprimento do seu terreno :')) m2 = largura * comprimento if m2 <= 100: print('Terreno Popular') elif m2 <= 500: print('Terreno Master') if m2 >= 500: print('Terreno VIP')
def mortgage_calculator(P,r,N): if r == 0: return P / N else: return ((r * P) / (1 - (1 + r)**-N)) if __name__ == '__main__': P = float(input('Enter the amount borrowed: ')) R = float(input('Enter the interest rate: ')) N = int(input("Enter the number of monthly payments: ")) r = R / (12*100) print(f'Your fixed monthly payment equal to {round(mortgage_calculator(P,r,N),2)} per month.')
def mortgage_calculator(P, r, N): if r == 0: return P / N else: return r * P / (1 - (1 + r) ** (-N)) if __name__ == '__main__': p = float(input('Enter the amount borrowed: ')) r = float(input('Enter the interest rate: ')) n = int(input('Enter the number of monthly payments: ')) r = R / (12 * 100) print(f'Your fixed monthly payment equal to {round(mortgage_calculator(P, r, N), 2)} per month.')
{ "target_defaults": { "make_global_settings": [ [ "CC", "echo" ], [ "LD", "echo" ], ], }, "targets": [{ "target_name": "test", "type": "executable", "sources": [ "main.c", ], }], }
{'target_defaults': {'make_global_settings': [['CC', 'echo'], ['LD', 'echo']]}, 'targets': [{'target_name': 'test', 'type': 'executable', 'sources': ['main.c']}]}
# # PySNMP MIB module SNMP-USM-HMAC-SHA2-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SNMP-USM-HMAC-SHA2-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:00:31 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") ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion, ConstraintsIntersection, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueRangeConstraint") snmpAuthProtocols, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "snmpAuthProtocols") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") ModuleIdentity, Bits, mib_2, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, ObjectIdentity, NotificationType, IpAddress, Counter32, Integer32, MibIdentifier, Counter64, Unsigned32, iso = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "Bits", "mib-2", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "ObjectIdentity", "NotificationType", "IpAddress", "Counter32", "Integer32", "MibIdentifier", "Counter64", "Unsigned32", "iso") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") snmpUsmHmacSha2MIB = ModuleIdentity((1, 3, 6, 1, 2, 1, 235)) snmpUsmHmacSha2MIB.setRevisions(('2016-04-18 00:00', '2015-10-14 00:00',)) if mibBuilder.loadTexts: snmpUsmHmacSha2MIB.setLastUpdated('201604180000Z') if mibBuilder.loadTexts: snmpUsmHmacSha2MIB.setOrganization('SNMPv3 Working Group') usmHMAC128SHA224AuthProtocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 1, 4)) if mibBuilder.loadTexts: usmHMAC128SHA224AuthProtocol.setStatus('current') usmHMAC192SHA256AuthProtocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 1, 5)) if mibBuilder.loadTexts: usmHMAC192SHA256AuthProtocol.setStatus('current') usmHMAC256SHA384AuthProtocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 1, 6)) if mibBuilder.loadTexts: usmHMAC256SHA384AuthProtocol.setStatus('current') usmHMAC384SHA512AuthProtocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 1, 7)) if mibBuilder.loadTexts: usmHMAC384SHA512AuthProtocol.setStatus('current') mibBuilder.exportSymbols("SNMP-USM-HMAC-SHA2-MIB", usmHMAC384SHA512AuthProtocol=usmHMAC384SHA512AuthProtocol, usmHMAC256SHA384AuthProtocol=usmHMAC256SHA384AuthProtocol, usmHMAC192SHA256AuthProtocol=usmHMAC192SHA256AuthProtocol, PYSNMP_MODULE_ID=snmpUsmHmacSha2MIB, usmHMAC128SHA224AuthProtocol=usmHMAC128SHA224AuthProtocol, snmpUsmHmacSha2MIB=snmpUsmHmacSha2MIB)
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, single_value_constraint, constraints_union, constraints_intersection, value_range_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'SingleValueConstraint', 'ConstraintsUnion', 'ConstraintsIntersection', 'ValueRangeConstraint') (snmp_auth_protocols,) = mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'snmpAuthProtocols') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (module_identity, bits, mib_2, gauge32, mib_scalar, mib_table, mib_table_row, mib_table_column, time_ticks, object_identity, notification_type, ip_address, counter32, integer32, mib_identifier, counter64, unsigned32, iso) = mibBuilder.importSymbols('SNMPv2-SMI', 'ModuleIdentity', 'Bits', 'mib-2', 'Gauge32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'TimeTicks', 'ObjectIdentity', 'NotificationType', 'IpAddress', 'Counter32', 'Integer32', 'MibIdentifier', 'Counter64', 'Unsigned32', 'iso') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') snmp_usm_hmac_sha2_mib = module_identity((1, 3, 6, 1, 2, 1, 235)) snmpUsmHmacSha2MIB.setRevisions(('2016-04-18 00:00', '2015-10-14 00:00')) if mibBuilder.loadTexts: snmpUsmHmacSha2MIB.setLastUpdated('201604180000Z') if mibBuilder.loadTexts: snmpUsmHmacSha2MIB.setOrganization('SNMPv3 Working Group') usm_hmac128_sha224_auth_protocol = object_identity((1, 3, 6, 1, 6, 3, 10, 1, 1, 4)) if mibBuilder.loadTexts: usmHMAC128SHA224AuthProtocol.setStatus('current') usm_hmac192_sha256_auth_protocol = object_identity((1, 3, 6, 1, 6, 3, 10, 1, 1, 5)) if mibBuilder.loadTexts: usmHMAC192SHA256AuthProtocol.setStatus('current') usm_hmac256_sha384_auth_protocol = object_identity((1, 3, 6, 1, 6, 3, 10, 1, 1, 6)) if mibBuilder.loadTexts: usmHMAC256SHA384AuthProtocol.setStatus('current') usm_hmac384_sha512_auth_protocol = object_identity((1, 3, 6, 1, 6, 3, 10, 1, 1, 7)) if mibBuilder.loadTexts: usmHMAC384SHA512AuthProtocol.setStatus('current') mibBuilder.exportSymbols('SNMP-USM-HMAC-SHA2-MIB', usmHMAC384SHA512AuthProtocol=usmHMAC384SHA512AuthProtocol, usmHMAC256SHA384AuthProtocol=usmHMAC256SHA384AuthProtocol, usmHMAC192SHA256AuthProtocol=usmHMAC192SHA256AuthProtocol, PYSNMP_MODULE_ID=snmpUsmHmacSha2MIB, usmHMAC128SHA224AuthProtocol=usmHMAC128SHA224AuthProtocol, snmpUsmHmacSha2MIB=snmpUsmHmacSha2MIB)
# # PySNMP MIB module XEDIA-FRAME-RELAY-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/XEDIA-FRAME-RELAY-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:42:46 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") ValueSizeConstraint, ValueRangeConstraint, ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint") frCircuitEntry, = mibBuilder.importSymbols("RFC1315-MIB", "frCircuitEntry") ObjectGroup, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "NotificationGroup", "ModuleCompliance") Integer32, MibIdentifier, Bits, IpAddress, iso, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, Counter32, ModuleIdentity, Gauge32, ObjectIdentity, TimeTicks, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "MibIdentifier", "Bits", "IpAddress", "iso", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "Counter32", "ModuleIdentity", "Gauge32", "ObjectIdentity", "TimeTicks", "NotificationType") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") xediaMibs, = mibBuilder.importSymbols("XEDIA-REG", "xediaMibs") xediaFrameRelayMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 838, 3, 19)) if mibBuilder.loadTexts: xediaFrameRelayMIB.setLastUpdated('9808242155Z') if mibBuilder.loadTexts: xediaFrameRelayMIB.setOrganization('Xedia Corp.') if mibBuilder.loadTexts: xediaFrameRelayMIB.setContactInfo('support@xedia.com') if mibBuilder.loadTexts: xediaFrameRelayMIB.setDescription("This module defines additional objects for management of Frame Relay in Xedia devices, above and beyond what is defined in the IETF's Frame Relay MIBs.") xfrObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 838, 3, 19, 1)) xfrNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 838, 3, 19, 2)) xfrConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 838, 3, 19, 3)) xfrArpTable = MibTable((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 1), ) if mibBuilder.loadTexts: xfrArpTable.setStatus('current') if mibBuilder.loadTexts: xfrArpTable.setDescription('The IP Address Translation table used for mapping from IP addresses to physical addresses, in this case frame relay DLCIs. This table contains much of the same information that is in the ipNetToMediaTable.') xfrArpEntry = MibTableRow((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 1, 1), ).setIndexNames((0, "XEDIA-FRAME-RELAY-MIB", "xfrArpIfIndex"), (0, "XEDIA-FRAME-RELAY-MIB", "xfrArpNetAddress")) if mibBuilder.loadTexts: xfrArpEntry.setStatus('current') if mibBuilder.loadTexts: xfrArpEntry.setDescription("Each entry contains one IpAddress to `physical' address equivalence.") xfrArpIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readcreate") if mibBuilder.loadTexts: xfrArpIfIndex.setStatus('current') if mibBuilder.loadTexts: xfrArpIfIndex.setDescription("The interface on which this entry's equivalence is effective. The interface identified by a particular value of this index is the same interface as identified by the same value of RFC 1573's ifIndex.") xfrArpNetAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 1, 1, 2), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: xfrArpNetAddress.setStatus('current') if mibBuilder.loadTexts: xfrArpNetAddress.setDescription('The IpAddress corresponding to the frame relay DLCI.') xfrArpType = MibTableColumn((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("other", 1), ("invalid", 2), ("dynamic", 3), ("static", 4))).clone('static')).setMaxAccess("readcreate") if mibBuilder.loadTexts: xfrArpType.setStatus('current') if mibBuilder.loadTexts: xfrArpType.setDescription('The type of mapping. Setting this object to the value invalid(2) has the effect of invalidating the corresponding entry in the xfrArpEntryTable. That is, it effectively disassociates the interface identified with said entry from the mapping identified with said entry. It is an implementation- specific matter as to whether the agent removes an invalidated entry from the table. Accordingly, management stations must be prepared to receive tabular information from agents that corresponds to entries not currently in use. Proper interpretation of such entries requires examination of the relevant xfrArpEntryType object.') xfrArpDlci = MibTableColumn((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(16, 991)).clone(16)).setMaxAccess("readcreate") if mibBuilder.loadTexts: xfrArpDlci.setStatus('current') if mibBuilder.loadTexts: xfrArpDlci.setDescription('The DLCI attached to the IP address.') xfrArpIfStack = MibTableColumn((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 1, 1, 5), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: xfrArpIfStack.setStatus('current') if mibBuilder.loadTexts: xfrArpIfStack.setDescription('A description of the interface stack containing this frame relay interface, with the IP interface, the frame relay interface, and the device interface.') xFrCircuitTable = MibTable((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 2), ) if mibBuilder.loadTexts: xFrCircuitTable.setStatus('current') if mibBuilder.loadTexts: xFrCircuitTable.setDescription('A table containing additional information about specific Data Link Connection Identifiers and corresponding virtual circuits.') xFrCircuitEntry = MibTableRow((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 2, 1), ) frCircuitEntry.registerAugmentions(("XEDIA-FRAME-RELAY-MIB", "xFrCircuitEntry")) xFrCircuitEntry.setIndexNames(*frCircuitEntry.getIndexNames()) if mibBuilder.loadTexts: xFrCircuitEntry.setStatus('current') if mibBuilder.loadTexts: xFrCircuitEntry.setDescription('The additional information regarding a single Data Link Connection Identifier.') xfrCircuitType = MibTableColumn((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 2, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("dynamic", 1), ("static", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: xfrCircuitType.setStatus('current') if mibBuilder.loadTexts: xfrCircuitType.setDescription('The type of DLCI ') xfrCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 838, 3, 19, 3, 1)) xfrGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 838, 3, 19, 3, 2)) xfrCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 838, 3, 19, 3, 1, 1)).setObjects(("XEDIA-FRAME-RELAY-MIB", "xfrAllGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): xfrCompliance = xfrCompliance.setStatus('current') if mibBuilder.loadTexts: xfrCompliance.setDescription('The compliance statement for all agents that support this MIB. A compliant agent implements all objects defined in this MIB.') xfrAllGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 838, 3, 19, 3, 2, 1)).setObjects(("XEDIA-FRAME-RELAY-MIB", "xfrArpIfIndex"), ("XEDIA-FRAME-RELAY-MIB", "xfrArpNetAddress"), ("XEDIA-FRAME-RELAY-MIB", "xfrArpDlci"), ("XEDIA-FRAME-RELAY-MIB", "xfrArpIfStack"), ("XEDIA-FRAME-RELAY-MIB", "xfrArpType"), ("XEDIA-FRAME-RELAY-MIB", "xfrCircuitType")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): xfrAllGroup = xfrAllGroup.setStatus('current') if mibBuilder.loadTexts: xfrAllGroup.setDescription('The set of all accessible objects in this MIB.') mibBuilder.exportSymbols("XEDIA-FRAME-RELAY-MIB", xfrArpEntry=xfrArpEntry, xfrArpNetAddress=xfrArpNetAddress, xFrCircuitEntry=xFrCircuitEntry, xfrCircuitType=xfrCircuitType, xFrCircuitTable=xFrCircuitTable, xfrArpIfIndex=xfrArpIfIndex, xfrArpDlci=xfrArpDlci, xfrConformance=xfrConformance, xfrNotifications=xfrNotifications, xediaFrameRelayMIB=xediaFrameRelayMIB, xfrArpTable=xfrArpTable, xfrArpIfStack=xfrArpIfStack, xfrCompliances=xfrCompliances, xfrArpType=xfrArpType, PYSNMP_MODULE_ID=xediaFrameRelayMIB, xfrObjects=xfrObjects, xfrAllGroup=xfrAllGroup, xfrGroups=xfrGroups, xfrCompliance=xfrCompliance)
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, value_range_constraint, constraints_intersection, constraints_union, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'ValueRangeConstraint', 'ConstraintsIntersection', 'ConstraintsUnion', 'SingleValueConstraint') (fr_circuit_entry,) = mibBuilder.importSymbols('RFC1315-MIB', 'frCircuitEntry') (object_group, notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'ObjectGroup', 'NotificationGroup', 'ModuleCompliance') (integer32, mib_identifier, bits, ip_address, iso, unsigned32, mib_scalar, mib_table, mib_table_row, mib_table_column, counter64, counter32, module_identity, gauge32, object_identity, time_ticks, notification_type) = mibBuilder.importSymbols('SNMPv2-SMI', 'Integer32', 'MibIdentifier', 'Bits', 'IpAddress', 'iso', 'Unsigned32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Counter64', 'Counter32', 'ModuleIdentity', 'Gauge32', 'ObjectIdentity', 'TimeTicks', 'NotificationType') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') (xedia_mibs,) = mibBuilder.importSymbols('XEDIA-REG', 'xediaMibs') xedia_frame_relay_mib = module_identity((1, 3, 6, 1, 4, 1, 838, 3, 19)) if mibBuilder.loadTexts: xediaFrameRelayMIB.setLastUpdated('9808242155Z') if mibBuilder.loadTexts: xediaFrameRelayMIB.setOrganization('Xedia Corp.') if mibBuilder.loadTexts: xediaFrameRelayMIB.setContactInfo('support@xedia.com') if mibBuilder.loadTexts: xediaFrameRelayMIB.setDescription("This module defines additional objects for management of Frame Relay in Xedia devices, above and beyond what is defined in the IETF's Frame Relay MIBs.") xfr_objects = mib_identifier((1, 3, 6, 1, 4, 1, 838, 3, 19, 1)) xfr_notifications = mib_identifier((1, 3, 6, 1, 4, 1, 838, 3, 19, 2)) xfr_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 838, 3, 19, 3)) xfr_arp_table = mib_table((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 1)) if mibBuilder.loadTexts: xfrArpTable.setStatus('current') if mibBuilder.loadTexts: xfrArpTable.setDescription('The IP Address Translation table used for mapping from IP addresses to physical addresses, in this case frame relay DLCIs. This table contains much of the same information that is in the ipNetToMediaTable.') xfr_arp_entry = mib_table_row((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 1, 1)).setIndexNames((0, 'XEDIA-FRAME-RELAY-MIB', 'xfrArpIfIndex'), (0, 'XEDIA-FRAME-RELAY-MIB', 'xfrArpNetAddress')) if mibBuilder.loadTexts: xfrArpEntry.setStatus('current') if mibBuilder.loadTexts: xfrArpEntry.setDescription("Each entry contains one IpAddress to `physical' address equivalence.") xfr_arp_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 2147483647))).setMaxAccess('readcreate') if mibBuilder.loadTexts: xfrArpIfIndex.setStatus('current') if mibBuilder.loadTexts: xfrArpIfIndex.setDescription("The interface on which this entry's equivalence is effective. The interface identified by a particular value of this index is the same interface as identified by the same value of RFC 1573's ifIndex.") xfr_arp_net_address = mib_table_column((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 1, 1, 2), ip_address()).setMaxAccess('readcreate') if mibBuilder.loadTexts: xfrArpNetAddress.setStatus('current') if mibBuilder.loadTexts: xfrArpNetAddress.setDescription('The IpAddress corresponding to the frame relay DLCI.') xfr_arp_type = mib_table_column((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('other', 1), ('invalid', 2), ('dynamic', 3), ('static', 4))).clone('static')).setMaxAccess('readcreate') if mibBuilder.loadTexts: xfrArpType.setStatus('current') if mibBuilder.loadTexts: xfrArpType.setDescription('The type of mapping. Setting this object to the value invalid(2) has the effect of invalidating the corresponding entry in the xfrArpEntryTable. That is, it effectively disassociates the interface identified with said entry from the mapping identified with said entry. It is an implementation- specific matter as to whether the agent removes an invalidated entry from the table. Accordingly, management stations must be prepared to receive tabular information from agents that corresponds to entries not currently in use. Proper interpretation of such entries requires examination of the relevant xfrArpEntryType object.') xfr_arp_dlci = mib_table_column((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 1, 1, 4), integer32().subtype(subtypeSpec=value_range_constraint(16, 991)).clone(16)).setMaxAccess('readcreate') if mibBuilder.loadTexts: xfrArpDlci.setStatus('current') if mibBuilder.loadTexts: xfrArpDlci.setDescription('The DLCI attached to the IP address.') xfr_arp_if_stack = mib_table_column((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 1, 1, 5), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: xfrArpIfStack.setStatus('current') if mibBuilder.loadTexts: xfrArpIfStack.setDescription('A description of the interface stack containing this frame relay interface, with the IP interface, the frame relay interface, and the device interface.') x_fr_circuit_table = mib_table((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 2)) if mibBuilder.loadTexts: xFrCircuitTable.setStatus('current') if mibBuilder.loadTexts: xFrCircuitTable.setDescription('A table containing additional information about specific Data Link Connection Identifiers and corresponding virtual circuits.') x_fr_circuit_entry = mib_table_row((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 2, 1)) frCircuitEntry.registerAugmentions(('XEDIA-FRAME-RELAY-MIB', 'xFrCircuitEntry')) xFrCircuitEntry.setIndexNames(*frCircuitEntry.getIndexNames()) if mibBuilder.loadTexts: xFrCircuitEntry.setStatus('current') if mibBuilder.loadTexts: xFrCircuitEntry.setDescription('The additional information regarding a single Data Link Connection Identifier.') xfr_circuit_type = mib_table_column((1, 3, 6, 1, 4, 1, 838, 3, 19, 1, 2, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('dynamic', 1), ('static', 2)))).setMaxAccess('readonly') if mibBuilder.loadTexts: xfrCircuitType.setStatus('current') if mibBuilder.loadTexts: xfrCircuitType.setDescription('The type of DLCI ') xfr_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 838, 3, 19, 3, 1)) xfr_groups = mib_identifier((1, 3, 6, 1, 4, 1, 838, 3, 19, 3, 2)) xfr_compliance = module_compliance((1, 3, 6, 1, 4, 1, 838, 3, 19, 3, 1, 1)).setObjects(('XEDIA-FRAME-RELAY-MIB', 'xfrAllGroup')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): xfr_compliance = xfrCompliance.setStatus('current') if mibBuilder.loadTexts: xfrCompliance.setDescription('The compliance statement for all agents that support this MIB. A compliant agent implements all objects defined in this MIB.') xfr_all_group = object_group((1, 3, 6, 1, 4, 1, 838, 3, 19, 3, 2, 1)).setObjects(('XEDIA-FRAME-RELAY-MIB', 'xfrArpIfIndex'), ('XEDIA-FRAME-RELAY-MIB', 'xfrArpNetAddress'), ('XEDIA-FRAME-RELAY-MIB', 'xfrArpDlci'), ('XEDIA-FRAME-RELAY-MIB', 'xfrArpIfStack'), ('XEDIA-FRAME-RELAY-MIB', 'xfrArpType'), ('XEDIA-FRAME-RELAY-MIB', 'xfrCircuitType')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): xfr_all_group = xfrAllGroup.setStatus('current') if mibBuilder.loadTexts: xfrAllGroup.setDescription('The set of all accessible objects in this MIB.') mibBuilder.exportSymbols('XEDIA-FRAME-RELAY-MIB', xfrArpEntry=xfrArpEntry, xfrArpNetAddress=xfrArpNetAddress, xFrCircuitEntry=xFrCircuitEntry, xfrCircuitType=xfrCircuitType, xFrCircuitTable=xFrCircuitTable, xfrArpIfIndex=xfrArpIfIndex, xfrArpDlci=xfrArpDlci, xfrConformance=xfrConformance, xfrNotifications=xfrNotifications, xediaFrameRelayMIB=xediaFrameRelayMIB, xfrArpTable=xfrArpTable, xfrArpIfStack=xfrArpIfStack, xfrCompliances=xfrCompliances, xfrArpType=xfrArpType, PYSNMP_MODULE_ID=xediaFrameRelayMIB, xfrObjects=xfrObjects, xfrAllGroup=xfrAllGroup, xfrGroups=xfrGroups, xfrCompliance=xfrCompliance)
def num(): a=int(input('input a : ')) b=int(input('input b : ')) return a, b def func(a,b): add = a+b multi = a*b devi = a/b return add, multi, devi if __name__=='__main__': try: a, b=num() add,_,_=func(a,b) _,multi,_=func(a,b) _,_,devi=func(a,b) except ZeroDivisionError: print('can not devide by zero') devi=func(a,1) pass finally: print(add, multi, devi) pass
def num(): a = int(input('input a : ')) b = int(input('input b : ')) return (a, b) def func(a, b): add = a + b multi = a * b devi = a / b return (add, multi, devi) if __name__ == '__main__': try: (a, b) = num() (add, _, _) = func(a, b) (_, multi, _) = func(a, b) (_, _, devi) = func(a, b) except ZeroDivisionError: print('can not devide by zero') devi = func(a, 1) pass finally: print(add, multi, devi) pass
############################################################# # FILE : additional_file.py # WRITER : Nadav Weisler , Weisler , 316493758 # EXERCISE : intro2cs ex1 2019 # DESCRIPTION: include function called "secret_function" # that print "My username is weisler and I read the submission response." ############################################################# def secret_function(): print("My username is weisler and I read the submission response.")
def secret_function(): print('My username is weisler and I read the submission response.')
def subsetsum(array,num): if num == 0 or num < 1: return None elif len(array) == 0: return None else: if array[0].marks == num: return [array[0]] else: x = subsetsum(array[1:],(num - array[0].marks)) if x: return [array[0]] + x else: return subsetsum(array[1:],num)
def subsetsum(array, num): if num == 0 or num < 1: return None elif len(array) == 0: return None elif array[0].marks == num: return [array[0]] else: x = subsetsum(array[1:], num - array[0].marks) if x: return [array[0]] + x else: return subsetsum(array[1:], num)
# File: imap_consts.py # # Copyright (c) 2016-2022 Splunk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed under # the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, # either express or implied. See the License for the specific language governing permissions # and limitations under the License. IMAP_JSON_USE_SSL = "use_ssl" IMAP_JSON_DATE = "date" IMAP_JSON_FILES = "files" IMAP_JSON_BODIES = "bodies" IMAP_JSON_FROM = "from" IMAP_JSON_MAIL = "mail" IMAP_JSON_SUBJECT = "subject" IMAP_JSON_TO = "to" IMAP_JSON_START_TIME = "start_time" IMAP_JSON_EXTRACT_ATTACHMENTS = "extract_attachments" IMAP_JSON_EXTRACT_URLS = "extract_urls" IMAP_JSON_EXTRACT_IPS = "extract_ips" IMAP_JSON_EXTRACT_DOMAINS = "extract_domains" IMAP_JSON_EXTRACT_HASHES = "extract_hashes" IMAP_JSON_TOTAL_EMAILS = "total_emails" IMAP_JSON_IPS = "ips" IMAP_JSON_HASHES = "hashes" IMAP_JSON_URLS = "urls" IMAP_JSON_DOMAINS = "domains" IMAP_JSON_EMAIL_ADDRESSES = "email_addresses" IMAP_JSON_DEF_NUM_DAYS = "interval_days" IMAP_JSON_MAX_EMAILS = "max_emails" IMAP_JSON_FIRST_RUN_MAX_EMAILS = "first_run_max_emails" IMAP_JSON_VAULT_IDS = "vault_ids" IMAP_JSON_INGEST_MANNER = "ingest_manner" IMAP_JSON_EMAIL_HEADERS = "email_headers" IMAP_JSON_FOLDER = "folder" IMAP_JSON_ID = "id" IMAP_JSON_CONTAINER_ID = "container_id" IMAP_JSON_INGEST_EMAIL = "ingest_email" IMAP_INGEST_LATEST_EMAILS = "latest first" IMAP_INGEST_OLDEST_EMAILS = "oldest first" IMAP_CONNECTED_TO_SERVER = "Initiated connection to server" IMAP_ERR_CONNECTING_TO_SERVER = "Error connecting to server" IMAP_ERR_LISTING_FOLDERS = "Error listing folders" IMAP_ERR_LOGGING_IN_TO_SERVER = "Error logging in to server" IMAP_ERR_SELECTING_FOLDER = "Error selecting folder '{folder}'" IMAP_GOT_LIST_FOLDERS = "Got folder listing" IMAP_LOGGED_IN = "User logged in" IMAP_SELECTED_FOLDER = "Selected folder '{folder}'" IMAP_SUCC_CONNECTIVITY_TEST = "Connectivity test passed" IMAP_ERR_CONNECTIVITY_TEST = "Connectivity test failed" IMAP_ERR_END_TIME_LT_START_TIME = "End time less than start time" IMAP_ERR_MAILBOX_SEARCH_FAILED = "Mailbox search failed" IMAP_ERR_MAILBOX_SEARCH_FAILED_RESULT = "Mailbox search failed, result: {result} data: {data}" IMAP_FETCH_ID_FAILED = "Fetch for uuid: {muuid} failed, reason: {excep}" IMAP_FETCH_ID_FAILED_RESULT = "Fetch for uuid: {muuid} failed, result: {result}, data: {data}" IMAP_VALIDATE_INTEGER_MESSAGE = "Please provide a valid integer value in the {key} parameter" IMAP_ERR_CODE_MESSAGE = "Error code unavailable" IMAP_ERR_MESSAGE = "Unknown error occurred. Please check the asset configuration and|or action parameters" IMAP_EXCEPTION_ERR_MESSAGE = "Error Code: {0}. Error Message: {1}" IMAP_REQUIRED_PARAM_OAUTH = "ERROR: {0} is a required parameter for OAuth Authentication, please specify one." IMAP_REQUIRED_PARAM_BASIC = "ERROR: {0} is a required parameter for Basic Authentication, please specify one." IMAP_GENERAL_ERR_MESSAGE = "{}. Details: {}" IMAP_STATE_FILE_CORRUPT_ERR = "Error occurred while loading the state file due to its unexpected format. " \ "Resetting the state file with the default format. Please try again." IMAP_MILLISECONDS_IN_A_DAY = 86400000 IMAP_NUMBER_OF_DAYS_BEFORE_ENDTIME = 10 IMAP_CONTENT_TYPE_MESSAGE = "message/rfc822" IMAP_DEFAULT_ARTIFACT_COUNT = 100 IMAP_DEFAULT_CONTAINER_COUNT = 100 MAX_COUNT_VALUE = 4294967295 DEFAULT_REQUEST_TIMEOUT = 30 # in seconds
imap_json_use_ssl = 'use_ssl' imap_json_date = 'date' imap_json_files = 'files' imap_json_bodies = 'bodies' imap_json_from = 'from' imap_json_mail = 'mail' imap_json_subject = 'subject' imap_json_to = 'to' imap_json_start_time = 'start_time' imap_json_extract_attachments = 'extract_attachments' imap_json_extract_urls = 'extract_urls' imap_json_extract_ips = 'extract_ips' imap_json_extract_domains = 'extract_domains' imap_json_extract_hashes = 'extract_hashes' imap_json_total_emails = 'total_emails' imap_json_ips = 'ips' imap_json_hashes = 'hashes' imap_json_urls = 'urls' imap_json_domains = 'domains' imap_json_email_addresses = 'email_addresses' imap_json_def_num_days = 'interval_days' imap_json_max_emails = 'max_emails' imap_json_first_run_max_emails = 'first_run_max_emails' imap_json_vault_ids = 'vault_ids' imap_json_ingest_manner = 'ingest_manner' imap_json_email_headers = 'email_headers' imap_json_folder = 'folder' imap_json_id = 'id' imap_json_container_id = 'container_id' imap_json_ingest_email = 'ingest_email' imap_ingest_latest_emails = 'latest first' imap_ingest_oldest_emails = 'oldest first' imap_connected_to_server = 'Initiated connection to server' imap_err_connecting_to_server = 'Error connecting to server' imap_err_listing_folders = 'Error listing folders' imap_err_logging_in_to_server = 'Error logging in to server' imap_err_selecting_folder = "Error selecting folder '{folder}'" imap_got_list_folders = 'Got folder listing' imap_logged_in = 'User logged in' imap_selected_folder = "Selected folder '{folder}'" imap_succ_connectivity_test = 'Connectivity test passed' imap_err_connectivity_test = 'Connectivity test failed' imap_err_end_time_lt_start_time = 'End time less than start time' imap_err_mailbox_search_failed = 'Mailbox search failed' imap_err_mailbox_search_failed_result = 'Mailbox search failed, result: {result} data: {data}' imap_fetch_id_failed = 'Fetch for uuid: {muuid} failed, reason: {excep}' imap_fetch_id_failed_result = 'Fetch for uuid: {muuid} failed, result: {result}, data: {data}' imap_validate_integer_message = 'Please provide a valid integer value in the {key} parameter' imap_err_code_message = 'Error code unavailable' imap_err_message = 'Unknown error occurred. Please check the asset configuration and|or action parameters' imap_exception_err_message = 'Error Code: {0}. Error Message: {1}' imap_required_param_oauth = 'ERROR: {0} is a required parameter for OAuth Authentication, please specify one.' imap_required_param_basic = 'ERROR: {0} is a required parameter for Basic Authentication, please specify one.' imap_general_err_message = '{}. Details: {}' imap_state_file_corrupt_err = 'Error occurred while loading the state file due to its unexpected format. Resetting the state file with the default format. Please try again.' imap_milliseconds_in_a_day = 86400000 imap_number_of_days_before_endtime = 10 imap_content_type_message = 'message/rfc822' imap_default_artifact_count = 100 imap_default_container_count = 100 max_count_value = 4294967295 default_request_timeout = 30
""" 1792. Maximum Average Pass Ratio Medium There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array classes, where classes[i] = [passi, totali]. You know beforehand that in the ith class, there are totali total students, but only passi number of students will pass the exam. You are also given an integer extraStudents. There are another extraStudents brilliant students that are guaranteed to pass the exam of any class they are assigned to. You want to assign each of the extraStudents students to a class in a way that maximizes the average pass ratio across all the classes. The pass ratio of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The average pass ratio is the sum of pass ratios of all the classes divided by the number of the classes. Return the maximum possible average pass ratio after assigning the extraStudents students. Answers within 10-5 of the actual answer will be accepted. Example 1: Input: classes = [[1,2],[3,5],[2,2]], extraStudents = 2 Output: 0.78333 Explanation: You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333. Example 2: Input: classes = [[2,4],[3,9],[4,5],[2,10]], extraStudents = 4 Output: 0.53485 Constraints: 1 <= classes.length <= 105 classes[i].length == 2 1 <= passi <= totali <= 105 1 <= extraStudents <= 105 """ class Solution: def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float: def profit(a, b): return (a + 1) / (b + 1) - a / b maxHeap = [] for a, b in classes: a, b = a * 1.0, b * 1.0 # Convert int to double maxHeap.append((-profit(a, b), a, b)) heapq.heapify(maxHeap) # Heapify maxHeap cost O(N) for _ in range(extraStudents): d, a, b = heapq.heappop(maxHeap) heapq.heappush(maxHeap, (-profit(a + 1, b + 1), a + 1, b + 1)) return mean(a / b for d, a, b in maxHeap)
""" 1792. Maximum Average Pass Ratio Medium There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array classes, where classes[i] = [passi, totali]. You know beforehand that in the ith class, there are totali total students, but only passi number of students will pass the exam. You are also given an integer extraStudents. There are another extraStudents brilliant students that are guaranteed to pass the exam of any class they are assigned to. You want to assign each of the extraStudents students to a class in a way that maximizes the average pass ratio across all the classes. The pass ratio of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The average pass ratio is the sum of pass ratios of all the classes divided by the number of the classes. Return the maximum possible average pass ratio after assigning the extraStudents students. Answers within 10-5 of the actual answer will be accepted. Example 1: Input: classes = [[1,2],[3,5],[2,2]], extraStudents = 2 Output: 0.78333 Explanation: You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333. Example 2: Input: classes = [[2,4],[3,9],[4,5],[2,10]], extraStudents = 4 Output: 0.53485 Constraints: 1 <= classes.length <= 105 classes[i].length == 2 1 <= passi <= totali <= 105 1 <= extraStudents <= 105 """ class Solution: def max_average_ratio(self, classes: List[List[int]], extraStudents: int) -> float: def profit(a, b): return (a + 1) / (b + 1) - a / b max_heap = [] for (a, b) in classes: (a, b) = (a * 1.0, b * 1.0) maxHeap.append((-profit(a, b), a, b)) heapq.heapify(maxHeap) for _ in range(extraStudents): (d, a, b) = heapq.heappop(maxHeap) heapq.heappush(maxHeap, (-profit(a + 1, b + 1), a + 1, b + 1)) return mean((a / b for (d, a, b) in maxHeap))
# The SavingsAccount class represents a # savings account. class SavingsAccount: # The __init__ method accepts arguments for the # account number, interest rate, and balance. def __init__(self, account_num, int_rate, bal): self.__account_num = account_num self.__interest_rate = int_rate self.__balance = bal # The following methods are mutators for the # data attributes. def set_account_num(self, account_num): self.__account_num = account_num def set_interest_rate(self, int_rate): self.__interest_rate = int_rate def set_balance(self, bal): self.__balance = bal # The following methods are accessors for the # data attributes. def get_account_num(self): return self.__account_num def get_interest_rate(self): return self.__interest_rate def get_balance(self): return self.__balance # The CD account represents a certificate of # deposit (CD) account. It is a subclass of # the SavingsAccount class. class CD(SavingsAccount): # The init method accepts arguments for the # account number, interest rate, balance, and # maturity date. def __init__(self, account_num, int_rate, bal, mat_date): # Call the superclass __init__ method. SavingsAccount.__init__(self, account_num, int_rate, bal) # Initialize the __maturity_date attribute. self.__maturity_date = mat_date # The set_maturity_date is a mutator for the # __maturity_date attribute. def set_maturity_date(self, mat_date): self.__maturity_date = mat_date # The get_maturity_date method is an accessor # for the __maturity_date attribute. def get_maturity_date(self): return self.__maturity_date
class Savingsaccount: def __init__(self, account_num, int_rate, bal): self.__account_num = account_num self.__interest_rate = int_rate self.__balance = bal def set_account_num(self, account_num): self.__account_num = account_num def set_interest_rate(self, int_rate): self.__interest_rate = int_rate def set_balance(self, bal): self.__balance = bal def get_account_num(self): return self.__account_num def get_interest_rate(self): return self.__interest_rate def get_balance(self): return self.__balance class Cd(SavingsAccount): def __init__(self, account_num, int_rate, bal, mat_date): SavingsAccount.__init__(self, account_num, int_rate, bal) self.__maturity_date = mat_date def set_maturity_date(self, mat_date): self.__maturity_date = mat_date def get_maturity_date(self): return self.__maturity_date
class memoize(object): """ Memoize wrapper for python Usage: @memoize def fib(n): pass """ def __init__(self, function): self.function = function self.memoized = {} def __call__(self, *args): try: return self.memoized[args] except KeyError: self.memoized[args] = self.function(*args) return self.memoized[args]
class Memoize(object): """ Memoize wrapper for python Usage: @memoize def fib(n): pass """ def __init__(self, function): self.function = function self.memoized = {} def __call__(self, *args): try: return self.memoized[args] except KeyError: self.memoized[args] = self.function(*args) return self.memoized[args]
with open("input_9.txt", "r") as f: lines = f.readlines() nums = [int(line.strip()) for line in lines] # for i, num in enumerate(nums[25:]): # preamble = set(nums[i:25 + i]) # found_pair = False # for prenum in preamble: # diff = num - prenum # if diff in preamble: # found_pair = True # break # if not found_pair: # print(num) # break invalid_num = 29221323 start_idx = 0 end_idx = -1 expand_upper = True # either expand the upper or the lower cur_sum = 0 while True: if expand_upper: end_idx += 1 cur_sum += nums[end_idx] else: cur_sum -= nums[start_idx] start_idx += 1 if cur_sum > invalid_num: expand_upper = False elif cur_sum < invalid_num: expand_upper = True else: break included_range = nums[start_idx : end_idx+1] ans = min(included_range) + max(included_range) print(ans)
with open('input_9.txt', 'r') as f: lines = f.readlines() nums = [int(line.strip()) for line in lines] invalid_num = 29221323 start_idx = 0 end_idx = -1 expand_upper = True cur_sum = 0 while True: if expand_upper: end_idx += 1 cur_sum += nums[end_idx] else: cur_sum -= nums[start_idx] start_idx += 1 if cur_sum > invalid_num: expand_upper = False elif cur_sum < invalid_num: expand_upper = True else: break included_range = nums[start_idx:end_idx + 1] ans = min(included_range) + max(included_range) print(ans)
__VERSION__ = "0.0.1" __AUTHOR__ = "helloqiu" __LICENSE__ = "MIT" __URL__ = "https://github.com/helloqiu/SillyServer"
__version__ = '0.0.1' __author__ = 'helloqiu' __license__ = 'MIT' __url__ = 'https://github.com/helloqiu/SillyServer'
""" Python solution for CCC '17 S1 - Sum Game """ n = int(input()) a = [int(i) for i in input().split()] b = [int(i) for i in input().split()] k = 0 a_sum = 0 b_sum = 0 for i in range(n): a_sum += a[i] b_sum += b[i] if a_sum == b_sum: k = i + 1 print(k)
""" Python solution for CCC '17 S1 - Sum Game """ n = int(input()) a = [int(i) for i in input().split()] b = [int(i) for i in input().split()] k = 0 a_sum = 0 b_sum = 0 for i in range(n): a_sum += a[i] b_sum += b[i] if a_sum == b_sum: k = i + 1 print(k)
""" Created by Chantal Worp, 24/01/2017 Solution to Problem Set 1 Introduction to Computer Science and Programming using Python (EDX) Problem Set 1: Assume s is a string of lower case characters. Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print Longest substring in alphabetical order is: beggh In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print Longest substring in alphabetical order is: abc """ s = input('Type a string: ') s = s.lower() #Variable 'overall_answer' will contain substring of strings in which the letters are in alphabetical order overall_answer = [] #Maximum number of outermost loops is determined by number of letters in s for letters in range(len(s)): search_string = s[letters:] #search_string slices s to ensure that every substring of s is investigated i = 0 # i is used as counter, set to zero in every outermost loop subanswer = "" #re-initialising subanswer subanswer += s[letters] #the first letter of every new subset is added to subanswer while i < (len(search_string)-1): #Innerloop, will loop as long as i is smaller than the number of letters in search_string minus 1 (to avoid index getting out of range) first_letter = search_string[i] # Determines first letter to be compared second_letter = search_string[i+1] # Determines second letter to be compared if first_letter <= second_letter: # If first letter is smaller than or equal to second letter, it means they are in alphabetical order subanswer += second_letter # second letter will be added to subanswer (first letter was already added) i += 1 # counter increases with 1 else: overall_answer.append(subanswer) # If first letter is greater than second letter, then they are not in alphabetical order. Second letter does not get added to subanswer break # subanswer gets added to list overall_answer and inner loop breaks, a new outerloop starts if i == (len(search_string)-1): # If counter i equals the length of search_string, then subanswer gets appended to overall_answer and a new outerloop starts overall_answer.append(subanswer) # after running the code above, overall_answer will be a list with substrings in alphabetical order # the answer is then the longest substring in list overall_answer ans = max(overall_answer, key=len) print("Longest substring in alphabetical order is: " + ans)
""" Created by Chantal Worp, 24/01/2017 Solution to Problem Set 1 Introduction to Computer Science and Programming using Python (EDX) Problem Set 1: Assume s is a string of lower case characters. Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print Longest substring in alphabetical order is: beggh In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print Longest substring in alphabetical order is: abc """ s = input('Type a string: ') s = s.lower() overall_answer = [] for letters in range(len(s)): search_string = s[letters:] i = 0 subanswer = '' subanswer += s[letters] while i < len(search_string) - 1: first_letter = search_string[i] second_letter = search_string[i + 1] if first_letter <= second_letter: subanswer += second_letter i += 1 else: overall_answer.append(subanswer) break if i == len(search_string) - 1: overall_answer.append(subanswer) ans = max(overall_answer, key=len) print('Longest substring in alphabetical order is: ' + ans)
# -*- coding: utf-8 -*- # # Copyright (c) 2021, SkyFoundry LLC # Licensed under the Academic Free License version 3.0 # # History: # 07 Dec 2021 Matthew Giannini Creation # class Ref: @staticmethod def make_handle(handle): time = (handle >> 32) & 0xffff_ffff rand = handle & 0xffff_ffff return Ref(f"{format(time, '08x')}-{format(rand, '08x')}") def __init__(self, id, dis=None): self._id = id self._dis = dis def id(self): return self._id def dis(self): return self._dis def __str__(self): return f'{self.id()}' def __eq__(self, other): if isinstance(other, Ref): return self.id() == other.id() return False # Ref
class Ref: @staticmethod def make_handle(handle): time = handle >> 32 & 4294967295 rand = handle & 4294967295 return ref(f"{format(time, '08x')}-{format(rand, '08x')}") def __init__(self, id, dis=None): self._id = id self._dis = dis def id(self): return self._id def dis(self): return self._dis def __str__(self): return f'{self.id()}' def __eq__(self, other): if isinstance(other, Ref): return self.id() == other.id() return False
class Solution: def getMaximumGenerated(self, n: int) -> int: if n < 2: return n ans = [None for _ in range(n + 1)] ans[0] = 0 ans[1] = 1 for i in range(1, n // 2 + 1): ans[2 * i] = ans[i] if 2 * i + 1 < n + 1: ans[2 * i + 1] = ans[i] + ans[i + 1] return max(ans)
class Solution: def get_maximum_generated(self, n: int) -> int: if n < 2: return n ans = [None for _ in range(n + 1)] ans[0] = 0 ans[1] = 1 for i in range(1, n // 2 + 1): ans[2 * i] = ans[i] if 2 * i + 1 < n + 1: ans[2 * i + 1] = ans[i] + ans[i + 1] return max(ans)
echo = "echo" gcc = "gcc" gpp = "g++" emcc = "emcc" empp = "em++" cl = "cl" clang = "clang" clangpp = "clang++"
echo = 'echo' gcc = 'gcc' gpp = 'g++' emcc = 'emcc' empp = 'em++' cl = 'cl' clang = 'clang' clangpp = 'clang++'
# Accept the marks of 5 subjects m1 = input(" Enter the Marks of first subject: ") m2 = input(" Enter the Marks of second subject: ") m3 = input(" Enter the Marks of third subject: ") m4 = input(" Enter the Marks of forth subject: ") m5 = input(" Enter the Marks of fifth subject: ") # Total Marks Total = int(m1)+int(m2)+int(m3)+int(m4)+int(m5) #Percentage: Percentage = (Total/500)*100 #Print the Answer print(' Percentage is {0} %'.format(Percentage))
m1 = input(' Enter the Marks of first subject: ') m2 = input(' Enter the Marks of second subject: ') m3 = input(' Enter the Marks of third subject: ') m4 = input(' Enter the Marks of forth subject: ') m5 = input(' Enter the Marks of fifth subject: ') total = int(m1) + int(m2) + int(m3) + int(m4) + int(m5) percentage = Total / 500 * 100 print(' Percentage is {0} %'.format(Percentage))
h = int(input()) w = int(input()) no_paint = int(input()) litres_paint = input() space = round((h * w * 4) * ((100 - no_paint) / 100)) while not litres_paint == "Tired!": space -= int(litres_paint) if space <= 0: break litres_paint = input() if space < 0: print(f"All walls are painted and you have {abs(space)} l paint left!") elif space == 0: print(f"All walls are painted! Great job, Pesho!") else: print(f"{space} quadratic m left.") # 2 # 3 # 25 # 6 # 7 # 8 # 2 # 3 # 25 # 6 # 7 # 5 # 2 # 3 # 0 # 6 # 7 # 5 # 6 # 2 # 3 # 25 # 17 # Tired!
h = int(input()) w = int(input()) no_paint = int(input()) litres_paint = input() space = round(h * w * 4 * ((100 - no_paint) / 100)) while not litres_paint == 'Tired!': space -= int(litres_paint) if space <= 0: break litres_paint = input() if space < 0: print(f'All walls are painted and you have {abs(space)} l paint left!') elif space == 0: print(f'All walls are painted! Great job, Pesho!') else: print(f'{space} quadratic m left.')
media_stats = { 'type': 'object', 'properties': { 'count': {'type': 'integer', 'minimum': 0}, 'download_size': {'type': 'integer', 'minimum': 0}, 'total_size': {'type': 'integer', 'minimum': 0}, 'duration': {'type': 'number', 'minimum': 0}, }, }
media_stats = {'type': 'object', 'properties': {'count': {'type': 'integer', 'minimum': 0}, 'download_size': {'type': 'integer', 'minimum': 0}, 'total_size': {'type': 'integer', 'minimum': 0}, 'duration': {'type': 'number', 'minimum': 0}}}
#!/usr/bin/env python3 # # vsim_defines.py # Francesco Conti <f.conti@unibo.it> # # Copyright (C) 2015-2017 ETH Zurich, University of Bologna # All rights reserved. # # This software may be modified and distributed under the terms # of the BSD license. See the LICENSE file for details. # # templates for vcompile.csh scripts VSIM_PREAMBLE = """#!/bin/tcsh source ${PULP_PATH}/%s/vcompile/setup.csh ############################################################################## # Settings ############################################################################## set IP=%s ############################################################################## # Check settings ############################################################################## # check if environment variables are defined if (! $?MSIM_LIBS_PATH ) then echo "${Red} MSIM_LIBS_PATH is not defined ${NC}" exit 1 endif if (! $?IPS_PATH ) then echo "${Red} IPS_PATH is not defined ${NC}" exit 1 endif set LIB_NAME="${IP}_lib" set LIB_PATH="${MSIM_LIBS_PATH}/${LIB_NAME}" set IP_PATH="${IPS_PATH}/%s" set RTL_PATH="${RTL_PATH}" ############################################################################## # Preparing library ############################################################################## echo "${Green}--> Compiling ${IP}... ${NC}" rm -rf $LIB_PATH vlib $LIB_PATH vmap $LIB_NAME $LIB_PATH ############################################################################## # Compiling RTL ############################################################################## """ VSIM_POSTAMBLE =""" echo "${Cyan}--> ${IP} compilation complete! ${NC}" exit 0 ############################################################################## # Error handler ############################################################################## error: echo "${NC}" exit 1 """ VSIM_PREAMBLE_SUBIP = """ echo "${Green}Compiling component: ${Brown} %s ${NC}" echo "${Red}" """ VSIM_VLOG_INCDIR_CMD = "+incdir+" ## Add -suppress 2583 to remove warning about always_comb|ff wrapped with # generate struct that can be only checked after elaboration at vopt stage VSIM_VLOG_CMD = "vlog -quiet -sv -suppress 2583 -work ${LIB_PATH} %s %s %s || goto error\n" VSIM_VCOM_CMD = "vcom -quiet -suppress 2583 -work ${LIB_PATH} %s %s || goto error\n" # templates for vsim.tcl VSIM_TCL_PREAMBLE = """set VSIM_%s_LIBS " \\\ """ VSIM_TCL_CMD = " -L %s_lib \\\n" VSIM_TCL_POSTAMBLE = """" """ # templates for vcompile_libs.tc VCOMPILE_LIBS_PREAMBLE = """#!/usr/bin/tcsh echo \"\" echo \"${Green}--> Compiling PULP IPs libraries... ${NC}\" """ VCOMPILE_LIBS_CMD = "tcsh ${PULP_PATH}/%s/vcompile/ips/vcompile_%s.csh || exit 1\n" VCOMPILE_LIBS_XILINX_CMD = "tcsh ${PULP_PATH}/fpga/sim/vcompile/ips/vcompile_%s.csh || exit 1\n"
vsim_preamble = '#!/bin/tcsh\nsource ${PULP_PATH}/%s/vcompile/setup.csh\n\n##############################################################################\n# Settings\n##############################################################################\n\nset IP=%s\n\n##############################################################################\n# Check settings\n##############################################################################\n\n# check if environment variables are defined\nif (! $?MSIM_LIBS_PATH ) then\n echo "${Red} MSIM_LIBS_PATH is not defined ${NC}"\n exit 1\nendif\n\nif (! $?IPS_PATH ) then\n echo "${Red} IPS_PATH is not defined ${NC}"\n exit 1\nendif\n\nset LIB_NAME="${IP}_lib"\nset LIB_PATH="${MSIM_LIBS_PATH}/${LIB_NAME}"\nset IP_PATH="${IPS_PATH}/%s"\nset RTL_PATH="${RTL_PATH}"\n\n##############################################################################\n# Preparing library\n##############################################################################\n\necho "${Green}--> Compiling ${IP}... ${NC}"\n\nrm -rf $LIB_PATH\n\nvlib $LIB_PATH\nvmap $LIB_NAME $LIB_PATH\n\n##############################################################################\n# Compiling RTL\n##############################################################################\n' vsim_postamble = '\necho "${Cyan}--> ${IP} compilation complete! ${NC}"\nexit 0\n\n##############################################################################\n# Error handler\n##############################################################################\n\nerror:\necho "${NC}"\nexit 1\n' vsim_preamble_subip = '\necho "${Green}Compiling component: ${Brown} %s ${NC}"\necho "${Red}"\n' vsim_vlog_incdir_cmd = '+incdir+' vsim_vlog_cmd = 'vlog -quiet -sv -suppress 2583 -work ${LIB_PATH} %s %s %s || goto error\n' vsim_vcom_cmd = 'vcom -quiet -suppress 2583 -work ${LIB_PATH} %s %s || goto error\n' vsim_tcl_preamble = 'set VSIM_%s_LIBS " \\\n' vsim_tcl_cmd = ' -L %s_lib \\\n' vsim_tcl_postamble = '"\n' vcompile_libs_preamble = '#!/usr/bin/tcsh\n\necho ""\necho "${Green}--> Compiling PULP IPs libraries... ${NC}"\n' vcompile_libs_cmd = 'tcsh ${PULP_PATH}/%s/vcompile/ips/vcompile_%s.csh || exit 1\n' vcompile_libs_xilinx_cmd = 'tcsh ${PULP_PATH}/fpga/sim/vcompile/ips/vcompile_%s.csh || exit 1\n'
class Solution: # my solution def numPairsDivisibleBy60(self, time: List[int]) -> int: dct = {} res = 0 for i, n in enumerate(time): dct[n % 60] = dct.get(n%60, []) + [i] print(dct) for left in dct.keys(): if left % 60 == 0 or left % 60 == 30: res += len(dct[left]) * (len(dct[left])-1) / 2 elif 60 - left in dct.keys(): res += len(dct[left]) * len(dct[60-left]) / 2 return int(res) # optimal solution # https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/642553/Python-O(n)-with-simple-math-explanation ''' 1. We are given that (a+b) % c = (a%c + b%c) % c = 0 2. So, (a%c + b%c) = n*c where n is an integer multiple. 3. We know that (a%c + b%c) has max of c-1 + c-1 = 2c - 2 < 2c 4. But rhs says it has to be an integer multiple of c, and we are bounded by the fact that this has to be less than 2. so only option is either 0 or 1 (no negative cuz song durations arent negative) 5. So given a, we look for b%c = n*c - a%c, where n = 0 or 1. 6. Can do this easily with hashmap, for each number a, take modulo of it, look for that in the hashmap where it maps number of occurance of b%c. 7. Update answer and the hashmap accordingly. ''' def numPairsDivisibleBy60(self, time: List[int]) -> int: res = 0 dct = {} for t in time: t_mod = t % 60 find = 0 if t_mod == 0 else 60 - t_mod res += dct.get(find, 0) dct[t_mod] = dct.get(t_mod, 0) + 1 return res
class Solution: def num_pairs_divisible_by60(self, time: List[int]) -> int: dct = {} res = 0 for (i, n) in enumerate(time): dct[n % 60] = dct.get(n % 60, []) + [i] print(dct) for left in dct.keys(): if left % 60 == 0 or left % 60 == 30: res += len(dct[left]) * (len(dct[left]) - 1) / 2 elif 60 - left in dct.keys(): res += len(dct[left]) * len(dct[60 - left]) / 2 return int(res) '\n 1. We are given that (a+b) % c = (a%c + b%c) % c = 0\n 2. So, (a%c + b%c) = n*c where n is an integer multiple.\n 3. We know that (a%c + b%c) has max of c-1 + c-1 = 2c - 2 < 2c\n 4. But rhs says it has to be an integer multiple of c, and we are bounded by the fact that this has to be less than 2. so only option is either 0 or 1 (no negative cuz song durations arent negative)\n 5. So given a, we look for b%c = n*c - a%c, where n = 0 or 1.\n 6. Can do this easily with hashmap, for each number a, take modulo of it, look for that in the hashmap where it maps number of occurance of b%c.\n 7. Update answer and the hashmap accordingly.\n ' def num_pairs_divisible_by60(self, time: List[int]) -> int: res = 0 dct = {} for t in time: t_mod = t % 60 find = 0 if t_mod == 0 else 60 - t_mod res += dct.get(find, 0) dct[t_mod] = dct.get(t_mod, 0) + 1 return res
def glyphs(): return 96 _font =\ b'\x00\x4a\x5a\x08\x4d\x57\x52\x46\x52\x54\x20\x52\x52\x59\x51'\ b'\x5a\x52\x5b\x53\x5a\x52\x59\x05\x4a\x5a\x4e\x46\x4e\x4d\x20'\ b'\x52\x56\x46\x56\x4d\x0b\x48\x5d\x53\x42\x4c\x62\x20\x52\x59'\ b'\x42\x52\x62\x20\x52\x4c\x4f\x5a\x4f\x20\x52\x4b\x55\x59\x55'\ b'\x1a\x48\x5c\x50\x42\x50\x5f\x20\x52\x54\x42\x54\x5f\x20\x52'\ b'\x59\x49\x57\x47\x54\x46\x50\x46\x4d\x47\x4b\x49\x4b\x4b\x4c'\ b'\x4d\x4d\x4e\x4f\x4f\x55\x51\x57\x52\x58\x53\x59\x55\x59\x58'\ b'\x57\x5a\x54\x5b\x50\x5b\x4d\x5a\x4b\x58\x1f\x46\x5e\x5b\x46'\ b'\x49\x5b\x20\x52\x4e\x46\x50\x48\x50\x4a\x4f\x4c\x4d\x4d\x4b'\ b'\x4d\x49\x4b\x49\x49\x4a\x47\x4c\x46\x4e\x46\x50\x47\x53\x48'\ b'\x56\x48\x59\x47\x5b\x46\x20\x52\x57\x54\x55\x55\x54\x57\x54'\ b'\x59\x56\x5b\x58\x5b\x5a\x5a\x5b\x58\x5b\x56\x59\x54\x57\x54'\ b'\x22\x45\x5f\x5c\x4f\x5c\x4e\x5b\x4d\x5a\x4d\x59\x4e\x58\x50'\ b'\x56\x55\x54\x58\x52\x5a\x50\x5b\x4c\x5b\x4a\x5a\x49\x59\x48'\ b'\x57\x48\x55\x49\x53\x4a\x52\x51\x4e\x52\x4d\x53\x4b\x53\x49'\ b'\x52\x47\x50\x46\x4e\x47\x4d\x49\x4d\x4b\x4e\x4e\x50\x51\x55'\ b'\x58\x57\x5a\x59\x5b\x5b\x5b\x5c\x5a\x5c\x59\x07\x4d\x57\x52'\ b'\x48\x51\x47\x52\x46\x53\x47\x53\x49\x52\x4b\x51\x4c\x0a\x4b'\ b'\x59\x56\x42\x54\x44\x52\x47\x50\x4b\x4f\x50\x4f\x54\x50\x59'\ b'\x52\x5d\x54\x60\x56\x62\x0a\x4b\x59\x4e\x42\x50\x44\x52\x47'\ b'\x54\x4b\x55\x50\x55\x54\x54\x59\x52\x5d\x50\x60\x4e\x62\x08'\ b'\x4a\x5a\x52\x4c\x52\x58\x20\x52\x4d\x4f\x57\x55\x20\x52\x57'\ b'\x4f\x4d\x55\x05\x45\x5f\x52\x49\x52\x5b\x20\x52\x49\x52\x5b'\ b'\x52\x07\x4e\x56\x53\x57\x52\x58\x51\x57\x52\x56\x53\x57\x53'\ b'\x59\x51\x5b\x02\x45\x5f\x49\x52\x5b\x52\x05\x4e\x56\x52\x56'\ b'\x51\x57\x52\x58\x53\x57\x52\x56\x02\x47\x5d\x5b\x42\x49\x62'\ b'\x11\x48\x5c\x51\x46\x4e\x47\x4c\x4a\x4b\x4f\x4b\x52\x4c\x57'\ b'\x4e\x5a\x51\x5b\x53\x5b\x56\x5a\x58\x57\x59\x52\x59\x4f\x58'\ b'\x4a\x56\x47\x53\x46\x51\x46\x04\x48\x5c\x4e\x4a\x50\x49\x53'\ b'\x46\x53\x5b\x0e\x48\x5c\x4c\x4b\x4c\x4a\x4d\x48\x4e\x47\x50'\ b'\x46\x54\x46\x56\x47\x57\x48\x58\x4a\x58\x4c\x57\x4e\x55\x51'\ b'\x4b\x5b\x59\x5b\x0f\x48\x5c\x4d\x46\x58\x46\x52\x4e\x55\x4e'\ b'\x57\x4f\x58\x50\x59\x53\x59\x55\x58\x58\x56\x5a\x53\x5b\x50'\ b'\x5b\x4d\x5a\x4c\x59\x4b\x57\x06\x48\x5c\x55\x46\x4b\x54\x5a'\ b'\x54\x20\x52\x55\x46\x55\x5b\x11\x48\x5c\x57\x46\x4d\x46\x4c'\ b'\x4f\x4d\x4e\x50\x4d\x53\x4d\x56\x4e\x58\x50\x59\x53\x59\x55'\ b'\x58\x58\x56\x5a\x53\x5b\x50\x5b\x4d\x5a\x4c\x59\x4b\x57\x17'\ b'\x48\x5c\x58\x49\x57\x47\x54\x46\x52\x46\x4f\x47\x4d\x4a\x4c'\ b'\x4f\x4c\x54\x4d\x58\x4f\x5a\x52\x5b\x53\x5b\x56\x5a\x58\x58'\ b'\x59\x55\x59\x54\x58\x51\x56\x4f\x53\x4e\x52\x4e\x4f\x4f\x4d'\ b'\x51\x4c\x54\x05\x48\x5c\x59\x46\x4f\x5b\x20\x52\x4b\x46\x59'\ b'\x46\x1d\x48\x5c\x50\x46\x4d\x47\x4c\x49\x4c\x4b\x4d\x4d\x4f'\ b'\x4e\x53\x4f\x56\x50\x58\x52\x59\x54\x59\x57\x58\x59\x57\x5a'\ b'\x54\x5b\x50\x5b\x4d\x5a\x4c\x59\x4b\x57\x4b\x54\x4c\x52\x4e'\ b'\x50\x51\x4f\x55\x4e\x57\x4d\x58\x4b\x58\x49\x57\x47\x54\x46'\ b'\x50\x46\x17\x48\x5c\x58\x4d\x57\x50\x55\x52\x52\x53\x51\x53'\ b'\x4e\x52\x4c\x50\x4b\x4d\x4b\x4c\x4c\x49\x4e\x47\x51\x46\x52'\ b'\x46\x55\x47\x57\x49\x58\x4d\x58\x52\x57\x57\x55\x5a\x52\x5b'\ b'\x50\x5b\x4d\x5a\x4c\x58\x0b\x4e\x56\x52\x4f\x51\x50\x52\x51'\ b'\x53\x50\x52\x4f\x20\x52\x52\x56\x51\x57\x52\x58\x53\x57\x52'\ b'\x56\x0d\x4e\x56\x52\x4f\x51\x50\x52\x51\x53\x50\x52\x4f\x20'\ b'\x52\x53\x57\x52\x58\x51\x57\x52\x56\x53\x57\x53\x59\x51\x5b'\ b'\x03\x46\x5e\x5a\x49\x4a\x52\x5a\x5b\x05\x45\x5f\x49\x4f\x5b'\ b'\x4f\x20\x52\x49\x55\x5b\x55\x03\x46\x5e\x4a\x49\x5a\x52\x4a'\ b'\x5b\x14\x49\x5b\x4c\x4b\x4c\x4a\x4d\x48\x4e\x47\x50\x46\x54'\ b'\x46\x56\x47\x57\x48\x58\x4a\x58\x4c\x57\x4e\x56\x4f\x52\x51'\ b'\x52\x54\x20\x52\x52\x59\x51\x5a\x52\x5b\x53\x5a\x52\x59\x37'\ b'\x45\x60\x57\x4e\x56\x4c\x54\x4b\x51\x4b\x4f\x4c\x4e\x4d\x4d'\ b'\x50\x4d\x53\x4e\x55\x50\x56\x53\x56\x55\x55\x56\x53\x20\x52'\ b'\x51\x4b\x4f\x4d\x4e\x50\x4e\x53\x4f\x55\x50\x56\x20\x52\x57'\ b'\x4b\x56\x53\x56\x55\x58\x56\x5a\x56\x5c\x54\x5d\x51\x5d\x4f'\ b'\x5c\x4c\x5b\x4a\x59\x48\x57\x47\x54\x46\x51\x46\x4e\x47\x4c'\ b'\x48\x4a\x4a\x49\x4c\x48\x4f\x48\x52\x49\x55\x4a\x57\x4c\x59'\ b'\x4e\x5a\x51\x5b\x54\x5b\x57\x5a\x59\x59\x5a\x58\x20\x52\x58'\ b'\x4b\x57\x53\x57\x55\x58\x56\x08\x49\x5b\x52\x46\x4a\x5b\x20'\ b'\x52\x52\x46\x5a\x5b\x20\x52\x4d\x54\x57\x54\x17\x47\x5c\x4b'\ b'\x46\x4b\x5b\x20\x52\x4b\x46\x54\x46\x57\x47\x58\x48\x59\x4a'\ b'\x59\x4c\x58\x4e\x57\x4f\x54\x50\x20\x52\x4b\x50\x54\x50\x57'\ b'\x51\x58\x52\x59\x54\x59\x57\x58\x59\x57\x5a\x54\x5b\x4b\x5b'\ b'\x05\x48\x5c\x4b\x46\x59\x5b\x20\x52\x4b\x5b\x59\x46\x08\x49'\ b'\x5b\x52\x46\x4a\x5b\x20\x52\x52\x46\x5a\x5b\x20\x52\x4a\x5b'\ b'\x5a\x5b\x0b\x48\x5b\x4c\x46\x4c\x5b\x20\x52\x4c\x46\x59\x46'\ b'\x20\x52\x4c\x50\x54\x50\x20\x52\x4c\x5b\x59\x5b\x14\x48\x5c'\ b'\x52\x46\x52\x5b\x20\x52\x50\x4b\x4d\x4c\x4c\x4d\x4b\x4f\x4b'\ b'\x52\x4c\x54\x4d\x55\x50\x56\x54\x56\x57\x55\x58\x54\x59\x52'\ b'\x59\x4f\x58\x4d\x57\x4c\x54\x4b\x50\x4b\x05\x48\x59\x4c\x46'\ b'\x4c\x5b\x20\x52\x4c\x46\x58\x46\x08\x47\x5d\x4b\x46\x4b\x5b'\ b'\x20\x52\x59\x46\x59\x5b\x20\x52\x4b\x50\x59\x50\x02\x4e\x56'\ b'\x52\x46\x52\x5b\x05\x50\x55\x52\x51\x52\x52\x53\x52\x53\x51'\ b'\x52\x51\x08\x47\x5c\x4b\x46\x4b\x5b\x20\x52\x59\x46\x4b\x54'\ b'\x20\x52\x50\x4f\x59\x5b\x05\x49\x5b\x52\x46\x4a\x5b\x20\x52'\ b'\x52\x46\x5a\x5b\x0b\x46\x5e\x4a\x46\x4a\x5b\x20\x52\x4a\x46'\ b'\x52\x5b\x20\x52\x5a\x46\x52\x5b\x20\x52\x5a\x46\x5a\x5b\x08'\ b'\x47\x5d\x4b\x46\x4b\x5b\x20\x52\x4b\x46\x59\x5b\x20\x52\x59'\ b'\x46\x59\x5b\x15\x47\x5d\x50\x46\x4e\x47\x4c\x49\x4b\x4b\x4a'\ b'\x4e\x4a\x53\x4b\x56\x4c\x58\x4e\x5a\x50\x5b\x54\x5b\x56\x5a'\ b'\x58\x58\x59\x56\x5a\x53\x5a\x4e\x59\x4b\x58\x49\x56\x47\x54'\ b'\x46\x50\x46\x08\x47\x5d\x4b\x46\x4b\x5b\x20\x52\x59\x46\x59'\ b'\x5b\x20\x52\x4b\x46\x59\x46\x18\x47\x5d\x50\x46\x4e\x47\x4c'\ b'\x49\x4b\x4b\x4a\x4e\x4a\x53\x4b\x56\x4c\x58\x4e\x5a\x50\x5b'\ b'\x54\x5b\x56\x5a\x58\x58\x59\x56\x5a\x53\x5a\x4e\x59\x4b\x58'\ b'\x49\x56\x47\x54\x46\x50\x46\x20\x52\x4f\x50\x55\x50\x0d\x47'\ b'\x5c\x4b\x46\x4b\x5b\x20\x52\x4b\x46\x54\x46\x57\x47\x58\x48'\ b'\x59\x4a\x59\x4d\x58\x4f\x57\x50\x54\x51\x4b\x51\x09\x49\x5b'\ b'\x4b\x46\x52\x50\x4b\x5b\x20\x52\x4b\x46\x59\x46\x20\x52\x4b'\ b'\x5b\x59\x5b\x05\x4a\x5a\x52\x46\x52\x5b\x20\x52\x4b\x46\x59'\ b'\x46\x12\x49\x5b\x4b\x4b\x4b\x49\x4c\x47\x4d\x46\x4f\x46\x50'\ b'\x47\x51\x49\x52\x4d\x52\x5b\x20\x52\x59\x4b\x59\x49\x58\x47'\ b'\x57\x46\x55\x46\x54\x47\x53\x49\x52\x4d\x0d\x4b\x59\x51\x46'\ b'\x4f\x47\x4e\x49\x4e\x4b\x4f\x4d\x51\x4e\x53\x4e\x55\x4d\x56'\ b'\x4b\x56\x49\x55\x47\x53\x46\x51\x46\x10\x48\x5c\x4b\x5b\x4f'\ b'\x5b\x4c\x54\x4b\x50\x4b\x4c\x4c\x49\x4e\x47\x51\x46\x53\x46'\ b'\x56\x47\x58\x49\x59\x4c\x59\x50\x58\x54\x55\x5b\x59\x5b\x08'\ b'\x49\x5b\x4b\x46\x59\x46\x20\x52\x4f\x50\x55\x50\x20\x52\x4b'\ b'\x5b\x59\x5b\x11\x47\x5d\x52\x46\x52\x5b\x20\x52\x49\x4c\x4a'\ b'\x4c\x4b\x4d\x4c\x51\x4d\x53\x4e\x54\x51\x55\x53\x55\x56\x54'\ b'\x57\x53\x58\x51\x59\x4d\x5a\x4c\x5b\x4c\x08\x48\x5c\x59\x46'\ b'\x4b\x5b\x20\x52\x4b\x46\x59\x46\x20\x52\x4b\x5b\x59\x5b\x0b'\ b'\x4b\x59\x4f\x42\x4f\x62\x20\x52\x50\x42\x50\x62\x20\x52\x4f'\ b'\x42\x56\x42\x20\x52\x4f\x62\x56\x62\x02\x4b\x59\x4b\x46\x59'\ b'\x5e\x0b\x4b\x59\x54\x42\x54\x62\x20\x52\x55\x42\x55\x62\x20'\ b'\x52\x4e\x42\x55\x42\x20\x52\x4e\x62\x55\x62\x05\x4a\x5a\x52'\ b'\x44\x4a\x52\x20\x52\x52\x44\x5a\x52\x02\x49\x5b\x49\x62\x5b'\ b'\x62\x07\x4e\x56\x53\x4b\x51\x4d\x51\x4f\x52\x50\x53\x4f\x52'\ b'\x4e\x51\x4f\x17\x48\x5d\x51\x4d\x4f\x4e\x4d\x50\x4c\x52\x4b'\ b'\x55\x4b\x58\x4c\x5a\x4e\x5b\x50\x5b\x52\x5a\x55\x57\x57\x54'\ b'\x59\x50\x5a\x4d\x20\x52\x51\x4d\x53\x4d\x54\x4e\x55\x50\x57'\ b'\x58\x58\x5a\x59\x5b\x5a\x5b\x1e\x49\x5c\x55\x46\x53\x47\x51'\ b'\x49\x4f\x4d\x4e\x50\x4d\x54\x4c\x5a\x4b\x62\x20\x52\x55\x46'\ b'\x57\x46\x59\x48\x59\x4b\x58\x4d\x57\x4e\x55\x4f\x52\x4f\x20'\ b'\x52\x52\x4f\x54\x50\x56\x52\x57\x54\x57\x57\x56\x59\x55\x5a'\ b'\x53\x5b\x51\x5b\x4f\x5a\x4e\x59\x4d\x56\x0d\x49\x5b\x4b\x4d'\ b'\x4d\x4d\x4f\x4f\x55\x60\x57\x62\x59\x62\x20\x52\x5a\x4d\x59'\ b'\x4f\x57\x52\x4d\x5d\x4b\x60\x4a\x62\x17\x49\x5b\x54\x4d\x51'\ b'\x4d\x4f\x4e\x4d\x50\x4c\x53\x4c\x56\x4d\x59\x4e\x5a\x50\x5b'\ b'\x52\x5b\x54\x5a\x56\x58\x57\x55\x57\x52\x56\x4f\x54\x4d\x52'\ b'\x4b\x51\x49\x51\x47\x52\x46\x54\x46\x56\x47\x58\x49\x12\x4a'\ b'\x5a\x57\x4f\x56\x4e\x54\x4d\x51\x4d\x4f\x4e\x4f\x50\x50\x52'\ b'\x53\x53\x20\x52\x53\x53\x4f\x54\x4d\x56\x4d\x58\x4e\x5a\x50'\ b'\x5b\x53\x5b\x55\x5a\x57\x58\x14\x47\x5d\x4f\x4e\x4d\x4f\x4b'\ b'\x51\x4a\x54\x4a\x57\x4b\x59\x4c\x5a\x4e\x5b\x51\x5b\x54\x5a'\ b'\x57\x58\x59\x55\x5a\x52\x5a\x4f\x58\x4d\x56\x4d\x54\x4f\x52'\ b'\x53\x50\x58\x4d\x62\x10\x49\x5c\x4a\x50\x4c\x4e\x4e\x4d\x4f'\ b'\x4d\x51\x4e\x52\x4f\x53\x52\x53\x56\x52\x5b\x20\x52\x5a\x4d'\ b'\x59\x50\x58\x52\x52\x5b\x50\x5f\x4f\x62\x12\x48\x5c\x49\x51'\ b'\x4a\x4f\x4c\x4d\x4e\x4d\x4f\x4e\x4f\x50\x4e\x54\x4c\x5b\x20'\ b'\x52\x4e\x54\x50\x50\x52\x4e\x54\x4d\x56\x4d\x58\x4f\x58\x52'\ b'\x57\x57\x54\x62\x08\x4c\x57\x52\x4d\x50\x54\x4f\x58\x4f\x5a'\ b'\x50\x5b\x52\x5b\x54\x59\x55\x57\x05\x47\x5d\x4b\x4b\x59\x59'\ b'\x20\x52\x59\x4b\x4b\x59\x12\x49\x5b\x4f\x4d\x4b\x5b\x20\x52'\ b'\x59\x4e\x58\x4d\x57\x4d\x55\x4e\x51\x52\x4f\x53\x4e\x53\x20'\ b'\x52\x4e\x53\x50\x54\x51\x55\x53\x5a\x54\x5b\x55\x5b\x56\x5a'\ b'\x08\x4a\x5a\x4b\x46\x4d\x46\x4f\x47\x50\x48\x58\x5b\x20\x52'\ b'\x52\x4d\x4c\x5b\x14\x48\x5d\x4f\x4d\x49\x62\x20\x52\x4e\x51'\ b'\x4d\x56\x4d\x59\x4f\x5b\x51\x5b\x53\x5a\x55\x58\x57\x54\x20'\ b'\x52\x59\x4d\x57\x54\x56\x58\x56\x5a\x57\x5b\x59\x5b\x5b\x59'\ b'\x5c\x57\x0d\x49\x5b\x4c\x4d\x4f\x4d\x4e\x53\x4d\x58\x4c\x5b'\ b'\x20\x52\x59\x4d\x58\x50\x57\x52\x55\x55\x52\x58\x4f\x5a\x4c'\ b'\x5b\x11\x4a\x5b\x52\x4d\x50\x4e\x4e\x50\x4d\x53\x4d\x56\x4e'\ b'\x59\x4f\x5a\x51\x5b\x53\x5b\x55\x5a\x57\x58\x58\x55\x58\x52'\ b'\x57\x4f\x56\x4e\x54\x4d\x52\x4d\x0c\x47\x5d\x50\x4d\x4c\x5b'\ b'\x20\x52\x55\x4d\x56\x53\x57\x58\x58\x5b\x20\x52\x49\x50\x4b'\ b'\x4e\x4e\x4d\x5b\x4d\x1a\x47\x5c\x48\x51\x49\x4f\x4b\x4d\x4d'\ b'\x4d\x4e\x4e\x4e\x50\x4d\x55\x4d\x58\x4e\x5a\x4f\x5b\x51\x5b'\ b'\x53\x5a\x55\x57\x56\x55\x57\x52\x58\x4d\x58\x4a\x57\x47\x55'\ b'\x46\x53\x46\x52\x48\x52\x4a\x53\x4d\x55\x50\x57\x52\x5a\x54'\ b'\x12\x49\x5b\x4d\x53\x4d\x56\x4e\x59\x4f\x5a\x51\x5b\x53\x5b'\ b'\x55\x5a\x57\x58\x58\x55\x58\x52\x57\x4f\x56\x4e\x54\x4d\x52'\ b'\x4d\x50\x4e\x4e\x50\x4d\x53\x49\x62\x11\x49\x5d\x5b\x4d\x51'\ b'\x4d\x4f\x4e\x4d\x50\x4c\x53\x4c\x56\x4d\x59\x4e\x5a\x50\x5b'\ b'\x52\x5b\x54\x5a\x56\x58\x57\x55\x57\x52\x56\x4f\x55\x4e\x53'\ b'\x4d\x07\x48\x5c\x53\x4d\x50\x5b\x20\x52\x4a\x50\x4c\x4e\x4f'\ b'\x4d\x5a\x4d\x0f\x48\x5c\x49\x51\x4a\x4f\x4c\x4d\x4e\x4d\x4f'\ b'\x4e\x4f\x50\x4d\x56\x4d\x59\x4f\x5b\x51\x5b\x54\x5a\x56\x58'\ b'\x58\x54\x59\x50\x59\x4d\x0e\x45\x5f\x52\x49\x51\x4a\x52\x4b'\ b'\x53\x4a\x52\x49\x20\x52\x49\x52\x5b\x52\x20\x52\x52\x59\x51'\ b'\x5a\x52\x5b\x53\x5a\x52\x59\x16\x46\x5d\x4e\x4d\x4c\x4e\x4a'\ b'\x51\x49\x54\x49\x57\x4a\x5a\x4b\x5b\x4d\x5b\x4f\x5a\x51\x57'\ b'\x20\x52\x52\x53\x51\x57\x52\x5a\x53\x5b\x55\x5b\x57\x5a\x59'\ b'\x57\x5a\x54\x5a\x51\x59\x4e\x58\x4d\x1c\x4a\x5a\x54\x46\x52'\ b'\x47\x51\x48\x51\x49\x52\x4a\x55\x4b\x58\x4b\x20\x52\x55\x4b'\ b'\x52\x4c\x50\x4d\x4f\x4f\x4f\x51\x51\x53\x54\x54\x56\x54\x20'\ b'\x52\x54\x54\x50\x55\x4e\x56\x4d\x58\x4d\x5a\x4f\x5c\x53\x5e'\ b'\x54\x5f\x54\x61\x52\x62\x50\x62\x13\x46\x5d\x56\x46\x4e\x62'\ b'\x20\x52\x47\x51\x48\x4f\x4a\x4d\x4c\x4d\x4d\x4e\x4d\x50\x4c'\ b'\x55\x4c\x58\x4d\x5a\x4f\x5b\x51\x5b\x54\x5a\x56\x58\x58\x55'\ b'\x5a\x50\x5b\x4d\x16\x4a\x59\x54\x46\x52\x47\x51\x48\x51\x49'\ b'\x52\x4a\x55\x4b\x58\x4b\x20\x52\x58\x4b\x54\x4d\x51\x4f\x4e'\ b'\x52\x4d\x55\x4d\x57\x4e\x59\x50\x5b\x53\x5d\x54\x5f\x54\x61'\ b'\x53\x62\x51\x62\x50\x60\x27\x4b\x59\x54\x42\x52\x43\x51\x44'\ b'\x50\x46\x50\x48\x51\x4a\x52\x4b\x53\x4d\x53\x4f\x51\x51\x20'\ b'\x52\x52\x43\x51\x45\x51\x47\x52\x49\x53\x4a\x54\x4c\x54\x4e'\ b'\x53\x50\x4f\x52\x53\x54\x54\x56\x54\x58\x53\x5a\x52\x5b\x51'\ b'\x5d\x51\x5f\x52\x61\x20\x52\x51\x53\x53\x55\x53\x57\x52\x59'\ b'\x51\x5a\x50\x5c\x50\x5e\x51\x60\x52\x61\x54\x62\x02\x4e\x56'\ b'\x52\x42\x52\x62\x27\x4b\x59\x50\x42\x52\x43\x53\x44\x54\x46'\ b'\x54\x48\x53\x4a\x52\x4b\x51\x4d\x51\x4f\x53\x51\x20\x52\x52'\ b'\x43\x53\x45\x53\x47\x52\x49\x51\x4a\x50\x4c\x50\x4e\x51\x50'\ b'\x55\x52\x51\x54\x50\x56\x50\x58\x51\x5a\x52\x5b\x53\x5d\x53'\ b'\x5f\x52\x61\x20\x52\x53\x53\x51\x55\x51\x57\x52\x59\x53\x5a'\ b'\x54\x5c\x54\x5e\x53\x60\x52\x61\x50\x62\x17\x46\x5e\x49\x55'\ b'\x49\x53\x4a\x50\x4c\x4f\x4e\x4f\x50\x50\x54\x53\x56\x54\x58'\ b'\x54\x5a\x53\x5b\x51\x20\x52\x49\x53\x4a\x51\x4c\x50\x4e\x50'\ b'\x50\x51\x54\x54\x56\x55\x58\x55\x5a\x54\x5b\x51\x5b\x4f\x22'\ b'\x4a\x5a\x4a\x46\x4a\x5b\x4b\x5b\x4b\x46\x4c\x46\x4c\x5b\x4d'\ b'\x5b\x4d\x46\x4e\x46\x4e\x5b\x4f\x5b\x4f\x46\x50\x46\x50\x5b'\ b'\x51\x5b\x51\x46\x52\x46\x52\x5b\x53\x5b\x53\x46\x54\x46\x54'\ b'\x5b\x55\x5b\x55\x46\x56\x46\x56\x5b\x57\x5b\x57\x46\x58\x46'\ b'\x58\x5b\x59\x5b\x59\x46\x5a\x46\x5a\x5b' _index =\ b'\x00\x00\x03\x00\x16\x00\x23\x00\x3c\x00\x73\x00\xb4\x00\xfb'\ b'\x00\x0c\x01\x23\x01\x3a\x01\x4d\x01\x5a\x01\x6b\x01\x72\x01'\ b'\x7f\x01\x86\x01\xab\x01\xb6\x01\xd5\x01\xf6\x01\x05\x02\x2a'\ b'\x02\x5b\x02\x68\x02\xa5\x02\xd6\x02\xef\x02\x0c\x03\x15\x03'\ b'\x22\x03\x2b\x03\x56\x03\xc7\x03\xda\x03\x0b\x04\x18\x04\x2b'\ b'\x04\x44\x04\x6f\x04\x7c\x04\x8f\x04\x96\x04\xa3\x04\xb6\x04'\ b'\xc3\x04\xdc\x04\xef\x04\x1c\x05\x2f\x05\x62\x05\x7f\x05\x94'\ b'\x05\xa1\x05\xc8\x05\xe5\x05\x08\x06\x1b\x06\x40\x06\x53\x06'\ b'\x6c\x06\x73\x06\x8c\x06\x99\x06\xa0\x06\xb1\x06\xe2\x06\x21'\ b'\x07\x3e\x07\x6f\x07\x96\x07\xc1\x07\xe4\x07\x0b\x08\x1e\x08'\ b'\x2b\x08\x52\x08\x65\x08\x90\x08\xad\x08\xd2\x08\xed\x08\x24'\ b'\x09\x4b\x09\x70\x09\x81\x09\xa2\x09\xc1\x09\xf0\x09\x2b\x0a'\ b'\x54\x0a\x83\x0a\xd4\x0a\xdb\x0a\x2c\x0b\x5d\x0b' _mvfont = memoryview(_font) def _chr_addr(ordch): offset = 2 * (ordch - 32) return int.from_bytes(_index[offset:offset + 2], 'little') def get_ch(ordch): offset = _chr_addr(ordch if 32 <= ordch <= 127 else ord('?')) count = _font[offset] return _mvfont[offset:offset+(count+2)*2-1]
def glyphs(): return 96 _font = b'\x00JZ\x08MWRFRT RRYQZR[SZRY\x05JZNFNM RVFVM\x0bH]SBLb RYBRb RLOZO RKUYU\x1aH\\PBP_ RTBT_ RYIWGTFPFMGKIKKLMMNOOUQWRXSYUYXWZT[P[MZKX\x1fF^[FI[ RNFPHPJOLMMKMIKIIJGLFNFPGSHVHYG[F RWTUUTWTYV[X[ZZ[X[VYTWT"E_\\O\\N[MZMYNXPVUTXRZP[L[JZIYHWHUISJRQNRMSKSIRGPFNGMIMKNNPQUXWZY[[[\\Z\\Y\x07MWRHQGRFSGSIRKQL\nKYVBTDRGPKOPOTPYR]T`Vb\nKYNBPDRGTKUPUTTYR]P`Nb\x08JZRLRX RMOWU RWOMU\x05E_RIR[ RIR[R\x07NVSWRXQWRVSWSYQ[\x02E_IR[R\x05NVRVQWRXSWRV\x02G][BIb\x11H\\QFNGLJKOKRLWNZQ[S[VZXWYRYOXJVGSFQF\x04H\\NJPISFS[\x0eH\\LKLJMHNGPFTFVGWHXJXLWNUQK[Y[\x0fH\\MFXFRNUNWOXPYSYUXXVZS[P[MZLYKW\x06H\\UFKTZT RUFU[\x11H\\WFMFLOMNPMSMVNXPYSYUXXVZS[P[MZLYKW\x17H\\XIWGTFRFOGMJLOLTMXOZR[S[VZXXYUYTXQVOSNRNOOMQLT\x05H\\YFO[ RKFYF\x1dH\\PFMGLILKMMONSOVPXRYTYWXYWZT[P[MZLYKWKTLRNPQOUNWMXKXIWGTFPF\x17H\\XMWPURRSQSNRLPKMKLLINGQFRFUGWIXMXRWWUZR[P[MZLX\x0bNVROQPRQSPRO RRVQWRXSWRV\rNVROQPRQSPRO RSWRXQWRVSWSYQ[\x03F^ZIJRZ[\x05E_IO[O RIU[U\x03F^JIZRJ[\x14I[LKLJMHNGPFTFVGWHXJXLWNVORQRT RRYQZR[SZRY7E`WNVLTKQKOLNMMPMSNUPVSVUUVS RQKOMNPNSOUPV RWKVSVUXVZV\\T]Q]O\\L[JYHWGTFQFNGLHJJILHOHRIUJWLYNZQ[T[WZYYZX RXKWSWUXV\x08I[RFJ[ RRFZ[ RMTWT\x17G\\KFK[ RKFTFWGXHYJYLXNWOTP RKPTPWQXRYTYWXYWZT[K[\x05H\\KFY[ RK[YF\x08I[RFJ[ RRFZ[ RJ[Z[\x0bH[LFL[ RLFYF RLPTP RL[Y[\x14H\\RFR[ RPKMLLMKOKRLTMUPVTVWUXTYRYOXMWLTKPK\x05HYLFL[ RLFXF\x08G]KFK[ RYFY[ RKPYP\x02NVRFR[\x05PURQRRSRSQRQ\x08G\\KFK[ RYFKT RPOY[\x05I[RFJ[ RRFZ[\x0bF^JFJ[ RJFR[ RZFR[ RZFZ[\x08G]KFK[ RKFY[ RYFY[\x15G]PFNGLIKKJNJSKVLXNZP[T[VZXXYVZSZNYKXIVGTFPF\x08G]KFK[ RYFY[ RKFYF\x18G]PFNGLIKKJNJSKVLXNZP[T[VZXXYVZSZNYKXIVGTFPF ROPUP\rG\\KFK[ RKFTFWGXHYJYMXOWPTQKQ\tI[KFRPK[ RKFYF RK[Y[\x05JZRFR[ RKFYF\x12I[KKKILGMFOFPGQIRMR[ RYKYIXGWFUFTGSIRM\rKYQFOGNINKOMQNSNUMVKVIUGSFQF\x10H\\K[O[LTKPKLLINGQFSFVGXIYLYPXTU[Y[\x08I[KFYF ROPUP RK[Y[\x11G]RFR[ RILJLKMLQMSNTQUSUVTWSXQYMZL[L\x08H\\YFK[ RKFYF RK[Y[\x0bKYOBOb RPBPb ROBVB RObVb\x02KYKFY^\x0bKYTBTb RUBUb RNBUB RNbUb\x05JZRDJR RRDZR\x02I[Ib[b\x07NVSKQMQORPSORNQO\x17H]QMONMPLRKUKXLZN[P[RZUWWTYPZM RQMSMTNUPWXXZY[Z[\x1eI\\UFSGQIOMNPMTLZKb RUFWFYHYKXMWNUORO RROTPVRWTWWVYUZS[Q[OZNYMV\rI[KMMMOOU`WbYb RZMYOWRM]K`Jb\x17I[TMQMONMPLSLVMYNZP[R[TZVXWUWRVOTMRKQIQGRFTFVGXI\x12JZWOVNTMQMONOPPRSS RSSOTMVMXNZP[S[UZWX\x14G]ONMOKQJTJWKYLZN[Q[TZWXYUZRZOXMVMTORSPXMb\x10I\\JPLNNMOMQNROSRSVR[ RZMYPXRR[P_Ob\x12H\\IQJOLMNMONOPNTL[ RNTPPRNTMVMXOXRWWTb\x08LWRMPTOXOZP[R[TYUW\x05G]KKYY RYKKY\x12I[OMK[ RYNXMWMUNQROSNS RNSPTQUSZT[U[VZ\x08JZKFMFOGPHX[ RRML[\x14H]OMIb RNQMVMYO[Q[SZUXWT RYMWTVXVZW[Y[[Y\\W\rI[LMOMNSMXL[ RYMXPWRUURXOZL[\x11J[RMPNNPMSMVNYOZQ[S[UZWXXUXRWOVNTMRM\x0cG]PML[ RUMVSWXX[ RIPKNNM[M\x1aG\\HQIOKMMMNNNPMUMXNZO[Q[SZUWVUWRXMXJWGUFSFRHRJSMUPWRZT\x12I[MSMVNYOZQ[S[UZWXXUXRWOVNTMRMPNNPMSIb\x11I][MQMONMPLSLVMYNZP[R[TZVXWUWRVOUNSM\x07H\\SMP[ RJPLNOMZM\x0fH\\IQJOLMNMONOPMVMYO[Q[TZVXXTYPYM\x0eE_RIQJRKSJRI RIR[R RRYQZR[SZRY\x16F]NMLNJQITIWJZK[M[OZQW RRSQWRZS[U[WZYWZTZQYNXM\x1cJZTFRGQHQIRJUKXK RUKRLPMOOOQQSTTVT RTTPUNVMXMZO\\S^T_TaRbPb\x13F]VFNb RGQHOJMLMMNMPLULXMZO[Q[TZVXXUZP[M\x16JYTFRGQHQIRJUKXK RXKTMQONRMUMWNYP[S]T_TaSbQbP`\'KYTBRCQDPFPHQJRKSMSOQQ RRCQEQGRISJTLTNSPORSTTVTXSZR[Q]Q_Ra RQSSUSWRYQZP\\P^Q`RaTb\x02NVRBRb\'KYPBRCSDTFTHSJRKQMQOSQ RRCSESGRIQJPLPNQPURQTPVPXQZR[S]S_Ra RSSQUQWRYSZT\\T^S`RaPb\x17F^IUISJPLONOPPTSVTXTZS[Q RISJQLPNPPQTTVUXUZT[Q[O"JZJFJ[K[KFLFL[M[MFNFN[O[OFPFP[Q[QFRFR[S[SFTFT[U[UFVFV[W[WFXFX[Y[YFZFZ[' _index = b'\x00\x00\x03\x00\x16\x00#\x00<\x00s\x00\xb4\x00\xfb\x00\x0c\x01#\x01:\x01M\x01Z\x01k\x01r\x01\x7f\x01\x86\x01\xab\x01\xb6\x01\xd5\x01\xf6\x01\x05\x02*\x02[\x02h\x02\xa5\x02\xd6\x02\xef\x02\x0c\x03\x15\x03"\x03+\x03V\x03\xc7\x03\xda\x03\x0b\x04\x18\x04+\x04D\x04o\x04|\x04\x8f\x04\x96\x04\xa3\x04\xb6\x04\xc3\x04\xdc\x04\xef\x04\x1c\x05/\x05b\x05\x7f\x05\x94\x05\xa1\x05\xc8\x05\xe5\x05\x08\x06\x1b\x06@\x06S\x06l\x06s\x06\x8c\x06\x99\x06\xa0\x06\xb1\x06\xe2\x06!\x07>\x07o\x07\x96\x07\xc1\x07\xe4\x07\x0b\x08\x1e\x08+\x08R\x08e\x08\x90\x08\xad\x08\xd2\x08\xed\x08$\tK\tp\t\x81\t\xa2\t\xc1\t\xf0\t+\nT\n\x83\n\xd4\n\xdb\n,\x0b]\x0b' _mvfont = memoryview(_font) def _chr_addr(ordch): offset = 2 * (ordch - 32) return int.from_bytes(_index[offset:offset + 2], 'little') def get_ch(ordch): offset = _chr_addr(ordch if 32 <= ordch <= 127 else ord('?')) count = _font[offset] return _mvfont[offset:offset + (count + 2) * 2 - 1]
''' Time: 2015.10.2 Author: Lionel Content: Company ''' class Company(object): def __init__(self, name=None): self.__name = name @property def name(self): return self.__name @name.setter def name(self, name): self.__name = name
""" Time: 2015.10.2 Author: Lionel Content: Company """ class Company(object): def __init__(self, name=None): self.__name = name @property def name(self): return self.__name @name.setter def name(self, name): self.__name = name
#!/usr/bin/env python class Solution: def nearestPalindromic(self, n): mid = len(n) // 2 if len(n) % 2 == 0: s1 = n[0:mid] + n[0:mid][::-1] else: s1 = n[0:mid+1] + n[0:mid][::-1] s2, s3, s2_list, s3_list = '0', '9'*len(n), list(s1), list(s1) # This is wrong, e.g. 230032, the smaller one should be 229932, not 220022 # So needs to use awice's method for i in range(mid, len(n)): if s2_list[i] != '0': s2_list[len(n)-1-i] = s2_list[i] = chr(ord(s1[i])-1) s2 = ''.join(s2_list) if s2 == '0' * len(n) and len(n) > 1: s2 = '9' * (len(n)-1) break for i in range(mid, len(n)): if s3_list[i] != '9': s3_list[len(n)-1-i] = s3_list[i] = chr(ord(s1[i])+1) s3 = ''.join(s3_list) break if s1 == '9' * len(n): s3 = '1' + '0'*(len(n)-1) + '1' slist = [s2, s1, s3] if s1 != n else [s2, s3] l = [max(abs(int(s)-int(n)), 1) for s in slist] return slist, l, slist[l.index(min(l))] sol = Solution() n = '123' n = '81' n = '21' n = '10' n = '1' n = '22' n = '99' n = '9' print(sol.nearestPalindromic(n))
class Solution: def nearest_palindromic(self, n): mid = len(n) // 2 if len(n) % 2 == 0: s1 = n[0:mid] + n[0:mid][::-1] else: s1 = n[0:mid + 1] + n[0:mid][::-1] (s2, s3, s2_list, s3_list) = ('0', '9' * len(n), list(s1), list(s1)) for i in range(mid, len(n)): if s2_list[i] != '0': s2_list[len(n) - 1 - i] = s2_list[i] = chr(ord(s1[i]) - 1) s2 = ''.join(s2_list) if s2 == '0' * len(n) and len(n) > 1: s2 = '9' * (len(n) - 1) break for i in range(mid, len(n)): if s3_list[i] != '9': s3_list[len(n) - 1 - i] = s3_list[i] = chr(ord(s1[i]) + 1) s3 = ''.join(s3_list) break if s1 == '9' * len(n): s3 = '1' + '0' * (len(n) - 1) + '1' slist = [s2, s1, s3] if s1 != n else [s2, s3] l = [max(abs(int(s) - int(n)), 1) for s in slist] return (slist, l, slist[l.index(min(l))]) sol = solution() n = '123' n = '81' n = '21' n = '10' n = '1' n = '22' n = '99' n = '9' print(sol.nearestPalindromic(n))
new_model = tf.keras.models.load_model('my_first_model.h5') cap = cv2.VideoCapture(0) faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') while 1: # get a frame ret, frame = cap.read() # show a frame gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale(gray, 1.1, 4) for x, y, w, h in faces: roi_gray = gray[y:y + h, x:x + h] roi_color = frame[y:y + h, x:x + h] # cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2) faces = faceCascade.detectMultiScale(roi_gray) for (ex, ey, ew, eh) in faces: face_roi = roi_color[ey:ey + eh, ex:ex + eh] final_image = cv2.resize(face_roi, (224, 224)) final_image = final_image.reshape(-1, 224, 224, 3) # return the image with shaping that TF wants. fianl_image = np.expand_dims(final_image, axis=0) # need forth dimension final_image = final_image / 225.0 Predictions = new_model.predict(final_image) print(Predictions) if (Predictions > 0.5): cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.putText(frame, 'Wearing Mask!', (x, y), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0), 1) # cv2.putText(img, str,origin,font,size,color,thickness) else: cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2) cv2.putText(frame, 'No Mask!', (x, y), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 255), 1) # if(Predictions<0.45): # print("No mask") # elif(Predictions>0.55): # print("With mask") # else: # print("Can not determine") cv2.imshow("capture", frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
new_model = tf.keras.models.load_model('my_first_model.h5') cap = cv2.VideoCapture(0) face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') while 1: (ret, frame) = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale(gray, 1.1, 4) for (x, y, w, h) in faces: roi_gray = gray[y:y + h, x:x + h] roi_color = frame[y:y + h, x:x + h] faces = faceCascade.detectMultiScale(roi_gray) for (ex, ey, ew, eh) in faces: face_roi = roi_color[ey:ey + eh, ex:ex + eh] final_image = cv2.resize(face_roi, (224, 224)) final_image = final_image.reshape(-1, 224, 224, 3) fianl_image = np.expand_dims(final_image, axis=0) final_image = final_image / 225.0 predictions = new_model.predict(final_image) print(Predictions) if Predictions > 0.5: cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.putText(frame, 'Wearing Mask!', (x, y), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0), 1) else: cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2) cv2.putText(frame, 'No Mask!', (x, y), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 255), 1) cv2.imshow('capture', frame) if cv2.waitKey(1) & 255 == ord('q'): break cap.release() cv2.destroyAllWindows()
JWT_SECRET_KEY = "e75a9e10168350b2a8869a8eb8a0f946a15eec8452048c0b51923f98ea9ea43b" JWT_ALGORITHM = "HS256" JWT_EXPIRATION_TIME_MINUTES = 60 * 24 * 5 TOKEN_DESCRIPTION = "It checks username and password if they are true, it returns JWT token to you." TOKEN_SUMMARY = "It returns JWT Token." ISBN_DESCRIPTION = "It is unique identifier for books."
jwt_secret_key = 'e75a9e10168350b2a8869a8eb8a0f946a15eec8452048c0b51923f98ea9ea43b' jwt_algorithm = 'HS256' jwt_expiration_time_minutes = 60 * 24 * 5 token_description = 'It checks username and password if they are true, it returns JWT token to you.' token_summary = 'It returns JWT Token.' isbn_description = 'It is unique identifier for books.'
load(":rollup_js_result.bzl", "RollupJsResult") def _impl(ctx): node_executable = ctx.attr.node_executable.files.to_list()[0] rollup_script = ctx.attr.rollup_script.files.to_list()[0] module_name = ctx.attr.module_name node_modules_path = rollup_script.path.split("/node_modules/")[0] + "/node_modules" exports = ctx.attr.exports dep_files = [] for d in ctx.attr.deps: dep_files.extend(d.files.to_list()) entrypoint_js_file = ctx.actions.declare_file("%s-entrypoint.js" % module_name) vendor_import_entries = [] for export_name in exports: vendor_import_entries.append("import * as %s from '%s'" % (exports[export_name], export_name)) vendor_entrypoint_content = \ "\n".join(vendor_import_entries) + \ "\n\n" + \ "export default {\n" + \ ",\n".join(exports.values()) + \ "}\n" ctx.actions.write( output=entrypoint_js_file, content=vendor_entrypoint_content) dest_file = ctx.actions.declare_file(module_name + ".js") sourcemap_file = ctx.actions.declare_file(module_name + ".js.map") # transitive deps are not properly imported without the includePaths fix, detailed here: # https://github.com/rollup/rollup-plugin-node-resolve/issues/105#issuecomment-332640015 rollup_config_content = """ const path = require('path'); import commonjs from 'rollup-plugin-commonjs'; import resolve from 'rollup-plugin-node-resolve'; import includePaths from 'rollup-plugin-includepaths'; import sourcemaps from 'rollup-plugin-sourcemaps'; import replace from 'rollup-plugin-replace' export default { input: '%s', output: { file: '%s', format: 'iife', sourcemap: true, sourcemapFile: '%s', name: '%s', intro: 'const global = window' }, plugins: [ sourcemaps(), resolve({ preferBuiltins: false, }), commonjs(), replace({ "process.env.NODE_ENV": JSON.stringify( "production" ) }) ], onwarn(warning) { if (['UNRESOLVED_IMPORT', 'MISSING_GLOBAL_NAME'].indexOf(warning.code)>=0) { console.error(warning.message) process.exit(1) } else { console.warn(warning.message) } } }; """ % ( entrypoint_js_file.path, dest_file.path, sourcemap_file.path, module_name, ) rollup_config_file = ctx.actions.declare_file("%s-rollup-config.js" % module_name) ctx.actions.write( output=rollup_config_file, content=rollup_config_content) ctx.actions.run_shell( command="ln -s %s node_modules;env NODE_PATH=node_modules %s %s -c %s" % ( node_modules_path, node_executable.path, rollup_script.path, rollup_config_file.path, ), inputs=dep_files, outputs = [dest_file, sourcemap_file], progress_message = "running rollup js '%s'..." % module_name, tools = [ node_executable, rollup_script, rollup_config_file, entrypoint_js_file, ] + ctx.attr.rollup_plugins.files.to_list() + dep_files ) return [ DefaultInfo(files=depset([dest_file, sourcemap_file])), RollupJsResult(js_file=dest_file, sourcemap_file=sourcemap_file), ] rollup_js_vendor_bundle = rule( implementation = _impl, attrs = { "module_name": attr.string(mandatory=True), "exports": attr.string_dict(), "deps": attr.label_list(), "node_executable": attr.label(allow_files=True, mandatory=True), "rollup_script": attr.label(allow_files=True, mandatory=True), "rollup_plugins": attr.label(mandatory=True), } )
load(':rollup_js_result.bzl', 'RollupJsResult') def _impl(ctx): node_executable = ctx.attr.node_executable.files.to_list()[0] rollup_script = ctx.attr.rollup_script.files.to_list()[0] module_name = ctx.attr.module_name node_modules_path = rollup_script.path.split('/node_modules/')[0] + '/node_modules' exports = ctx.attr.exports dep_files = [] for d in ctx.attr.deps: dep_files.extend(d.files.to_list()) entrypoint_js_file = ctx.actions.declare_file('%s-entrypoint.js' % module_name) vendor_import_entries = [] for export_name in exports: vendor_import_entries.append("import * as %s from '%s'" % (exports[export_name], export_name)) vendor_entrypoint_content = '\n'.join(vendor_import_entries) + '\n\n' + 'export default {\n' + ',\n'.join(exports.values()) + '}\n' ctx.actions.write(output=entrypoint_js_file, content=vendor_entrypoint_content) dest_file = ctx.actions.declare_file(module_name + '.js') sourcemap_file = ctx.actions.declare_file(module_name + '.js.map') rollup_config_content = '\nconst path = require(\'path\');\nimport commonjs from \'rollup-plugin-commonjs\';\nimport resolve from \'rollup-plugin-node-resolve\';\nimport includePaths from \'rollup-plugin-includepaths\';\nimport sourcemaps from \'rollup-plugin-sourcemaps\';\nimport replace from \'rollup-plugin-replace\'\n\nexport default {\n input: \'%s\',\n output: {\n file: \'%s\',\n format: \'iife\',\n sourcemap: true,\n sourcemapFile: \'%s\',\n name: \'%s\',\n intro: \'const global = window\'\n },\n plugins: [\n sourcemaps(),\n resolve({\n preferBuiltins: false,\n }),\n commonjs(),\n replace({\n "process.env.NODE_ENV": JSON.stringify( "production" )\n })\n ],\n onwarn(warning) {\n if ([\'UNRESOLVED_IMPORT\', \'MISSING_GLOBAL_NAME\'].indexOf(warning.code)>=0) {\n console.error(warning.message)\n process.exit(1)\n } else {\n console.warn(warning.message)\n }\n }\n\n};\n ' % (entrypoint_js_file.path, dest_file.path, sourcemap_file.path, module_name) rollup_config_file = ctx.actions.declare_file('%s-rollup-config.js' % module_name) ctx.actions.write(output=rollup_config_file, content=rollup_config_content) ctx.actions.run_shell(command='ln -s %s node_modules;env NODE_PATH=node_modules %s %s -c %s' % (node_modules_path, node_executable.path, rollup_script.path, rollup_config_file.path), inputs=dep_files, outputs=[dest_file, sourcemap_file], progress_message="running rollup js '%s'..." % module_name, tools=[node_executable, rollup_script, rollup_config_file, entrypoint_js_file] + ctx.attr.rollup_plugins.files.to_list() + dep_files) return [default_info(files=depset([dest_file, sourcemap_file])), rollup_js_result(js_file=dest_file, sourcemap_file=sourcemap_file)] rollup_js_vendor_bundle = rule(implementation=_impl, attrs={'module_name': attr.string(mandatory=True), 'exports': attr.string_dict(), 'deps': attr.label_list(), 'node_executable': attr.label(allow_files=True, mandatory=True), 'rollup_script': attr.label(allow_files=True, mandatory=True), 'rollup_plugins': attr.label(mandatory=True)})
''' A format for expressing an ordered list of integers is to use a comma separated list of either individual integers or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. The range includes all integers in the interval including both endpoints. It is not considered a range unless it spans at least 3 numbers. For example ("12, 13, 15-17") Complete the solution so that it takes a list of integers in increasing order and returns a correctly formatted string in the range format. Example: solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]) # returns "-6,-3-1,3-5,7-11,14,15,17-20" ''' def solution(args): out = [] beg = end = args[0] for n in args[1:] + [""]: if n != end + 1: if end == beg: out.append(str(beg)) elif end == beg + 1: out.extend([str(beg), str(end)]) else: out.append(str(beg) + "-" + str(end)) beg = n end = n return ",".join(out) # '-6,-3-1,3-5,7-11,14,15,17-20' if __name__ == '__main__': print(solution(([-60, -58, -56])))
""" A format for expressing an ordered list of integers is to use a comma separated list of either individual integers or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. The range includes all integers in the interval including both endpoints. It is not considered a range unless it spans at least 3 numbers. For example ("12, 13, 15-17") Complete the solution so that it takes a list of integers in increasing order and returns a correctly formatted string in the range format. Example: solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]) # returns "-6,-3-1,3-5,7-11,14,15,17-20" """ def solution(args): out = [] beg = end = args[0] for n in args[1:] + ['']: if n != end + 1: if end == beg: out.append(str(beg)) elif end == beg + 1: out.extend([str(beg), str(end)]) else: out.append(str(beg) + '-' + str(end)) beg = n end = n return ','.join(out) if __name__ == '__main__': print(solution([-60, -58, -56]))
class Pattern_Seven: '''Pattern seven * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ''' def __init__(self, strings='*', steps=10): self.steps = steps if isinstance(strings, str): self.strings = strings else: # If provided 'strings' is integer then converting it to string self.strings = str(strings) def method_one(self): print('Method One') for i in range(1, self.steps): joining_word = ' '.join(self.strings * i) print(joining_word.center(len(joining_word) * 2).rstrip(' ')) def method_two(self): print('\nMethod Two') steps = 1 while steps != self.steps: joining_word = ' '.join(self.strings * steps) print(joining_word.center(len(joining_word) * 2).rstrip(' ')) steps += 1 if __name__ == '__main__': pattern_seven = Pattern_Seven() pattern_seven.method_one() pattern_seven.method_two()
class Pattern_Seven: """Pattern seven * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * """ def __init__(self, strings='*', steps=10): self.steps = steps if isinstance(strings, str): self.strings = strings else: self.strings = str(strings) def method_one(self): print('Method One') for i in range(1, self.steps): joining_word = ' '.join(self.strings * i) print(joining_word.center(len(joining_word) * 2).rstrip(' ')) def method_two(self): print('\nMethod Two') steps = 1 while steps != self.steps: joining_word = ' '.join(self.strings * steps) print(joining_word.center(len(joining_word) * 2).rstrip(' ')) steps += 1 if __name__ == '__main__': pattern_seven = pattern__seven() pattern_seven.method_one() pattern_seven.method_two()
# Example 1: # Input: haystack = "hello", needle = "ll" # Output: 2 # Example 2: # Input: haystack = "aaaaa", needle = "bba" # Output: -1 # Example 3: # Input: haystack = "", needle = "" # Output: 0 class Solution: def strStr(self, haystack: str, needle: str) -> int: return haystack.find(needle)
class Solution: def str_str(self, haystack: str, needle: str) -> int: return haystack.find(needle)
#!/usr/bin/env python3 for file_name in ['file_ignored_by_git_included_explicitly', 'file_managed_by_git']: with open(file_name) as f: print(f.read(), end='') for file_name in ['file_managed_by_git_excluded', 'file_ignored_by_git']: try: with open(file_name) as f: raise Exception(f'File {file_name} shouldn\'t be here') except FileNotFoundError: pass
for file_name in ['file_ignored_by_git_included_explicitly', 'file_managed_by_git']: with open(file_name) as f: print(f.read(), end='') for file_name in ['file_managed_by_git_excluded', 'file_ignored_by_git']: try: with open(file_name) as f: raise exception(f"File {file_name} shouldn't be here") except FileNotFoundError: pass
# https://leetcode.com/problems/ugly-number/ # # Write a program to check whether a given number is an ugly number. # # Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. # For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. # # Note that 1 is typically treated as an ugly number. # # Credits: # Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. class Solution(object): def isUgly(self, num): """ :type num: int :rtype: bool """ if num <= 0: return False def defactor(num, n): while num % n == 0: num = num / n return num num = defactor(num, 2) num = defactor(num, 3) num = defactor(num, 5) if num == 1: return True else: return False
class Solution(object): def is_ugly(self, num): """ :type num: int :rtype: bool """ if num <= 0: return False def defactor(num, n): while num % n == 0: num = num / n return num num = defactor(num, 2) num = defactor(num, 3) num = defactor(num, 5) if num == 1: return True else: return False
#! usr/bin/python3 """ This is the python script used to download few codechef questions from the website. Put them in the correct place as the structure demands like beginner questions in beginner and so on. Add the question statement as a Readme.md for each question and the link to the question. <Add the features of @SuperCodeBot on telegram.> """
""" This is the python script used to download few codechef questions from the website. Put them in the correct place as the structure demands like beginner questions in beginner and so on. Add the question statement as a Readme.md for each question and the link to the question. <Add the features of @SuperCodeBot on telegram.> """
captcha="428122498997587283996116951397957933569136949848379417125362532269869461185743113733992331379856446362482129646556286611543756564275715359874924898113424472782974789464348626278532936228881786273586278886575828239366794429223317476722337424399239986153675275924113322561873814364451339186918813451685263192891627186769818128715595715444565444581514677521874935942913547121751851631373316122491471564697731298951989511917272684335463436218283261962158671266625299188764589814518793576375629163896349665312991285776595142146261792244475721782941364787968924537841698538288459355159783985638187254653851864874544584878999193242641611859756728634623853475638478923744471563845635468173824196684361934269459459124269196811512927442662761563824323621758785866391424778683599179447845595931928589255935953295111937431266815352781399967295389339626178664148415561175386725992469782888757942558362117938629369129439717427474416851628121191639355646394276451847131182652486561415942815818785884559193483878139351841633366398788657844396925423217662517356486193821341454889283266691224778723833397914224396722559593959125317175899594685524852419495793389481831354787287452367145661829287518771631939314683137722493531318181315216342994141683484111969476952946378314883421677952397588613562958741328987734565492378977396431481215983656814486518865642645612413945129485464979535991675776338786758997128124651311153182816188924935186361813797251997643992686294724699281969473142721116432968216434977684138184481963845141486793996476793954226225885432422654394439882842163295458549755137247614338991879966665925466545111899714943716571113326479432925939227996799951279485722836754457737668191845914566732285928453781818792236447816127492445993945894435692799839217467253986218213131249786833333936332257795191937942688668182629489191693154184177398186462481316834678733713614889439352976144726162214648922159719979143735815478633912633185334529484779322818611438194522292278787653763328944421516569181178517915745625295158611636365253948455727653672922299582352766484" # captcha="123123" def check(val, next): if val == next: return int(val) else: return 0 def two(): sum = 0 dist = int(len(captcha) / 2) for i, d in enumerate(captcha): # print("i={}; d={}; i+dist={}; i + dist - len(captcha)={}".format(i,d,(i + dist),(i + dist - len(captcha)))) if i + dist > len(captcha) - 1: next = captcha[(i + dist - len(captcha))] else: next = captcha[(i + dist)] sum += check(d, next) print("sum is {}".format(sum)) def one(): sum = 0 for i, d in enumerate(captcha): # print("i={}; d={}".format(i,d)) if i == len(captcha) - 1: next = captcha[0] else: next = captcha[i] sum += check(d, next) print("sum is {}".format(sum)) def main(): # one() two() if __name__ == "__main__": main()
captcha = '428122498997587283996116951397957933569136949848379417125362532269869461185743113733992331379856446362482129646556286611543756564275715359874924898113424472782974789464348626278532936228881786273586278886575828239366794429223317476722337424399239986153675275924113322561873814364451339186918813451685263192891627186769818128715595715444565444581514677521874935942913547121751851631373316122491471564697731298951989511917272684335463436218283261962158671266625299188764589814518793576375629163896349665312991285776595142146261792244475721782941364787968924537841698538288459355159783985638187254653851864874544584878999193242641611859756728634623853475638478923744471563845635468173824196684361934269459459124269196811512927442662761563824323621758785866391424778683599179447845595931928589255935953295111937431266815352781399967295389339626178664148415561175386725992469782888757942558362117938629369129439717427474416851628121191639355646394276451847131182652486561415942815818785884559193483878139351841633366398788657844396925423217662517356486193821341454889283266691224778723833397914224396722559593959125317175899594685524852419495793389481831354787287452367145661829287518771631939314683137722493531318181315216342994141683484111969476952946378314883421677952397588613562958741328987734565492378977396431481215983656814486518865642645612413945129485464979535991675776338786758997128124651311153182816188924935186361813797251997643992686294724699281969473142721116432968216434977684138184481963845141486793996476793954226225885432422654394439882842163295458549755137247614338991879966665925466545111899714943716571113326479432925939227996799951279485722836754457737668191845914566732285928453781818792236447816127492445993945894435692799839217467253986218213131249786833333936332257795191937942688668182629489191693154184177398186462481316834678733713614889439352976144726162214648922159719979143735815478633912633185334529484779322818611438194522292278787653763328944421516569181178517915745625295158611636365253948455727653672922299582352766484' def check(val, next): if val == next: return int(val) else: return 0 def two(): sum = 0 dist = int(len(captcha) / 2) for (i, d) in enumerate(captcha): if i + dist > len(captcha) - 1: next = captcha[i + dist - len(captcha)] else: next = captcha[i + dist] sum += check(d, next) print('sum is {}'.format(sum)) def one(): sum = 0 for (i, d) in enumerate(captcha): if i == len(captcha) - 1: next = captcha[0] else: next = captcha[i] sum += check(d, next) print('sum is {}'.format(sum)) def main(): two() if __name__ == '__main__': main()
class Metric: def __init__(self): pass def update(self, outputs, target): raise NotImplementedError def value(self): raise NotImplementedError def name(self): raise NotImplementedError def reset(self): pass
class Metric: def __init__(self): pass def update(self, outputs, target): raise NotImplementedError def value(self): raise NotImplementedError def name(self): raise NotImplementedError def reset(self): pass
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Copyright (c) 2011 Cubic ERP - Teradata SAC. (http://cubicerp.com). { 'name': 'Peru - Accounting', 'description': """ Peruvian accounting chart and tax localization. According the PCGE 2010. ======================================================================== Plan contable peruano e impuestos de acuerdo a disposiciones vigentes de la SUNAT 2011 (PCGE 2010). """, 'author': ['Cubic ERP'], 'category': 'Localization', 'depends': ['account'], 'data': [ 'data/l10n_pe_chart_data.xml', 'data/account.account.template.csv', 'data/l10n_pe_chart_post_data.xml', 'data/account_data.xml', 'data/account_tax_data.xml', 'data/account_chart_template_data.xml', ], }
{'name': 'Peru - Accounting', 'description': '\nPeruvian accounting chart and tax localization. According the PCGE 2010.\n========================================================================\n\nPlan contable peruano e impuestos de acuerdo a disposiciones vigentes de la\nSUNAT 2011 (PCGE 2010).\n\n ', 'author': ['Cubic ERP'], 'category': 'Localization', 'depends': ['account'], 'data': ['data/l10n_pe_chart_data.xml', 'data/account.account.template.csv', 'data/l10n_pe_chart_post_data.xml', 'data/account_data.xml', 'data/account_tax_data.xml', 'data/account_chart_template_data.xml']}
"""Proper parenthetics.""" def lisp_parens_with_count(parens): """Output with count to see whether parens are open(1), broken(-1), or balanced(0).""" open_count = 0 for par in parens: if par == '(': open_count elif par == ')': open_count -= 1 if open_count < 0: return -1 if open_count == 0: return 0 else: return 1 def lisp_parens_with_stack(parens): """Output with stack to see whether parens are open(1), broken(-1), or balanced(0).""" open_stack = [] for par in parens: if par == '(': open_stack.append(par) if par == ')': try: open_stack.pop() except IndexError: return -1 if open_stack: return 1 else: return 0
"""Proper parenthetics.""" def lisp_parens_with_count(parens): """Output with count to see whether parens are open(1), broken(-1), or balanced(0).""" open_count = 0 for par in parens: if par == '(': open_count elif par == ')': open_count -= 1 if open_count < 0: return -1 if open_count == 0: return 0 else: return 1 def lisp_parens_with_stack(parens): """Output with stack to see whether parens are open(1), broken(-1), or balanced(0).""" open_stack = [] for par in parens: if par == '(': open_stack.append(par) if par == ')': try: open_stack.pop() except IndexError: return -1 if open_stack: return 1 else: return 0
## Local ems economic dispatch computing format # Diesel generator set PG = 0 RG = 1 # Utility grid set PUG = 2 RUG = 3 # Bi-directional convertor set PBIC_AC2DC = 4 PBIC_DC2AC = 5 # Energy storage system set PESS_C = 6 PESS_DC = 7 RESS = 8 EESS = 9 # Neighboring MG set PMG = 10 # Emergency curtailment or shedding set PPV = 11 PWP = 12 PL_AC = 13 PL_UAC = 14 PL_DC = 15 PL_UDC = 16 # Total number of decision variables NX = 17
pg = 0 rg = 1 pug = 2 rug = 3 pbic_ac2_dc = 4 pbic_dc2_ac = 5 pess_c = 6 pess_dc = 7 ress = 8 eess = 9 pmg = 10 ppv = 11 pwp = 12 pl_ac = 13 pl_uac = 14 pl_dc = 15 pl_udc = 16 nx = 17
def find(n): l = [''] * (n + 1) size = 1 m = 1 while (size <= n): i = 0 while(i < m and (size + i) <= n): l[size + i] = "1" + l[size - m + i] i += 1 i = 0 while(i < m and (size + m + i) <= n): l[size + m + i] = "2" + l[size - m + i] i += 1 m = m << 1 size = size + m print(l[n]) for _ in range(int(input())): find(int(input()))
def find(n): l = [''] * (n + 1) size = 1 m = 1 while size <= n: i = 0 while i < m and size + i <= n: l[size + i] = '1' + l[size - m + i] i += 1 i = 0 while i < m and size + m + i <= n: l[size + m + i] = '2' + l[size - m + i] i += 1 m = m << 1 size = size + m print(l[n]) for _ in range(int(input())): find(int(input()))
# -*- coding: utf-8 -*- class warehouse: def __init__(self, location, product): self.location = location self.deliveryPoints = list() self.allProducts = product self.wishlist = list() self.excessInventory = [] self.allProducts = self.convertInv(self.allProducts) def take(self,item): for i in xrange(0, len(self.excessInventory)): if item == self.excessInventory[i]: self.excessInventory.pop(i) self.allProducts.pop(i) return true return false def inventoryCheck(self): self.excessInventory = self.allProducts for i in self.deliveryPoints: for j in i.productIDsRequired: found = False for k in xrange(0, len(self.excessInventory)): if k == j: del excessInventory[k] found = True break if found != True: self.wishlist.append(j) def convertInv(self,before): before = map(int, before) after = [] for i in xrange(0, len(before)): for j in xrange(0, before[i]): after.append(i) return after
class Warehouse: def __init__(self, location, product): self.location = location self.deliveryPoints = list() self.allProducts = product self.wishlist = list() self.excessInventory = [] self.allProducts = self.convertInv(self.allProducts) def take(self, item): for i in xrange(0, len(self.excessInventory)): if item == self.excessInventory[i]: self.excessInventory.pop(i) self.allProducts.pop(i) return true return false def inventory_check(self): self.excessInventory = self.allProducts for i in self.deliveryPoints: for j in i.productIDsRequired: found = False for k in xrange(0, len(self.excessInventory)): if k == j: del excessInventory[k] found = True break if found != True: self.wishlist.append(j) def convert_inv(self, before): before = map(int, before) after = [] for i in xrange(0, len(before)): for j in xrange(0, before[i]): after.append(i) return after
# dummy variables for flake8 # see: https://github.com/patrick-kidger/torchtyping/blob/master/FURTHER-DOCUMENTATION.md batch = None channels = None time = None behavior = None annotator = None classes = None
batch = None channels = None time = None behavior = None annotator = None classes = None
T = input() soma = 0 matriz = [] for i in range(0,12,+1): linha = [] for j in range(0,12,+1): numeros = float(input()) linha.append(numeros) matriz.append(linha) contagem = 0 pegaNum = 0 for i in range(1, 12,+1): #linha for j in range(0, i, +1): pegaNum = float(matriz[i][j]) contagem+=1 soma = soma + pegaNum if T == "S": print("{:.1f}".format(soma)) else: media = soma/contagem print("{:.1f}".format(media))
t = input() soma = 0 matriz = [] for i in range(0, 12, +1): linha = [] for j in range(0, 12, +1): numeros = float(input()) linha.append(numeros) matriz.append(linha) contagem = 0 pega_num = 0 for i in range(1, 12, +1): for j in range(0, i, +1): pega_num = float(matriz[i][j]) contagem += 1 soma = soma + pegaNum if T == 'S': print('{:.1f}'.format(soma)) else: media = soma / contagem print('{:.1f}'.format(media))
"""A library to help interacting with omegaUp. This is composed of two modules: - [**`omegaup.api`**](./omegaup/api/) helps interacting with [omegaUp's API](https://github.com/omegaup/omegaup/blob/master/frontend/server/src/Controllers/README.md) and is auto-generated with correct types and the docstrings straight from the code. - [**`omegaup.validator`**](./omegaup/validator/) has runtime helper functions to aid in problem validation. """
"""A library to help interacting with omegaUp. This is composed of two modules: - [**`omegaup.api`**](./omegaup/api/) helps interacting with [omegaUp's API](https://github.com/omegaup/omegaup/blob/master/frontend/server/src/Controllers/README.md) and is auto-generated with correct types and the docstrings straight from the code. - [**`omegaup.validator`**](./omegaup/validator/) has runtime helper functions to aid in problem validation. """
# -*- coding: utf-8 -*- """ cli structs module. """ class CLIGroups: """ cli groups class. each cli handler group will be registered with its relevant group name. usage example: `python cli.py alembic upgrade --arg value` `python cli.py babel extract --arg value` `python cli.py template package` `python cli.py celery worker --arg value` `python cli.py security token --arg value` """ pass
""" cli structs module. """ class Cligroups: """ cli groups class. each cli handler group will be registered with its relevant group name. usage example: `python cli.py alembic upgrade --arg value` `python cli.py babel extract --arg value` `python cli.py template package` `python cli.py celery worker --arg value` `python cli.py security token --arg value` """ pass
#!/usr/bin/env python3 def word_frequencies(filename="src/alice.txt"): with open(filename, "r") as f: lines = f.readlines() d = {} for line in lines: words = line.split() for word in words: word = word.strip("""!"#$%&'()*,-./:;?@[]_""") if d.get(word) != None: d[word] += 1 else: d[word] = 1 return d def main(): d = word_frequencies() for line in d: print(line, d[line]) if __name__ == "__main__": main()
def word_frequencies(filename='src/alice.txt'): with open(filename, 'r') as f: lines = f.readlines() d = {} for line in lines: words = line.split() for word in words: word = word.strip('!"#$%&\'()*,-./:;?@[]_') if d.get(word) != None: d[word] += 1 else: d[word] = 1 return d def main(): d = word_frequencies() for line in d: print(line, d[line]) if __name__ == '__main__': main()
class REQUEST_MSG(object): TYPE_FIELD = "type" GET_ID = "get-id" CONNECT_NODE = "connect-node" AUTHENTICATE = "authentication" HOST_MODEL = "host-model" RUN_INFERENCE = "run-inference" LIST_MODELS = "list-models" DELETE_MODEL = "delete-model" DOWNLOAD_MODEL = "download-model" SYFT_COMMAND = "syft-command" PING = "socket-ping" class RESPONSE_MSG(object): NODE_ID = "id" INFERENCE_RESULT = "prediction" MODELS = "models" ERROR = "error" SUCCESS = "success"
class Request_Msg(object): type_field = 'type' get_id = 'get-id' connect_node = 'connect-node' authenticate = 'authentication' host_model = 'host-model' run_inference = 'run-inference' list_models = 'list-models' delete_model = 'delete-model' download_model = 'download-model' syft_command = 'syft-command' ping = 'socket-ping' class Response_Msg(object): node_id = 'id' inference_result = 'prediction' models = 'models' error = 'error' success = 'success'
valid_passwords = 0 with open('input.txt', 'r') as f: for line in f: min_max, letter_colon, password = line.split() pmin, pmax = [int(c) for c in min_max.split('-')] letter = letter_colon[0:1] # remove colon password = ' ' + password # account for 1-indexing matching_chars = 0 if password[pmin] == letter: matching_chars += 1 if password[pmax] == letter: matching_chars += 1 if matching_chars == 1: # exactly one match valid_passwords += 1 # print(f"{pmin} | {pmax} | {letter} | {password} | {num_letters}") print(valid_passwords)
valid_passwords = 0 with open('input.txt', 'r') as f: for line in f: (min_max, letter_colon, password) = line.split() (pmin, pmax) = [int(c) for c in min_max.split('-')] letter = letter_colon[0:1] password = ' ' + password matching_chars = 0 if password[pmin] == letter: matching_chars += 1 if password[pmax] == letter: matching_chars += 1 if matching_chars == 1: valid_passwords += 1 print(valid_passwords)
class Globee404NotFound(Exception): def __init__(self): super().__init__() self.message = 'Payment Request returned 404: Not Found' def __str__(self): return self.message class Globee422UnprocessableEntity(Exception): def __init__(self, errors): super().__init__() self.message = 'Payment Request returned 422:' self.errors = errors or [] def __str__(self): ret = '%s\n' % self.message for error in self.errors: ret += '\ttype: %s\n' % error['type'] ret += '\textra: %s\n' % error['extra'] ret += '\tfield: %s\n' % error['field'] ret += '\tmessage: %s\n' % error['message'] return ret class GlobeeMissingCredentials(Exception): def __init__(self, missing_key_name): super().__init__() self.message = "The '%s' is missing!" % missing_key_name def __str__(self): return self.message
class Globee404Notfound(Exception): def __init__(self): super().__init__() self.message = 'Payment Request returned 404: Not Found' def __str__(self): return self.message class Globee422Unprocessableentity(Exception): def __init__(self, errors): super().__init__() self.message = 'Payment Request returned 422:' self.errors = errors or [] def __str__(self): ret = '%s\n' % self.message for error in self.errors: ret += '\ttype: %s\n' % error['type'] ret += '\textra: %s\n' % error['extra'] ret += '\tfield: %s\n' % error['field'] ret += '\tmessage: %s\n' % error['message'] return ret class Globeemissingcredentials(Exception): def __init__(self, missing_key_name): super().__init__() self.message = "The '%s' is missing!" % missing_key_name def __str__(self): return self.message
class BaseExchangeContactService(object): def __init__(self, service, folder_id): self.service = service self.folder_id = folder_id def get_contact(self, id): raise NotImplementedError def new_contact(self, **properties): raise NotImplementedError class BaseExchangeContactItem(object): _id = None _change_key = None _service = None folder_id = None _track_dirty_attributes = False _dirty_attributes = set() # any attributes that have changed, and we need to update in Exchange first_name = None last_name = None full_name = None display_name = None sort_name = None email_address1 = None email_address2 = None email_address3 = None birthday = None job_title = None department = None company_name = None office_location = None primary_phone = None business_phone = None home_phone = None mobile_phone = None def __init__(self, service, id=None, xml=None, folder_id=None, **kwargs): self.service = service self.folder_id = folder_id if xml is not None: self._init_from_xml(xml) elif id is None: self._update_properties(kwargs) else: self._init_from_service(id) def _init_from_xml(self, xml): raise NotImplementedError def _init_from_service(self, id): raise NotImplementedError def create(self): raise NotImplementedError def update(self): raise NotImplementedError def delete(self): raise NotImplementedError @property def id(self): """ **Read-only.** The internal id Exchange uses to refer to this folder. """ return self._id @property def change_key(self): """ **Read-only.** When you change a contact, Exchange makes you pass a change key to prevent overwriting a previous version. """ return self._change_key def _update_properties(self, properties): self._track_dirty_attributes = False for key in properties: setattr(self, key, properties[key]) self._track_dirty_attributes = True def __setattr__(self, key, value): """ Magically track public attributes, so we can track what we need to flush to the Exchange store """ if self._track_dirty_attributes and not key.startswith(u"_"): self._dirty_attributes.add(key) object.__setattr__(self, key, value) def _reset_dirty_attributes(self): self._dirty_attributes = set() def validate(self): """ Validates that all required fields are present """ if not self.display_name: raise ValueError("Folder has no display_name") if not self.parent_id: raise ValueError("Folder has no parent_id")
class Baseexchangecontactservice(object): def __init__(self, service, folder_id): self.service = service self.folder_id = folder_id def get_contact(self, id): raise NotImplementedError def new_contact(self, **properties): raise NotImplementedError class Baseexchangecontactitem(object): _id = None _change_key = None _service = None folder_id = None _track_dirty_attributes = False _dirty_attributes = set() first_name = None last_name = None full_name = None display_name = None sort_name = None email_address1 = None email_address2 = None email_address3 = None birthday = None job_title = None department = None company_name = None office_location = None primary_phone = None business_phone = None home_phone = None mobile_phone = None def __init__(self, service, id=None, xml=None, folder_id=None, **kwargs): self.service = service self.folder_id = folder_id if xml is not None: self._init_from_xml(xml) elif id is None: self._update_properties(kwargs) else: self._init_from_service(id) def _init_from_xml(self, xml): raise NotImplementedError def _init_from_service(self, id): raise NotImplementedError def create(self): raise NotImplementedError def update(self): raise NotImplementedError def delete(self): raise NotImplementedError @property def id(self): """ **Read-only.** The internal id Exchange uses to refer to this folder. """ return self._id @property def change_key(self): """ **Read-only.** When you change a contact, Exchange makes you pass a change key to prevent overwriting a previous version. """ return self._change_key def _update_properties(self, properties): self._track_dirty_attributes = False for key in properties: setattr(self, key, properties[key]) self._track_dirty_attributes = True def __setattr__(self, key, value): """ Magically track public attributes, so we can track what we need to flush to the Exchange store """ if self._track_dirty_attributes and (not key.startswith(u'_')): self._dirty_attributes.add(key) object.__setattr__(self, key, value) def _reset_dirty_attributes(self): self._dirty_attributes = set() def validate(self): """ Validates that all required fields are present """ if not self.display_name: raise value_error('Folder has no display_name') if not self.parent_id: raise value_error('Folder has no parent_id')
# coding: utf-8 n, t = [int(i) for i in input().split()] queue = list(input()) for i in range(t): queue_new = list(queue) for j in range(n-1): if queue[j]=='B' and queue[j+1]=='G': queue_new[j], queue_new[j+1] = queue_new[j+1], queue_new[j] queue = list(queue_new) print(''.join(queue))
(n, t) = [int(i) for i in input().split()] queue = list(input()) for i in range(t): queue_new = list(queue) for j in range(n - 1): if queue[j] == 'B' and queue[j + 1] == 'G': (queue_new[j], queue_new[j + 1]) = (queue_new[j + 1], queue_new[j]) queue = list(queue_new) print(''.join(queue))
### global constants ### hbar = None ### dictionary for hbar ### hbars = {'ev': 0.658229, 'cm': 5308.8, 'au': 1.0 } ### energy units ### conv = {'ev': 0.0367493, 'cm': 4.556e-6, 'au': 1.0, 'fs': 41.3413745758, 'ps': 41.3413745758*1000.} ### mass units ### me2au = 0.00054858 # amu/m_e ### distance units ### ang2bohr = 1.88973 # bohr/ang def convert_to(unit): """ """ return conv[unit] def convert_from(unit): """ """ return 1./conv[unit]
hbar = None hbars = {'ev': 0.658229, 'cm': 5308.8, 'au': 1.0} conv = {'ev': 0.0367493, 'cm': 4.556e-06, 'au': 1.0, 'fs': 41.3413745758, 'ps': 41.3413745758 * 1000.0} me2au = 0.00054858 ang2bohr = 1.88973 def convert_to(unit): """ """ return conv[unit] def convert_from(unit): """ """ return 1.0 / conv[unit]
# Per kobotoolbox/kobo-docker#301, we have changed the uWSGI port to 8001. This # provides a helpful message to anyone still trying to use port 8000. # Based upon # https://uwsgi-docs.readthedocs.io/en/latest/WSGIquickstart.html#the-first-wsgi-application html_response = b''' <html> <head><title>System configuration error</title></head> <body> <h1>System configuration error</h1> <p>Please contact the administrator of this server.</p> <p style="border: 0.1em solid black; padding: 0.5em">If you are the administrator of this server: KoBoCAT received this request on port 8000, when 8001 should have been used. Please see <a href="https://github.com/kobotoolbox/kobo-docker/issues/301"> https://github.com/kobotoolbox/kobo-docker/issues/301</a> for more information.</p> <p>Thanks for using KoBoToolbox.</p></body></html> ''' def application(env, start_response): start_response('503 Service Unavailable', [('Content-Type','text/html')]) return [html_response]
html_response = b'\n<html>\n<head><title>System configuration error</title></head>\n<body>\n<h1>System configuration error</h1>\n<p>Please contact the administrator of this server.</p>\n<p style="border: 0.1em solid black; padding: 0.5em">If you are the\nadministrator of this server: KoBoCAT received this request on port 8000, when\n8001 should have been used. Please see\n<a href="https://github.com/kobotoolbox/kobo-docker/issues/301">\nhttps://github.com/kobotoolbox/kobo-docker/issues/301</a> for more\ninformation.</p>\n<p>Thanks for using KoBoToolbox.</p></body></html>\n' def application(env, start_response): start_response('503 Service Unavailable', [('Content-Type', 'text/html')]) return [html_response]
class Action: def __init__(self, num1: float, num2: float): self.num1 = num1 self.num2 = num2 class History: def __init__(self, goldenNums: list, userActs: dict): self.goldenNums = goldenNums self.userActs = userActs class Game: def __init__(self): self.goldenNums = [] self.userActs = {} self.round = 0 self.scores = {} self.userNum = 0 def initUsers(self, users: list): """Initialize players""" self.userNum = len(users) for name in users: self.userActs[name] = [] self.scores[name] = 0 def beginRound(self): """Start a new round""" self.round += 1 def endRound(self): """End current round and judge for scores""" sm = 0 cnt = 0 for acts in self.userActs.values(): if len(acts) == self.round: sm += acts[-1].num1 + acts[-1].num2 cnt += 2 avg = 0.618 * (sm / cnt) self.goldenNums.append(avg) if self.userNum >= 2: mn, mnName = 200, set() mx, mxName = -200, set() for name, acts in self.userActs.items(): if len(acts) == self.round: x, y = abs(acts[-1].num1-avg), abs(acts[-1].num2-avg) if x < mn: mn = x mnName.clear() mnName.add(name) elif x == mn: mnName.add(name) if x > mx: mx = x mxName.clear() mxName.add(name) elif x == mx: mxName.add(name) if y < mn: mn = y mnName.clear() mnName.add(name) elif y == mn: mnName.add(name) if y > mx: mx = y mxName.clear() mxName.add(name) elif y == mx: mxName.add(name) for name in mnName: self.scores[name] += self.userNum - 2 for name in mxName: self.scores[name] += -2 for acts in self.userActs.values(): if len(acts) != self.round: acts.append(Action(0, 0)) def getHistory(self) -> History: """Gets history""" return History(self.goldenNums, self.userActs) def userAct(self, name: str, action: Action) -> bool: """Do a user action""" if (not (0 < action.num1 < 100)) or (not (0 < action.num2 < 100)): return False if name not in self.userActs: return False if len(self.userActs[name]) == self.round: return False self.userActs[name].append(action) return True
class Action: def __init__(self, num1: float, num2: float): self.num1 = num1 self.num2 = num2 class History: def __init__(self, goldenNums: list, userActs: dict): self.goldenNums = goldenNums self.userActs = userActs class Game: def __init__(self): self.goldenNums = [] self.userActs = {} self.round = 0 self.scores = {} self.userNum = 0 def init_users(self, users: list): """Initialize players""" self.userNum = len(users) for name in users: self.userActs[name] = [] self.scores[name] = 0 def begin_round(self): """Start a new round""" self.round += 1 def end_round(self): """End current round and judge for scores""" sm = 0 cnt = 0 for acts in self.userActs.values(): if len(acts) == self.round: sm += acts[-1].num1 + acts[-1].num2 cnt += 2 avg = 0.618 * (sm / cnt) self.goldenNums.append(avg) if self.userNum >= 2: (mn, mn_name) = (200, set()) (mx, mx_name) = (-200, set()) for (name, acts) in self.userActs.items(): if len(acts) == self.round: (x, y) = (abs(acts[-1].num1 - avg), abs(acts[-1].num2 - avg)) if x < mn: mn = x mnName.clear() mnName.add(name) elif x == mn: mnName.add(name) if x > mx: mx = x mxName.clear() mxName.add(name) elif x == mx: mxName.add(name) if y < mn: mn = y mnName.clear() mnName.add(name) elif y == mn: mnName.add(name) if y > mx: mx = y mxName.clear() mxName.add(name) elif y == mx: mxName.add(name) for name in mnName: self.scores[name] += self.userNum - 2 for name in mxName: self.scores[name] += -2 for acts in self.userActs.values(): if len(acts) != self.round: acts.append(action(0, 0)) def get_history(self) -> History: """Gets history""" return history(self.goldenNums, self.userActs) def user_act(self, name: str, action: Action) -> bool: """Do a user action""" if not 0 < action.num1 < 100 or not 0 < action.num2 < 100: return False if name not in self.userActs: return False if len(self.userActs[name]) == self.round: return False self.userActs[name].append(action) return True
PORT = 8050 DEBUG = True DASH_TABLE_PAGE_SIZE = 5 DEFAULT_WAVELENGTH_UNIT = "angstrom" DEFAULT_FLUX_UNIT = "F_lambda" LOGS = { "do_log":True, "base_logs_directory":"/base/logs/directory/" } MAX_NUM_TRACES = 30 CATALOGS = { "sdss": { "base_data_path":"/base/data/path/", "api_url":"http://skyserver.sdss.org/public/SkyServerWS/SearchTools/SqlSearch", "example_specid":"2947691243863304192" } }
port = 8050 debug = True dash_table_page_size = 5 default_wavelength_unit = 'angstrom' default_flux_unit = 'F_lambda' logs = {'do_log': True, 'base_logs_directory': '/base/logs/directory/'} max_num_traces = 30 catalogs = {'sdss': {'base_data_path': '/base/data/path/', 'api_url': 'http://skyserver.sdss.org/public/SkyServerWS/SearchTools/SqlSearch', 'example_specid': '2947691243863304192'}}
def show_urls( urllist, depth=0 ): for entry in urllist: if ( hasattr( entry, 'namespace' ) ): print( "\t" * depth, entry.pattern.regex.pattern, "[%s]" % entry.namespace ) else: print( "\t" * depth, entry.pattern.regex.pattern, "[%s]" % entry.name ) if hasattr( entry, 'url_patterns' ): show_urls( entry.url_patterns, depth + 1 )
def show_urls(urllist, depth=0): for entry in urllist: if hasattr(entry, 'namespace'): print('\t' * depth, entry.pattern.regex.pattern, '[%s]' % entry.namespace) else: print('\t' * depth, entry.pattern.regex.pattern, '[%s]' % entry.name) if hasattr(entry, 'url_patterns'): show_urls(entry.url_patterns, depth + 1)
class DictToObject(object): def __init__(self, dictionary): def _traverse(key, element): if isinstance(element, dict): return key, DictToObject(element) else: return key, element objd = dict(_traverse(k, v) for k, v in dictionary.items()) self.__dict__.update(objd)
class Dicttoobject(object): def __init__(self, dictionary): def _traverse(key, element): if isinstance(element, dict): return (key, dict_to_object(element)) else: return (key, element) objd = dict((_traverse(k, v) for (k, v) in dictionary.items())) self.__dict__.update(objd)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- MAX_SEQUENCE_LENGTH = 800 MAX_NB_WORDS = 20000 EMBEDDING_DIM = 50 #300 VALIDATION_SPLIT = 0.2 TEST_SPLIT = 0.10 K=10 #10 EPOCHES=100 #100 OVER_SAMPLE_NUM = 800 UNDER_SAMPLE_NUM = 500 ACTIVATION_M = 'sigmoid' LOSS_M = 'binary_crossentropy' OPTIMIZER_M = 'adam' ACTIVATION_S = 'softmax' LOSS_S = 'categorical_crossentropy' OPTIMIZER_S = 'rmsprop' head_short=['Func.','Conc.', 'Dire.', 'Purp.', 'Qual.', 'Cont.', 'Stru.', 'Patt.', 'Exam.', 'Envi.', 'Refe.', 'Non-Inf.'] head_medica = ['Class-0-593_70,Class-1-079_99,Class-2-786_09,Class-3-759_89,Class-4-753_0,Class-5-786_2,Class-6-V72_5,Class-7-511_9,Class-8-596_8,Class-9-599_0,Class-10-518_0,Class-11-593_5,Class-12-V13_09,Class-13-791_0,Class-14-789_00,Class-15-593_1,Class-16-462,Class-17-592_0,Class-18-786_59,Class-19-785_6,Class-20-V67_09,Class-21-795_5,Class-22-789_09,Class-23-786_50,Class-24-596_54,Class-25-787_03,Class-26-V42_0,Class-27-786_05,Class-28-753_21,Class-29-783_0,Class-30-277_00,Class-31-780_6,Class-32-486,Class-33-788_41,Class-34-V13_02,Class-35-493_90,Class-36-788_30,Class-37-753_3,Class-38-593_89,Class-39-758_6,Class-40-741_90,Class-41-591,Class-42-599_7,Class-43-279_12,Class-44-786_07']
max_sequence_length = 800 max_nb_words = 20000 embedding_dim = 50 validation_split = 0.2 test_split = 0.1 k = 10 epoches = 100 over_sample_num = 800 under_sample_num = 500 activation_m = 'sigmoid' loss_m = 'binary_crossentropy' optimizer_m = 'adam' activation_s = 'softmax' loss_s = 'categorical_crossentropy' optimizer_s = 'rmsprop' head_short = ['Func.', 'Conc.', 'Dire.', 'Purp.', 'Qual.', 'Cont.', 'Stru.', 'Patt.', 'Exam.', 'Envi.', 'Refe.', 'Non-Inf.'] head_medica = ['Class-0-593_70,Class-1-079_99,Class-2-786_09,Class-3-759_89,Class-4-753_0,Class-5-786_2,Class-6-V72_5,Class-7-511_9,Class-8-596_8,Class-9-599_0,Class-10-518_0,Class-11-593_5,Class-12-V13_09,Class-13-791_0,Class-14-789_00,Class-15-593_1,Class-16-462,Class-17-592_0,Class-18-786_59,Class-19-785_6,Class-20-V67_09,Class-21-795_5,Class-22-789_09,Class-23-786_50,Class-24-596_54,Class-25-787_03,Class-26-V42_0,Class-27-786_05,Class-28-753_21,Class-29-783_0,Class-30-277_00,Class-31-780_6,Class-32-486,Class-33-788_41,Class-34-V13_02,Class-35-493_90,Class-36-788_30,Class-37-753_3,Class-38-593_89,Class-39-758_6,Class-40-741_90,Class-41-591,Class-42-599_7,Class-43-279_12,Class-44-786_07']
{"tablejoin_id": 204, "matched_record_count": 156, "layer_join_attribute": "TRACT", "join_layer_id": "641", "worldmap_username": "rp", "unmatched_records_list": "", "layer_typename": "geonode:join_boston_census_blocks_0zm_boston_income_01tab_1_1", "join_layer_url": "/data/geonode:join_boston_census_blocks_0zm_boston_income_01tab_1_1", "join_layer_typename": "geonode:join_boston_census_blocks_0zm_boston_income_01tab_1_1", "table_name": "boston_income_01tab_1_1", "tablejoin_view_name": "join_boston_census_blocks_0zm_boston_income_01tab_1_1", "unmatched_record_count": 0, "layer_link": "http://localhost:8000/data/geonode:join_boston_census_blocks_0zm_boston_income_01tab_1_1", "table_id": 330, "table_join_attribute": "tract", "llbbox": "[-71.1908629979881,42.2278900020655,-70.9862559993925,42.3987970008647]", "map_image_link": "http://localhost:8000/download/wms/641/png?layers=geonode%3Ajoin_boston_census_blocks_0zm_boston_income_01tab_1_1&width=658&bbox=-71.190862998%2C42.2278900021%2C-70.9862559994%2C42.3987970009&service=WMS&format=image%2Fpng&srs=EPSG%3A4326&request=GetMap&height=550", "layer_name": "geonode:join_boston_census_blocks_0zm_boston_income_01tab_1_1", "embed_map_link": "http://localhost:8000/maps/embed/?layer=geonode:join_boston_census_blocks_0zm_boston_income_01tab_1_1"}
{'tablejoin_id': 204, 'matched_record_count': 156, 'layer_join_attribute': 'TRACT', 'join_layer_id': '641', 'worldmap_username': 'rp', 'unmatched_records_list': '', 'layer_typename': 'geonode:join_boston_census_blocks_0zm_boston_income_01tab_1_1', 'join_layer_url': '/data/geonode:join_boston_census_blocks_0zm_boston_income_01tab_1_1', 'join_layer_typename': 'geonode:join_boston_census_blocks_0zm_boston_income_01tab_1_1', 'table_name': 'boston_income_01tab_1_1', 'tablejoin_view_name': 'join_boston_census_blocks_0zm_boston_income_01tab_1_1', 'unmatched_record_count': 0, 'layer_link': 'http://localhost:8000/data/geonode:join_boston_census_blocks_0zm_boston_income_01tab_1_1', 'table_id': 330, 'table_join_attribute': 'tract', 'llbbox': '[-71.1908629979881,42.2278900020655,-70.9862559993925,42.3987970008647]', 'map_image_link': 'http://localhost:8000/download/wms/641/png?layers=geonode%3Ajoin_boston_census_blocks_0zm_boston_income_01tab_1_1&width=658&bbox=-71.190862998%2C42.2278900021%2C-70.9862559994%2C42.3987970009&service=WMS&format=image%2Fpng&srs=EPSG%3A4326&request=GetMap&height=550', 'layer_name': 'geonode:join_boston_census_blocks_0zm_boston_income_01tab_1_1', 'embed_map_link': 'http://localhost:8000/maps/embed/?layer=geonode:join_boston_census_blocks_0zm_boston_income_01tab_1_1'}
""" network-structure of vgg16 excludes fully-connection layer date: 9/17 author: arabian9ts """ # structure of convolution and pooling layer up to fully-connection layer """ size-format: [ [ convolution_kernel ], [ bias ] ] [ [ f_h, f_w, in_size, out_size ], [ out_size ] ] """ structure = { # convolution layer 1 'conv1_1': [[3, 3, 3, 64], [64]], 'conv1_2': [[3, 3, 64, 64], [64]], # convolution layer 2 'conv2_1': [[3, 3, 64, 128], [128]], 'conv2_2': [[3, 3, 128, 128], [128]], # convolution layer 3 'conv3_1': [[3, 3, 128, 256], [256]], 'conv3_2': [[3, 3, 256, 256], [256]], 'conv3_3': [[3, 3, 256, 256], [256]], # convolution layer 4 'conv4_1': [[3, 3, 256, 512], [512]], 'conv4_2': [[3, 3, 512, 512], [512]], 'conv4_3': [[3, 3, 512, 512], [512]], # convolution layer 5 'conv5_1': [[3, 3, 512, 512], [512]], 'conv5_2': [[3, 3, 512, 512], [512]], 'conv5_3': [[3, 3, 512, 512], [512]], # fully-connection 6 'fc6': [[4096, 0, 0, 0], [4096]], # fully-connection 7 'fc7': [[4096, 0, 0, 0], [4096]], # fully-connection 8 'fc8': [[1000, 0, 0, 0], [1000]], # for cifar 'cifar': [[512, 0, 0, 0], [512]], } # kernel_size is constant, so defined here ksize = [1, 2, 2, 1,] # convolution-layer-strides is already below conv_strides = [1, 1, 1, 1,] # pooling-layer-strides is already below pool_strides = [1, 2, 2, 1,]
""" network-structure of vgg16 excludes fully-connection layer date: 9/17 author: arabian9ts """ '\nsize-format:\n [ [ convolution_kernel ], [ bias ] ]\n [ [ f_h, f_w, in_size, out_size ], [ out_size ] ]\n' structure = {'conv1_1': [[3, 3, 3, 64], [64]], 'conv1_2': [[3, 3, 64, 64], [64]], 'conv2_1': [[3, 3, 64, 128], [128]], 'conv2_2': [[3, 3, 128, 128], [128]], 'conv3_1': [[3, 3, 128, 256], [256]], 'conv3_2': [[3, 3, 256, 256], [256]], 'conv3_3': [[3, 3, 256, 256], [256]], 'conv4_1': [[3, 3, 256, 512], [512]], 'conv4_2': [[3, 3, 512, 512], [512]], 'conv4_3': [[3, 3, 512, 512], [512]], 'conv5_1': [[3, 3, 512, 512], [512]], 'conv5_2': [[3, 3, 512, 512], [512]], 'conv5_3': [[3, 3, 512, 512], [512]], 'fc6': [[4096, 0, 0, 0], [4096]], 'fc7': [[4096, 0, 0, 0], [4096]], 'fc8': [[1000, 0, 0, 0], [1000]], 'cifar': [[512, 0, 0, 0], [512]]} ksize = [1, 2, 2, 1] conv_strides = [1, 1, 1, 1] pool_strides = [1, 2, 2, 1]
""" Set of tools to work with different observations. """ __all__ = ["hinode", "iris"]
""" Set of tools to work with different observations. """ __all__ = ['hinode', 'iris']
def wiki_json(name): name = name.strip().title() url = 'https://en.wikipedia.org/w/api.php?action=query&titles={0}&continue=&prop=categories&format=json'.format(name) return url def categories(response): return response.json()["query"]["pages"].values()[0]["categories"] def is_ambiguous(dic): for item in dic: if 'disambiguation' in item["title"]: return True return False def is_dead(dic): for item in dic: if 'deaths' in item["title"]: return True return False def was_born(dic): for item in dic: if 'births' in item["title"]: return True return False
def wiki_json(name): name = name.strip().title() url = 'https://en.wikipedia.org/w/api.php?action=query&titles={0}&continue=&prop=categories&format=json'.format(name) return url def categories(response): return response.json()['query']['pages'].values()[0]['categories'] def is_ambiguous(dic): for item in dic: if 'disambiguation' in item['title']: return True return False def is_dead(dic): for item in dic: if 'deaths' in item['title']: return True return False def was_born(dic): for item in dic: if 'births' in item['title']: return True return False
class ValidationError(Exception): pass class MaxSizeValidator: def __init__(self, max_size): self.so_far = 0 self.max_size = max_size def __call__(self, chunk): self.so_far += len(chunk) if self.so_far > self.max_size: raise ValidationError( 'Size must not be greater than {}'.format(self.max_size))
class Validationerror(Exception): pass class Maxsizevalidator: def __init__(self, max_size): self.so_far = 0 self.max_size = max_size def __call__(self, chunk): self.so_far += len(chunk) if self.so_far > self.max_size: raise validation_error('Size must not be greater than {}'.format(self.max_size))
# # JSON Output # def GenerateJSONArray(list, startIndex=0, endIndex=None, date=False): # Generate a json array string from a list # ASSUMPTION: All items are of the same type / if one is list all are list if(len(list) > 0 and type(list[0]) == type([])): # If the list has entries and the type of the list items is list as well acc = "[" # Accumulate the data for i in range(0, len(list)): # Recursively add the json strings of each list to the accumulator acc += GenerateJSONArray(list[i]) if(not i == len(list) - 1): acc += "," return acc + "]" # Return the accumulator else: # If the list contains non list items acc = "[" if(endIndex == None): endIndex = len(list) # Set a default endIndex if None is provided for i in range(startIndex, endIndex): # Iterate the list value = "" # Get value as string number = False # False if item is not a number try: # Try to parse the string to a number value = int(list[i]) number = True except ValueError: try: value = round(float(list[i]), 2) number = True except ValueError: value = list[i] if(not number or date): # If the item is not a number add " acc += "\"" + list[i].replace("\"", "\\\"") + "\"" else: # Else add it just as string acc += str(value).replace('.0', '') # Replace unnecessary 0s if(not i == len(list) - 1): acc += "," return acc + "]" def GenerateJSONArrayFromDict(dict, endIndex): # Generate json string from dictionary # ASSUMPTION: Dict only has number keys acc = "[" for i in range(0, endIndex): # Go through all possible keys starting from 0 if(not i in dict): # If the key is not in the dictionary val = 0 # Its value is 0 else: val = dict[i] # Else get value acc += str(val) # Add value to accumulator if(not i == endIndex - 1): acc += "," return acc + "]"
def generate_json_array(list, startIndex=0, endIndex=None, date=False): if len(list) > 0 and type(list[0]) == type([]): acc = '[' for i in range(0, len(list)): acc += generate_json_array(list[i]) if not i == len(list) - 1: acc += ',' return acc + ']' else: acc = '[' if endIndex == None: end_index = len(list) for i in range(startIndex, endIndex): value = '' number = False try: value = int(list[i]) number = True except ValueError: try: value = round(float(list[i]), 2) number = True except ValueError: value = list[i] if not number or date: acc += '"' + list[i].replace('"', '\\"') + '"' else: acc += str(value).replace('.0', '') if not i == len(list) - 1: acc += ',' return acc + ']' def generate_json_array_from_dict(dict, endIndex): acc = '[' for i in range(0, endIndex): if not i in dict: val = 0 else: val = dict[i] acc += str(val) if not i == endIndex - 1: acc += ',' return acc + ']'
#!/usr/bin/python3 def target_in(box, position): xs, xe = min(box[0]), max(box[0]) ys, ye = min(box[1]), max(box[1]) if position[0] >= xs and position[0] <= xe and position[1] >= ys and position[1] <= ye: return True return False def do_step(pos, v): next_pos = (pos[0] + v[0], pos[1] + v[1]) next_v = list(v) if next_v[0] > 0: next_v[0] -= 1 elif next_v[0] < 0: next_v[0] += 1 next_v[1] -= 1 return next_pos, tuple(next_v) def loop(target, v): pos = (0,0) max_y = 0 reached = False while pos[1] >= min(target[1]): pos, v = do_step(pos, v) if pos[1] > max_y: max_y = pos[1] t_in = target_in(target,pos) if t_in: reached = True break return reached, max_y def run(file_name): line = open(file_name, "r").readline().strip() line = line.replace("target area: ", "") tx, ty = line.split(", ") target_x = [int(i) for i in tx.replace("x=", "").split("..")] target_y = [int(i) for i in ty.replace("y=", "").split("..")] target = (target_x,target_y) trajectories = [] for y in range(min(target_y)*2,abs(max(target_y))*2): for x in range(max(target_x)*2): reached, m_y = loop(target, (x,y)) if reached: trajectories.append((x,y)) return trajectories def run_tests(): assert target_in(((20,30),(-10,-5)), (28,-7)) assert target_in(((20,30),(-10,-5)), (28,-4)) == False run_tests() traj = run('inputest') assert len(traj) == 112 traj = run('input') print(f"Answer: {len(traj)}")
def target_in(box, position): (xs, xe) = (min(box[0]), max(box[0])) (ys, ye) = (min(box[1]), max(box[1])) if position[0] >= xs and position[0] <= xe and (position[1] >= ys) and (position[1] <= ye): return True return False def do_step(pos, v): next_pos = (pos[0] + v[0], pos[1] + v[1]) next_v = list(v) if next_v[0] > 0: next_v[0] -= 1 elif next_v[0] < 0: next_v[0] += 1 next_v[1] -= 1 return (next_pos, tuple(next_v)) def loop(target, v): pos = (0, 0) max_y = 0 reached = False while pos[1] >= min(target[1]): (pos, v) = do_step(pos, v) if pos[1] > max_y: max_y = pos[1] t_in = target_in(target, pos) if t_in: reached = True break return (reached, max_y) def run(file_name): line = open(file_name, 'r').readline().strip() line = line.replace('target area: ', '') (tx, ty) = line.split(', ') target_x = [int(i) for i in tx.replace('x=', '').split('..')] target_y = [int(i) for i in ty.replace('y=', '').split('..')] target = (target_x, target_y) trajectories = [] for y in range(min(target_y) * 2, abs(max(target_y)) * 2): for x in range(max(target_x) * 2): (reached, m_y) = loop(target, (x, y)) if reached: trajectories.append((x, y)) return trajectories def run_tests(): assert target_in(((20, 30), (-10, -5)), (28, -7)) assert target_in(((20, 30), (-10, -5)), (28, -4)) == False run_tests() traj = run('inputest') assert len(traj) == 112 traj = run('input') print(f'Answer: {len(traj)}')
# login.py # # Copyright 2011 Joseph Lewis <joehms22@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. #Check password user_pass = {"admin":"21232f297a57a5a743894a0e4a801fc3"} if SESSION and 'login' in SESSION.keys() and SESSION['login']: #Redirect to the index page if already logged in. self.redirect('index.py') elif POST_DICT: try: #If the user validated correctly redirect. if POST_DICT['password'] == user_pass[POST_DICT['username']]: #Send headder SESSION['login'] = True SESSION['username'] = POST_DICT['username'] self.redirect('index.py') else: POST_DICT = [] except: POST_DICT = [] if not POST_DICT: self.send_200() page = ''' <!-- login.py Copyright 2010 Joseph Lewis <joehms22@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --> <html lang="en"> <head> <title>AI Webserver Login</title> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <LINK REL=StyleSheet HREF="assets/login.css" TYPE="text/css"> </LINK> <script type="text/javascript" src="assets/jquery.js"></script> <script type="text/javascript" src="assets/md5.js"></script> <script type="text/javascript"> function start() { $('#login').hide(); $('#login_text').hide(); $('#login').delay(1000).fadeIn(2000, function() {}); $('#login_text').fadeIn(2000, function() {}); } function hash() { //Hash the password before submission, not secure against //things like wireshark, but will at least hide plaintext. :) document.getElementById('pass').value = MD5(document.getElementById('pass').value); $('#bg').fadeOut(1000, function() {}); $('#login').fadeOut(2000, function() {}); $('#login_text').fadeOut(2000, function() {}); } </script> </head> <body id="login_page" onLoad="start()"> <!--Stretched background--> <img src="assets/earthrise.jpg" alt="background image" id="bg" /> <h1 id="login_text">AI Webserver Login</h1> <!--Login form--> <div id="login"> <form method="post"> <input type="text" name="username" placeholder="Username"/> <br /> <input type="password" id="pass" name="password" placeholder="Password"/> <br /> <input type="submit" value="Submit" onClick="hash()"/> </form> </div> </html> </body> ''' #Send body self.wfile.write(page)
user_pass = {'admin': '21232f297a57a5a743894a0e4a801fc3'} if SESSION and 'login' in SESSION.keys() and SESSION['login']: self.redirect('index.py') elif POST_DICT: try: if POST_DICT['password'] == user_pass[POST_DICT['username']]: SESSION['login'] = True SESSION['username'] = POST_DICT['username'] self.redirect('index.py') else: post_dict = [] except: post_dict = [] if not POST_DICT: self.send_200() page = '\n <!--\n login.py\n\n Copyright 2010 Joseph Lewis <joehms22@gmail.com>\n\n This program is free software; you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n MA 02110-1301, USA.\n -->\n\n <html lang="en">\n\n <head>\n <title>AI Webserver Login</title>\n <meta http-equiv="content-type" content="text/html;charset=utf-8" />\n <LINK REL=StyleSheet HREF="assets/login.css" TYPE="text/css"> </LINK>\n <script type="text/javascript" src="assets/jquery.js"></script>\n <script type="text/javascript" src="assets/md5.js"></script>\n <script type="text/javascript">\n function start()\n {\n $(\'#login\').hide();\n $(\'#login_text\').hide();\n $(\'#login\').delay(1000).fadeIn(2000, function() {});\n $(\'#login_text\').fadeIn(2000, function() {});\n }\n function hash()\n {\n //Hash the password before submission, not secure against\n //things like wireshark, but will at least hide plaintext. :)\n document.getElementById(\'pass\').value = MD5(document.getElementById(\'pass\').value);\n $(\'#bg\').fadeOut(1000, function() {});\n $(\'#login\').fadeOut(2000, function() {});\n $(\'#login_text\').fadeOut(2000, function() {});\n }\n </script>\n </head>\n\n <body id="login_page" onLoad="start()">\n <!--Stretched background-->\n <img src="assets/earthrise.jpg" alt="background image" id="bg" />\n\n <h1 id="login_text">AI Webserver Login</h1>\n <!--Login form-->\n <div id="login">\n <form method="post">\n <input type="text" name="username" placeholder="Username"/> <br />\n <input type="password" id="pass" name="password" placeholder="Password"/> <br />\n <input type="submit" value="Submit" onClick="hash()"/>\n </form>\n </div>\n </html>\n </body>\n ' self.wfile.write(page)
def print_line(): print("-" * 60) def print_full_header(build_step_name): print_line() print(" Build Step /// {}".format(build_step_name)) def print_footer(): print_line() def log(level, data): print("{0}: {1}".format(level, data))
def print_line(): print('-' * 60) def print_full_header(build_step_name): print_line() print(' Build Step /// {}'.format(build_step_name)) def print_footer(): print_line() def log(level, data): print('{0}: {1}'.format(level, data))
def partition(lst,strt,end): pindex = strt for i in range(strt,end-1): if lst[i] <= lst[end-1]: lst[pindex],lst[i] = lst[i],lst[pindex] pindex += 1 lst[pindex],lst[end-1] = lst[end-1],lst[pindex] return pindex def quickSort(lst,strt=0,end=0): if strt >= end: return pivot = partition(lst,strt,end) quickSort(lst,strt,pivot) quickSort(lst,pivot+1,end) lst = list(map(int,input('Enter the number list: ').split())) quickSort(lst,end=len(lst)) print(lst)
def partition(lst, strt, end): pindex = strt for i in range(strt, end - 1): if lst[i] <= lst[end - 1]: (lst[pindex], lst[i]) = (lst[i], lst[pindex]) pindex += 1 (lst[pindex], lst[end - 1]) = (lst[end - 1], lst[pindex]) return pindex def quick_sort(lst, strt=0, end=0): if strt >= end: return pivot = partition(lst, strt, end) quick_sort(lst, strt, pivot) quick_sort(lst, pivot + 1, end) lst = list(map(int, input('Enter the number list: ').split())) quick_sort(lst, end=len(lst)) print(lst)
class Encapsulation: def __init__(self): self.__my_price = 10 def sell(self): print("my selling price is {}".format(self.__my_price)) def setprice(self, price): self.__my_price = price encap = Encapsulation() encap.sell() encap.__my_price = 20 encap.sell() encap.setprice(20) encap.sell()
class Encapsulation: def __init__(self): self.__my_price = 10 def sell(self): print('my selling price is {}'.format(self.__my_price)) def setprice(self, price): self.__my_price = price encap = encapsulation() encap.sell() encap.__my_price = 20 encap.sell() encap.setprice(20) encap.sell()
#Code that can be used to calculate the total cost of room makeover in a house def room_area(width, length): return width*length def room_name(): print("What is the name of the room?") return input() def price(name,area): if name == "bathroom": return 20*area elif name == "kitchen": return 10*area elif name == "bedroom": return 5*area else: return 7*area def run(): name = room_name() print("What is the width of the room?") w = float(input()) print("What is the length of the room?") l = float(input())
def room_area(width, length): return width * length def room_name(): print('What is the name of the room?') return input() def price(name, area): if name == 'bathroom': return 20 * area elif name == 'kitchen': return 10 * area elif name == 'bedroom': return 5 * area else: return 7 * area def run(): name = room_name() print('What is the width of the room?') w = float(input()) print('What is the length of the room?') l = float(input())
epochs=300 batch_size=16 latent=10 lr=0.0002 weight_decay=5e-4 encode_dim=[3200, 1600, 800, 400] decode_dim=[] print_interval=10
epochs = 300 batch_size = 16 latent = 10 lr = 0.0002 weight_decay = 0.0005 encode_dim = [3200, 1600, 800, 400] decode_dim = [] print_interval = 10
def histogram(data, n, b, h): # data is a list # n is an integer # b and h are floats # Write your code here # return the variable storing the histogram # Output should be a list pass def addressbook(name_to_phone, name_to_address): #name_to_phone and name_to_address are both dictionaries # Write your code here # return the variable storing address_to_all # Output should be a dictionary pass
def histogram(data, n, b, h): pass def addressbook(name_to_phone, name_to_address): pass
class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: count = {0:0, 1:0} for el in students: count[el] += 1 i = 0 while i < len(students) and count[sandwiches[i]]: count[sandwiches[i]] -= 1 i += 1 return len(students) - i
class Solution: def count_students(self, students: List[int], sandwiches: List[int]) -> int: count = {0: 0, 1: 0} for el in students: count[el] += 1 i = 0 while i < len(students) and count[sandwiches[i]]: count[sandwiches[i]] -= 1 i += 1 return len(students) - i
streetlights = [ { "_id": "5c33cb90633a6f0003bcb38b", "latitude": 40.109356050955824, "longitude": -88.23546712954632, }, { "_id": "5c33cb90633a6f0003bcb38c", "latitude": 40.10956288950609, "longitude": -88.23546931624688, }, { "_id": "5c33cb90633a6f0003bcb38d", "latitude": 40.11072693111868, "longitude": -88.23548184676547, }, { "_id": "5c33cb90633a6f0003bcb38e", "latitude": 40.11052593366689, "longitude": -88.23548345321224, }, { "_id": "5c33cb90633a6f0003bcb38f", "latitude": 40.1105317123791, "longitude": -88.23527189093869, }, ] def get_streetlights(): return streetlights
streetlights = [{'_id': '5c33cb90633a6f0003bcb38b', 'latitude': 40.109356050955824, 'longitude': -88.23546712954632}, {'_id': '5c33cb90633a6f0003bcb38c', 'latitude': 40.10956288950609, 'longitude': -88.23546931624688}, {'_id': '5c33cb90633a6f0003bcb38d', 'latitude': 40.11072693111868, 'longitude': -88.23548184676547}, {'_id': '5c33cb90633a6f0003bcb38e', 'latitude': 40.11052593366689, 'longitude': -88.23548345321224}, {'_id': '5c33cb90633a6f0003bcb38f', 'latitude': 40.1105317123791, 'longitude': -88.23527189093869}] def get_streetlights(): return streetlights
def contador(*num): for valor in num: print(num) contad contador(1, 2, 3,)
def contador(*num): for valor in num: print(num) contad contador(1, 2, 3)
a = [[1, 2, 3], [1, 2, 3], [1, 2, 3]] def t(): for i in range(len(a)): a[i][i] = a[i][i]*2 t() print(a)
a = [[1, 2, 3], [1, 2, 3], [1, 2, 3]] def t(): for i in range(len(a)): a[i][i] = a[i][i] * 2 t() print(a)
# Vipul Patel Hectoberfest def fun1(n): for i in range(1, n + 1): if i % 3 == 0 and i % 5 != 0: print("Fizz") elif i % 5 == 0 and i % 3 != 0: print("Buzz") elif i % 3 == 0 and i % 5 == 0: print("FizzBuzz") else: print(i) num = 100 # Change num to change range fun1(num)
def fun1(n): for i in range(1, n + 1): if i % 3 == 0 and i % 5 != 0: print('Fizz') elif i % 5 == 0 and i % 3 != 0: print('Buzz') elif i % 3 == 0 and i % 5 == 0: print('FizzBuzz') else: print(i) num = 100 fun1(num)
# Find the first n ugly numbers # Ugly numbers are the numbers whose prime factors are 2,3 or 5. # Normal Approach : # Run a loop till n and check if it has 2,3 or 5 as the only prime factors # if yes, then print the number. It is in-efficient but has constant extra space. # DP approach : # As we know, every other number which is an ugly number can be easily computed by # again multiplying it with that prime factor. So stor previous ugly numbers till we get n ugly numbers # This approach is efficient than naive solution but has O(n) space requirement. def ugly_numbers(n): # keeping a list initialised to 1(as it a ugly number) to store ugly numbers ugly = [1] # keeping three index values for tracking index of current number # being divisible by 2,3 or 5 index_of_2, index_of_3, index_of_5 = 0, 0, 0 # loop till the length of ugly reaches n i.e we have n amount of ugly numbers while len(ugly) < n: # append the multiples checking for the minimum value of all multiples ugly.append(min(ugly[index_of_2] * 2, min(ugly[index_of_3] * 3, ugly[index_of_5] * 5))) # keep incrementing the indexes as well encounter multiples of 2,3 or 5 respectively if ugly[-1] == ugly[index_of_2] * 2: index_of_2 += 1 if ugly[-1] == ugly[index_of_3] * 3: index_of_3 += 1 if ugly[-1] == ugly[index_of_5] * 5: index_of_5 += 1 # return the list return ugly # Driver Code n = 20 print(ugly_numbers(n)) # Time Complexity : O(n) # Space Complexity : O(n)
def ugly_numbers(n): ugly = [1] (index_of_2, index_of_3, index_of_5) = (0, 0, 0) while len(ugly) < n: ugly.append(min(ugly[index_of_2] * 2, min(ugly[index_of_3] * 3, ugly[index_of_5] * 5))) if ugly[-1] == ugly[index_of_2] * 2: index_of_2 += 1 if ugly[-1] == ugly[index_of_3] * 3: index_of_3 += 1 if ugly[-1] == ugly[index_of_5] * 5: index_of_5 += 1 return ugly n = 20 print(ugly_numbers(n))