content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class BST: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right @staticmethod def array2BST(array): ''' array:sorted array ''' n = len(array) if n == 0: return None m = n//2 left,root,right = array[:m],array[m],array[m+1:] return BST(root,BST.array2BST(left),BST.array2BST(right)) @staticmethod def BST2array(node): ''' node:BST node ''' if not node: return [] return BST.BST2array(node.left)+[node.val]+BST.BST2array(node.right)
class Bst: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right @staticmethod def array2_bst(array): """ array:sorted array """ n = len(array) if n == 0: return None m = n // 2 (left, root, right) = (array[:m], array[m], array[m + 1:]) return bst(root, BST.array2BST(left), BST.array2BST(right)) @staticmethod def bst2array(node): """ node:BST node """ if not node: return [] return BST.BST2array(node.left) + [node.val] + BST.BST2array(node.right)
TANGO_PALLETE = [ '2e2e34343636', 'cccc00000000', '4e4e9a9a0606', 'c4c4a0a00000', '34346565a4a4', '757550507b7b', '060698989a9a', 'd3d3d7d7cfcf', '555557575353', 'efef29292929', '8a8ae2e23434', 'fcfce9e94f4f', '72729f9fcfcf', 'adad7f7fa8a8', '3434e2e2e2e2', 'eeeeeeeeecec', ] def parse_tango_color(c): r = int(c[:4][:2], 16) g = int(c[4:8][:2], 16) b = int(c[8:][:2], 16) return [r, g, b, 0xFF] def apply_color(cfg, color_table): cfg.default_foreground_color = parse_tango_color('eeeeeeeeecec') cfg.default_background_color = parse_tango_color('323232323232') cfg.default_cursor_color = cfg.default_foreground_color for i in range(len(TANGO_PALLETE)): if i < len(color_table): color_table[i] = parse_tango_color(TANGO_PALLETE[i])
tango_pallete = ['2e2e34343636', 'cccc00000000', '4e4e9a9a0606', 'c4c4a0a00000', '34346565a4a4', '757550507b7b', '060698989a9a', 'd3d3d7d7cfcf', '555557575353', 'efef29292929', '8a8ae2e23434', 'fcfce9e94f4f', '72729f9fcfcf', 'adad7f7fa8a8', '3434e2e2e2e2', 'eeeeeeeeecec'] def parse_tango_color(c): r = int(c[:4][:2], 16) g = int(c[4:8][:2], 16) b = int(c[8:][:2], 16) return [r, g, b, 255] def apply_color(cfg, color_table): cfg.default_foreground_color = parse_tango_color('eeeeeeeeecec') cfg.default_background_color = parse_tango_color('323232323232') cfg.default_cursor_color = cfg.default_foreground_color for i in range(len(TANGO_PALLETE)): if i < len(color_table): color_table[i] = parse_tango_color(TANGO_PALLETE[i])
def gen(): i = 0 while 1: yield i i += 1 g = gen() try: g.pend_throw except AttributeError: print("SKIP") raise SystemExit print(next(g)) print(next(g)) g.pend_throw(ValueError()) v = None try: v = next(g) except Exception as e: print("raised", repr(e)) print("ret was:", v) # It's legal to pend exception in a just-started generator, just the same # as it's legal to .throw() into it. g = gen() g.pend_throw(ValueError()) try: next(g) except ValueError: print("ValueError from just-started gen")
def gen(): i = 0 while 1: yield i i += 1 g = gen() try: g.pend_throw except AttributeError: print('SKIP') raise SystemExit print(next(g)) print(next(g)) g.pend_throw(value_error()) v = None try: v = next(g) except Exception as e: print('raised', repr(e)) print('ret was:', v) g = gen() g.pend_throw(value_error()) try: next(g) except ValueError: print('ValueError from just-started gen')
_base_ = [ '../../../_base_/datasets/imagenet/swin_sz224_4xbs256.py', '../../../_base_/default_runtime.py', ] # model settings model = dict( type='MixUpClassification', pretrained=None, alpha=0.2, mix_mode="cutmix", mix_args=dict( attentivemix=dict(grid_size=32, top_k=None, beta=8), # AttentiveMix+ in this repo (use pre-trained) automix=dict(mask_adjust=0, lam_margin=0), # require pre-trained mixblock fmix=dict(decay_power=3, size=(224,224), max_soft=0., reformulate=False), manifoldmix=dict(layer=(0, 3)), puzzlemix=dict(transport=True, t_batch_size=32, t_size=-1, # adjust t_batch_size if CUDA out of memory mp=None, block_num=4, # block_num<=4 and mp=2/4 for fast training beta=1.2, gamma=0.5, eta=0.2, neigh_size=4, n_labels=3, t_eps=0.8), resizemix=dict(scope=(0.1, 0.8), use_alpha=True), samix=dict(mask_adjust=0, lam_margin=0.08), # require pre-trained mixblock ), backbone=dict( type='ConvNeXt', arch='tiny', out_indices=(3,), norm_cfg=dict(type='LN2d', eps=1e-6), act_cfg=dict(type='GELU'), drop_path_rate=0.1, gap_before_final_norm=True, ), head=dict( type='ClsMixupHead', # mixup CE + label smooth loss=dict(type='LabelSmoothLoss', label_smooth_val=0.1, num_classes=1000, mode='original', loss_weight=1.0), with_avg_pool=False, # gap_before_final_norm is True in_channels=768, num_classes=1000) ) # interval for accumulate gradient update_interval = 2 # total: 8 x bs256 x 2 accumulates = bs4096 # additional hooks custom_hooks = [ dict(type='EMAHook', # EMA_W = (1 - m) * EMA_W + m * W momentum=0.9999, warmup='linear', warmup_iters=20 * 626, warmup_ratio=0.9, # warmup 20 epochs. update_interval=update_interval, ), ] # optimizer optimizer = dict( type='AdamW', lr=4e-3, # lr = 5e-4 * (256 * 4) * 4 accumulate / 1024 = 4e-3 / bs4096 weight_decay=0.05, eps=1e-8, betas=(0.9, 0.999), paramwise_options={ '(bn|ln|gn)(\d+)?.(weight|bias)': dict(weight_decay=0.), 'bias': dict(weight_decay=0.), }) # apex use_fp16 = True fp16 = dict(type='apex', loss_scale=dict(init_scale=512., mode='dynamic')) optimizer_config = dict(grad_clip=None, update_interval=update_interval, use_fp16=use_fp16) # lr scheduler lr_config = dict( policy='CosineAnnealing', by_epoch=False, min_lr=1e-5, warmup='linear', warmup_iters=20, warmup_by_epoch=True, # warmup 20 epochs. warmup_ratio=1e-6, ) # runtime settings runner = dict(type='EpochBasedRunner', max_epochs=300)
_base_ = ['../../../_base_/datasets/imagenet/swin_sz224_4xbs256.py', '../../../_base_/default_runtime.py'] model = dict(type='MixUpClassification', pretrained=None, alpha=0.2, mix_mode='cutmix', mix_args=dict(attentivemix=dict(grid_size=32, top_k=None, beta=8), automix=dict(mask_adjust=0, lam_margin=0), fmix=dict(decay_power=3, size=(224, 224), max_soft=0.0, reformulate=False), manifoldmix=dict(layer=(0, 3)), puzzlemix=dict(transport=True, t_batch_size=32, t_size=-1, mp=None, block_num=4, beta=1.2, gamma=0.5, eta=0.2, neigh_size=4, n_labels=3, t_eps=0.8), resizemix=dict(scope=(0.1, 0.8), use_alpha=True), samix=dict(mask_adjust=0, lam_margin=0.08)), backbone=dict(type='ConvNeXt', arch='tiny', out_indices=(3,), norm_cfg=dict(type='LN2d', eps=1e-06), act_cfg=dict(type='GELU'), drop_path_rate=0.1, gap_before_final_norm=True), head=dict(type='ClsMixupHead', loss=dict(type='LabelSmoothLoss', label_smooth_val=0.1, num_classes=1000, mode='original', loss_weight=1.0), with_avg_pool=False, in_channels=768, num_classes=1000)) update_interval = 2 custom_hooks = [dict(type='EMAHook', momentum=0.9999, warmup='linear', warmup_iters=20 * 626, warmup_ratio=0.9, update_interval=update_interval)] optimizer = dict(type='AdamW', lr=0.004, weight_decay=0.05, eps=1e-08, betas=(0.9, 0.999), paramwise_options={'(bn|ln|gn)(\\d+)?.(weight|bias)': dict(weight_decay=0.0), 'bias': dict(weight_decay=0.0)}) use_fp16 = True fp16 = dict(type='apex', loss_scale=dict(init_scale=512.0, mode='dynamic')) optimizer_config = dict(grad_clip=None, update_interval=update_interval, use_fp16=use_fp16) lr_config = dict(policy='CosineAnnealing', by_epoch=False, min_lr=1e-05, warmup='linear', warmup_iters=20, warmup_by_epoch=True, warmup_ratio=1e-06) runner = dict(type='EpochBasedRunner', max_epochs=300)
# Level: Hard def isMatch(s: str, p: str) -> bool: if not p: return not s n_s = len(s) n_p = len(p) j = 0 i = -1 while i < n_s-1: i = i+ 1 if j >= n_p: return False if p[j] == '*': while s[i]==s[i-1]: i += 1 j += 1 if p[j] == '.' or s[i] == p[j]: j += 1 # continue elif s[i] != p[j] and j<n_p-1: j += 2 else: return False return True if __name__ == "__main__": ss = 'abbbbbc' p = 'a*' print(isMatch(ss, p))
def is_match(s: str, p: str) -> bool: if not p: return not s n_s = len(s) n_p = len(p) j = 0 i = -1 while i < n_s - 1: i = i + 1 if j >= n_p: return False if p[j] == '*': while s[i] == s[i - 1]: i += 1 j += 1 if p[j] == '.' or s[i] == p[j]: j += 1 elif s[i] != p[j] and j < n_p - 1: j += 2 else: return False return True if __name__ == '__main__': ss = 'abbbbbc' p = 'a*' print(is_match(ss, p))
# Take number, and convert integer to string # Calculate and return number of digits def get_num_digits(num): # Convert int to str num_str = str(num) # Calculate number of digits digits = len(num_str) return digits # Define main function def main(): # Prompt user for an integer number = int(input('Enter an integer: ')) # Obtain number of digits num_digits = get_num_digits(number) # Display result print(f'The number of digits in number {number} is {num_digits}.') # Call main function main()
def get_num_digits(num): num_str = str(num) digits = len(num_str) return digits def main(): number = int(input('Enter an integer: ')) num_digits = get_num_digits(number) print(f'The number of digits in number {number} is {num_digits}.') main()
#Atoi stands for ASCII to Integer Conversion def atoi(string): res = 0 # Iterate through all characters of # input and update result for i in range(len(string)): res = res * 10 + (ord(string[i]) - ord('0')) return res #Adjustment contains rule of three for calculating an integer given another integer representing a percentage def Adjustment(a, b): return (a * b) / 100
def atoi(string): res = 0 for i in range(len(string)): res = res * 10 + (ord(string[i]) - ord('0')) return res def adjustment(a, b): return a * b / 100
def bypass_incompatible_branch(job): return (job.settings.bypass_incompatible_branch or job.author_bypass.get('bypass_incompatible_branch', False)) def bypass_peer_approval(job): return (job.settings.bypass_peer_approval or job.author_bypass.get('bypass_peer_approval', False)) def bypass_leader_approval(job): return (job.settings.bypass_leader_approval or job.author_bypass.get('bypass_leader_approval', False)) def bypass_author_approval(job): return (job.settings.bypass_author_approval or job.author_bypass.get('bypass_author_approval', False)) def bypass_build_status(job): return (job.settings.bypass_build_status or job.author_bypass.get('bypass_build_status', False)) def bypass_jira_check(job): return (job.settings.bypass_jira_check or job.author_bypass.get('bypass_jira_check', False))
def bypass_incompatible_branch(job): return job.settings.bypass_incompatible_branch or job.author_bypass.get('bypass_incompatible_branch', False) def bypass_peer_approval(job): return job.settings.bypass_peer_approval or job.author_bypass.get('bypass_peer_approval', False) def bypass_leader_approval(job): return job.settings.bypass_leader_approval or job.author_bypass.get('bypass_leader_approval', False) def bypass_author_approval(job): return job.settings.bypass_author_approval or job.author_bypass.get('bypass_author_approval', False) def bypass_build_status(job): return job.settings.bypass_build_status or job.author_bypass.get('bypass_build_status', False) def bypass_jira_check(job): return job.settings.bypass_jira_check or job.author_bypass.get('bypass_jira_check', False)
class Heap: def __init__(self): self.items = dict() # key - (value, index) self.indexes = [] # index - key // to know indexes # Usefull functions def swap(self, i, j): x = self.indexes[i] # key of 1 item y = self.indexes[j] # key of 2 item # swap keys in index array self.indexes[i] = y self.indexes[j] = x temp = self.items[x][1] # index of 1 item # swap indexes in dictionary self.items.update({x: (self.items[x][0], self.items[y][1])}) self.items.update({y: (self.items[y][0], temp)}) def bigger(self, i, j): if self.indexes[i] <= self.indexes[j]: return False else: return True # Check family UwU def hasParent(self, i): if (i - 1)/2 >= 0: return True return False def parentIndex(self, i): return int((i - 1)/2) def hasLeft(self, i): if i*2 + 1 < len(self.indexes): return True return False def leftIndex(self, i): return int(i*2 + 1) def hasRight(self, i): if i*2 + 2 < len(self.indexes): return True return False def rightIndex(self, i): return int(i*2 + 2) # heapifys def heapifyUp(self, i=None): if i: index = i else: index = len(self.indexes) - 1 while self.hasParent(index) and self.bigger(self.parentIndex(index), index): self.swap(self.parentIndex(index), index) index = self.parentIndex(index) def heapifyDown(self, i=0): index = i while self.hasLeft(index): smaller = self.leftIndex(index) if self.hasRight(index) and self.bigger(self.leftIndex(index), self.rightIndex(index)): smaller = self.rightIndex(index) if self.bigger(smaller, index): break else: self.swap(index, smaller) index = smaller # all needed methods def add(self, key, data): if self.items.get(key, None): raise(Exception) self.items[key] = (data, int(len(self.indexes))) self.indexes.append(key) self.heapifyUp() def set(self, key, data): temp = self.items.get(key, None) if not temp: raise(Exception) self.items[key] = (data, temp[1]) def delete(self, key): temp = self.items.get(key, None) if not temp: raise(Exception) if len(self.indexes) > 1: lastKey = self.indexes[-1] last = self.items.get(lastKey, None) # set last item index of deleted self.items.update({lastKey: (last[0], temp[1])}) # set key of last item to deleted index self.indexes[temp[1]] = lastKey self.indexes.pop() del self.items[key] if temp[1] < len(self.indexes): # dont heapify if deleted last element self.heapifyDown(i=temp[1]) self.heapifyUp(i=temp[1]) def search(self, key): temp = self.items.get(key, None) if temp: print('1', temp[1], temp[0]) else: print('0') def min(self): if len(self.indexes) == 0: raise(Exception) key = self.indexes[0] print(key, '0', self.items[key][0]) def max(self): if len(self.indexes) == 0: raise(Exception) i = int(len(self.indexes)/2) maxKey = self.indexes[i] index = i while i < len(self.indexes): if maxKey < self.indexes[i]: maxKey = self.indexes[i] index = i i += 1 print(maxKey, index, self.items[maxKey][0]) def extract(self): if len(self.indexes) == 0: raise(Exception) rootKey = self.indexes[0] rootData = self.items[rootKey][0] del self.items[rootKey] if len(self.indexes) > 1: self.indexes[0] = self.indexes.pop() # set top item index to 0 self.items.update({self.indexes[0] : (self.items[self.indexes[0]][0], 0)}) self.heapifyDown() else: self.indexes.pop() print(rootKey, rootData) def print(self): height = 0 index = 0 out = '' i = 0 if len(self.indexes) == 0: out += '_\n' print('_') return while i < len(self.indexes): lineLen = 1 << height index += 1 key = self.indexes[i] out += '[' + str(key) + ' ' + self.items[key][0] if height != 0: out += ' ' + str(self.indexes[self.parentIndex(i)]) out += ']' if index == lineLen: out += '\n' index = 0 height += 1 else: out += ' ' i += 1 if index != 0 and index < lineLen: out += '_ ' * (lineLen - index) print(out[0:-1]) else: print(out, end='') cycle = True heap = Heap() while cycle: try: line = input() cmd = line.split(' ', 2) try: if len(cmd) == 1 and cmd[0] == '': continue if len(cmd) == 2 and cmd[0] == '' and cmd[1] == '': continue if cmd[0] == 'add': heap.add(int(cmd[1]), cmd[2]) elif cmd[0] == 'set': heap.set(int(cmd[1]), cmd[2]) elif cmd[0] == 'delete': heap.delete(int(cmd[1])) elif cmd[0] == 'search': heap.search(int(cmd[1])) elif cmd[0] == 'min': heap.min() elif cmd[0] == 'max': heap.max() elif cmd[0] == 'extract': heap.extract() elif cmd[0] == 'print': heap.print() else: raise(Exception) except Exception: print('error') continue except Exception: cycle = False
class Heap: def __init__(self): self.items = dict() self.indexes = [] def swap(self, i, j): x = self.indexes[i] y = self.indexes[j] self.indexes[i] = y self.indexes[j] = x temp = self.items[x][1] self.items.update({x: (self.items[x][0], self.items[y][1])}) self.items.update({y: (self.items[y][0], temp)}) def bigger(self, i, j): if self.indexes[i] <= self.indexes[j]: return False else: return True def has_parent(self, i): if (i - 1) / 2 >= 0: return True return False def parent_index(self, i): return int((i - 1) / 2) def has_left(self, i): if i * 2 + 1 < len(self.indexes): return True return False def left_index(self, i): return int(i * 2 + 1) def has_right(self, i): if i * 2 + 2 < len(self.indexes): return True return False def right_index(self, i): return int(i * 2 + 2) def heapify_up(self, i=None): if i: index = i else: index = len(self.indexes) - 1 while self.hasParent(index) and self.bigger(self.parentIndex(index), index): self.swap(self.parentIndex(index), index) index = self.parentIndex(index) def heapify_down(self, i=0): index = i while self.hasLeft(index): smaller = self.leftIndex(index) if self.hasRight(index) and self.bigger(self.leftIndex(index), self.rightIndex(index)): smaller = self.rightIndex(index) if self.bigger(smaller, index): break else: self.swap(index, smaller) index = smaller def add(self, key, data): if self.items.get(key, None): raise Exception self.items[key] = (data, int(len(self.indexes))) self.indexes.append(key) self.heapifyUp() def set(self, key, data): temp = self.items.get(key, None) if not temp: raise Exception self.items[key] = (data, temp[1]) def delete(self, key): temp = self.items.get(key, None) if not temp: raise Exception if len(self.indexes) > 1: last_key = self.indexes[-1] last = self.items.get(lastKey, None) self.items.update({lastKey: (last[0], temp[1])}) self.indexes[temp[1]] = lastKey self.indexes.pop() del self.items[key] if temp[1] < len(self.indexes): self.heapifyDown(i=temp[1]) self.heapifyUp(i=temp[1]) def search(self, key): temp = self.items.get(key, None) if temp: print('1', temp[1], temp[0]) else: print('0') def min(self): if len(self.indexes) == 0: raise Exception key = self.indexes[0] print(key, '0', self.items[key][0]) def max(self): if len(self.indexes) == 0: raise Exception i = int(len(self.indexes) / 2) max_key = self.indexes[i] index = i while i < len(self.indexes): if maxKey < self.indexes[i]: max_key = self.indexes[i] index = i i += 1 print(maxKey, index, self.items[maxKey][0]) def extract(self): if len(self.indexes) == 0: raise Exception root_key = self.indexes[0] root_data = self.items[rootKey][0] del self.items[rootKey] if len(self.indexes) > 1: self.indexes[0] = self.indexes.pop() self.items.update({self.indexes[0]: (self.items[self.indexes[0]][0], 0)}) self.heapifyDown() else: self.indexes.pop() print(rootKey, rootData) def print(self): height = 0 index = 0 out = '' i = 0 if len(self.indexes) == 0: out += '_\n' print('_') return while i < len(self.indexes): line_len = 1 << height index += 1 key = self.indexes[i] out += '[' + str(key) + ' ' + self.items[key][0] if height != 0: out += ' ' + str(self.indexes[self.parentIndex(i)]) out += ']' if index == lineLen: out += '\n' index = 0 height += 1 else: out += ' ' i += 1 if index != 0 and index < lineLen: out += '_ ' * (lineLen - index) print(out[0:-1]) else: print(out, end='') cycle = True heap = heap() while cycle: try: line = input() cmd = line.split(' ', 2) try: if len(cmd) == 1 and cmd[0] == '': continue if len(cmd) == 2 and cmd[0] == '' and (cmd[1] == ''): continue if cmd[0] == 'add': heap.add(int(cmd[1]), cmd[2]) elif cmd[0] == 'set': heap.set(int(cmd[1]), cmd[2]) elif cmd[0] == 'delete': heap.delete(int(cmd[1])) elif cmd[0] == 'search': heap.search(int(cmd[1])) elif cmd[0] == 'min': heap.min() elif cmd[0] == 'max': heap.max() elif cmd[0] == 'extract': heap.extract() elif cmd[0] == 'print': heap.print() else: raise Exception except Exception: print('error') continue except Exception: cycle = False
''' All the reserved, individual words used in MAlice. ''' A = "a" ALICE = "Alice" AND = "and" ATE = "ate" BECAME = "became" BECAUSE = "because" BUT = "but" CLOSED = "closed" COMMA = "," CONTAINED = "contained" DOT = "." DRANK = "drank" EITHER = "either" ENOUGH = "enough" EVENTUALLY = "eventually" FOUND = "found" HAD = "had" HATTA = "hatta" LETTER = "letter" LOOKING_GLASS = "looking-glass" LPAR = "(" MAYBE = "maybe" NUMBER = "number" OF = "of" OPENED = "opened" OR = "or" PERHAPS = "perhaps" PIECE = "piece" QUESTION = "?" ROOM = "room" RPAR = ")" S = "'s" SAID = "said" SENTENCE = "sentence" SO = "so" SPIDER = "spider" SPOKE = "spoke" THE = "The" THEN = "then" TIMES = "times" TOO = "too" UNDERSCORE = "_" UNSURE = "unsure" WAS = "was" WHAT = "what" WHICH = "which" RESTRICTED = [ A, ALICE, AND, ATE, BECAME ,BECAUSE ,BUT ,CLOSED ,COMMA ,CONTAINED ,DOT ,DRANK ,EITHER ,ENOUGH ,EVENTUALLY ,FOUND ,HAD ,HATTA ,LETTER ,LOOKING_GLASS ,LPAR ,MAYBE ,NUMBER ,OF ,OPENED ,OR ,PERHAPS ,PIECE ,QUESTION ,ROOM ,RPAR ,S ,SAID, SENTENCE ,SO ,SPIDER ,SPOKE ,THE ,THEN ,TIMES ,TOO ,UNDERSCORE ,UNSURE ,WAS ,WHAT ,WHICH]
""" All the reserved, individual words used in MAlice. """ a = 'a' alice = 'Alice' and = 'and' ate = 'ate' became = 'became' because = 'because' but = 'but' closed = 'closed' comma = ',' contained = 'contained' dot = '.' drank = 'drank' either = 'either' enough = 'enough' eventually = 'eventually' found = 'found' had = 'had' hatta = 'hatta' letter = 'letter' looking_glass = 'looking-glass' lpar = '(' maybe = 'maybe' number = 'number' of = 'of' opened = 'opened' or = 'or' perhaps = 'perhaps' piece = 'piece' question = '?' room = 'room' rpar = ')' s = "'s" said = 'said' sentence = 'sentence' so = 'so' spider = 'spider' spoke = 'spoke' the = 'The' then = 'then' times = 'times' too = 'too' underscore = '_' unsure = 'unsure' was = 'was' what = 'what' which = 'which' restricted = [A, ALICE, AND, ATE, BECAME, BECAUSE, BUT, CLOSED, COMMA, CONTAINED, DOT, DRANK, EITHER, ENOUGH, EVENTUALLY, FOUND, HAD, HATTA, LETTER, LOOKING_GLASS, LPAR, MAYBE, NUMBER, OF, OPENED, OR, PERHAPS, PIECE, QUESTION, ROOM, RPAR, S, SAID, SENTENCE, SO, SPIDER, SPOKE, THE, THEN, TIMES, TOO, UNDERSCORE, UNSURE, WAS, WHAT, WHICH]
def migrate(): print('migrating to version 2')
def migrate(): print('migrating to version 2')
test = { 'name': 'q2b3', 'points': 5, 'suites': [ { 'cases': [ { 'code': '>>> ' 'histories_2b[2].model.count_params()\n' '119260', 'hidden': False, 'locked': False}, { 'code': '>>> ' 'histories_2b[2].model.layers[1].activation.__name__\n' "'sigmoid'", 'hidden': False, 'locked': False}, { 'code': '>>> ' 'histories_2b[2].model.layers[1].units\n' '150', 'hidden': False, 'locked': False}, { 'code': '>>> ' "histories_2b[2].history['loss'][4] " '<= ' "histories_2b[1].history['loss'][4]\n" 'True', 'hidden': False, 'locked': False}], 'scored': True, 'setup': '', 'teardown': '', 'type': 'doctest'}]}
test = {'name': 'q2b3', 'points': 5, 'suites': [{'cases': [{'code': '>>> histories_2b[2].model.count_params()\n119260', 'hidden': False, 'locked': False}, {'code': ">>> histories_2b[2].model.layers[1].activation.__name__\n'sigmoid'", 'hidden': False, 'locked': False}, {'code': '>>> histories_2b[2].model.layers[1].units\n150', 'hidden': False, 'locked': False}, {'code': ">>> histories_2b[2].history['loss'][4] <= histories_2b[1].history['loss'][4]\nTrue", 'hidden': False, 'locked': False}], 'scored': True, 'setup': '', 'teardown': '', 'type': 'doctest'}]}
def solve(n, red , blue): rcount = bcount = 0 for i in range(n): if int(red[i]) > int(blue[i]): rcount = rcount +1 elif int(red[i]) < int(blue[i]): bcount = bcount + 1 print( 'RED' if rcount>bcount else ('BLUE' if bcount>rcount else 'EQUAL')) if __name__ == "__main__": T = int(input()) for t in range(T): n = int(input()) red = input() blue = input() solve(n, red, blue)
def solve(n, red, blue): rcount = bcount = 0 for i in range(n): if int(red[i]) > int(blue[i]): rcount = rcount + 1 elif int(red[i]) < int(blue[i]): bcount = bcount + 1 print('RED' if rcount > bcount else 'BLUE' if bcount > rcount else 'EQUAL') if __name__ == '__main__': t = int(input()) for t in range(T): n = int(input()) red = input() blue = input() solve(n, red, blue)
class a: def __init__(self,da): self.da = da return def go(self): dd() return None def dd(): print('ok') return None aa = a(1) aa.go()
class A: def __init__(self, da): self.da = da return def go(self): dd() return None def dd(): print('ok') return None aa = a(1) aa.go()
''' Created on Dec 27, 2019 @author: duane ''' DOLLAR = ord('$') LBRACE = ord('{') RBRACE = ord('}') LPAREN = ord('(') RPAREN = ord(')') class IStrFindResult(object): OK = 0 NOTFOUND = 1 SYNTAX = 2 def __init__(self): self.result = IStrFindResult.SYNTAX self.lhs = 0 self.rhs = 0 self.name = None class IStr(list): ''' This closely models a basic ASCII string Note: Unicode strings are expressly not supported here. The problem this addresses occurs during macro processing. Sometimes macros are defined externally Other times, macros are fully defined with a package. Often macros need to be resolved either partially or fully When a macro is only external - they get in the way of resolving other macros To work around that, we convert the string into an array of integers Then for every macro byte that is 'external' we add 0x100 This makes the byte 'non-matchable' Later, when we convert the resolved string into we strip the 0x100. ''' IGNORE = 0x100 def __init__(self, s): ''' Constructor ''' # convert to integers list.__init__(self, map(ord, s)) def __str__(self): # return as string, stripping flags return ''.join(map(lambda v: chr(v & 0xff), self)) def sslice(self, lhs, rhs): # return as string, stripping flags return ''.join(map(lambda v: chr(v & 0xff), self[lhs:rhs])) def iarray(self): return self[:] def mark(self, lhs, rhs, flagvalue=IGNORE): ''' Apply flags to locations between left and right hand sides, ie: [lhs:rhs] ''' for idx in range(lhs, rhs): self[idx] |= flagvalue def locate(self, needle, lhs, rhs): '''Find this needle(char) in the hay stack(list).''' try: return self.index(needle, lhs, rhs) except: # not found return -1 def replace(self, lhs, rhs, newcontent): '''replace the data between [lhs:rhs] with newcontent''' self[lhs: rhs] = map(ord, newcontent) def next_macro(self, lhs, rhs): ''' Find a macro within the string, return (lhs,rhs) if found If not found, return (-1,-1) If syntax error, return (-2,-2) ''' result = IStrFindResult() result.lhs = lhs result.rhs = rhs # if it is not long enough... if (rhs - lhs) < 4: result.code = result.NOTFOUND return result # We search for the CLOSING # Consider nested: ${ ${foo}_${bar} } # The first thing we must do is "foo" # So find the close tmp = self.locate(RBRACE, result.lhs,result.rhs) if tmp >= 0: _open_symbol = LBRACE else: tmp = self.locate(RPAREN,result.lhs,result.rhs) _open_symbol = RPAREN if tmp < 0: # not found result.code = result.NOTFOUND return result # We want to end at RHS where the closing symbol is result.rhs = tmp while result.lhs < result.rhs: # find DOLLAR dollar_loc = self.locate(DOLLAR, result.lhs, result.rhs) if dollar_loc < 0: # above, we know we have a CLOSE # We could call this a SYNTAX error # but ... we won't we'll leave this as NOT FOUND result.code = result.NOTFOUND return result # we have: DOLLAR + CLOSE # Can we find DOLLAR + OPEN? ch = self[dollar_loc+1] if ch != _open_symbol: # Nope... try again after dollar result.lhs = dollar_loc+1 continue result.lhs = dollar_loc # Do we have a nested macro, ie: ${${x}} tmp = self.locate(DOLLAR, dollar_loc + 1, result.rhs) if tmp >= 0: # we do have a nested macro result.lhs = tmp continue # nope, we are good # Everything between LHS and RHS should be a macro result.code = result.OK result.name = self.sslice(result.lhs + 2, result.rhs) # the RHS should include the closing symbol result.rhs += 1 return result # not found syntax stray dollar or brace result.code = result.SYNTAX return result def test_istr(): def check2(l, r, text, dut): print("----") print("Check (%d,%d)" % (l, r)) print("s = %s" % str(dut)) print("i = %s" % dut.iarray()) result = dut.next_macro(0, len(dut)) if (result.lhs != l) or (result.rhs != r): print("str = %s" % str(dut)) print("int = %s" % dut.iarray()) print("Error: (%d,%d) != (%d,%d)" % (l, r, result.lhs, result.rhs)) assert (False) if text is not None: assert( result.name == text ) dut.mark(l, r) return dut def check(l, r, s): if l >= 0: expected = s[l + 2:r - 1] else: expected = None dut = IStr(s) check2(l, r, expected, dut) st = str(dut) assert (st == s) return dut check(-1, -1, "") check(-1, -1, "a") check(-1, -1, "ab") check(-1, -1, "abc") check(-1, -1, "abcd") check(-1, -1, "abcde") check(-1, -1, "abcdef") check(0, 4, "${a}") check(0, 5, "${ab}") check(0, 6, "${abc}") check(0, 7, "${abcd}") check(1, 5, "a${a}") check(2, 6, "ab${a}") check(3, 7, "abc${a}") check(4, 8, "abcd${a}") check(5, 9, "abcde${a}") check(0, 4, "${a}a") check(0, 4, "${a}ab") check(0, 4, "${a}abc") check(0, 4, "${a}abcd") check(0, 4, "${a}abcde") dut = check(4, 8, "abcd${a}xyz") dut.replace(4, 8, "X") check2(-1, -1, None, dut) r = str(dut) print("Got: %s" % r) assert ("abcdXxyz" == str(dut)) # now nested tests dut = check(5, 9, "abc${${Y}}xyz") dut.replace(5, 9, "X") r = str(dut) assert (r == "abc${X}xyz") dut = check2(3, 7, "${X}", dut) dut.replace(3, 7, "ABC") s = str(dut) r = "abcABCxyz" assert (s == r) print("Success") if __name__ == '__main__': test_istr()
""" Created on Dec 27, 2019 @author: duane """ dollar = ord('$') lbrace = ord('{') rbrace = ord('}') lparen = ord('(') rparen = ord(')') class Istrfindresult(object): ok = 0 notfound = 1 syntax = 2 def __init__(self): self.result = IStrFindResult.SYNTAX self.lhs = 0 self.rhs = 0 self.name = None class Istr(list): """ This closely models a basic ASCII string Note: Unicode strings are expressly not supported here. The problem this addresses occurs during macro processing. Sometimes macros are defined externally Other times, macros are fully defined with a package. Often macros need to be resolved either partially or fully When a macro is only external - they get in the way of resolving other macros To work around that, we convert the string into an array of integers Then for every macro byte that is 'external' we add 0x100 This makes the byte 'non-matchable' Later, when we convert the resolved string into we strip the 0x100. """ ignore = 256 def __init__(self, s): """ Constructor """ list.__init__(self, map(ord, s)) def __str__(self): return ''.join(map(lambda v: chr(v & 255), self)) def sslice(self, lhs, rhs): return ''.join(map(lambda v: chr(v & 255), self[lhs:rhs])) def iarray(self): return self[:] def mark(self, lhs, rhs, flagvalue=IGNORE): """ Apply flags to locations between left and right hand sides, ie: [lhs:rhs] """ for idx in range(lhs, rhs): self[idx] |= flagvalue def locate(self, needle, lhs, rhs): """Find this needle(char) in the hay stack(list).""" try: return self.index(needle, lhs, rhs) except: return -1 def replace(self, lhs, rhs, newcontent): """replace the data between [lhs:rhs] with newcontent""" self[lhs:rhs] = map(ord, newcontent) def next_macro(self, lhs, rhs): """ Find a macro within the string, return (lhs,rhs) if found If not found, return (-1,-1) If syntax error, return (-2,-2) """ result = i_str_find_result() result.lhs = lhs result.rhs = rhs if rhs - lhs < 4: result.code = result.NOTFOUND return result tmp = self.locate(RBRACE, result.lhs, result.rhs) if tmp >= 0: _open_symbol = LBRACE else: tmp = self.locate(RPAREN, result.lhs, result.rhs) _open_symbol = RPAREN if tmp < 0: result.code = result.NOTFOUND return result result.rhs = tmp while result.lhs < result.rhs: dollar_loc = self.locate(DOLLAR, result.lhs, result.rhs) if dollar_loc < 0: result.code = result.NOTFOUND return result ch = self[dollar_loc + 1] if ch != _open_symbol: result.lhs = dollar_loc + 1 continue result.lhs = dollar_loc tmp = self.locate(DOLLAR, dollar_loc + 1, result.rhs) if tmp >= 0: result.lhs = tmp continue result.code = result.OK result.name = self.sslice(result.lhs + 2, result.rhs) result.rhs += 1 return result result.code = result.SYNTAX return result def test_istr(): def check2(l, r, text, dut): print('----') print('Check (%d,%d)' % (l, r)) print('s = %s' % str(dut)) print('i = %s' % dut.iarray()) result = dut.next_macro(0, len(dut)) if result.lhs != l or result.rhs != r: print('str = %s' % str(dut)) print('int = %s' % dut.iarray()) print('Error: (%d,%d) != (%d,%d)' % (l, r, result.lhs, result.rhs)) assert False if text is not None: assert result.name == text dut.mark(l, r) return dut def check(l, r, s): if l >= 0: expected = s[l + 2:r - 1] else: expected = None dut = i_str(s) check2(l, r, expected, dut) st = str(dut) assert st == s return dut check(-1, -1, '') check(-1, -1, 'a') check(-1, -1, 'ab') check(-1, -1, 'abc') check(-1, -1, 'abcd') check(-1, -1, 'abcde') check(-1, -1, 'abcdef') check(0, 4, '${a}') check(0, 5, '${ab}') check(0, 6, '${abc}') check(0, 7, '${abcd}') check(1, 5, 'a${a}') check(2, 6, 'ab${a}') check(3, 7, 'abc${a}') check(4, 8, 'abcd${a}') check(5, 9, 'abcde${a}') check(0, 4, '${a}a') check(0, 4, '${a}ab') check(0, 4, '${a}abc') check(0, 4, '${a}abcd') check(0, 4, '${a}abcde') dut = check(4, 8, 'abcd${a}xyz') dut.replace(4, 8, 'X') check2(-1, -1, None, dut) r = str(dut) print('Got: %s' % r) assert 'abcdXxyz' == str(dut) dut = check(5, 9, 'abc${${Y}}xyz') dut.replace(5, 9, 'X') r = str(dut) assert r == 'abc${X}xyz' dut = check2(3, 7, '${X}', dut) dut.replace(3, 7, 'ABC') s = str(dut) r = 'abcABCxyz' assert s == r print('Success') if __name__ == '__main__': test_istr()
P, R = input().split() if P == '0': print('C') elif R == '0': print('B') else: print('A')
(p, r) = input().split() if P == '0': print('C') elif R == '0': print('B') else: print('A')
dosyaadi = input("Enter file name: ") dosyaadi = str(dosyaadi + ".txt") with open(dosyaadi, 'r') as file : dosyaicerigi = file.read() silinecek = str(input("Enter the text that you wish to delete: ")) dosyaicerigi = dosyaicerigi.replace(silinecek, '') with open(dosyaadi, 'w') as file: file.write(dosyaicerigi) file.close() print("-" * 30) print("Successfully deleted!") print("-" * 30)
dosyaadi = input('Enter file name: ') dosyaadi = str(dosyaadi + '.txt') with open(dosyaadi, 'r') as file: dosyaicerigi = file.read() silinecek = str(input('Enter the text that you wish to delete: ')) dosyaicerigi = dosyaicerigi.replace(silinecek, '') with open(dosyaadi, 'w') as file: file.write(dosyaicerigi) file.close() print('-' * 30) print('Successfully deleted!') print('-' * 30)
''' DNA++ (c) DNA++ 2017 All rights reserved. @author: neilswainston '''
""" DNA++ (c) DNA++ 2017 All rights reserved. @author: neilswainston """
class Solution: def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if root: root.left,root.right = self.invertTree(root.right),self.invertTree(root.left) return root return None
class Solution: def invert_tree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if root: (root.left, root.right) = (self.invertTree(root.right), self.invertTree(root.left)) return root return None
def assert_not_none(actual_result, message=""): if not message: message = f"{actual_result} resulted with None" assert actual_result, message def assert_equal(actual_result, expected_result, message=""): if not message: message = f"{actual_result} is not equal to expected " \ f"result {expected_result}" assert actual_result == expected_result, message def assert_in_list(searched_list, wanted_element, message=""): if not message: message = f"Failed to find '{wanted_element}' in list {searched_list}" assert wanted_element in searched_list, message def assert_not_in_list(searched_list, unwanted_element, message=""): if not message: message = f"'{unwanted_element}' found in list {searched_list} \n " \ f"although it should not be" assert unwanted_element not in searched_list, message def assert_of_type(wanted_type, wanted_object, message=""): if not message: message = f"{wanted_object} is not of type: {wanted_type}" assert isinstance(wanted_object, wanted_type), message
def assert_not_none(actual_result, message=''): if not message: message = f'{actual_result} resulted with None' assert actual_result, message def assert_equal(actual_result, expected_result, message=''): if not message: message = f'{actual_result} is not equal to expected result {expected_result}' assert actual_result == expected_result, message def assert_in_list(searched_list, wanted_element, message=''): if not message: message = f"Failed to find '{wanted_element}' in list {searched_list}" assert wanted_element in searched_list, message def assert_not_in_list(searched_list, unwanted_element, message=''): if not message: message = f"'{unwanted_element}' found in list {searched_list} \n although it should not be" assert unwanted_element not in searched_list, message def assert_of_type(wanted_type, wanted_object, message=''): if not message: message = f'{wanted_object} is not of type: {wanted_type}' assert isinstance(wanted_object, wanted_type), message
# 2019 advent day 3 MOVES = { 'R': (lambda x: (x[0], x[1] + 1)), 'L': (lambda x: (x[0], x[1] - 1)), 'U': (lambda x: (x[0] + 1, x[1])), 'D': (lambda x: (x[0] - 1, x[1])), } def build_route(directions: list) -> list: current_location = (0, 0) route = [] for d in directions: direction, amount = d[0], int(d[1:]) for _ in range(amount): current_location = MOVES[direction](current_location) route.append(current_location) return route def find_intersections(r1: list, r2: list) -> set: return set(r1).intersection(set(r2)) def find_shortest_manhattan_distance(points: set) -> int: return min((abs(p[0]) + abs(p[1])) for p in points) #R1 = 'R75,D30,R83,U83,L12,D49,R71,U7,L72' #R2 = 'U62,R66,U55,R34,D71,R55,D58,R83' #R1 = 'R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51' #R2 = 'U98,R91,D20,R16,D67,R40,U7,R15,U6,R7' def main(): #route1 = build_route(R1.split(',')) #route2 = build_route(R2.split(',')) with open('day3input.txt') as f: line1, line2 = f.readlines() route1 = build_route(line1.strip().split(',')) route2 = build_route(line2.strip().split(',')) print(find_shortest_manhattan_distance(find_intersections(route1, route2))) if __name__ == "__main__": main()
moves = {'R': lambda x: (x[0], x[1] + 1), 'L': lambda x: (x[0], x[1] - 1), 'U': lambda x: (x[0] + 1, x[1]), 'D': lambda x: (x[0] - 1, x[1])} def build_route(directions: list) -> list: current_location = (0, 0) route = [] for d in directions: (direction, amount) = (d[0], int(d[1:])) for _ in range(amount): current_location = MOVES[direction](current_location) route.append(current_location) return route def find_intersections(r1: list, r2: list) -> set: return set(r1).intersection(set(r2)) def find_shortest_manhattan_distance(points: set) -> int: return min((abs(p[0]) + abs(p[1]) for p in points)) def main(): with open('day3input.txt') as f: (line1, line2) = f.readlines() route1 = build_route(line1.strip().split(',')) route2 = build_route(line2.strip().split(',')) print(find_shortest_manhattan_distance(find_intersections(route1, route2))) if __name__ == '__main__': main()
budget = float(input()) nights = int(input()) price_night = float(input()) percent_extra = int(input()) if nights > 7: price_night = price_night - (price_night * 0.05) sum = nights * price_night total_sum = sum + (budget * percent_extra / 100) if total_sum <= budget: print(f"Ivanovi will be left with {(budget - total_sum):.2f} leva after vacation.") else: print(f"{(total_sum - budget):.2f} leva needed.")
budget = float(input()) nights = int(input()) price_night = float(input()) percent_extra = int(input()) if nights > 7: price_night = price_night - price_night * 0.05 sum = nights * price_night total_sum = sum + budget * percent_extra / 100 if total_sum <= budget: print(f'Ivanovi will be left with {budget - total_sum:.2f} leva after vacation.') else: print(f'{total_sum - budget:.2f} leva needed.')
class Skidoo(object): ''' a mapping which claims to contain all keys, each with a value of 23; item setting and deletion are no-ops; you can also call an instance with arbitrary positional args, result is 23. ''' __metaclass__ = MetaInterfaceChecker __implements__ = IMinimalMapping, ICallable def __getitem__(self, key): return 23 def __setitem__(self, key, value): pass def __delitem__(self, key): pass def __contains__(self, key): return True def __call__(self, *args): return 23 sk = Skidoo()
class Skidoo(object): """ a mapping which claims to contain all keys, each with a value of 23; item setting and deletion are no-ops; you can also call an instance with arbitrary positional args, result is 23. """ __metaclass__ = MetaInterfaceChecker __implements__ = (IMinimalMapping, ICallable) def __getitem__(self, key): return 23 def __setitem__(self, key, value): pass def __delitem__(self, key): pass def __contains__(self, key): return True def __call__(self, *args): return 23 sk = skidoo()
#!/usr/bin/env python # coding: UTF-8 # # @package Actor # @author Ariadne Pinheiro # @date 26/08/2020 # # Actor class, which is the base class for Disease objects. # ## class Actor: # Holds the value of the next "free" id. __ID = 0 ## # Construct a new Actor object. # - Sets the initial values of its member variables. # - Sets the unique ID for the object and initializes the reference to the World # object to which this Actor object belongs to null. # - The ID of the first Actor object is 0. # - The ID gets incremented by one each time a new Actor object is created. # - Sets the iteration counter to zero and initialize the location of the # object to cell (0,0). # def __init__(self): # X coordinate of this actor. self.__locX = 0 # Y coordinate of this actor. self.__locY = 0 # World this actor belongs to. self.__world = None # Unique identifier for this actor. self.__actorID = Actor.__ID Actor.__ID += 1 # Iteration counter. self.__itCounter = 0 ## # Used for testing # @return ActorID # def getID(self): return self.__actorID ## # Used for testing # @return number of iterations # def Iteration(self): return self.__itCounter ## # Prints on screen in the format "Iteration <ID>: Actor <Actor ID>". # # The @f$<ID>@f$ is replaced by the current iteration number. @f$<Actor ID>@f$ is # replaced by the unique ID of the Actor object that performs the act(self) # method. # # For instance, the actor with ID 1 shows the following result on # the output screen after its act(self) method has been called twice. # <PRE> # Iteration 0: Actor 1 # Iteration 1: Actor 1 # </PRE> # def act(self): print("Iteration {}: Actor {}".format(self.__itCounter, self.__actorID)) self.__itCounter += 1 ## # Sets the cell coordinates of this object. # # @param x the column. # @param y the row. # # @throws ValueError when x < 0 or x >= world width, # @throws ValueError when y < 0 or y >= world height, # @throws RuntimeError when the world is null. # def setLocation(self, x, y): if self.__world is None: raise RuntimeError if (0 <= x < self.__world.getWidth()) and (0 <= y < self.__world.getHeight()): self.__locX = x self.__locY = y else: raise ValueError ## # Sets the world this actor is into. # # @param world Reference to the World object this Actor object is added. # @throws RuntimeError when world is null. # def addedToWorld(self, world): if world is None: raise RuntimeError self.__world = world ## # Gets the world this object in into. # # @return the world this object belongs to # def getWorld(self): return self.__world ## # Gets the X coordinate of the cell this actor object is into. # # @return the x coordinate of this Actor object. # def getX(self): return self.__locX ## # Gets the Y coordinate of the cell this actor object is into. # # @return the y coordinate of this Actor object. # def getY(self): return self.__locY ## # Return a string with this actor ID and position. # def __str__(self): try: st = "ID = %d "u'\u2192 '.encode('utf-8') % self.getID() st += 'position = (%d, %d)\n' % (self.getX(), self.getY()) except TypeError: st = "ID = %d "u'\u2192 ' % self.getID() st += 'position = (%d, %d)\n' % (self.getX(), self.getY()) return st
class Actor: __id = 0 def __init__(self): self.__locX = 0 self.__locY = 0 self.__world = None self.__actorID = Actor.__ID Actor.__ID += 1 self.__itCounter = 0 def get_id(self): return self.__actorID def iteration(self): return self.__itCounter def act(self): print('Iteration {}: Actor {}'.format(self.__itCounter, self.__actorID)) self.__itCounter += 1 def set_location(self, x, y): if self.__world is None: raise RuntimeError if 0 <= x < self.__world.getWidth() and 0 <= y < self.__world.getHeight(): self.__locX = x self.__locY = y else: raise ValueError def added_to_world(self, world): if world is None: raise RuntimeError self.__world = world def get_world(self): return self.__world def get_x(self): return self.__locX def get_y(self): return self.__locY def __str__(self): try: st = 'ID = %d → '.encode('utf-8') % self.getID() st += 'position = (%d, %d)\n' % (self.getX(), self.getY()) except TypeError: st = 'ID = %d → ' % self.getID() st += 'position = (%d, %d)\n' % (self.getX(), self.getY()) return st
NAMES_SAML2_PROTOCOL = "urn:oasis:names:tc:SAML:2.0:protocol" NAMES_SAML2_ASSERTION = "urn:oasis:names:tc:SAML:2.0:assertion" NAMEID_FORMAT_UNSPECIFIED = "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified" BINDINGS_HTTP_POST = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" DATE_TIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ" DATE_TIME_FORMAT_FRACTIONAL = "%Y-%m-%dT%H:%M:%S.%fZ"
names_saml2_protocol = 'urn:oasis:names:tc:SAML:2.0:protocol' names_saml2_assertion = 'urn:oasis:names:tc:SAML:2.0:assertion' nameid_format_unspecified = 'urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified' bindings_http_post = 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST' date_time_format = '%Y-%m-%dT%H:%M:%SZ' date_time_format_fractional = '%Y-%m-%dT%H:%M:%S.%fZ'
groupSize = input() groups = list(map(int,input().split(' '))) tmpArray1 = set() tmpArray2 = set() for i in groups: if i in tmpArray1: tmpArray2.discard(i) else: tmpArray1.add(i) tmpArray2.add(i) for i in tmpArray2: print(i)
group_size = input() groups = list(map(int, input().split(' '))) tmp_array1 = set() tmp_array2 = set() for i in groups: if i in tmpArray1: tmpArray2.discard(i) else: tmpArray1.add(i) tmpArray2.add(i) for i in tmpArray2: print(i)
class Calculations: def __init__(self, first, second): self.first = first self.second = second def add(self): print(self.first + self.second) def subtract(self): print(self.first - self.second) def multiply(self): print(self.first * self.second) def divide(self): if second == 0: print("Can't divide by zero") else: print(self.first / self.second) def main(): print("Calculator has started") while True: a = float(input("Enter first number ")) b = float(input("Enter second number ")) chooseop = 1 calc=Calculations(a, b) while (chooseop == 1) | (chooseop == 2) | (chooseop == 3) | (chooseop == 4): chooseop = int(input("Enter 1 for addition, 2 for subtraction, 3 for multiplication and 4 for division ")) print(chooseop) if chooseop == 1: calc.add() break elif chooseop == 2: calc.subtract() break elif chooseop == 3: calc.multiply() break elif chooseop == 4: calc.divide() break elif (chooseop != 1) & (chooseop != 2) & (chooseop != 3) & (chooseop != 4): print("Invalid operation number") if __name__ == "__main__": main()
class Calculations: def __init__(self, first, second): self.first = first self.second = second def add(self): print(self.first + self.second) def subtract(self): print(self.first - self.second) def multiply(self): print(self.first * self.second) def divide(self): if second == 0: print("Can't divide by zero") else: print(self.first / self.second) def main(): print('Calculator has started') while True: a = float(input('Enter first number ')) b = float(input('Enter second number ')) chooseop = 1 calc = calculations(a, b) while (chooseop == 1) | (chooseop == 2) | (chooseop == 3) | (chooseop == 4): chooseop = int(input('Enter 1 for addition, 2 for subtraction, 3 for multiplication and 4 for division ')) print(chooseop) if chooseop == 1: calc.add() break elif chooseop == 2: calc.subtract() break elif chooseop == 3: calc.multiply() break elif chooseop == 4: calc.divide() break elif (chooseop != 1) & (chooseop != 2) & (chooseop != 3) & (chooseop != 4): print('Invalid operation number') if __name__ == '__main__': main()
n, k = map(int, input().split()) w = list(map(int, input().split())) r = sum(map(lambda x: (x+k-1)//k, w)) print((r+1)//2)
(n, k) = map(int, input().split()) w = list(map(int, input().split())) r = sum(map(lambda x: (x + k - 1) // k, w)) print((r + 1) // 2)
# -*- coding: utf-8 -*- def main(): a = input() # See: # https://www.slideshare.net/chokudai/abc007 if a == 'a': print('-1') else: print('a') if __name__ == '__main__': main()
def main(): a = input() if a == 'a': print('-1') else: print('a') if __name__ == '__main__': main()
# input N, M = map(int, input().split()) Ds = [*map(int, input().split())] # compute dp = [False] * (N+1) for ni in range(N+1): if ni == 0: dp[ni] = True for D in Ds: if ni >= D: dp[ni] = dp[ni] or dp[ni-D] # output print("Yes" if dp[-1] else "No")
(n, m) = map(int, input().split()) ds = [*map(int, input().split())] dp = [False] * (N + 1) for ni in range(N + 1): if ni == 0: dp[ni] = True for d in Ds: if ni >= D: dp[ni] = dp[ni] or dp[ni - D] print('Yes' if dp[-1] else 'No')
# sorting n=int(input()) array=list(map(int,input().split())) i=0 count=[] counter=0 while i<len(array): min=i start=i+1 while(start<len(array)): if array[start]<array[min]: min=start start+=1 if i!=min: array[i],array[min]=array[min],array[i] count.append(i) count.append(min) counter+=1 i+=1 print(counter) for i in range(0,len(count)): print(count[i],end=" ")
n = int(input()) array = list(map(int, input().split())) i = 0 count = [] counter = 0 while i < len(array): min = i start = i + 1 while start < len(array): if array[start] < array[min]: min = start start += 1 if i != min: (array[i], array[min]) = (array[min], array[i]) count.append(i) count.append(min) counter += 1 i += 1 print(counter) for i in range(0, len(count)): print(count[i], end=' ')
#Basics a = "hello" a += " I'm a dog" print(a) print(len(a)) print(a[1:]) #Output: ello I'm a dog print(a[:5]) #Output: hello(index 5 is not included) print(a[2:5])#Output: llo(index 2 is included) print(a[::2])#Step size #string is immutable so you can't assign a[1]= b x = a.upper() print(x) x = a.capitalize() print(x) x = a.split('e') print(x) x = a.split() #splits the string by space print(x) x = a.strip() #removes any whitespace from beginning or the end print(x) x = a.replace('l','xxx') print(x) x = "Insert another string here: {}".format('insert me!') x = "Item One: {} Item Two: {}".format('dog', 'cat') print(x) x = "Item One: {m} Item Two: {m}".format(m='dog', n='cat') print(x) #command-line string input print("Enter your name:") x = input() print("Hello: {}".format(x))
a = 'hello' a += " I'm a dog" print(a) print(len(a)) print(a[1:]) print(a[:5]) print(a[2:5]) print(a[::2]) x = a.upper() print(x) x = a.capitalize() print(x) x = a.split('e') print(x) x = a.split() print(x) x = a.strip() print(x) x = a.replace('l', 'xxx') print(x) x = 'Insert another string here: {}'.format('insert me!') x = 'Item One: {} Item Two: {}'.format('dog', 'cat') print(x) x = 'Item One: {m} Item Two: {m}'.format(m='dog', n='cat') print(x) print('Enter your name:') x = input() print('Hello: {}'.format(x))
def is_even(i: int) -> bool: if i == 1: return False elif i == 2: return True elif i == 3: return False elif i == 4: return True elif i == 5: ... # Never do that! Use one of these instead... is_even = lambda i : i % 2 == 0 is_even = lambda i : not i & 1 is_odd = lambda i : not is_even(i)
def is_even(i: int) -> bool: if i == 1: return False elif i == 2: return True elif i == 3: return False elif i == 4: return True elif i == 5: ... is_even = lambda i: i % 2 == 0 is_even = lambda i: not i & 1 is_odd = lambda i: not is_even(i)
__title__ = 'har2case' __description__ = 'Convert HAR(HTTP Archive) to YAML/JSON testcases for HttpRunner.' __url__ = 'https://github.com/HttpRunner/har2case' __version__ = '0.2.0' __author__ = 'debugtalk' __author_email__ = '[email protected]' __license__ = 'Apache-2.0' __copyright__ = 'Copyright 2017 debugtalk'
__title__ = 'har2case' __description__ = 'Convert HAR(HTTP Archive) to YAML/JSON testcases for HttpRunner.' __url__ = 'https://github.com/HttpRunner/har2case' __version__ = '0.2.0' __author__ = 'debugtalk' __author_email__ = '[email protected]' __license__ = 'Apache-2.0' __copyright__ = 'Copyright 2017 debugtalk'
def pictureInserter(og,address,list): j=0 for i in og: file1 = open(address+'/'+i, "a") x="\ncover::https://image.tmdb.org/t/p/original/"+list[j] file1.writelines(x) file1.close() j=j+1
def picture_inserter(og, address, list): j = 0 for i in og: file1 = open(address + '/' + i, 'a') x = '\ncover::https://image.tmdb.org/t/p/original/' + list[j] file1.writelines(x) file1.close() j = j + 1
class Solution: def removeOuterParentheses(self, s: str) -> str: ans = [] ct = 0 for ch in s: if ch == '(': ct += 1 if ct != 1: ans.append(ch) else: ct -= 1 if ct != 0: ans.append(ch) return ''.join(ans) if __name__ == '__main__': # s = '(()())(())' # s = '(()())(())(()(()))' s = '()()' ret = Solution().removeOuterParentheses(s) print(ret)
class Solution: def remove_outer_parentheses(self, s: str) -> str: ans = [] ct = 0 for ch in s: if ch == '(': ct += 1 if ct != 1: ans.append(ch) else: ct -= 1 if ct != 0: ans.append(ch) return ''.join(ans) if __name__ == '__main__': s = '()()' ret = solution().removeOuterParentheses(s) print(ret)
####################################################################################################################### # Given a string, find the length of the longest substring which has no repeating characters. # # Input: String="aabccbb" # Output: 3 # Explanation: The longest substring without any repeating characters is "abc". # # Input: String="abbbb" # Output: 2 # Explanation: The longest substring without any repeating characters is "ab". # # Input: String="abccde" # Output: 3 # Explanation: Longest substrings without any repeating characters are "abc" & "cde". ####################################################################################################################### def longest_substring_no_repeating_char(input_str: str) -> int: window_start = 0 is_present = [None for i in range(26)] max_window = 0 for i in range(len(input_str)): char_ord = ord(input_str[i]) - 97 if is_present[char_ord] is not None: window_start = max(window_start, is_present[char_ord] + 1) is_present[char_ord] = i max_window = max(max_window, i - window_start + 1) return max_window print(longest_substring_no_repeating_char('aabccbb')) print(longest_substring_no_repeating_char('abbbb')) print(longest_substring_no_repeating_char('abccde')) print(longest_substring_no_repeating_char('abcabcbb')) print(longest_substring_no_repeating_char('bbbbb')) print(longest_substring_no_repeating_char('pwwkew'))
def longest_substring_no_repeating_char(input_str: str) -> int: window_start = 0 is_present = [None for i in range(26)] max_window = 0 for i in range(len(input_str)): char_ord = ord(input_str[i]) - 97 if is_present[char_ord] is not None: window_start = max(window_start, is_present[char_ord] + 1) is_present[char_ord] = i max_window = max(max_window, i - window_start + 1) return max_window print(longest_substring_no_repeating_char('aabccbb')) print(longest_substring_no_repeating_char('abbbb')) print(longest_substring_no_repeating_char('abccde')) print(longest_substring_no_repeating_char('abcabcbb')) print(longest_substring_no_repeating_char('bbbbb')) print(longest_substring_no_repeating_char('pwwkew'))
# ------------------------------ # Binary Tree Level Order Traversal # # Description: # Given a binary tree, return the level order traversal of its nodes' values. (ie, from # left to right, level by level). # # For example: # Given binary tree [3,9,20,null,null,15,7], # 3 # / \ # 9 20 # / \ # 15 7 # return its level order traversal as: # [ # [3], # [9,20], # [15,7] # ] # # Version: 2.0 # 11/11/19 by Jianfa # ------------------------------ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: if not root: return [] # BFS res = [] queue = [root] while queue: temp = [] # values of this level of nodes children = [] # next level of nodes for node in queue: temp.append(node.val) if node.left: children.append(node.left) if node.right: children.append(node.right) res.append(temp[:]) # actually here can be res.append(temp), res will not change as temp changes queue = children[:] # here must be children[:] otherwise queue will change as children changes return res # Used for testing if __name__ == "__main__": test = Solution() # ------------------------------ # Summary: # Similar BFS solution but use a little more spaces. # On 102.py, using list.pop(0) actually takes O(n) time because it needs to remap the index # of values. Use collections.deque instead. # # O(N) time O(N) space
class Solution: def level_order(self, root: TreeNode) -> List[List[int]]: if not root: return [] res = [] queue = [root] while queue: temp = [] children = [] for node in queue: temp.append(node.val) if node.left: children.append(node.left) if node.right: children.append(node.right) res.append(temp[:]) queue = children[:] return res if __name__ == '__main__': test = solution()
def take_beer(fridge, number=1): if "beer" not in fridge: raise Exception("No beer at all:(") if number > fridge["beer"]: raise Exception("Not enough beer:(") fridge["beer"] -= number if __name__ == "__main__": fridge = { "beer": 2, "milk": 1, "meat": 3, } print("I wanna drink 1 bottle of beer...") take_beer(fridge) print("Oooh, great!") print("I wanna drink 2 bottle of beer...") try: take_beer(fridge, 2) except Exception as e: print("Error: {}. Let's continue".format(e)) print("Fallback. Try to take 1 bottle of beer...") take_beer(fridge, 1) print("Oooh, awesome!")
def take_beer(fridge, number=1): if 'beer' not in fridge: raise exception('No beer at all:(') if number > fridge['beer']: raise exception('Not enough beer:(') fridge['beer'] -= number if __name__ == '__main__': fridge = {'beer': 2, 'milk': 1, 'meat': 3} print('I wanna drink 1 bottle of beer...') take_beer(fridge) print('Oooh, great!') print('I wanna drink 2 bottle of beer...') try: take_beer(fridge, 2) except Exception as e: print("Error: {}. Let's continue".format(e)) print('Fallback. Try to take 1 bottle of beer...') take_beer(fridge, 1) print('Oooh, awesome!')
camera_width = 640 camera_height = 480 film_back_width = 1.417 film_back_height = 0.945 x_center = 320 y_center = 240 P_1 = (-0.023, -0.261, 2.376) p_11 = P_1[0] p_12 = P_1[1] p_13 = P_1[2] P_2 = (0.659, -0.071, 2.082) p_21 = P_2[0] p_22 = P_2[1] p_23 = P_2[2] p_1_prime = (52, 163) x_1 = p_1_prime[0] y_1 = p_1_prime[1] p_2_prime = (218, 216) x_2 = p_2_prime[0] y_2 = p_2_prime[1] f = 1.378 k_x = camera_width / film_back_width k_y = camera_height / film_back_height # f_k_x = f * k_x f_k_x = f # f_k_y = f * k_y f_k_y = f u_1_prime = (x_1 - x_center) / k_x v_1_prime = (y_1 - y_center) / k_y u_2_prime = (x_2 - x_center) / k_x v_2_prime = (y_2 - y_center) / k_y c_1_prime = (f_k_x * p_21 + (p_13 - p_23) * u_2_prime - u_2_prime/u_1_prime * f_k_x * p_11) / (f_k_x * (1 - u_2_prime/u_1_prime)) c_2_prime = (f_k_y * p_22 - (p_23 - (p_13*u_1_prime - f_k_x*(p_11 - c_1_prime))/u_1_prime) * v_2_prime) / f_k_y c_2_prime_alt = (f_k_y * p_12 - (p_13 - (p_13*u_1_prime - f_k_x*(p_11 - c_1_prime))/u_1_prime) * v_1_prime) / f_k_y c_3_prime = p_13 - (f_k_x / u_1_prime) * (p_11 - c_1_prime) rho_1_prime = p_13 - c_3_prime rho_2_prime = p_23 - c_3_prime print(f"C' = ({c_1_prime}, {c_2_prime}, {c_3_prime})") print(f"c_2_prime_alt = {c_2_prime_alt}") print(f"rho_1_prime = {rho_1_prime}") print(f"rho_2_prime = {rho_2_prime}") print("------------------") r_11 = f_k_x * (p_11 - c_1_prime) r_12 = f_k_y * (p_12 - c_2_prime) r_13 = 1 * (p_13 - c_3_prime) l_11 = rho_1_prime * u_1_prime l_12 = rho_1_prime * v_1_prime l_13 = rho_1_prime * 1 print(f"L: ({l_11}, {l_12}, {l_13})") print(f"R: ({r_11}, {r_12}, {r_13})") print("------------------") r_21 = f_k_x * (p_21 - c_1_prime) r_22 = f_k_y * (p_22 - c_2_prime) r_23 = 1 * (p_23 - c_3_prime) l_21 = rho_2_prime * u_2_prime l_22 = rho_2_prime * v_2_prime l_23 = rho_2_prime * 1 print(f"L: ({l_11}, {l_12}, {l_13})") print(f"R: ({r_11}, {r_12}, {r_13})")
camera_width = 640 camera_height = 480 film_back_width = 1.417 film_back_height = 0.945 x_center = 320 y_center = 240 p_1 = (-0.023, -0.261, 2.376) p_11 = P_1[0] p_12 = P_1[1] p_13 = P_1[2] p_2 = (0.659, -0.071, 2.082) p_21 = P_2[0] p_22 = P_2[1] p_23 = P_2[2] p_1_prime = (52, 163) x_1 = p_1_prime[0] y_1 = p_1_prime[1] p_2_prime = (218, 216) x_2 = p_2_prime[0] y_2 = p_2_prime[1] f = 1.378 k_x = camera_width / film_back_width k_y = camera_height / film_back_height f_k_x = f f_k_y = f u_1_prime = (x_1 - x_center) / k_x v_1_prime = (y_1 - y_center) / k_y u_2_prime = (x_2 - x_center) / k_x v_2_prime = (y_2 - y_center) / k_y c_1_prime = (f_k_x * p_21 + (p_13 - p_23) * u_2_prime - u_2_prime / u_1_prime * f_k_x * p_11) / (f_k_x * (1 - u_2_prime / u_1_prime)) c_2_prime = (f_k_y * p_22 - (p_23 - (p_13 * u_1_prime - f_k_x * (p_11 - c_1_prime)) / u_1_prime) * v_2_prime) / f_k_y c_2_prime_alt = (f_k_y * p_12 - (p_13 - (p_13 * u_1_prime - f_k_x * (p_11 - c_1_prime)) / u_1_prime) * v_1_prime) / f_k_y c_3_prime = p_13 - f_k_x / u_1_prime * (p_11 - c_1_prime) rho_1_prime = p_13 - c_3_prime rho_2_prime = p_23 - c_3_prime print(f"C' = ({c_1_prime}, {c_2_prime}, {c_3_prime})") print(f'c_2_prime_alt = {c_2_prime_alt}') print(f'rho_1_prime = {rho_1_prime}') print(f'rho_2_prime = {rho_2_prime}') print('------------------') r_11 = f_k_x * (p_11 - c_1_prime) r_12 = f_k_y * (p_12 - c_2_prime) r_13 = 1 * (p_13 - c_3_prime) l_11 = rho_1_prime * u_1_prime l_12 = rho_1_prime * v_1_prime l_13 = rho_1_prime * 1 print(f'L: ({l_11}, {l_12}, {l_13})') print(f'R: ({r_11}, {r_12}, {r_13})') print('------------------') r_21 = f_k_x * (p_21 - c_1_prime) r_22 = f_k_y * (p_22 - c_2_prime) r_23 = 1 * (p_23 - c_3_prime) l_21 = rho_2_prime * u_2_prime l_22 = rho_2_prime * v_2_prime l_23 = rho_2_prime * 1 print(f'L: ({l_11}, {l_12}, {l_13})') print(f'R: ({r_11}, {r_12}, {r_13})')
def main(): val=int(input("input a num")) if val<10: print("A") elif val<20: print("B") elif val<30: print("C") else: print("D") main()
def main(): val = int(input('input a num')) if val < 10: print('A') elif val < 20: print('B') elif val < 30: print('C') else: print('D') main()
__all__ = ['cross_validation', 'metrics', 'datasets', 'recommender']
__all__ = ['cross_validation', 'metrics', 'datasets', 'recommender']
def is_leap(year): leap=False if year%400==0: leap=True elif year%4==0 and year%100!=0: leap=True else: leap=False return leap year = int(input())
def is_leap(year): leap = False if year % 400 == 0: leap = True elif year % 4 == 0 and year % 100 != 0: leap = True else: leap = False return leap year = int(input())
print("Press q to quit") quit = False while quit is False: in_val = input("Please enter a positive integer.\n > ") if in_val is 'q': quit = True elif int(in_val) % 3 == 0 and int(in_val) % 5 == 0: print("FizzBuzz") elif int(in_val) % 5 == 0: print("Buzz") elif int(in_val) % 3 == 0: print("Fizz") else: pass
print('Press q to quit') quit = False while quit is False: in_val = input('Please enter a positive integer.\n > ') if in_val is 'q': quit = True elif int(in_val) % 3 == 0 and int(in_val) % 5 == 0: print('FizzBuzz') elif int(in_val) % 5 == 0: print('Buzz') elif int(in_val) % 3 == 0: print('Fizz') else: pass
# --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # --------------------------------------------------------- class DashboardInfo: MODEL_ID_KEY = "id" # To match Model schema MODEL_INFO_FILENAME = "model_info.json" RAI_INSIGHTS_MODEL_ID_KEY = "model_id" RAI_INSIGHTS_RUN_ID_KEY = "rai_insights_parent_run_id" RAI_INSIGHTS_PARENT_FILENAME = "rai_insights.json" class PropertyKeyValues: # The property to indicate the type of Run RAI_INSIGHTS_TYPE_KEY = "_azureml.responsibleai.rai_insights.type" RAI_INSIGHTS_TYPE_CONSTRUCT = "construction" RAI_INSIGHTS_TYPE_CAUSAL = "causal" RAI_INSIGHTS_TYPE_COUNTERFACTUAL = "counterfactual" RAI_INSIGHTS_TYPE_EXPLANATION = "explanation" RAI_INSIGHTS_TYPE_ERROR_ANALYSIS = "error_analysis" RAI_INSIGHTS_TYPE_GATHER = "gather" # Property to point at the model under examination RAI_INSIGHTS_MODEL_ID_KEY = "_azureml.responsibleai.rai_insights.model_id" # Property for tool runs to point at their constructor run RAI_INSIGHTS_CONSTRUCTOR_RUN_ID_KEY = ( "_azureml.responsibleai.rai_insights.constructor_run" ) # Property to record responsibleai version RAI_INSIGHTS_RESPONSIBLEAI_VERSION_KEY = ( "_azureml.responsibleai.rai_insights.responsibleai_version" ) # Property format to indicate presence of a tool RAI_INSIGHTS_TOOL_KEY_FORMAT = "_azureml.responsibleai.rai_insights.has_{0}" class RAIToolType: CAUSAL = "causal" COUNTERFACTUAL = "counterfactual" ERROR_ANALYSIS = "error_analysis" EXPLANATION = "explanation"
class Dashboardinfo: model_id_key = 'id' model_info_filename = 'model_info.json' rai_insights_model_id_key = 'model_id' rai_insights_run_id_key = 'rai_insights_parent_run_id' rai_insights_parent_filename = 'rai_insights.json' class Propertykeyvalues: rai_insights_type_key = '_azureml.responsibleai.rai_insights.type' rai_insights_type_construct = 'construction' rai_insights_type_causal = 'causal' rai_insights_type_counterfactual = 'counterfactual' rai_insights_type_explanation = 'explanation' rai_insights_type_error_analysis = 'error_analysis' rai_insights_type_gather = 'gather' rai_insights_model_id_key = '_azureml.responsibleai.rai_insights.model_id' rai_insights_constructor_run_id_key = '_azureml.responsibleai.rai_insights.constructor_run' rai_insights_responsibleai_version_key = '_azureml.responsibleai.rai_insights.responsibleai_version' rai_insights_tool_key_format = '_azureml.responsibleai.rai_insights.has_{0}' class Raitooltype: causal = 'causal' counterfactual = 'counterfactual' error_analysis = 'error_analysis' explanation = 'explanation'
#4 lines: Fibonacci, tuple assignment parents, babies = (1, 1) while babies < 100: print ('This generation has {0} babies'.format(babies)) parents, babies = (babies, parents + babies)
(parents, babies) = (1, 1) while babies < 100: print('This generation has {0} babies'.format(babies)) (parents, babies) = (babies, parents + babies)
# model settings norm_cfg = dict(type='BN', requires_grad=True) model = dict( type='EncoderDecoder', pretrained='pretrain/vit_base_patch16_224.pth', backbone=dict( type='VisionTransformer', img_size=(224, 224), patch_size=16, in_channels=3, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, # out_indices=(2, 5, 8, 11), qkv_bias=True, drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.0, with_cls_token=True, norm_cfg=dict(type='LN', eps=1e-6), act_cfg=dict(type='GELU'), norm_eval=False, interpolate_mode='bicubic'), neck=None, decode_head=dict( type='ASPPHead', in_channels=768, # in_index=3, channels=512, dilations=(1, 6, 12, 18), dropout_ratio=0.1, num_classes=21, contrast=True, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), auxiliary_head=None, # model training and testing settings train_cfg=dict(), test_cfg=dict(mode='whole')) # yapf: disable
norm_cfg = dict(type='BN', requires_grad=True) model = dict(type='EncoderDecoder', pretrained='pretrain/vit_base_patch16_224.pth', backbone=dict(type='VisionTransformer', img_size=(224, 224), patch_size=16, in_channels=3, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, qkv_bias=True, drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.0, with_cls_token=True, norm_cfg=dict(type='LN', eps=1e-06), act_cfg=dict(type='GELU'), norm_eval=False, interpolate_mode='bicubic'), neck=None, decode_head=dict(type='ASPPHead', in_channels=768, channels=512, dilations=(1, 6, 12, 18), dropout_ratio=0.1, num_classes=21, contrast=True, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict(type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), auxiliary_head=None, train_cfg=dict(), test_cfg=dict(mode='whole'))
# Copyright (C) 2019 Intel Corporation. All rights reserved. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES") load( "@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl", "feature", "flag_group", "flag_set", "tool_path", ) all_compile_actions = [ ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ] all_link_actions = [ ACTION_NAMES.cpp_link_executable, ACTION_NAMES.cpp_link_dynamic_library, ACTION_NAMES.cpp_link_nodeps_dynamic_library, ] def _impl(ctx): tool_paths = [ tool_path( name = "gcc", path = "/opt/emsdk/upstream/emscripten/emcc", ), tool_path( name = "ld", path = "/opt/emsdk/upstream/emscripten/emcc", ), tool_path( name = "ar", path = "/opt/emsdk/upstream/emscripten/emar", ), tool_path( name = "cpp", path = "/opt/emsdk/upstream/emscripten/em++", ), tool_path( name = "gcov", path = "/bin/false", ), tool_path( name = "nm", path = "/bin/false", ), tool_path( name = "objdump", path = "/bin/false", ), tool_path( name = "strip", path = "/bin/false", ), ] features = [ # NEW feature( name = "default_compile_flags", enabled = True, flag_sets = [ flag_set( actions = all_compile_actions, flag_groups = ([ flag_group( flags = [ "-O3", "-msimd128", "-s", "USE_PTHREADS=0", "-s", "ERROR_ON_UNDEFINED_SYMBOLS=0", "-s", "STANDALONE_WASM=1", ], ), ]), ), ], ), feature( name = "default_linker_flags", enabled = True, flag_sets = [ flag_set( actions = all_link_actions, flag_groups = ([ flag_group( flags = [ "-O3", "-msimd128", "-s", "USE_PTHREADS=0", "-s", "ERROR_ON_UNDEFINED_SYMBOLS=0", "-s", "STANDALONE_WASM=1", "-Wl,--export=__heap_base", "-Wl,--export=__data_end", ], ), ]), ), ], ), ] return cc_common.create_cc_toolchain_config_info( ctx = ctx, features = features, # NEW cxx_builtin_include_directories = [ "/opt/emsdk/upstream/emscripten/system/include/libcxx", "/opt/emsdk/upstream/emscripten/system/lib/libcxxabi/include", "/opt/emsdk/upstream/emscripten/system/include", "/opt/emsdk/upstream/emscripten/system/include/libc", "/opt/emsdk/upstream/emscripten/system/lib/libc/musl/arch/emscripten", "/opt/emsdk/upstream/lib/clang/12.0.0/include/", ], toolchain_identifier = "wasm-emsdk", host_system_name = "i686-unknown-linux-gnu", target_system_name = "wasm32-unknown-emscripten", target_cpu = "wasm32", target_libc = "unknown", compiler = "emsdk", abi_version = "unknown", abi_libc_version = "unknown", tool_paths = tool_paths, ) emsdk_toolchain_config = rule( implementation = _impl, attrs = {}, provides = [CcToolchainConfigInfo], )
load('@bazel_tools//tools/build_defs/cc:action_names.bzl', 'ACTION_NAMES') load('@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl', 'feature', 'flag_group', 'flag_set', 'tool_path') all_compile_actions = [ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile] all_link_actions = [ACTION_NAMES.cpp_link_executable, ACTION_NAMES.cpp_link_dynamic_library, ACTION_NAMES.cpp_link_nodeps_dynamic_library] def _impl(ctx): tool_paths = [tool_path(name='gcc', path='/opt/emsdk/upstream/emscripten/emcc'), tool_path(name='ld', path='/opt/emsdk/upstream/emscripten/emcc'), tool_path(name='ar', path='/opt/emsdk/upstream/emscripten/emar'), tool_path(name='cpp', path='/opt/emsdk/upstream/emscripten/em++'), tool_path(name='gcov', path='/bin/false'), tool_path(name='nm', path='/bin/false'), tool_path(name='objdump', path='/bin/false'), tool_path(name='strip', path='/bin/false')] features = [feature(name='default_compile_flags', enabled=True, flag_sets=[flag_set(actions=all_compile_actions, flag_groups=[flag_group(flags=['-O3', '-msimd128', '-s', 'USE_PTHREADS=0', '-s', 'ERROR_ON_UNDEFINED_SYMBOLS=0', '-s', 'STANDALONE_WASM=1'])])]), feature(name='default_linker_flags', enabled=True, flag_sets=[flag_set(actions=all_link_actions, flag_groups=[flag_group(flags=['-O3', '-msimd128', '-s', 'USE_PTHREADS=0', '-s', 'ERROR_ON_UNDEFINED_SYMBOLS=0', '-s', 'STANDALONE_WASM=1', '-Wl,--export=__heap_base', '-Wl,--export=__data_end'])])])] return cc_common.create_cc_toolchain_config_info(ctx=ctx, features=features, cxx_builtin_include_directories=['/opt/emsdk/upstream/emscripten/system/include/libcxx', '/opt/emsdk/upstream/emscripten/system/lib/libcxxabi/include', '/opt/emsdk/upstream/emscripten/system/include', '/opt/emsdk/upstream/emscripten/system/include/libc', '/opt/emsdk/upstream/emscripten/system/lib/libc/musl/arch/emscripten', '/opt/emsdk/upstream/lib/clang/12.0.0/include/'], toolchain_identifier='wasm-emsdk', host_system_name='i686-unknown-linux-gnu', target_system_name='wasm32-unknown-emscripten', target_cpu='wasm32', target_libc='unknown', compiler='emsdk', abi_version='unknown', abi_libc_version='unknown', tool_paths=tool_paths) emsdk_toolchain_config = rule(implementation=_impl, attrs={}, provides=[CcToolchainConfigInfo])
train_data_path = "../data/no_cycle/train.data" dev_data_path = "../data/no_cycle/dev.data" test_data_path = "../data/no_cycle/test.data" word_idx_file_path = "../data/word.idx" word_embedding_dim = 100 train_batch_size = 32 dev_batch_size = 500 test_batch_size = 500 l2_lambda = 0.000001 learning_rate = 0.001 epochs = 100 encoder_hidden_dim = 200 num_layers_decode = 1 word_size_max = 1 dropout = 0.0 path_embed_method = "lstm" # cnn or lstm or bi-lstm unknown_word = "<unk>" PAD = "<PAD>" GO = "<GO>" EOS = "<EOS>" deal_unknown_words = True seq_max_len = 11 decoder_type = "greedy" # greedy, beam beam_width = 4 attention = True num_layers = 1 # 1 or 2 # the following are for the graph encoding method weight_decay = 0.0000 sample_size_per_layer = 4 sample_layer_size = 4 hidden_layer_dim = 100 feature_max_len = 1 feature_encode_type = "uni" # graph_encode_method = "max-pooling" # "lstm" or "max-pooling" graph_encode_direction = "bi" # "single" or "bi" concat = True encoder = "gated_gcn" # "gated_gcn" "gcn" "seq" lstm_in_gcn = "none" # before, after, none
train_data_path = '../data/no_cycle/train.data' dev_data_path = '../data/no_cycle/dev.data' test_data_path = '../data/no_cycle/test.data' word_idx_file_path = '../data/word.idx' word_embedding_dim = 100 train_batch_size = 32 dev_batch_size = 500 test_batch_size = 500 l2_lambda = 1e-06 learning_rate = 0.001 epochs = 100 encoder_hidden_dim = 200 num_layers_decode = 1 word_size_max = 1 dropout = 0.0 path_embed_method = 'lstm' unknown_word = '<unk>' pad = '<PAD>' go = '<GO>' eos = '<EOS>' deal_unknown_words = True seq_max_len = 11 decoder_type = 'greedy' beam_width = 4 attention = True num_layers = 1 weight_decay = 0.0 sample_size_per_layer = 4 sample_layer_size = 4 hidden_layer_dim = 100 feature_max_len = 1 feature_encode_type = 'uni' graph_encode_direction = 'bi' concat = True encoder = 'gated_gcn' lstm_in_gcn = 'none'
class Input(object): def __init__(self, type, data): self.__type = type self.__data = deepcopy(data) def __repr__(self): return repr(self.__data) def __str__(self): return str(self.__type) + str(self.__data)
class Input(object): def __init__(self, type, data): self.__type = type self.__data = deepcopy(data) def __repr__(self): return repr(self.__data) def __str__(self): return str(self.__type) + str(self.__data)
class Player: def __init__(self, nickname, vapor_id, player_id, ip): self.nickname = nickname self.vapor_id = vapor_id self.player_id = player_id self.ip = ip self.not_joined = True self.loads_map = True self.joined_after_change_map = True class Players: def __init__(self, main_object, modded, lobby): self.main = main_object self.players = [] self.modded = modded self.map_changed = False self.lobby = lobby self.commands = None def get_commands_object(self, commands_object): self.commands = commands_object def _on_map_change(self, map_name): self.map_changed = map_name if self.modded and self.players: for player in self.players: player.loads_map = True def check_if_everyone_joined_after_change_map(self): for player in self.players: if player.loads_map and not player.joined_after_change_map: return False return True def _on_player_info_ev(self, player_id): player = [player for player in self.players if player.player_id == player_id][0] if self.map_changed or hasattr(player, "not_joined"): if player.loads_map and player.joined_after_change_map: player.joined_after_change_map = False elif player.loads_map and not player.joined_after_change_map: player.loads_map = False player.joined_after_change_map = True self.main.on_player_map_change(player, self.map_changed) if hasattr(player, "not_joined"): del player.not_joined self.main.on_client_join(player) if self.check_if_everyone_joined_after_change_map(): self.map_changed = False def check_nickname_existence(self, nickname): for player in self.players: if nickname == player.nickname: return True return False def get_all_players(self, nicknames, vapor_ids, player_ids, ips): players_list = [nicknames, vapor_ids, player_ids, ips] for count in range(len(nicknames)): self.players.append(Player(*[player[count] for player in players_list])) def add(self, nickname, vapor_id, player_id, ip): self.players.append(Player(nickname, vapor_id, player_id, ip)) def remove(self, nickname): for player in self.players: if nickname == player.nickname: self.players.remove(player) break if self.lobby and len(self.players) == 0: self.commands.change_map(self.lobby) def nickname_change(self, old_nickname, new_nickname): for player in self.players: if old_nickname == player.nickname: player.nickname = new_nickname break def all_nicknames(self): return [player.nickname for player in self.players] def player_from_nickname(self, nickname): for player in self.players: if nickname == player.nickname: return player def player_from_vapor_id(self, vapor_id): for player in self.players: if vapor_id == player.vapor_id: return player def player_from_player_id(self, player_id): for player in self.players: if player_id == player.player_id: return player def get_all_vapor_ids(self): return [player.vapor_id for player in self.players]
class Player: def __init__(self, nickname, vapor_id, player_id, ip): self.nickname = nickname self.vapor_id = vapor_id self.player_id = player_id self.ip = ip self.not_joined = True self.loads_map = True self.joined_after_change_map = True class Players: def __init__(self, main_object, modded, lobby): self.main = main_object self.players = [] self.modded = modded self.map_changed = False self.lobby = lobby self.commands = None def get_commands_object(self, commands_object): self.commands = commands_object def _on_map_change(self, map_name): self.map_changed = map_name if self.modded and self.players: for player in self.players: player.loads_map = True def check_if_everyone_joined_after_change_map(self): for player in self.players: if player.loads_map and (not player.joined_after_change_map): return False return True def _on_player_info_ev(self, player_id): player = [player for player in self.players if player.player_id == player_id][0] if self.map_changed or hasattr(player, 'not_joined'): if player.loads_map and player.joined_after_change_map: player.joined_after_change_map = False elif player.loads_map and (not player.joined_after_change_map): player.loads_map = False player.joined_after_change_map = True self.main.on_player_map_change(player, self.map_changed) if hasattr(player, 'not_joined'): del player.not_joined self.main.on_client_join(player) if self.check_if_everyone_joined_after_change_map(): self.map_changed = False def check_nickname_existence(self, nickname): for player in self.players: if nickname == player.nickname: return True return False def get_all_players(self, nicknames, vapor_ids, player_ids, ips): players_list = [nicknames, vapor_ids, player_ids, ips] for count in range(len(nicknames)): self.players.append(player(*[player[count] for player in players_list])) def add(self, nickname, vapor_id, player_id, ip): self.players.append(player(nickname, vapor_id, player_id, ip)) def remove(self, nickname): for player in self.players: if nickname == player.nickname: self.players.remove(player) break if self.lobby and len(self.players) == 0: self.commands.change_map(self.lobby) def nickname_change(self, old_nickname, new_nickname): for player in self.players: if old_nickname == player.nickname: player.nickname = new_nickname break def all_nicknames(self): return [player.nickname for player in self.players] def player_from_nickname(self, nickname): for player in self.players: if nickname == player.nickname: return player def player_from_vapor_id(self, vapor_id): for player in self.players: if vapor_id == player.vapor_id: return player def player_from_player_id(self, player_id): for player in self.players: if player_id == player.player_id: return player def get_all_vapor_ids(self): return [player.vapor_id for player in self.players]
# # PySNMP MIB module DABING-MIB (http://snmplabs.com/pysmi) # ASN.1 source file://..\DABING-MIB.mib # Produced by pysmi-0.3.4 at Tue Mar 22 12:53:47 2022 # On host ? platform ? version ? by user ? # Using Python version 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (Intel)] # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "ValueRangeConstraint", "SingleValueConstraint", "ValueSizeConstraint") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, ModuleIdentity, IpAddress, ObjectIdentity, iso, Counter32, Unsigned32, Bits, NotificationType, TimeTicks, Counter64, enterprises, MibIdentifier, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Gauge32", "ModuleIdentity", "IpAddress", "ObjectIdentity", "iso", "Counter32", "Unsigned32", "Bits", "NotificationType", "TimeTicks", "Counter64", "enterprises", "MibIdentifier", "Integer32") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") dabing = ModuleIdentity((1, 3, 6, 1, 4, 1, 55532)) dabing.setRevisions(('2022-03-17 00:00',)) if mibBuilder.loadTexts: dabing.setLastUpdated('202203170000Z') if mibBuilder.loadTexts: dabing.setOrganization('www.stuba.sk') Parameters = MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 1)) Agent = MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 2)) Manager = MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 3)) Notifications = MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 4)) NotificationPrefix = MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 4, 1)) NotificationObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 55532, 4, 2)) channel = MibScalar((1, 3, 6, 1, 4, 1, 55532, 1, 1), OctetString().clone('12C')).setMaxAccess("readonly") if mibBuilder.loadTexts: channel.setStatus('current') interval = MibScalar((1, 3, 6, 1, 4, 1, 55532, 1, 2), Integer32().clone(960)).setMaxAccess("readonly") if mibBuilder.loadTexts: interval.setStatus('current') trapEnabled = MibScalar((1, 3, 6, 1, 4, 1, 55532, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: trapEnabled.setStatus('current') agentIdentifier = MibScalar((1, 3, 6, 1, 4, 1, 55532, 2, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: agentIdentifier.setStatus('current') agentLabel = MibScalar((1, 3, 6, 1, 4, 1, 55532, 2, 2), OctetString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: agentLabel.setStatus('current') agentStatus = MibScalar((1, 3, 6, 1, 4, 1, 55532, 2, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: agentStatus.setStatus('current') managerHostname = MibScalar((1, 3, 6, 1, 4, 1, 55532, 3, 1), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: managerHostname.setStatus('current') managerPort = MibScalar((1, 3, 6, 1, 4, 1, 55532, 3, 2), Integer32().clone(162)).setMaxAccess("readonly") if mibBuilder.loadTexts: managerPort.setStatus('current') genericPayload = MibScalar((1, 3, 6, 1, 4, 1, 55532, 4, 2, 1), OctetString()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: genericPayload.setStatus('current') malfunctionTrap = NotificationType((1, 3, 6, 1, 4, 1, 55532, 4, 1, 1)).setObjects(("DABING-MIB", "genericPayload")) if mibBuilder.loadTexts: malfunctionTrap.setStatus('current') testTrap = NotificationType((1, 3, 6, 1, 4, 1, 55532, 4, 1, 2)).setObjects(("DABING-MIB", "genericPayload")) if mibBuilder.loadTexts: testTrap.setStatus('current') mibBuilder.exportSymbols("DABING-MIB", Notifications=Notifications, channel=channel, PYSNMP_MODULE_ID=dabing, testTrap=testTrap, malfunctionTrap=malfunctionTrap, Parameters=Parameters, agentLabel=agentLabel, managerPort=managerPort, trapEnabled=trapEnabled, managerHostname=managerHostname, Manager=Manager, NotificationPrefix=NotificationPrefix, Agent=Agent, genericPayload=genericPayload, NotificationObjects=NotificationObjects, agentIdentifier=agentIdentifier, dabing=dabing, agentStatus=agentStatus, interval=interval)
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, constraints_union, value_range_constraint, single_value_constraint, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ConstraintsUnion', 'ValueRangeConstraint', 'SingleValueConstraint', 'ValueSizeConstraint') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (mib_scalar, mib_table, mib_table_row, mib_table_column, gauge32, module_identity, ip_address, object_identity, iso, counter32, unsigned32, bits, notification_type, time_ticks, counter64, enterprises, mib_identifier, integer32) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Gauge32', 'ModuleIdentity', 'IpAddress', 'ObjectIdentity', 'iso', 'Counter32', 'Unsigned32', 'Bits', 'NotificationType', 'TimeTicks', 'Counter64', 'enterprises', 'MibIdentifier', 'Integer32') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') dabing = module_identity((1, 3, 6, 1, 4, 1, 55532)) dabing.setRevisions(('2022-03-17 00:00',)) if mibBuilder.loadTexts: dabing.setLastUpdated('202203170000Z') if mibBuilder.loadTexts: dabing.setOrganization('www.stuba.sk') parameters = mib_identifier((1, 3, 6, 1, 4, 1, 55532, 1)) agent = mib_identifier((1, 3, 6, 1, 4, 1, 55532, 2)) manager = mib_identifier((1, 3, 6, 1, 4, 1, 55532, 3)) notifications = mib_identifier((1, 3, 6, 1, 4, 1, 55532, 4)) notification_prefix = mib_identifier((1, 3, 6, 1, 4, 1, 55532, 4, 1)) notification_objects = mib_identifier((1, 3, 6, 1, 4, 1, 55532, 4, 2)) channel = mib_scalar((1, 3, 6, 1, 4, 1, 55532, 1, 1), octet_string().clone('12C')).setMaxAccess('readonly') if mibBuilder.loadTexts: channel.setStatus('current') interval = mib_scalar((1, 3, 6, 1, 4, 1, 55532, 1, 2), integer32().clone(960)).setMaxAccess('readonly') if mibBuilder.loadTexts: interval.setStatus('current') trap_enabled = mib_scalar((1, 3, 6, 1, 4, 1, 55532, 1, 3), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: trapEnabled.setStatus('current') agent_identifier = mib_scalar((1, 3, 6, 1, 4, 1, 55532, 2, 1), integer32()).setMaxAccess('readwrite') if mibBuilder.loadTexts: agentIdentifier.setStatus('current') agent_label = mib_scalar((1, 3, 6, 1, 4, 1, 55532, 2, 2), octet_string()).setMaxAccess('readwrite') if mibBuilder.loadTexts: agentLabel.setStatus('current') agent_status = mib_scalar((1, 3, 6, 1, 4, 1, 55532, 2, 3), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: agentStatus.setStatus('current') manager_hostname = mib_scalar((1, 3, 6, 1, 4, 1, 55532, 3, 1), octet_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: managerHostname.setStatus('current') manager_port = mib_scalar((1, 3, 6, 1, 4, 1, 55532, 3, 2), integer32().clone(162)).setMaxAccess('readonly') if mibBuilder.loadTexts: managerPort.setStatus('current') generic_payload = mib_scalar((1, 3, 6, 1, 4, 1, 55532, 4, 2, 1), octet_string()).setMaxAccess('accessiblefornotify') if mibBuilder.loadTexts: genericPayload.setStatus('current') malfunction_trap = notification_type((1, 3, 6, 1, 4, 1, 55532, 4, 1, 1)).setObjects(('DABING-MIB', 'genericPayload')) if mibBuilder.loadTexts: malfunctionTrap.setStatus('current') test_trap = notification_type((1, 3, 6, 1, 4, 1, 55532, 4, 1, 2)).setObjects(('DABING-MIB', 'genericPayload')) if mibBuilder.loadTexts: testTrap.setStatus('current') mibBuilder.exportSymbols('DABING-MIB', Notifications=Notifications, channel=channel, PYSNMP_MODULE_ID=dabing, testTrap=testTrap, malfunctionTrap=malfunctionTrap, Parameters=Parameters, agentLabel=agentLabel, managerPort=managerPort, trapEnabled=trapEnabled, managerHostname=managerHostname, Manager=Manager, NotificationPrefix=NotificationPrefix, Agent=Agent, genericPayload=genericPayload, NotificationObjects=NotificationObjects, agentIdentifier=agentIdentifier, dabing=dabing, agentStatus=agentStatus, interval=interval)
class TreeNode: def __init__(self, name, data, parent=None): self.name = name self.parent = parent self.data = data self.childs = {} def add_child(self, name, data): self.childs.update({name:(type(self))(name, data, self)}) def rm_branch(self, name, ansistors_n: list = None,): focus = self.childs while True: if ansistors_n == None or ansistors_n == self.name: del focus[name] break elif ansistors_n[0] in focus: focus = (focus[ansistors_n[0]]).childs del ansistors_n[0] elif name in focus and ansistors_n is None: del focus[name] break else: print(focus) raise NameError(f"couldn't find branch {ansistors_n[0]}") def __getitem__(self, item): return self.childs[item] def __setitem__(self, key, value): self.childs[key] = value def __delitem__(self, key, ansistors_n: list = None): self.rm_branch(key, ansistors_n)
class Treenode: def __init__(self, name, data, parent=None): self.name = name self.parent = parent self.data = data self.childs = {} def add_child(self, name, data): self.childs.update({name: type(self)(name, data, self)}) def rm_branch(self, name, ansistors_n: list=None): focus = self.childs while True: if ansistors_n == None or ansistors_n == self.name: del focus[name] break elif ansistors_n[0] in focus: focus = focus[ansistors_n[0]].childs del ansistors_n[0] elif name in focus and ansistors_n is None: del focus[name] break else: print(focus) raise name_error(f"couldn't find branch {ansistors_n[0]}") def __getitem__(self, item): return self.childs[item] def __setitem__(self, key, value): self.childs[key] = value def __delitem__(self, key, ansistors_n: list=None): self.rm_branch(key, ansistors_n)
api_key = "9N7hvPP9yFrjBnELpBdthluBjiOWzJZw" mongo_url = 'mongodb://localhost:27017' mongo_db = 'CarPopularity' mongo_collections = ['CarSalesByYear', 'PopularCarsByRegion'] years_data = ['2019', '2018', '2017', '2016', '2015'] test_mode = True
api_key = '9N7hvPP9yFrjBnELpBdthluBjiOWzJZw' mongo_url = 'mongodb://localhost:27017' mongo_db = 'CarPopularity' mongo_collections = ['CarSalesByYear', 'PopularCarsByRegion'] years_data = ['2019', '2018', '2017', '2016', '2015'] test_mode = True
# # PySNMP MIB module MWORKS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MWORKS-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:16:04 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ValueSizeConstraint", "ConstraintsIntersection") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Gauge32, Unsigned32, ObjectIdentity, IpAddress, Bits, MibIdentifier, Integer32, enterprises, ModuleIdentity, TimeTicks, Counter32, NotificationType, iso, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "Unsigned32", "ObjectIdentity", "IpAddress", "Bits", "MibIdentifier", "Integer32", "enterprises", "ModuleIdentity", "TimeTicks", "Counter32", "NotificationType", "iso", "Counter64", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") tecElite = MibIdentifier((1, 3, 6, 1, 4, 1, 217)) meterWorks = MibIdentifier((1, 3, 6, 1, 4, 1, 217, 16)) mw501 = MibIdentifier((1, 3, 6, 1, 4, 1, 217, 16, 1)) mwMem = MibIdentifier((1, 3, 6, 1, 4, 1, 217, 16, 1, 1)) mwHeap = MibIdentifier((1, 3, 6, 1, 4, 1, 217, 16, 1, 2)) mwMemCeiling = MibScalar((1, 3, 6, 1, 4, 1, 217, 16, 1, 1, 1), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mwMemCeiling.setStatus('mandatory') if mibBuilder.loadTexts: mwMemCeiling.setDescription('bytes of memory the agent memory manager will allow the agent to use.') mwMemUsed = MibScalar((1, 3, 6, 1, 4, 1, 217, 16, 1, 1, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mwMemUsed.setStatus('mandatory') if mibBuilder.loadTexts: mwMemUsed.setDescription("bytes of memory that meterworks has malloc'ed. some of this may be in free pools.") mwHeapTotal = MibScalar((1, 3, 6, 1, 4, 1, 217, 16, 1, 2, 1), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mwHeapTotal.setStatus('mandatory') if mibBuilder.loadTexts: mwHeapTotal.setDescription('bytes of memory given to the heap manager.') mwHeapUsed = MibScalar((1, 3, 6, 1, 4, 1, 217, 16, 1, 2, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mwHeapUsed.setStatus('mandatory') if mibBuilder.loadTexts: mwHeapUsed.setDescription('bytes of available memory in the heap.') mibBuilder.exportSymbols("MWORKS-MIB", mwHeap=mwHeap, mwHeapUsed=mwHeapUsed, mwMemCeiling=mwMemCeiling, meterWorks=meterWorks, tecElite=tecElite, mwMem=mwMem, mw501=mw501, mwHeapTotal=mwHeapTotal, mwMemUsed=mwMemUsed)
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, single_value_constraint, constraints_union, value_size_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'SingleValueConstraint', 'ConstraintsUnion', 'ValueSizeConstraint', 'ConstraintsIntersection') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (gauge32, unsigned32, object_identity, ip_address, bits, mib_identifier, integer32, enterprises, module_identity, time_ticks, counter32, notification_type, iso, counter64, mib_scalar, mib_table, mib_table_row, mib_table_column) = mibBuilder.importSymbols('SNMPv2-SMI', 'Gauge32', 'Unsigned32', 'ObjectIdentity', 'IpAddress', 'Bits', 'MibIdentifier', 'Integer32', 'enterprises', 'ModuleIdentity', 'TimeTicks', 'Counter32', 'NotificationType', 'iso', 'Counter64', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn') (textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString') tec_elite = mib_identifier((1, 3, 6, 1, 4, 1, 217)) meter_works = mib_identifier((1, 3, 6, 1, 4, 1, 217, 16)) mw501 = mib_identifier((1, 3, 6, 1, 4, 1, 217, 16, 1)) mw_mem = mib_identifier((1, 3, 6, 1, 4, 1, 217, 16, 1, 1)) mw_heap = mib_identifier((1, 3, 6, 1, 4, 1, 217, 16, 1, 2)) mw_mem_ceiling = mib_scalar((1, 3, 6, 1, 4, 1, 217, 16, 1, 1, 1), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mwMemCeiling.setStatus('mandatory') if mibBuilder.loadTexts: mwMemCeiling.setDescription('bytes of memory the agent memory manager will allow the agent to use.') mw_mem_used = mib_scalar((1, 3, 6, 1, 4, 1, 217, 16, 1, 1, 2), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mwMemUsed.setStatus('mandatory') if mibBuilder.loadTexts: mwMemUsed.setDescription("bytes of memory that meterworks has malloc'ed. some of this may be in free pools.") mw_heap_total = mib_scalar((1, 3, 6, 1, 4, 1, 217, 16, 1, 2, 1), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mwHeapTotal.setStatus('mandatory') if mibBuilder.loadTexts: mwHeapTotal.setDescription('bytes of memory given to the heap manager.') mw_heap_used = mib_scalar((1, 3, 6, 1, 4, 1, 217, 16, 1, 2, 2), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mwHeapUsed.setStatus('mandatory') if mibBuilder.loadTexts: mwHeapUsed.setDescription('bytes of available memory in the heap.') mibBuilder.exportSymbols('MWORKS-MIB', mwHeap=mwHeap, mwHeapUsed=mwHeapUsed, mwMemCeiling=mwMemCeiling, meterWorks=meterWorks, tecElite=tecElite, mwMem=mwMem, mw501=mw501, mwHeapTotal=mwHeapTotal, mwMemUsed=mwMemUsed)
# == 1 == bar = [1, 2] def foo(bar): bar = sum(bar) return bar print(foo(bar)) # == 2 == bar = [1, 2] def foo(bar): bar[0] = 1 return sum(bar) print(foo(bar)) # == 3 == bar = [1, 2] def foo(): bar = sum(bar) return bar print(foo()) # == 4 == bar = [1, 2] def foo(bar): bar = [1, 2, 3, ] return sum(bar) print(foo(bar), bar) # == 5 == bar = [1, 2] def foo(bar): bar[:] = [1, 2, 3, ] return sum(bar) print(foo(bar), bar) # == 6 == try: bar = 1 / 0 print(bar) except ZeroDivisionError as bar: print(bar) print(bar) # == 7 == bar = [1, 2] print(list(bar for bar in bar)) print(bar) # == 8 == bar = [1, 2] f = lambda: sum(bar) print(f()) bar = [1, 2, 3, ] print(f()) # == 9 == bar = [1, 2] def foo(bar): return lambda: sum(bar) f = foo(bar) print(f()) bar = [1, 2, 3, ] print(f()) # == 10 == bar = [1, 2] foo = [] for i in bar: foo.append(lambda: i) print([f() for f in foo]) # == 11 == bar = [1, 2] foo = [ lambda: i for i in bar ] print(list(f() for f in foo)) # == 12 == bar = [1, 2] foo = [ lambda: i for i in bar ] print(list(f() for f in foo)) bar = [1, 2, 3, ] print(list(f() for f in foo)) bar[:] = [1, 2, 3, ] print(list(f() for f in foo)) # == 13 == bar = [1, 2] foo = [ lambda i=i: i for i in bar ] print(list(f() for f in foo))
bar = [1, 2] def foo(bar): bar = sum(bar) return bar print(foo(bar)) bar = [1, 2] def foo(bar): bar[0] = 1 return sum(bar) print(foo(bar)) bar = [1, 2] def foo(): bar = sum(bar) return bar print(foo()) bar = [1, 2] def foo(bar): bar = [1, 2, 3] return sum(bar) print(foo(bar), bar) bar = [1, 2] def foo(bar): bar[:] = [1, 2, 3] return sum(bar) print(foo(bar), bar) try: bar = 1 / 0 print(bar) except ZeroDivisionError as bar: print(bar) print(bar) bar = [1, 2] print(list((bar for bar in bar))) print(bar) bar = [1, 2] f = lambda : sum(bar) print(f()) bar = [1, 2, 3] print(f()) bar = [1, 2] def foo(bar): return lambda : sum(bar) f = foo(bar) print(f()) bar = [1, 2, 3] print(f()) bar = [1, 2] foo = [] for i in bar: foo.append(lambda : i) print([f() for f in foo]) bar = [1, 2] foo = [lambda : i for i in bar] print(list((f() for f in foo))) bar = [1, 2] foo = [lambda : i for i in bar] print(list((f() for f in foo))) bar = [1, 2, 3] print(list((f() for f in foo))) bar[:] = [1, 2, 3] print(list((f() for f in foo))) bar = [1, 2] foo = [lambda i=i: i for i in bar] print(list((f() for f in foo)))
n = int(input()) row = 0 for i in range(100): if 2 ** i <= n <= 2 ** (i + 1) - 1: row = i break def seki(k, n): for _ in range(n): k = 4 * k + 2 return k k = 0 if row % 2 != 0: k = 2 cri = seki(k, row // 2) if n < cri: print("Aoki") else: print("Takahashi") else: k = 1 cri = seki(k, row // 2) if n < cri: print("Takahashi") else: print("Aoki")
n = int(input()) row = 0 for i in range(100): if 2 ** i <= n <= 2 ** (i + 1) - 1: row = i break def seki(k, n): for _ in range(n): k = 4 * k + 2 return k k = 0 if row % 2 != 0: k = 2 cri = seki(k, row // 2) if n < cri: print('Aoki') else: print('Takahashi') else: k = 1 cri = seki(k, row // 2) if n < cri: print('Takahashi') else: print('Aoki')
bino = int(input()) cino = int(input()) if (bino+cino)%2==0: print("Bino") else: print("Cino")
bino = int(input()) cino = int(input()) if (bino + cino) % 2 == 0: print('Bino') else: print('Cino')
print(b) print(c) print(d) print(e) print(f) print(g)
print(b) print(c) print(d) print(e) print(f) print(g)
print("hiiiiiiiiiiiiiiiix") def sayhi(): print("2nd pkg said hi")
print('hiiiiiiiiiiiiiiiix') def sayhi(): print('2nd pkg said hi')
base = int(input('Digite o valor da base: ')) expoente = 0 while expoente <= 0: expoente = int(input('Digite o valor do expoente: ')) if expoente <= 0: print('O expoente tem que ser positivo') potencia = 1 for c in range(1, expoente + 1): potencia *= base print(f'{base}^ {expoente} = {potencia}')
base = int(input('Digite o valor da base: ')) expoente = 0 while expoente <= 0: expoente = int(input('Digite o valor do expoente: ')) if expoente <= 0: print('O expoente tem que ser positivo') potencia = 1 for c in range(1, expoente + 1): potencia *= base print(f'{base}^ {expoente} = {potencia}')
# 084 # Ask the user to type in their postcode.Display the first two # letters in uppercase. # very simple print(input('Enter your postcode: ')[0:2].upper())
print(input('Enter your postcode: ')[0:2].upper())
MAP = 1 SPEED = 1.5 VELOCITYRESET = 6 WIDTH = 1280 HEIGHT = 720 X = WIDTH / 2 - 50 Y = HEIGHT / 2 - 50 MOUSER = 325 TICKRATES = 120 nfc = False raspberry = False
map = 1 speed = 1.5 velocityreset = 6 width = 1280 height = 720 x = WIDTH / 2 - 50 y = HEIGHT / 2 - 50 mouser = 325 tickrates = 120 nfc = False raspberry = False
def main(): n = 111 gen = (n * 7 for x in range(10)) if 777 in gen: print("Yes!") if __name__ == '__main__': main()
def main(): n = 111 gen = (n * 7 for x in range(10)) if 777 in gen: print('Yes!') if __name__ == '__main__': main()
class BaseStorageManager(object): def __init__(self, adpter): self.adapter = adpter def put(self, options): try: return self.adapter.put(options) except Exception: raise Exception('Failed to write data to storage') def get(self, options): try: data = self.adapter.get(options) return data except Exception as e: raise Exception('Failed to read data from storage' + str(e)) def list(self, options): try: return self.adapter.list(options) except Exception: raise Exception('Failed to list storage data') def listPrefix(self, options): try: return self.adapter.listPrefix(options) except Exception: raise Exception('Failed to listPrefix storage data') def delete(self, options): try: self.adapter.delete(options) except Exception: raise Exception('Failed to delete storage data')
class Basestoragemanager(object): def __init__(self, adpter): self.adapter = adpter def put(self, options): try: return self.adapter.put(options) except Exception: raise exception('Failed to write data to storage') def get(self, options): try: data = self.adapter.get(options) return data except Exception as e: raise exception('Failed to read data from storage' + str(e)) def list(self, options): try: return self.adapter.list(options) except Exception: raise exception('Failed to list storage data') def list_prefix(self, options): try: return self.adapter.listPrefix(options) except Exception: raise exception('Failed to listPrefix storage data') def delete(self, options): try: self.adapter.delete(options) except Exception: raise exception('Failed to delete storage data')
def keychain_value_iter(d, key_chain=None, allowed_values=None): key_chain = [] if key_chain is None else list(key_chain).copy() if not isinstance(d, dict): if allowed_values is not None: assert isinstance(d, allowed_values), 'Value needs to be of type {}!'.format( allowed_values) yield key_chain, d else: for k, v in d.items(): yield from keychain_value_iter( v, key_chain + [k], allowed_values=allowed_values)
def keychain_value_iter(d, key_chain=None, allowed_values=None): key_chain = [] if key_chain is None else list(key_chain).copy() if not isinstance(d, dict): if allowed_values is not None: assert isinstance(d, allowed_values), 'Value needs to be of type {}!'.format(allowed_values) yield (key_chain, d) else: for (k, v) in d.items(): yield from keychain_value_iter(v, key_chain + [k], allowed_values=allowed_values)
#!/usr/bin/python # -*- coding: utf-8 -*- def getstatus(code): if code == "1000": value = "Success!" elif code == "1001": value = "Unknown Message Received" elif code == "1002": value = "Connection to Fishbowl Server was lost" elif code == "1003": value = "Some Requests had errors -- now isn't that helpful..." elif code == "1004": value = "There was an error with the database." elif code == "1009": value = "Fishbowl Server has been shut down." elif code == "1010": value = "You have been logged off the server by an administrator." elif code == "1012": value = "Unknown request function." elif code == "1100": value = "Unknown login error occurred." elif code == "1110": value = "A new Integrated Application has been added to Fishbowl Inventory. Please contact your Fishbowl Inventory Administrator to approve this Integrated Application." elif code == "1111": value = "This Integrated Application registration key does not match." elif code == "1112": value = "This Integrated Application has not been approved by the Fishbowl Inventory Administrator." elif code == "1120": value = "Invalid Username or Password." elif code == "1130": value = "Invalid Ticket passed to Fishbowl Inventory Server." elif code == "1131": value = "Invalid Key value." elif code == "1140": value = "Initialization token is not correct type." elif code == "1150": value = "Request was invalid" elif code == "1160": value = "Response was invalid." elif code == "1162": value = "The login limit has been reached for the server's key." elif code == "1200": value = "Custom Field is invalid." elif code == "1500": value = "The import was not properly formed." elif code == "1501": value = "That import type is not supported" elif code == "1502": value = "File not found." elif code == "1503": value = "That export type is not supported." elif code == "1504": value = "File could not be written to." elif code == "1505": value = "The import data was of the wrong type." elif code == "2000": value = "Was not able to find the Part {0}." elif code == "2001": value = "The part was invalid." elif code == "2100": value = "Was not able to find the Product {0}." elif code == "2101": value = "The product was invalid." elif code == "2200": value = "The yield failed." elif code == "2201": value = "Commit failed." elif code == "2202": value = "Add initial inventory failed." elif code == "2203": value = "Can not adjust committed inventory." elif code == "2300": value = "Was not able to find the Tag number {0}." elif code == "2301": value = "The tag is invalid." elif code == "2302": value = "The tag move failed." elif code == "2303": value = "Was not able to save Tag number {0}." elif code == "2304": value = "Not enough available inventory in Tagnumber {0}." elif code == "2305": value = "Tag number {0} is a location." elif code == "2400": value = "Invalid UOM." elif code == "2401": value = "UOM {0} not found." elif code == "2402": value = "Integer UOM {0} cannot have non-integer quantity." elif code == "2500": value = "The Tracking is not valid." elif code == "2510": value = "Serial number is missing." elif code == "2511": value = "Serial number is null." elif code == "2512": value = "Serial number is duplicate." elif code == "2513": value = "Serial number is not valid." elif code == "2600": value = "Location not found." elif code == "2601": value = "Invalid location." elif code == "2602": value = "Location Group {0} not found." elif code == "3000": value = "Customer {0} not found." elif code == "3001": value = "Customer is invalid." elif code == "3100": value = "Vendor {0} not found." elif code == "3101": value = "Vendor is invalid." elif code == "4000": value = "There was an error load PO {0}." elif code == "4001": value = "Unknow status {0}." elif code == "4002": value = "Unknown carrier {0}." elif code == "4003": value = "Unknown QuickBooks class {0}." elif code == "4004": value = "PO does not have a PO number. Please turn on the auto-assign PO number option in the purchase order module options." else: value = 'Unknown status' return value
def getstatus(code): if code == '1000': value = 'Success!' elif code == '1001': value = 'Unknown Message Received' elif code == '1002': value = 'Connection to Fishbowl Server was lost' elif code == '1003': value = "Some Requests had errors -- now isn't that helpful..." elif code == '1004': value = 'There was an error with the database.' elif code == '1009': value = 'Fishbowl Server has been shut down.' elif code == '1010': value = 'You have been logged off the server by an administrator.' elif code == '1012': value = 'Unknown request function.' elif code == '1100': value = 'Unknown login error occurred.' elif code == '1110': value = 'A new Integrated Application has been added to Fishbowl Inventory. Please contact your Fishbowl Inventory Administrator to approve this Integrated Application.' elif code == '1111': value = 'This Integrated Application registration key does not match.' elif code == '1112': value = 'This Integrated Application has not been approved by the Fishbowl Inventory Administrator.' elif code == '1120': value = 'Invalid Username or Password.' elif code == '1130': value = 'Invalid Ticket passed to Fishbowl Inventory Server.' elif code == '1131': value = 'Invalid Key value.' elif code == '1140': value = 'Initialization token is not correct type.' elif code == '1150': value = 'Request was invalid' elif code == '1160': value = 'Response was invalid.' elif code == '1162': value = "The login limit has been reached for the server's key." elif code == '1200': value = 'Custom Field is invalid.' elif code == '1500': value = 'The import was not properly formed.' elif code == '1501': value = 'That import type is not supported' elif code == '1502': value = 'File not found.' elif code == '1503': value = 'That export type is not supported.' elif code == '1504': value = 'File could not be written to.' elif code == '1505': value = 'The import data was of the wrong type.' elif code == '2000': value = 'Was not able to find the Part {0}.' elif code == '2001': value = 'The part was invalid.' elif code == '2100': value = 'Was not able to find the Product {0}.' elif code == '2101': value = 'The product was invalid.' elif code == '2200': value = 'The yield failed.' elif code == '2201': value = 'Commit failed.' elif code == '2202': value = 'Add initial inventory failed.' elif code == '2203': value = 'Can not adjust committed inventory.' elif code == '2300': value = 'Was not able to find the Tag number {0}.' elif code == '2301': value = 'The tag is invalid.' elif code == '2302': value = 'The tag move failed.' elif code == '2303': value = 'Was not able to save Tag number {0}.' elif code == '2304': value = 'Not enough available inventory in Tagnumber {0}.' elif code == '2305': value = 'Tag number {0} is a location.' elif code == '2400': value = 'Invalid UOM.' elif code == '2401': value = 'UOM {0} not found.' elif code == '2402': value = 'Integer UOM {0} cannot have non-integer quantity.' elif code == '2500': value = 'The Tracking is not valid.' elif code == '2510': value = 'Serial number is missing.' elif code == '2511': value = 'Serial number is null.' elif code == '2512': value = 'Serial number is duplicate.' elif code == '2513': value = 'Serial number is not valid.' elif code == '2600': value = 'Location not found.' elif code == '2601': value = 'Invalid location.' elif code == '2602': value = 'Location Group {0} not found.' elif code == '3000': value = 'Customer {0} not found.' elif code == '3001': value = 'Customer is invalid.' elif code == '3100': value = 'Vendor {0} not found.' elif code == '3101': value = 'Vendor is invalid.' elif code == '4000': value = 'There was an error load PO {0}.' elif code == '4001': value = 'Unknow status {0}.' elif code == '4002': value = 'Unknown carrier {0}.' elif code == '4003': value = 'Unknown QuickBooks class {0}.' elif code == '4004': value = 'PO does not have a PO number. Please turn on the auto-assign PO number option in the purchase order module options.' else: value = 'Unknown status' return value
ans = dict() pairs = dict() def create_tree(p): if p in ans: return ans[p] else: try: res = 0 if p in pairs: for ch in pairs[p]: res += create_tree(ch) + 1 ans[p] = res return res except: pass n = int(input()) for i in range(0, n-1): child, parent = input().split() if parent in pairs: pairs[parent].append(child) else: pairs[parent] = [child] if n > 0: for k in pairs: create_tree(k) for key in sorted(ans.keys()): print(key, ans[key])
ans = dict() pairs = dict() def create_tree(p): if p in ans: return ans[p] else: try: res = 0 if p in pairs: for ch in pairs[p]: res += create_tree(ch) + 1 ans[p] = res return res except: pass n = int(input()) for i in range(0, n - 1): (child, parent) = input().split() if parent in pairs: pairs[parent].append(child) else: pairs[parent] = [child] if n > 0: for k in pairs: create_tree(k) for key in sorted(ans.keys()): print(key, ans[key])
def italicize(s): b = False res = '' for e in s: if e == '"': if b: res += '{\\i}' + e else: res += e + '{i}' b=not b else: res += e return res def main(): F=open('test_in.txt','r') X=F.read() F.close() print(italicize(X)) return if __name__ == "__main__": main()
def italicize(s): b = False res = '' for e in s: if e == '"': if b: res += '{\\i}' + e else: res += e + '{i}' b = not b else: res += e return res def main(): f = open('test_in.txt', 'r') x = F.read() F.close() print(italicize(X)) return if __name__ == '__main__': main()
#!venv/bin/python3 cs = [int(c) for c in open("inputs/23.in", "r").readline().strip()] def f(cs, ts): p,cc = {n: cs[(i+1)%len(cs)] for i,n in enumerate(cs)},cs[-1] for _ in range(ts): cc,dc = p[cc],p[cc]-1 if p[cc]-1 > 0 else max(p.keys()) hc,p[cc] = [p[cc], p[p[cc]], p[p[p[cc]]]],p[p[p[p[cc]]]] while dc in hc: dc -= 1 if dc < 1: dc = max(p.keys()) p[dc],p[hc[-1]] = hc[0],p[dc] a,n = [],1 for _ in range(8): n = p[n] a.append(str(n)) return "".join(a), p[1] * p[p[1]] print("Part 1:", f(cs.copy(), 100)[0]) print("Part 2:", f(cs.copy() + [i for i in range(10, 1000001)], 10000000)[1])
cs = [int(c) for c in open('inputs/23.in', 'r').readline().strip()] def f(cs, ts): (p, cc) = ({n: cs[(i + 1) % len(cs)] for (i, n) in enumerate(cs)}, cs[-1]) for _ in range(ts): (cc, dc) = (p[cc], p[cc] - 1 if p[cc] - 1 > 0 else max(p.keys())) (hc, p[cc]) = ([p[cc], p[p[cc]], p[p[p[cc]]]], p[p[p[p[cc]]]]) while dc in hc: dc -= 1 if dc < 1: dc = max(p.keys()) (p[dc], p[hc[-1]]) = (hc[0], p[dc]) (a, n) = ([], 1) for _ in range(8): n = p[n] a.append(str(n)) return (''.join(a), p[1] * p[p[1]]) print('Part 1:', f(cs.copy(), 100)[0]) print('Part 2:', f(cs.copy() + [i for i in range(10, 1000001)], 10000000)[1])
entrada = input("palabra") listaDeLetras = [] for i in entrada: listaDeLetras.append(i)
entrada = input('palabra') lista_de_letras = [] for i in entrada: listaDeLetras.append(i)
class Machine(): def __init__(self): self.pointer = 0 self.accum = 0 self.visited = [] def run(self,program): salir = False while (salir == False): if (self.pointer in self.visited): return False if (self.pointer >= len(program)): return True self.visited.append(self.pointer) incremento = 1 if (program[self.pointer][0] == "acc"): self.accum += program[self.pointer][1] if (program[self.pointer][0] == "jmp"): incremento = program[self.pointer][1] self.pointer += incremento return True def getVisited(self): return self.visited def getAccum(self): return self.accum
class Machine: def __init__(self): self.pointer = 0 self.accum = 0 self.visited = [] def run(self, program): salir = False while salir == False: if self.pointer in self.visited: return False if self.pointer >= len(program): return True self.visited.append(self.pointer) incremento = 1 if program[self.pointer][0] == 'acc': self.accum += program[self.pointer][1] if program[self.pointer][0] == 'jmp': incremento = program[self.pointer][1] self.pointer += incremento return True def get_visited(self): return self.visited def get_accum(self): return self.accum
class PayabbhiError(Exception): def __init__(self, description=None, http_status=None, field=None): self.description = description self.http_status = http_status self.field = field self._message = self.error_message() super(PayabbhiError, self).__init__(self._message) def error_message(self): msg = "message: " + self.description msg = (msg + ", http_code: " + str(self.http_status)) if self.http_status else msg msg = (msg + ", field: " + self.field) if self.field else msg return msg + "\n" class APIError(PayabbhiError): pass class APIConnectionError(PayabbhiError): pass class AuthenticationError(PayabbhiError): pass class InvalidRequestError(PayabbhiError): pass class GatewayError(PayabbhiError): pass class SignatureVerificationError(PayabbhiError): pass
class Payabbhierror(Exception): def __init__(self, description=None, http_status=None, field=None): self.description = description self.http_status = http_status self.field = field self._message = self.error_message() super(PayabbhiError, self).__init__(self._message) def error_message(self): msg = 'message: ' + self.description msg = msg + ', http_code: ' + str(self.http_status) if self.http_status else msg msg = msg + ', field: ' + self.field if self.field else msg return msg + '\n' class Apierror(PayabbhiError): pass class Apiconnectionerror(PayabbhiError): pass class Authenticationerror(PayabbhiError): pass class Invalidrequesterror(PayabbhiError): pass class Gatewayerror(PayabbhiError): pass class Signatureverificationerror(PayabbhiError): pass
class OrderedStream: def __init__(self, n: int): self.data = [None]*n self.ptr = 0 def insert(self, id: int, value: str) -> List[str]: id -= 1 self.data[id] = value if id > self.ptr: return [] while self.ptr < len(self.data) and self.data[self.ptr]: self.ptr += 1 return self.data[id:self.ptr] # Your OrderedStream object will be instantiated and called as such: # obj = OrderedStream(n) # param_1 = obj.insert(id,value)
class Orderedstream: def __init__(self, n: int): self.data = [None] * n self.ptr = 0 def insert(self, id: int, value: str) -> List[str]: id -= 1 self.data[id] = value if id > self.ptr: return [] while self.ptr < len(self.data) and self.data[self.ptr]: self.ptr += 1 return self.data[id:self.ptr]
# convert2.py # A program to convert Celsius temps to Fahrenheit. # This version issues heat and cold warnings. def main(): celsius = float(input("What is the Celsius temperature? ")) fahrenheit = 9 / 5 * celsius + 32 print("The temperature is", fahrenheit, "degrees fahrenheit.") if fahrenheit >= 90: print("It's really hot out there, be careful!") if fahrenheit <= 30: print("Brrrrr. Be sure to dress warmly") main()
def main(): celsius = float(input('What is the Celsius temperature? ')) fahrenheit = 9 / 5 * celsius + 32 print('The temperature is', fahrenheit, 'degrees fahrenheit.') if fahrenheit >= 90: print("It's really hot out there, be careful!") if fahrenheit <= 30: print('Brrrrr. Be sure to dress warmly') main()
class LevenshteinDistance: def solve(self, str_a, str_b): a, b = str_a, str_b dist = {(x,y):0 for x in range(len(a)) for y in range(len(b))} for x in range(len(a)): dist[(x,-1)] = x+1 for y in range(len(b)): dist[(-1,y)] = y+1 dist[(-1,-1)] = 0 for i in range(len(a)): for j in range(len(b)): need_edit = a[i]!=b[j] last_edits = min(dist[(i,j-1)], dist[(i-1,j)], dist[(i-1,j-1)]) dist[(i,j)] = last_edits + int(need_edit) self.distance = dist return dist[(i,j)] def show(self): if hasattr(self, 'distance'): dist = self.distance for x in range(-1,len(a)): row = [] for y in range(-1, len(b)): row.append(dist[(x,y)]) print(row) # test ld = LevenshteinDistance() ld.solve('kitten','sitting') ld.show()
class Levenshteindistance: def solve(self, str_a, str_b): (a, b) = (str_a, str_b) dist = {(x, y): 0 for x in range(len(a)) for y in range(len(b))} for x in range(len(a)): dist[x, -1] = x + 1 for y in range(len(b)): dist[-1, y] = y + 1 dist[-1, -1] = 0 for i in range(len(a)): for j in range(len(b)): need_edit = a[i] != b[j] last_edits = min(dist[i, j - 1], dist[i - 1, j], dist[i - 1, j - 1]) dist[i, j] = last_edits + int(need_edit) self.distance = dist return dist[i, j] def show(self): if hasattr(self, 'distance'): dist = self.distance for x in range(-1, len(a)): row = [] for y in range(-1, len(b)): row.append(dist[x, y]) print(row) ld = levenshtein_distance() ld.solve('kitten', 'sitting') ld.show()
# -*- coding: utf-8 -*- BROKER_URL = 'amqp://guest@localhost//' CELERY_ACCEPT_CONTENT = ['json'], CELERY_RESULT_BACKEND = 'amqp://guest@localhost//' CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Shanghai' CELERY_ENABLE_UTC = False
broker_url = 'amqp://guest@localhost//' celery_accept_content = (['json'],) celery_result_backend = 'amqp://guest@localhost//' celery_result_serializer = 'json' celery_task_serializer = 'json' celery_timezone = 'Asia/Shanghai' celery_enable_utc = False
''' Created on 2011-6-22 @author: dholer '''
""" Created on 2011-6-22 @author: dholer """
total = 0 for n in range(1000, 1000000): suma = 0 for i in str(n): suma += int(i)**5 if (n == suma): total += n print(total)
total = 0 for n in range(1000, 1000000): suma = 0 for i in str(n): suma += int(i) ** 5 if n == suma: total += n print(total)
class Solution: @staticmethod def naive(board,word): rows,cols,n = len(board),len(board[0]),len(word) visited = set() def dfs(i,j,k): idf = str(i)+','+str(j) if i<0 or j<0 or i>cols-1 or j>rows-1 or \ board[j][i]!=word[k] or idf in visited: return False if k==n-1 and word[k]==board[j][i]: return True visited.add(idf) if word[k]==board[j][i]: return dfs(i+1,j,k+1) or dfs(i-1,j,k+1) or\ dfs(i,j+1,k+1) or dfs(i,j-1,k+1) for j in range(rows): for i in range(cols): if board[j][i]==word[0]: if dfs(i,j,0): return True return False @staticmethod def quick(board,word): ''' Improve by, 1. Exclude set which stores visited coordinates, and use #. 2. No indicing in original word. 3. Quick exit for 4 directions. ''' rows,cols,n = len(board),len(board[0]),len(word) def dfs(i,j,remain): if len(remain)==0: return True if i<0 or j<0 or i>cols-1 or j>rows-1 or \ board[j][i]!=remain[0]: return False board[j][i]="#" ret = False for rowOff,colOff in [(1,0),(-1,0),(0,1),(0,-1)]: ret = dfs(i+colOff,j+rowOff,remain[1:]) if ret: break board[j][i]=remain[0] return ret for j in range(rows): for i in range(cols): if board[j][i]==word[0]: if dfs(i,j,word): return True return False
class Solution: @staticmethod def naive(board, word): (rows, cols, n) = (len(board), len(board[0]), len(word)) visited = set() def dfs(i, j, k): idf = str(i) + ',' + str(j) if i < 0 or j < 0 or i > cols - 1 or (j > rows - 1) or (board[j][i] != word[k]) or (idf in visited): return False if k == n - 1 and word[k] == board[j][i]: return True visited.add(idf) if word[k] == board[j][i]: return dfs(i + 1, j, k + 1) or dfs(i - 1, j, k + 1) or dfs(i, j + 1, k + 1) or dfs(i, j - 1, k + 1) for j in range(rows): for i in range(cols): if board[j][i] == word[0]: if dfs(i, j, 0): return True return False @staticmethod def quick(board, word): """ Improve by, 1. Exclude set which stores visited coordinates, and use #. 2. No indicing in original word. 3. Quick exit for 4 directions. """ (rows, cols, n) = (len(board), len(board[0]), len(word)) def dfs(i, j, remain): if len(remain) == 0: return True if i < 0 or j < 0 or i > cols - 1 or (j > rows - 1) or (board[j][i] != remain[0]): return False board[j][i] = '#' ret = False for (row_off, col_off) in [(1, 0), (-1, 0), (0, 1), (0, -1)]: ret = dfs(i + colOff, j + rowOff, remain[1:]) if ret: break board[j][i] = remain[0] return ret for j in range(rows): for i in range(cols): if board[j][i] == word[0]: if dfs(i, j, word): return True return False
# ---------------------------------------------------------------------- # CISCO-VLAN-MEMBERSHIP-MIB # Compiled MIB # Do not modify this file directly # Run ./noc mib make-cmib instead # ---------------------------------------------------------------------- # Copyright (C) 2007-2020 The NOC Project # See LICENSE for details # ---------------------------------------------------------------------- # MIB Name NAME = "CISCO-VLAN-MEMBERSHIP-MIB" # Metadata LAST_UPDATED = "2007-12-14" COMPILED = "2020-01-19" # MIB Data: name -> oid MIB = { "CISCO-VLAN-MEMBERSHIP-MIB::ciscoVlanMembershipMIB": "1.3.6.1.4.1.9.9.68", "CISCO-VLAN-MEMBERSHIP-MIB::ciscoVlanMembershipMIBObjects": "1.3.6.1.4.1.9.9.68.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmVmps": "1.3.6.1.4.1.9.9.68.1.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsVQPVersion": "1.3.6.1.4.1.9.9.68.1.1.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsRetries": "1.3.6.1.4.1.9.9.68.1.1.2", "CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsReconfirmInterval": "1.3.6.1.4.1.9.9.68.1.1.3", "CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsReconfirm": "1.3.6.1.4.1.9.9.68.1.1.4", "CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsReconfirmResult": "1.3.6.1.4.1.9.9.68.1.1.5", "CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsCurrent": "1.3.6.1.4.1.9.9.68.1.1.6", "CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsTable": "1.3.6.1.4.1.9.9.68.1.1.7", "CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsEntry": "1.3.6.1.4.1.9.9.68.1.1.7.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsIpAddress": "1.3.6.1.4.1.9.9.68.1.1.7.1.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsPrimary": "1.3.6.1.4.1.9.9.68.1.1.7.1.2", "CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsRowStatus": "1.3.6.1.4.1.9.9.68.1.1.7.1.3", "CISCO-VLAN-MEMBERSHIP-MIB::vmMembership": "1.3.6.1.4.1.9.9.68.1.2", "CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipSummaryTable": "1.3.6.1.4.1.9.9.68.1.2.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipSummaryEntry": "1.3.6.1.4.1.9.9.68.1.2.1.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipSummaryVlanIndex": "1.3.6.1.4.1.9.9.68.1.2.1.1.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipSummaryMemberPorts": "1.3.6.1.4.1.9.9.68.1.2.1.1.2", "CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipSummaryMember2kPorts": "1.3.6.1.4.1.9.9.68.1.2.1.1.3", "CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipTable": "1.3.6.1.4.1.9.9.68.1.2.2", "CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipEntry": "1.3.6.1.4.1.9.9.68.1.2.2.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmVlanType": "1.3.6.1.4.1.9.9.68.1.2.2.1.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmVlan": "1.3.6.1.4.1.9.9.68.1.2.2.1.2", "CISCO-VLAN-MEMBERSHIP-MIB::vmPortStatus": "1.3.6.1.4.1.9.9.68.1.2.2.1.3", "CISCO-VLAN-MEMBERSHIP-MIB::vmVlans": "1.3.6.1.4.1.9.9.68.1.2.2.1.4", "CISCO-VLAN-MEMBERSHIP-MIB::vmVlans2k": "1.3.6.1.4.1.9.9.68.1.2.2.1.5", "CISCO-VLAN-MEMBERSHIP-MIB::vmVlans3k": "1.3.6.1.4.1.9.9.68.1.2.2.1.6", "CISCO-VLAN-MEMBERSHIP-MIB::vmVlans4k": "1.3.6.1.4.1.9.9.68.1.2.2.1.7", "CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipSummaryExtTable": "1.3.6.1.4.1.9.9.68.1.2.3", "CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipSummaryExtEntry": "1.3.6.1.4.1.9.9.68.1.2.3.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipPortRangeIndex": "1.3.6.1.4.1.9.9.68.1.2.3.1.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipSummaryExtPorts": "1.3.6.1.4.1.9.9.68.1.2.3.1.2", "CISCO-VLAN-MEMBERSHIP-MIB::vmVlanCreationMode": "1.3.6.1.4.1.9.9.68.1.2.4", "CISCO-VLAN-MEMBERSHIP-MIB::vmStatistics": "1.3.6.1.4.1.9.9.68.1.3", "CISCO-VLAN-MEMBERSHIP-MIB::vmVQPQueries": "1.3.6.1.4.1.9.9.68.1.3.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmVQPResponses": "1.3.6.1.4.1.9.9.68.1.3.2", "CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsChanges": "1.3.6.1.4.1.9.9.68.1.3.3", "CISCO-VLAN-MEMBERSHIP-MIB::vmVQPShutdown": "1.3.6.1.4.1.9.9.68.1.3.4", "CISCO-VLAN-MEMBERSHIP-MIB::vmVQPDenied": "1.3.6.1.4.1.9.9.68.1.3.5", "CISCO-VLAN-MEMBERSHIP-MIB::vmVQPWrongDomain": "1.3.6.1.4.1.9.9.68.1.3.6", "CISCO-VLAN-MEMBERSHIP-MIB::vmVQPWrongVersion": "1.3.6.1.4.1.9.9.68.1.3.7", "CISCO-VLAN-MEMBERSHIP-MIB::vmInsufficientResources": "1.3.6.1.4.1.9.9.68.1.3.8", "CISCO-VLAN-MEMBERSHIP-MIB::vmStatus": "1.3.6.1.4.1.9.9.68.1.4", "CISCO-VLAN-MEMBERSHIP-MIB::vmNotificationsEnabled": "1.3.6.1.4.1.9.9.68.1.4.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmVoiceVlan": "1.3.6.1.4.1.9.9.68.1.5", "CISCO-VLAN-MEMBERSHIP-MIB::vmVoiceVlanTable": "1.3.6.1.4.1.9.9.68.1.5.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmVoiceVlanEntry": "1.3.6.1.4.1.9.9.68.1.5.1.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmVoiceVlanId": "1.3.6.1.4.1.9.9.68.1.5.1.1.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmVoiceVlanCdpVerifyEnable": "1.3.6.1.4.1.9.9.68.1.5.1.1.2", "CISCO-VLAN-MEMBERSHIP-MIB::vmNotifications": "1.3.6.1.4.1.9.9.68.2", "CISCO-VLAN-MEMBERSHIP-MIB::vmNotificationsPrefix": "1.3.6.1.4.1.9.9.68.2.0", "CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsChange": "1.3.6.1.4.1.9.9.68.2.0.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmMIBConformance": "1.3.6.1.4.1.9.9.68.3", "CISCO-VLAN-MEMBERSHIP-MIB::vmMIBCompliances": "1.3.6.1.4.1.9.9.68.3.1", "CISCO-VLAN-MEMBERSHIP-MIB::vmMIBGroups": "1.3.6.1.4.1.9.9.68.3.2", } DISPLAY_HINTS = {}
name = 'CISCO-VLAN-MEMBERSHIP-MIB' last_updated = '2007-12-14' compiled = '2020-01-19' mib = {'CISCO-VLAN-MEMBERSHIP-MIB::ciscoVlanMembershipMIB': '1.3.6.1.4.1.9.9.68', 'CISCO-VLAN-MEMBERSHIP-MIB::ciscoVlanMembershipMIBObjects': '1.3.6.1.4.1.9.9.68.1', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVmps': '1.3.6.1.4.1.9.9.68.1.1', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsVQPVersion': '1.3.6.1.4.1.9.9.68.1.1.1', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsRetries': '1.3.6.1.4.1.9.9.68.1.1.2', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsReconfirmInterval': '1.3.6.1.4.1.9.9.68.1.1.3', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsReconfirm': '1.3.6.1.4.1.9.9.68.1.1.4', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsReconfirmResult': '1.3.6.1.4.1.9.9.68.1.1.5', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsCurrent': '1.3.6.1.4.1.9.9.68.1.1.6', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsTable': '1.3.6.1.4.1.9.9.68.1.1.7', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsEntry': '1.3.6.1.4.1.9.9.68.1.1.7.1', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsIpAddress': '1.3.6.1.4.1.9.9.68.1.1.7.1.1', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsPrimary': '1.3.6.1.4.1.9.9.68.1.1.7.1.2', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsRowStatus': '1.3.6.1.4.1.9.9.68.1.1.7.1.3', 'CISCO-VLAN-MEMBERSHIP-MIB::vmMembership': '1.3.6.1.4.1.9.9.68.1.2', 'CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipSummaryTable': '1.3.6.1.4.1.9.9.68.1.2.1', 'CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipSummaryEntry': '1.3.6.1.4.1.9.9.68.1.2.1.1', 'CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipSummaryVlanIndex': '1.3.6.1.4.1.9.9.68.1.2.1.1.1', 'CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipSummaryMemberPorts': '1.3.6.1.4.1.9.9.68.1.2.1.1.2', 'CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipSummaryMember2kPorts': '1.3.6.1.4.1.9.9.68.1.2.1.1.3', 'CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipTable': '1.3.6.1.4.1.9.9.68.1.2.2', 'CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipEntry': '1.3.6.1.4.1.9.9.68.1.2.2.1', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVlanType': '1.3.6.1.4.1.9.9.68.1.2.2.1.1', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVlan': '1.3.6.1.4.1.9.9.68.1.2.2.1.2', 'CISCO-VLAN-MEMBERSHIP-MIB::vmPortStatus': '1.3.6.1.4.1.9.9.68.1.2.2.1.3', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVlans': '1.3.6.1.4.1.9.9.68.1.2.2.1.4', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVlans2k': '1.3.6.1.4.1.9.9.68.1.2.2.1.5', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVlans3k': '1.3.6.1.4.1.9.9.68.1.2.2.1.6', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVlans4k': '1.3.6.1.4.1.9.9.68.1.2.2.1.7', 'CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipSummaryExtTable': '1.3.6.1.4.1.9.9.68.1.2.3', 'CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipSummaryExtEntry': '1.3.6.1.4.1.9.9.68.1.2.3.1', 'CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipPortRangeIndex': '1.3.6.1.4.1.9.9.68.1.2.3.1.1', 'CISCO-VLAN-MEMBERSHIP-MIB::vmMembershipSummaryExtPorts': '1.3.6.1.4.1.9.9.68.1.2.3.1.2', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVlanCreationMode': '1.3.6.1.4.1.9.9.68.1.2.4', 'CISCO-VLAN-MEMBERSHIP-MIB::vmStatistics': '1.3.6.1.4.1.9.9.68.1.3', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVQPQueries': '1.3.6.1.4.1.9.9.68.1.3.1', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVQPResponses': '1.3.6.1.4.1.9.9.68.1.3.2', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsChanges': '1.3.6.1.4.1.9.9.68.1.3.3', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVQPShutdown': '1.3.6.1.4.1.9.9.68.1.3.4', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVQPDenied': '1.3.6.1.4.1.9.9.68.1.3.5', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVQPWrongDomain': '1.3.6.1.4.1.9.9.68.1.3.6', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVQPWrongVersion': '1.3.6.1.4.1.9.9.68.1.3.7', 'CISCO-VLAN-MEMBERSHIP-MIB::vmInsufficientResources': '1.3.6.1.4.1.9.9.68.1.3.8', 'CISCO-VLAN-MEMBERSHIP-MIB::vmStatus': '1.3.6.1.4.1.9.9.68.1.4', 'CISCO-VLAN-MEMBERSHIP-MIB::vmNotificationsEnabled': '1.3.6.1.4.1.9.9.68.1.4.1', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVoiceVlan': '1.3.6.1.4.1.9.9.68.1.5', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVoiceVlanTable': '1.3.6.1.4.1.9.9.68.1.5.1', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVoiceVlanEntry': '1.3.6.1.4.1.9.9.68.1.5.1.1', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVoiceVlanId': '1.3.6.1.4.1.9.9.68.1.5.1.1.1', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVoiceVlanCdpVerifyEnable': '1.3.6.1.4.1.9.9.68.1.5.1.1.2', 'CISCO-VLAN-MEMBERSHIP-MIB::vmNotifications': '1.3.6.1.4.1.9.9.68.2', 'CISCO-VLAN-MEMBERSHIP-MIB::vmNotificationsPrefix': '1.3.6.1.4.1.9.9.68.2.0', 'CISCO-VLAN-MEMBERSHIP-MIB::vmVmpsChange': '1.3.6.1.4.1.9.9.68.2.0.1', 'CISCO-VLAN-MEMBERSHIP-MIB::vmMIBConformance': '1.3.6.1.4.1.9.9.68.3', 'CISCO-VLAN-MEMBERSHIP-MIB::vmMIBCompliances': '1.3.6.1.4.1.9.9.68.3.1', 'CISCO-VLAN-MEMBERSHIP-MIB::vmMIBGroups': '1.3.6.1.4.1.9.9.68.3.2'} display_hints = {}
# module for adapting templates on the fly if components are reused # check that all reused components are defined consistently -> else: exception def check_consistency(components): for j1 in components: for j2 in components: # compare all components if j1 == j2 and j1.__dict__ != j2.__dict__: # same name and reuseID but different other attributes raise ValueError("Inconsistent definition of reused component {}.".format(j1)) # check and return number of reuses def reuses(component, arcs): # count number of reuses for each port times = set() # set => no duplicates for k in range(component.inputs): times.add(len([a for a in arcs if a.ends_in(k, component)])) for k in range(component.outputs): times.add(len([a for a in arcs if a.starts_at(k, component)])) # check if each port was reused the same number of times (requirement/assumption) if len(times) != 1: raise ValueError("Not all ports of {} are (re-)used the same number of times (required).".format(component)) return times.pop() # return adapted templates with adapted reused components and exactly one arc per port (allows proportional output) def adapt_for_reuse(templates): # create set of components and arcs arcs = [] for t in templates: arcs += t.arcs # find reused components and adapt them component_reuses = {} # dictionary with components-#reuses reused_components = [] # list of all reused components (contains duplicates) for consistency check for t in templates: for j in t.components: uses = reuses(j, arcs) if uses > 1: # used by >1 => reuse if j.source: raise ValueError("Source component {} cannot be reused".format(j)) j.adapt(uses) # add ports and functions on the fly component_reuses[j] = uses reused_components.append(j) check_consistency(reused_components) # check consistent def of reused components # adjust arcs to use new ports for j in component_reuses: uses = component_reuses[j] port_offset = 0 for t in templates: # adjust/shift ingoing arcs by offset to correct port arc_shifted = False for a in t.arcs: if a.dest == j: a.dest_in += port_offset arc_shifted = True if a.source == j: a.src_out += port_offset arc_shifted = True # increase the offset for the next template if an arc was shifted if arc_shifted: if port_offset >= uses: # arc was shifted too often: something went wrong raise ValueError("Port offset {} too high. Should be < {} (#reuses).".format(port_offset, uses)) port_offset += 1 return templates
def check_consistency(components): for j1 in components: for j2 in components: if j1 == j2 and j1.__dict__ != j2.__dict__: raise value_error('Inconsistent definition of reused component {}.'.format(j1)) def reuses(component, arcs): times = set() for k in range(component.inputs): times.add(len([a for a in arcs if a.ends_in(k, component)])) for k in range(component.outputs): times.add(len([a for a in arcs if a.starts_at(k, component)])) if len(times) != 1: raise value_error('Not all ports of {} are (re-)used the same number of times (required).'.format(component)) return times.pop() def adapt_for_reuse(templates): arcs = [] for t in templates: arcs += t.arcs component_reuses = {} reused_components = [] for t in templates: for j in t.components: uses = reuses(j, arcs) if uses > 1: if j.source: raise value_error('Source component {} cannot be reused'.format(j)) j.adapt(uses) component_reuses[j] = uses reused_components.append(j) check_consistency(reused_components) for j in component_reuses: uses = component_reuses[j] port_offset = 0 for t in templates: arc_shifted = False for a in t.arcs: if a.dest == j: a.dest_in += port_offset arc_shifted = True if a.source == j: a.src_out += port_offset arc_shifted = True if arc_shifted: if port_offset >= uses: raise value_error('Port offset {} too high. Should be < {} (#reuses).'.format(port_offset, uses)) port_offset += 1 return templates
def findDecision(obj): #obj[0]: Passanger, obj[1]: Time, obj[2]: Coupon, obj[3]: Gender, obj[4]: Age, obj[5]: Education, obj[6]: Occupation, obj[7]: Bar, obj[8]: Coffeehouse, obj[9]: Restaurant20to50, obj[10]: Direction_same, obj[11]: Distance # {"feature": "Age", "instances": 51, "metric_value": 0.9662, "depth": 1} if obj[4]>0: # {"feature": "Occupation", "instances": 44, "metric_value": 0.9024, "depth": 2} if obj[6]>1: # {"feature": "Bar", "instances": 33, "metric_value": 0.9834, "depth": 3} if obj[7]<=1.0: # {"feature": "Education", "instances": 22, "metric_value": 0.994, "depth": 4} if obj[5]>0: # {"feature": "Passanger", "instances": 17, "metric_value": 0.9774, "depth": 5} if obj[0]<=2: # {"feature": "Time", "instances": 11, "metric_value": 0.994, "depth": 6} if obj[1]<=2: # {"feature": "Restaurant20to50", "instances": 8, "metric_value": 0.9544, "depth": 7} if obj[9]>0.0: # {"feature": "Coffeehouse", "instances": 6, "metric_value": 0.65, "depth": 8} if obj[8]<=2.0: return 'True' elif obj[8]>2.0: return 'False' else: return 'False' elif obj[9]<=0.0: return 'False' else: return 'False' elif obj[1]>2: return 'False' else: return 'False' elif obj[0]>2: # {"feature": "Gender", "instances": 6, "metric_value": 0.65, "depth": 6} if obj[3]>0: return 'True' elif obj[3]<=0: # {"feature": "Time", "instances": 2, "metric_value": 1.0, "depth": 7} if obj[1]<=2: return 'True' elif obj[1]>2: return 'False' else: return 'False' else: return 'True' else: return 'True' elif obj[5]<=0: return 'False' else: return 'False' elif obj[7]>1.0: # {"feature": "Coupon", "instances": 11, "metric_value": 0.684, "depth": 4} if obj[2]>2: return 'True' elif obj[2]<=2: # {"feature": "Direction_same", "instances": 4, "metric_value": 1.0, "depth": 5} if obj[10]>0: return 'True' elif obj[10]<=0: return 'False' else: return 'False' else: return 'True' else: return 'True' elif obj[6]<=1: return 'True' else: return 'True' elif obj[4]<=0: # {"feature": "Passanger", "instances": 7, "metric_value": 0.5917, "depth": 2} if obj[0]>0: return 'False' elif obj[0]<=0: return 'True' else: return 'True' else: return 'False'
def find_decision(obj): if obj[4] > 0: if obj[6] > 1: if obj[7] <= 1.0: if obj[5] > 0: if obj[0] <= 2: if obj[1] <= 2: if obj[9] > 0.0: if obj[8] <= 2.0: return 'True' elif obj[8] > 2.0: return 'False' else: return 'False' elif obj[9] <= 0.0: return 'False' else: return 'False' elif obj[1] > 2: return 'False' else: return 'False' elif obj[0] > 2: if obj[3] > 0: return 'True' elif obj[3] <= 0: if obj[1] <= 2: return 'True' elif obj[1] > 2: return 'False' else: return 'False' else: return 'True' else: return 'True' elif obj[5] <= 0: return 'False' else: return 'False' elif obj[7] > 1.0: if obj[2] > 2: return 'True' elif obj[2] <= 2: if obj[10] > 0: return 'True' elif obj[10] <= 0: return 'False' else: return 'False' else: return 'True' else: return 'True' elif obj[6] <= 1: return 'True' else: return 'True' elif obj[4] <= 0: if obj[0] > 0: return 'False' elif obj[0] <= 0: return 'True' else: return 'True' else: return 'False'
# -*- coding: utf-8 -*- PIXIVUTIL_VERSION = '20191220-beta1' PIXIVUTIL_LINK = 'https://github.com/Nandaka/PixivUtil2/releases' PIXIVUTIL_DONATE = 'https://bit.ly/PixivUtilDonation' # Log Settings PIXIVUTIL_LOG_FILE = 'pixivutil.log' PIXIVUTIL_LOG_SIZE = 10485760 PIXIVUTIL_LOG_COUNT = 10 PIXIVUTIL_LOG_FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" # Download Results PIXIVUTIL_NOT_OK = -1 PIXIVUTIL_OK = 0 PIXIVUTIL_SKIP_OLDER = 1 PIXIVUTIL_SKIP_BLACKLIST = 2 PIXIVUTIL_KEYBOARD_INTERRUPT = 3 PIXIVUTIL_SKIP_DUPLICATE = 4 PIXIVUTIL_SKIP_LOCAL_LARGER = 5 PIXIVUTIL_CHECK_DOWNLOAD = 6 PIXIVUTIL_ABORTED = 9999 BUFFER_SIZE = 8192
pixivutil_version = '20191220-beta1' pixivutil_link = 'https://github.com/Nandaka/PixivUtil2/releases' pixivutil_donate = 'https://bit.ly/PixivUtilDonation' pixivutil_log_file = 'pixivutil.log' pixivutil_log_size = 10485760 pixivutil_log_count = 10 pixivutil_log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' pixivutil_not_ok = -1 pixivutil_ok = 0 pixivutil_skip_older = 1 pixivutil_skip_blacklist = 2 pixivutil_keyboard_interrupt = 3 pixivutil_skip_duplicate = 4 pixivutil_skip_local_larger = 5 pixivutil_check_download = 6 pixivutil_aborted = 9999 buffer_size = 8192
class Solution: def destCity(self, paths: List[List[str]]) -> str: bads = set() cities = set() for u, v in paths: cities.add(u) cities.add(v) bads.add(u) ans = cities - bads return list(ans)[0]
class Solution: def dest_city(self, paths: List[List[str]]) -> str: bads = set() cities = set() for (u, v) in paths: cities.add(u) cities.add(v) bads.add(u) ans = cities - bads return list(ans)[0]
#!/usr/bin/env python3 # The format of your own localizable method. # This is an example of '"string".localized' SUFFIX = '.localized' KEY = r'"(?:\\.|[^"\\])*"' LOCALIZABLE_RE = r'%s%s' % (KEY, SUFFIX) # Specify the path of localizable files in project. LOCALIZABLE_FILE_PATH = '' LOCALIZABLE_FILE_NAMES = ['Localizable'] LOCALIZABLE_FILE_TYPES = ['strings'] # File types of source file. SEARCH_TYPES = ['swift', 'm', 'json'] SOURCE_FILE_EXCLUSIVE_PATHS = [ 'Assets.xcassets', 'Carthage', 'ThirdParty', 'Pods', 'Media.xcassets', 'Framework', 'bin'] LOCALIZABLE_FILE_EXCLUSIVE_PATHS = ['Carthage', 'ThirdParty', 'Pods', 'Framework', 'bin'] LOCALIZABLE_FORMAT_RE = r'"(?:\\.|[^"\\])*"\s*=\s*"(?:\\.|[^"\\])*";\n' DEFAULT_TARGET_PATH = 'generated.strings'
suffix = '.localized' key = '"(?:\\\\.|[^"\\\\])*"' localizable_re = '%s%s' % (KEY, SUFFIX) localizable_file_path = '' localizable_file_names = ['Localizable'] localizable_file_types = ['strings'] search_types = ['swift', 'm', 'json'] source_file_exclusive_paths = ['Assets.xcassets', 'Carthage', 'ThirdParty', 'Pods', 'Media.xcassets', 'Framework', 'bin'] localizable_file_exclusive_paths = ['Carthage', 'ThirdParty', 'Pods', 'Framework', 'bin'] localizable_format_re = '"(?:\\\\.|[^"\\\\])*"\\s*=\\s*"(?:\\\\.|[^"\\\\])*";\\n' default_target_path = 'generated.strings'
def task_pos_args(): def show_params(param1, pos): print('param1 is: {0}'.format(param1)) for index, pos_arg in enumerate(pos): print('positional-{0}: {1}'.format(index, pos_arg)) return {'actions':[(show_params,)], 'params':[{'name':'param1', 'short':'p', 'default':'default value'}, ], 'pos_arg': 'pos', 'verbosity': 2, }
def task_pos_args(): def show_params(param1, pos): print('param1 is: {0}'.format(param1)) for (index, pos_arg) in enumerate(pos): print('positional-{0}: {1}'.format(index, pos_arg)) return {'actions': [(show_params,)], 'params': [{'name': 'param1', 'short': 'p', 'default': 'default value'}], 'pos_arg': 'pos', 'verbosity': 2}
# Lets create a linked list that has the following elements ''' 1. FE 2. SE 3. TE 4. BE ''' # Creating a Node class to create individual Nodes class Node: def __init__(self,data): self.__data = data self.__next = None def get_data(self): return self.__data def set_data(self, data): self.__data = data def get_next(self): return self.__next def set_next(self,next_node): self.__next = next_node class LinkedList: def __init__(self): self.__head = None self.__tail = None def get_head(self): return self.__head def get_tail(self): return self.__tail # ADDING ELEMENT IN THE LINKED LIST def add(self,data): new_node = Node(data) if(self.__head==None): self.__head=self.__tail=new_node else: self.__tail.set_next(new_node) self.__tail=new_node number_list= LinkedList() number_list.add("FE") number_list.add("SE") number_list.add("TE") number_list.add("BE")
""" 1. FE 2. SE 3. TE 4. BE """ class Node: def __init__(self, data): self.__data = data self.__next = None def get_data(self): return self.__data def set_data(self, data): self.__data = data def get_next(self): return self.__next def set_next(self, next_node): self.__next = next_node class Linkedlist: def __init__(self): self.__head = None self.__tail = None def get_head(self): return self.__head def get_tail(self): return self.__tail def add(self, data): new_node = node(data) if self.__head == None: self.__head = self.__tail = new_node else: self.__tail.set_next(new_node) self.__tail = new_node number_list = linked_list() number_list.add('FE') number_list.add('SE') number_list.add('TE') number_list.add('BE')
ten_things = "Apples Oranges cows Telephone Light Sugar" print ("Wait there are not 10 things in that list. Let's fix") stuff = ten_things.split(' ') more_stuff = {"Day", "Night", "Song", "Firebee", "Corn", "Banana", "Girl", "Boy"} while len(stuff) !=10: next_one = more_stuff.pop() print("Adding: ", next_one) stuff.append(next_one) print (f"There are {len(stuff)} items n ow.") print ("There we go : ", stuff) print ("Let's do some things with stuff.") print (stuff[1]) print (stuff[-1]) # whoa! cool! print (stuff.pop()) print (' '.join(stuff)) # what? cool ! print ('#'.join(stuff[3:5])) #super stealler!
ten_things = 'Apples Oranges cows Telephone Light Sugar' print("Wait there are not 10 things in that list. Let's fix") stuff = ten_things.split(' ') more_stuff = {'Day', 'Night', 'Song', 'Firebee', 'Corn', 'Banana', 'Girl', 'Boy'} while len(stuff) != 10: next_one = more_stuff.pop() print('Adding: ', next_one) stuff.append(next_one) print(f'There are {len(stuff)} items n ow.') print('There we go : ', stuff) print("Let's do some things with stuff.") print(stuff[1]) print(stuff[-1]) print(stuff.pop()) print(' '.join(stuff)) print('#'.join(stuff[3:5]))
_base_ = './pspnet_r50-d8_512x512_80k_loveda.py' model = dict( backbone=dict( depth=18, init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://resnet18_v1c')), decode_head=dict( in_channels=512, channels=128, ), auxiliary_head=dict(in_channels=256, channels=64))
_base_ = './pspnet_r50-d8_512x512_80k_loveda.py' model = dict(backbone=dict(depth=18, init_cfg=dict(type='Pretrained', checkpoint='open-mmlab://resnet18_v1c')), decode_head=dict(in_channels=512, channels=128), auxiliary_head=dict(in_channels=256, channels=64))
# Easy # https://leetcode.com/problems/palindrome-number/ # Time Complexity: O(log(x) to base 10) # Space Complexity: O(1) class Solution: def isPalindrome(self, x: int) -> bool: temp = x rev = 0 while temp > 0: rev = rev * 10 + temp % 10 temp //= 10 return rev == x
class Solution: def is_palindrome(self, x: int) -> bool: temp = x rev = 0 while temp > 0: rev = rev * 10 + temp % 10 temp //= 10 return rev == x
# Use zip() to create a new variable called names_and_dogs_names that combines owners and dogs_names lists into a zip object. # Then, create a new variable named list_of_names_and_dogs_names by calling the list() function on names_and_dogs_names. # Print list_of_names_and_dogs_names. owners = ["Jenny", "Alexus", "Sam", "Grace"] dogs_names = ["Elphonse", "Dr. Doggy DDS", "Carter", "Ralph"] names_and_dogs_names = zip(owners, dogs_names) list_of_names_and_dogs_names = list(names_and_dogs_names) print(list_of_names_and_dogs_names)
owners = ['Jenny', 'Alexus', 'Sam', 'Grace'] dogs_names = ['Elphonse', 'Dr. Doggy DDS', 'Carter', 'Ralph'] names_and_dogs_names = zip(owners, dogs_names) list_of_names_and_dogs_names = list(names_and_dogs_names) print(list_of_names_and_dogs_names)
r, c, m = map(int, input().split()) n = int(input()) op = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(n)] board = [[0 for _ in range(c)] for _ in range(r)] for ra, rb, ca, cb in op: for j in range(ra, rb + 1): for k in range(ca, cb + 1): board[j][k] += 1 cnt = 0 for i in range(r): for j in range(c): board[i][j] %= 4 if board[i][j] == 0: cnt += 1 for i in range(n): ra, rb, ca, cb = op[i] cnti = cnt for j in range(ra, rb + 1): for k in range(ca, cb + 1): if board[j][k] == 0: cnti -= 1 elif board[j][k] == 1: cnti += 1 if cnti == m: print(i + 1)
(r, c, m) = map(int, input().split()) n = int(input()) op = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(n)] board = [[0 for _ in range(c)] for _ in range(r)] for (ra, rb, ca, cb) in op: for j in range(ra, rb + 1): for k in range(ca, cb + 1): board[j][k] += 1 cnt = 0 for i in range(r): for j in range(c): board[i][j] %= 4 if board[i][j] == 0: cnt += 1 for i in range(n): (ra, rb, ca, cb) = op[i] cnti = cnt for j in range(ra, rb + 1): for k in range(ca, cb + 1): if board[j][k] == 0: cnti -= 1 elif board[j][k] == 1: cnti += 1 if cnti == m: print(i + 1)
# Convert a Number to a String! # We need a function that can transform a number into a string. # What ways of achieving this do you know? def number_to_string(num: int) -> str: str_num = str(num) return str_num print(number_to_string(123)) print(type(number_to_string(123)))
def number_to_string(num: int) -> str: str_num = str(num) return str_num print(number_to_string(123)) print(type(number_to_string(123)))
floatVar = 1.0 listVar = [3, "hello"] dictVar = { "myField": "value" } aotVar = [dictVar, dictVar] intVar = 1
float_var = 1.0 list_var = [3, 'hello'] dict_var = {'myField': 'value'} aot_var = [dictVar, dictVar] int_var = 1
# Python3 program to print # given matrix in spiral form def spiralPrint(m, n, a): start_row_index = 0 start_col_index = 0 l = 0 ''' start_row_index - starting row index m - ending row index start_col_index - starting column index n - ending column index i - iterator ''' while (start_row_index < m and start_col_index < n): # Print the first row from # the remaining rows for i in range(start_col_index, n): print(a[start_row_index][i], end=" ") start_row_index += 1 # Print the last column from # the remaining columns for i in range(start_row_index, m): print(a[i][n - 1], end=" ") n -= 1 # Print the last row from # the remaining rows if (start_row_index < m): for i in range(n - 1, (start_col_index - 1), -1): print(a[m - 1][i], end=" ") m -= 1 # Print the first column from # the remaining columns if (start_col_index < n): for i in range(m - 1, start_row_index - 1, -1): print(a[i][start_col_index], end=" ") start_col_index += 1 # Driver Code a = [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18]] R = 3 C = 6 spiralPrint(R, C, a)
def spiral_print(m, n, a): start_row_index = 0 start_col_index = 0 l = 0 ' start_row_index - starting row index \n\t\tm - ending row index \n\t\tstart_col_index - starting column index \n\t\tn - ending column index \n\t\ti - iterator ' while start_row_index < m and start_col_index < n: for i in range(start_col_index, n): print(a[start_row_index][i], end=' ') start_row_index += 1 for i in range(start_row_index, m): print(a[i][n - 1], end=' ') n -= 1 if start_row_index < m: for i in range(n - 1, start_col_index - 1, -1): print(a[m - 1][i], end=' ') m -= 1 if start_col_index < n: for i in range(m - 1, start_row_index - 1, -1): print(a[i][start_col_index], end=' ') start_col_index += 1 a = [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18]] r = 3 c = 6 spiral_print(R, C, a)
# configs for the model training class model_training_configs: VALIDATION_ERRORS_DIRECTORY = 'results/validation_errors/' INFO_FREQ = 1 # configs for the model testing class model_testing_configs: RNN_FORECASTS_DIRECTORY = 'results/rnn_forecasts/' RNN_ERRORS_DIRECTORY = 'results/errors' PROCESSED_RNN_FORECASTS_DIRECTORY = '/results/processed_rnn_forecasts/' # configs for hyperparameter tuning(SMAC3) class hyperparameter_tuning_configs: SMAC_RUNCOUNT_LIMIT = 50 class gpu_configs: log_device_placement = False
class Model_Training_Configs: validation_errors_directory = 'results/validation_errors/' info_freq = 1 class Model_Testing_Configs: rnn_forecasts_directory = 'results/rnn_forecasts/' rnn_errors_directory = 'results/errors' processed_rnn_forecasts_directory = '/results/processed_rnn_forecasts/' class Hyperparameter_Tuning_Configs: smac_runcount_limit = 50 class Gpu_Configs: log_device_placement = False
workdays = float(input()) daily_tips = float(input()) exchange_rate = float(input()) salary = workdays * daily_tips annual_income = salary * 12 + salary * 2.5 net_income = annual_income - annual_income * 25 / 100 result = net_income / 365 * exchange_rate print('%.2f' % result)
workdays = float(input()) daily_tips = float(input()) exchange_rate = float(input()) salary = workdays * daily_tips annual_income = salary * 12 + salary * 2.5 net_income = annual_income - annual_income * 25 / 100 result = net_income / 365 * exchange_rate print('%.2f' % result)
def main(): # Pass a string to show_mammal_info... show_mammal_info('I am a string') # The show_mammal_info function accepts an object # as an argument, and calls its show_species # and make_sound methods. def show_mammal_info(creature): creature.show_species() creature.make_sound() # Call the main function. main()
def main(): show_mammal_info('I am a string') def show_mammal_info(creature): creature.show_species() creature.make_sound() main()
COLOR_BLUE = '\033[0;34m' COLOR_GREEN = '\033[0;32m' COLOR_CYAN = '\033[0;36m' COLOR_RED = '\033[0;31m' COLOR_PURPLE = '\033[0;35m' COLOR_BROWN = '\033[0;33m' COLOR_YELLOW = '\033[1;33m' COLOR_GRAY = '\033[1;30m' COLOR_RESET = '\033[0m' FG_COLORS = [ # COLOR_BLUE, COLOR_GREEN, # COLOR_CYAN, # COLOR_RED, # COLOR_PURPLE, # COLOR_BROWN, # COLOR_YELLOW, ] def next_color(color): assert color in FG_COLORS index = FG_COLORS.index(color) index += 1 try: return FG_COLORS[index] except IndexError: index = 0 return FG_COLORS[index] def c(string, color): global COLOR_RESET return f"{color}{string}{COLOR_RESET}"
color_blue = '\x1b[0;34m' color_green = '\x1b[0;32m' color_cyan = '\x1b[0;36m' color_red = '\x1b[0;31m' color_purple = '\x1b[0;35m' color_brown = '\x1b[0;33m' color_yellow = '\x1b[1;33m' color_gray = '\x1b[1;30m' color_reset = '\x1b[0m' fg_colors = [COLOR_GREEN] def next_color(color): assert color in FG_COLORS index = FG_COLORS.index(color) index += 1 try: return FG_COLORS[index] except IndexError: index = 0 return FG_COLORS[index] def c(string, color): global COLOR_RESET return f'{color}{string}{COLOR_RESET}'