content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
DEBUG = True SERVE_MEDIA = DEBUG TEMPLATE_DEBUG = DEBUG EMAIL_DEBUG = DEBUG THUMBNAIL_DEBUG = DEBUG DEBUG_PROPAGATE_EXCEPTIONS = False # DATABASE_ENGINE = 'postgresql_psycopg2' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. # DATABASE_HOST = '192.168.0.2' # Set to empty string for localhost. Not used with sqlite3. # DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. EMAIL_HOST = 'localhost' EMAIL_PORT = 1025 #python -u -m smtpd -n -c DebuggingServer localhost:1025
debug = True serve_media = DEBUG template_debug = DEBUG email_debug = DEBUG thumbnail_debug = DEBUG debug_propagate_exceptions = False email_host = 'localhost' email_port = 1025
# Example of Iterator Design Pattern def count_to(count): numbers = ["one", "two", "three", "four", "five"] for number in numbers[:count]: yield number count_to_two = count_to(2) count_to_five = count_to(5) for count in [count_to_two, count_to_five]: for number in count: print(number, end=' ') print()
def count_to(count): numbers = ['one', 'two', 'three', 'four', 'five'] for number in numbers[:count]: yield number count_to_two = count_to(2) count_to_five = count_to(5) for count in [count_to_two, count_to_five]: for number in count: print(number, end=' ') print()
"""AoC Day 10""" pairs = ( "{", "}", "[", "]", "<", ">", "(", ")", ) openings = pairs[0::2] closings = pairs[1::2] def compose(*functions): def inner(arg): for f in reversed(functions): arg = f(arg) return arg return inner def find_corrupted(line): """Return the first bad char in line or None if the line isn't corrupted. By "bad", we mean a closing bracket without a matching opening bracket.""" stack = [] for char in line: if char in openings: stack.append(char) elif char in closings: closing_index = closings.index(char) if stack[-1] == openings[closing_index]: stack.pop() else: return char else: raise RuntimeError(char + " not recognised") def one(lines): """Score the corrupted lines.""" points = { ")": 3, "]": 57, "}": 1197, ">": 25137, } lookup = lambda x: points.get(x, 0) total = sum(map(compose(lookup, find_corrupted), lines)) return total def find_closings(line): stack = [] for char in line: if char in openings: stack.append(char) elif char in closings: closing_index = closings.index(char) if stack[-1] == openings[closing_index]: stack.pop() else: raise RuntimeError(char + " not recognised") result = "" for x in stack[::-1]: # If, e.g., "{" is the zeroth element in openings then we want "}", # which will be the zeroth element in closings result += closings[openings.index(x)] return result def get_score(string): points = { ")": 1, "]": 2, "}": 3, ">": 4, } total = 0 for x in string: total *= 5 total += points[x] return total def two(lines): """Score the incomplete lines.""" scores = sorted(map(compose(get_score, find_closings), filter(lambda line: find_corrupted(line) is None, lines))) return scores[len(scores)//2] if __name__ == "__main__": with open("input.txt", encoding="utf-8") as file: input_list = file.read().splitlines() answer = one(input_list) print("one: ", answer) answer = two(input_list) print("two: ", answer)
"""AoC Day 10""" pairs = ('{', '}', '[', ']', '<', '>', '(', ')') openings = pairs[0::2] closings = pairs[1::2] def compose(*functions): def inner(arg): for f in reversed(functions): arg = f(arg) return arg return inner def find_corrupted(line): """Return the first bad char in line or None if the line isn't corrupted. By "bad", we mean a closing bracket without a matching opening bracket.""" stack = [] for char in line: if char in openings: stack.append(char) elif char in closings: closing_index = closings.index(char) if stack[-1] == openings[closing_index]: stack.pop() else: return char else: raise runtime_error(char + ' not recognised') def one(lines): """Score the corrupted lines.""" points = {')': 3, ']': 57, '}': 1197, '>': 25137} lookup = lambda x: points.get(x, 0) total = sum(map(compose(lookup, find_corrupted), lines)) return total def find_closings(line): stack = [] for char in line: if char in openings: stack.append(char) elif char in closings: closing_index = closings.index(char) if stack[-1] == openings[closing_index]: stack.pop() else: raise runtime_error(char + ' not recognised') result = '' for x in stack[::-1]: result += closings[openings.index(x)] return result def get_score(string): points = {')': 1, ']': 2, '}': 3, '>': 4} total = 0 for x in string: total *= 5 total += points[x] return total def two(lines): """Score the incomplete lines.""" scores = sorted(map(compose(get_score, find_closings), filter(lambda line: find_corrupted(line) is None, lines))) return scores[len(scores) // 2] if __name__ == '__main__': with open('input.txt', encoding='utf-8') as file: input_list = file.read().splitlines() answer = one(input_list) print('one: ', answer) answer = two(input_list) print('two: ', answer)
class Layout: def __init__(self, keyboard): if keyboard == "azerty": self.up = 'Z' self.down = 'S' self.left = 'Q' self.right = 'D' self.ok = 'C' self.no = 'K' self.drop = 'L' self.change = 'P' self.random = 'O' else: self.up = 'W' self.down = 'S' self.left = 'A' self.right = 'D' self.ok = 'C' self.no = 'K' self.drop = 'L' self.change = 'P' self.random = 'O'
class Layout: def __init__(self, keyboard): if keyboard == 'azerty': self.up = 'Z' self.down = 'S' self.left = 'Q' self.right = 'D' self.ok = 'C' self.no = 'K' self.drop = 'L' self.change = 'P' self.random = 'O' else: self.up = 'W' self.down = 'S' self.left = 'A' self.right = 'D' self.ok = 'C' self.no = 'K' self.drop = 'L' self.change = 'P' self.random = 'O'
# Factorial program with memoization using decorators. # Memoization is a technique of recording the intermediate results so that it can be used to avoid repeated calculations and speed up the programs. # memoization can be done with the help of function decorators. def Memoize(func): history={} def wrapper(*args): if args not in history: history[args]=func(*args) return history[args] return wrapper def factorial(n): if type(n)!=int: raise ValueError("passed value is not integer") if(n<0): raise ValueError("number cant be negative passed value{}".format(n)) if n==0 or n==1: return 1 fact=n*factorial(n-1) return fact print(format(factorial(5))) # Input : 5 # Output : 120
def memoize(func): history = {} def wrapper(*args): if args not in history: history[args] = func(*args) return history[args] return wrapper def factorial(n): if type(n) != int: raise value_error('passed value is not integer') if n < 0: raise value_error('number cant be negative passed value{}'.format(n)) if n == 0 or n == 1: return 1 fact = n * factorial(n - 1) return fact print(format(factorial(5)))
NUM, IMG_SIZE, FACE = 8, 720, False def config(): return None config.expName = None config.checkpoint_dir = None config.train = lambda: None config.train.batch_size = 4 config.train.lr = 0.001 config.train.decay = 0.001 config.train.epochs = 10 config.latent_code_garms_sz = 1024 config.PCA_ = 35 config.garmentKeys = ['Pants', 'ShortPants', 'ShirtNoCoat', 'TShirtNoCoat', 'LongCoat'] config.NVERTS = 27554
(num, img_size, face) = (8, 720, False) def config(): return None config.expName = None config.checkpoint_dir = None config.train = lambda : None config.train.batch_size = 4 config.train.lr = 0.001 config.train.decay = 0.001 config.train.epochs = 10 config.latent_code_garms_sz = 1024 config.PCA_ = 35 config.garmentKeys = ['Pants', 'ShortPants', 'ShirtNoCoat', 'TShirtNoCoat', 'LongCoat'] config.NVERTS = 27554
# -*- coding: utf-8 -*- def main(): n = int(input()) b = [0 for _ in range(n)] for i in range(n): ai = int(input()) ai -= 1 b[ai] += 1 y = 0 x = 0 for index, bi in enumerate(b, 1): if bi == 0: x = index elif bi == 2: y = index if x == 0 and y == 0: print('Correct') else: print(y, x) if __name__ == '__main__': main()
def main(): n = int(input()) b = [0 for _ in range(n)] for i in range(n): ai = int(input()) ai -= 1 b[ai] += 1 y = 0 x = 0 for (index, bi) in enumerate(b, 1): if bi == 0: x = index elif bi == 2: y = index if x == 0 and y == 0: print('Correct') else: print(y, x) if __name__ == '__main__': main()
class VoteBreakdownTotals: def __init__(self, headers: list[str]): self.__headers = headers self.__failures = {} self.__current_row = 0 votes = "votes" if votes in self.__headers: self.__votes_index = self.__headers.index(votes) else: self.__votes_index = None if "candidate" in self.__headers: self.__candidate_index = self.__headers.index("candidate") else: self.__candidate_index = None components = {"absentee", "early_voting", "election_day", "mail", "provisional"} self.__component_indices = [i for i, x in enumerate(self.__headers) if x in components] @property def passed(self) -> bool: return len(self.__failures) == 0 def get_failure_message(self, max_examples: int = -1) -> str: components = [self.__headers[i] for i in self.__component_indices] message = f"There are {len(self.__failures)} rows where the sum of {components} is greater than 'votes':\n\n" \ f"\tHeaders: {self.__headers}:" count = 0 for row_number, row in self.__failures.items(): if (max_examples >= 0) and (count >= max_examples): message += f"\n\t[Truncated to {max_examples} examples]" return message else: message += f"\n\tRow {row_number}: {row}" count += 1 return message def test(self, row: list[str]): self.__current_row += 1 if (len(row) == len(self.__headers)) and self.__votes_index is not None and self.__component_indices: # There are cases where over votes and under votes are reported as a single aggregate. As such, it's # possible for the votes to be negative. We will try and avoid these rows. if self.__candidate_index is not None: aggregates = {"over/under", "under/over"} if any(x in row[self.__candidate_index].lower().replace(" ", "") for x in aggregates): return try: # We use float instead of int to allow for values like "3.0". votes = float(row[self.__votes_index]) except ValueError: return component_sum = 0 for component in (row[i] for i in self.__component_indices): try: component_value = float(component) except ValueError: component_value = 0 component_sum += component_value if votes < component_sum: self.__failures[self.__current_row] = row
class Votebreakdowntotals: def __init__(self, headers: list[str]): self.__headers = headers self.__failures = {} self.__current_row = 0 votes = 'votes' if votes in self.__headers: self.__votes_index = self.__headers.index(votes) else: self.__votes_index = None if 'candidate' in self.__headers: self.__candidate_index = self.__headers.index('candidate') else: self.__candidate_index = None components = {'absentee', 'early_voting', 'election_day', 'mail', 'provisional'} self.__component_indices = [i for (i, x) in enumerate(self.__headers) if x in components] @property def passed(self) -> bool: return len(self.__failures) == 0 def get_failure_message(self, max_examples: int=-1) -> str: components = [self.__headers[i] for i in self.__component_indices] message = f"There are {len(self.__failures)} rows where the sum of {components} is greater than 'votes':\n\n\tHeaders: {self.__headers}:" count = 0 for (row_number, row) in self.__failures.items(): if max_examples >= 0 and count >= max_examples: message += f'\n\t[Truncated to {max_examples} examples]' return message else: message += f'\n\tRow {row_number}: {row}' count += 1 return message def test(self, row: list[str]): self.__current_row += 1 if len(row) == len(self.__headers) and self.__votes_index is not None and self.__component_indices: if self.__candidate_index is not None: aggregates = {'over/under', 'under/over'} if any((x in row[self.__candidate_index].lower().replace(' ', '') for x in aggregates)): return try: votes = float(row[self.__votes_index]) except ValueError: return component_sum = 0 for component in (row[i] for i in self.__component_indices): try: component_value = float(component) except ValueError: component_value = 0 component_sum += component_value if votes < component_sum: self.__failures[self.__current_row] = row
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def rob(self, root: Optional[TreeNode]) -> int: """ subproblems: 1. rob current node 2. not rob current node recurrence: 1. find max amount can be robbed for current node 2. pass to the parent: current robbed current not robbed max so far base cases: if not root: return current, max_so_far (0, float(-inf)) answer : rob(root) -> max amount can be robbed Compelexity: Time (V*E) Space (V*E) """ return max(self.rob_houses(root)) def rob_houses(self, root): if not root: return 0, 0, float(-inf) left_robbed, left_not_robbed, left_max = self.rob_houses(root.left) # 1, 0, 1 right_robbed, right_not_robbed, right_max = self.rob_houses(root.right) # 3, 0, 3 curren_robbed = left_not_robbed + right_not_robbed + root.val # 4 current_not_robbed = max(left_robbed, left_not_robbed) + max(right_robbed, right_not_robbed) max_robbed = max(left_max + right_max, curren_robbed, current_not_robbed) # 1, 3, 4 return curren_robbed, current_not_robbed, max_robbed
class Solution: def rob(self, root: Optional[TreeNode]) -> int: """ subproblems: 1. rob current node 2. not rob current node recurrence: 1. find max amount can be robbed for current node 2. pass to the parent: current robbed current not robbed max so far base cases: if not root: return current, max_so_far (0, float(-inf)) answer : rob(root) -> max amount can be robbed Compelexity: Time (V*E) Space (V*E) """ return max(self.rob_houses(root)) def rob_houses(self, root): if not root: return (0, 0, float(-inf)) (left_robbed, left_not_robbed, left_max) = self.rob_houses(root.left) (right_robbed, right_not_robbed, right_max) = self.rob_houses(root.right) curren_robbed = left_not_robbed + right_not_robbed + root.val current_not_robbed = max(left_robbed, left_not_robbed) + max(right_robbed, right_not_robbed) max_robbed = max(left_max + right_max, curren_robbed, current_not_robbed) return (curren_robbed, current_not_robbed, max_robbed)
def splitCols(saleRow): '''this function will split a string with '. Some columns are quoted with "". So we need to handle it''' saleRow = saleRow.split(',') result = [] flag = True # if flag is false, the current i is within a pair of " for i in range(len(saleRow)): if flag: result.append(saleRow[i]) if '"' in saleRow[i]: flag = False else: result[-1] = result[-1] + saleRow[i] if '"' in saleRow[i]: flag = True return result
def split_cols(saleRow): """this function will split a string with '. Some columns are quoted with "". So we need to handle it""" sale_row = saleRow.split(',') result = [] flag = True for i in range(len(saleRow)): if flag: result.append(saleRow[i]) if '"' in saleRow[i]: flag = False else: result[-1] = result[-1] + saleRow[i] if '"' in saleRow[i]: flag = True return result
# # PySNMP MIB module H3C-OBJECT-INFO-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/H3C-OBJECT-INFO-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:10:08 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection") h3cCommon, = mibBuilder.importSymbols("HUAWEI-3COM-OID-MIB", "h3cCommon") NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup") MibIdentifier, IpAddress, Unsigned32, Integer32, Counter32, ObjectIdentity, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, Gauge32, iso, TimeTicks, ModuleIdentity, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "IpAddress", "Unsigned32", "Integer32", "Counter32", "ObjectIdentity", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "Gauge32", "iso", "TimeTicks", "ModuleIdentity", "Counter64") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") h3cObjectInfo = ModuleIdentity((1, 3, 6, 1, 4, 1, 2011, 10, 2, 55)) h3cObjectInfo.setRevisions(('2004-12-27 00:00',)) if mibBuilder.loadTexts: h3cObjectInfo.setLastUpdated('200412270000Z') if mibBuilder.loadTexts: h3cObjectInfo.setOrganization(' Huawei 3Com Technologies Co., Ltd. ') h3cObjectInformation = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 55, 1)) h3cObjectInfoTable = MibTable((1, 3, 6, 1, 4, 1, 2011, 10, 2, 55, 1, 1), ) if mibBuilder.loadTexts: h3cObjectInfoTable.setStatus('current') h3cObjectInfoEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2011, 10, 2, 55, 1, 1, 1), ).setIndexNames((0, "H3C-OBJECT-INFO-MIB", "h3cObjectInfoOID"), (0, "H3C-OBJECT-INFO-MIB", "h3cObjectInfoType"), (0, "H3C-OBJECT-INFO-MIB", "h3cObjectInfoTypeExtension")) if mibBuilder.loadTexts: h3cObjectInfoEntry.setStatus('current') h3cObjectInfoOID = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 10, 2, 55, 1, 1, 1, 1), ObjectIdentifier()) if mibBuilder.loadTexts: h3cObjectInfoOID.setStatus('current') h3cObjectInfoType = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 10, 2, 55, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("reserved", 1), ("accessType", 2), ("dataType", 3), ("dataRange", 4), ("dataLength", 5)))) if mibBuilder.loadTexts: h3cObjectInfoType.setStatus('current') h3cObjectInfoTypeExtension = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 10, 2, 55, 1, 1, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 10))) if mibBuilder.loadTexts: h3cObjectInfoTypeExtension.setStatus('current') h3cObjectInfoValue = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 10, 2, 55, 1, 1, 1, 4), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: h3cObjectInfoValue.setStatus('current') h3cObjectInfoMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 55, 2)) h3cObjectInfoMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 55, 2, 1)) h3cObjectInfoMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 2011, 10, 2, 55, 2, 1, 1)).setObjects(("H3C-OBJECT-INFO-MIB", "h3cObjectInfoTableGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): h3cObjectInfoMIBCompliance = h3cObjectInfoMIBCompliance.setStatus('current') h3cObjectInfoMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 55, 2, 2)) h3cObjectInfoTableGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 2011, 10, 2, 55, 2, 2, 1)).setObjects(("H3C-OBJECT-INFO-MIB", "h3cObjectInfoValue")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): h3cObjectInfoTableGroup = h3cObjectInfoTableGroup.setStatus('current') mibBuilder.exportSymbols("H3C-OBJECT-INFO-MIB", h3cObjectInfoEntry=h3cObjectInfoEntry, h3cObjectInfo=h3cObjectInfo, h3cObjectInfoTable=h3cObjectInfoTable, h3cObjectInfoType=h3cObjectInfoType, h3cObjectInfoValue=h3cObjectInfoValue, h3cObjectInfoMIBConformance=h3cObjectInfoMIBConformance, h3cObjectInformation=h3cObjectInformation, h3cObjectInfoTypeExtension=h3cObjectInfoTypeExtension, h3cObjectInfoTableGroup=h3cObjectInfoTableGroup, h3cObjectInfoMIBGroups=h3cObjectInfoMIBGroups, h3cObjectInfoMIBCompliances=h3cObjectInfoMIBCompliances, h3cObjectInfoOID=h3cObjectInfoOID, h3cObjectInfoMIBCompliance=h3cObjectInfoMIBCompliance, PYSNMP_MODULE_ID=h3cObjectInfo)
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, value_range_constraint, constraints_union, single_value_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'ValueRangeConstraint', 'ConstraintsUnion', 'SingleValueConstraint', 'ConstraintsIntersection') (h3c_common,) = mibBuilder.importSymbols('HUAWEI-3COM-OID-MIB', 'h3cCommon') (notification_group, module_compliance, object_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance', 'ObjectGroup') (mib_identifier, ip_address, unsigned32, integer32, counter32, object_identity, bits, mib_scalar, mib_table, mib_table_row, mib_table_column, notification_type, gauge32, iso, time_ticks, module_identity, counter64) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibIdentifier', 'IpAddress', 'Unsigned32', 'Integer32', 'Counter32', 'ObjectIdentity', 'Bits', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'NotificationType', 'Gauge32', 'iso', 'TimeTicks', 'ModuleIdentity', 'Counter64') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') h3c_object_info = module_identity((1, 3, 6, 1, 4, 1, 2011, 10, 2, 55)) h3cObjectInfo.setRevisions(('2004-12-27 00:00',)) if mibBuilder.loadTexts: h3cObjectInfo.setLastUpdated('200412270000Z') if mibBuilder.loadTexts: h3cObjectInfo.setOrganization(' Huawei 3Com Technologies Co., Ltd. ') h3c_object_information = mib_identifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 55, 1)) h3c_object_info_table = mib_table((1, 3, 6, 1, 4, 1, 2011, 10, 2, 55, 1, 1)) if mibBuilder.loadTexts: h3cObjectInfoTable.setStatus('current') h3c_object_info_entry = mib_table_row((1, 3, 6, 1, 4, 1, 2011, 10, 2, 55, 1, 1, 1)).setIndexNames((0, 'H3C-OBJECT-INFO-MIB', 'h3cObjectInfoOID'), (0, 'H3C-OBJECT-INFO-MIB', 'h3cObjectInfoType'), (0, 'H3C-OBJECT-INFO-MIB', 'h3cObjectInfoTypeExtension')) if mibBuilder.loadTexts: h3cObjectInfoEntry.setStatus('current') h3c_object_info_oid = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 10, 2, 55, 1, 1, 1, 1), object_identifier()) if mibBuilder.loadTexts: h3cObjectInfoOID.setStatus('current') h3c_object_info_type = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 10, 2, 55, 1, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5))).clone(namedValues=named_values(('reserved', 1), ('accessType', 2), ('dataType', 3), ('dataRange', 4), ('dataLength', 5)))) if mibBuilder.loadTexts: h3cObjectInfoType.setStatus('current') h3c_object_info_type_extension = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 10, 2, 55, 1, 1, 1, 3), octet_string().subtype(subtypeSpec=value_size_constraint(1, 10))) if mibBuilder.loadTexts: h3cObjectInfoTypeExtension.setStatus('current') h3c_object_info_value = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 10, 2, 55, 1, 1, 1, 4), octet_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: h3cObjectInfoValue.setStatus('current') h3c_object_info_mib_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 55, 2)) h3c_object_info_mib_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 55, 2, 1)) h3c_object_info_mib_compliance = module_compliance((1, 3, 6, 1, 4, 1, 2011, 10, 2, 55, 2, 1, 1)).setObjects(('H3C-OBJECT-INFO-MIB', 'h3cObjectInfoTableGroup')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): h3c_object_info_mib_compliance = h3cObjectInfoMIBCompliance.setStatus('current') h3c_object_info_mib_groups = mib_identifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 55, 2, 2)) h3c_object_info_table_group = object_group((1, 3, 6, 1, 4, 1, 2011, 10, 2, 55, 2, 2, 1)).setObjects(('H3C-OBJECT-INFO-MIB', 'h3cObjectInfoValue')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): h3c_object_info_table_group = h3cObjectInfoTableGroup.setStatus('current') mibBuilder.exportSymbols('H3C-OBJECT-INFO-MIB', h3cObjectInfoEntry=h3cObjectInfoEntry, h3cObjectInfo=h3cObjectInfo, h3cObjectInfoTable=h3cObjectInfoTable, h3cObjectInfoType=h3cObjectInfoType, h3cObjectInfoValue=h3cObjectInfoValue, h3cObjectInfoMIBConformance=h3cObjectInfoMIBConformance, h3cObjectInformation=h3cObjectInformation, h3cObjectInfoTypeExtension=h3cObjectInfoTypeExtension, h3cObjectInfoTableGroup=h3cObjectInfoTableGroup, h3cObjectInfoMIBGroups=h3cObjectInfoMIBGroups, h3cObjectInfoMIBCompliances=h3cObjectInfoMIBCompliances, h3cObjectInfoOID=h3cObjectInfoOID, h3cObjectInfoMIBCompliance=h3cObjectInfoMIBCompliance, PYSNMP_MODULE_ID=h3cObjectInfo)
# Most football fans love it for the goals and excitement. Well, this problem does not. # You are up to handle the referee's little notebook and count the players who were sent off for fouls and misbehavior. # The rules: Two teams, named "A" and "B" have 11 players each. The players on each team are numbered from 1 to 11. # Any player may be sent off the field by being given a red card. If one of the teams has less than 7 players remaining, # the game is stopped immediately by the referee, and the team with less than 7 players loses. # A card is a string with the team's letter ('A' or 'B') followed by a single dash and player's number. # e.g. the card 'B-7' means player #7 from team B received a card. # The task: You will be given a sequence of cards (could be empty), separated by a single space. # You should print the count of remaining players on each team at the end of the game in the format: # "Team A - {players_count}; Team B - {players_count}". If the game was terminated by the referee, # print an additional line: "Game was terminated". # Note for the random tests: If a player that has already been sent off receives another card - ignore it. # # 01 solution # team_a = 11 # team_b = 11 # cards = input().split() # while True: # found = True # value for breaking the while loop # for i in range(len(cards)): # loop the whole list (0, end of str) # test_digit = cards[i] # take the element on the current position # for j in range(len(cards)): # loop the whole list for the comparison with the element and the whole list # if test_digit == cards[j] and (not i == j): # compare the element in test_digit with the current one # cards.remove(test_digit) # remove the match # cards.append("") # replace the removed element to keep the integrity of the list # found = False # break # if found: # break # stop = False # for i in cards: # x = "".join(i) # if "A" in x: # team_a -= 1 # elif "B" in x: # team_b -= 1 # if team_a < 7 or team_b < 7: # stop = True # break # print(f"Team A - {team_a}; Team B - {team_b}") # if stop: # print("Game was terminated") # # 02 solution team_a = 11 team_b = 11 cards = input().split() card_list = set(cards) stop = False for i in cards: x = "".join(i) if "A" in x: team_a -= 1 elif "B" in x: team_b -= 1 if team_a < 7 or team_b < 7: stop = True break print(f"Team A - {team_a}; Team B - {team_b}") if stop: print("Game was terminated") # # INPUT 1 # A-1 A-5 A-10 B-2 # # INPUT 2 # A-1 A-5 A-10 B-2 A-10 A-7 A-3 # # INPUT END
team_a = 11 team_b = 11 cards = input().split() card_list = set(cards) stop = False for i in cards: x = ''.join(i) if 'A' in x: team_a -= 1 elif 'B' in x: team_b -= 1 if team_a < 7 or team_b < 7: stop = True break print(f'Team A - {team_a}; Team B - {team_b}') if stop: print('Game was terminated')
K, X = tuple(map(int, input().split())) start = X - K + 1 end = X + K print(*range(start, end))
(k, x) = tuple(map(int, input().split())) start = X - K + 1 end = X + K print(*range(start, end))
# -*- coding: utf-8 -*- config = { "consumer_key": "VALUE", "consumer_secret": "VALUE", "access_token": "VALUE", "access_token_secret": "VALUE", }
config = {'consumer_key': 'VALUE', 'consumer_secret': 'VALUE', 'access_token': 'VALUE', 'access_token_secret': 'VALUE'}
class Solution: # @param {integer[]} nums # @return {integer[][]} def permuteUnique(self, nums): if len(nums) == 0: return nums if len(nums) == 1: return [nums] res = [] bag = set() for i in range(len(nums)): if nums[i] not in bag: tmp = nums[:] head = tmp.pop(i) tail = self.permuteUnique(tmp) [t.insert(0, head) for t in tail] res.extend(tail) bag.add(nums[i]) return res
class Solution: def permute_unique(self, nums): if len(nums) == 0: return nums if len(nums) == 1: return [nums] res = [] bag = set() for i in range(len(nums)): if nums[i] not in bag: tmp = nums[:] head = tmp.pop(i) tail = self.permuteUnique(tmp) [t.insert(0, head) for t in tail] res.extend(tail) bag.add(nums[i]) return res
def benjHochFDR(pVals,pValColumn=1): """ pVals = 2D list(hypothesis,p-value) hypothesis could = geneName tested for enrichment pValColumn = integer of column index containing the p-value. returns _ALL_ items passed to it with no filtering at the moment. """ assert type(pValColumn) == type(1),\ "ERROR: pValColumn must be int type!" # Sort pVals from highest to lowest after converting them all to floats. for i in range(len(pVals)): pVals[i][pValColumn] = float(pVals[i][pValColumn]) pVals.sort(key=lambda x: x[pValColumn]) pVals.reverse() n = len(pVals) lastPval = pVals[0][pValColumn] for i in range(len(pVals)): p = pVals[i][pValColumn] adj = (float(n)/(n-i)) adjP = p*adj miN = min(adjP,lastPval) pVals[i].append(miN) lastPval = pVals[i][-1] pVals.reverse() return pVals
def benj_hoch_fdr(pVals, pValColumn=1): """ pVals = 2D list(hypothesis,p-value) hypothesis could = geneName tested for enrichment pValColumn = integer of column index containing the p-value. returns _ALL_ items passed to it with no filtering at the moment. """ assert type(pValColumn) == type(1), 'ERROR: pValColumn must be int type!' for i in range(len(pVals)): pVals[i][pValColumn] = float(pVals[i][pValColumn]) pVals.sort(key=lambda x: x[pValColumn]) pVals.reverse() n = len(pVals) last_pval = pVals[0][pValColumn] for i in range(len(pVals)): p = pVals[i][pValColumn] adj = float(n) / (n - i) adj_p = p * adj mi_n = min(adjP, lastPval) pVals[i].append(miN) last_pval = pVals[i][-1] pVals.reverse() return pVals
{ "targets": [ { "target_name": "posix", "sources": [ "src/posix.cc" ] } ] }
{'targets': [{'target_name': 'posix', 'sources': ['src/posix.cc']}]}
DATABASE_NAME = "glass_rooms.sqlite" STARTING_ROOM_NUMBER = 1 ENDING_ROOM_NUMBER = 9 TABLE_NAME_HEADER = "Room_" TABLE_NAME = "Bookings" URL_HEADER = "https://www.scss.tcd.ie/cgi-bin/webcal/sgmr/sgmr" URL_ENDER = ".pl" URL_BOOKING = ".request" # Regex Constants # DATE_HEADER_REGEX: regex to match '4 Nov 2015 (Wednesday):' # BOOKING_BODY_REGEX: regex to match '13:00-14:00 Sterling Archer [ba3] NATO phonetic alphabet practice' DATE_HEADER_REGEX = "[0-9]{1,2} [A-Z][a-z]+ 20[0-9]{2,2} \([A-Z][a-z]+\):" BOOKING_BODY_REGEX = "[0-9][0-9]:00-[0-9][0-9]:00 "
database_name = 'glass_rooms.sqlite' starting_room_number = 1 ending_room_number = 9 table_name_header = 'Room_' table_name = 'Bookings' url_header = 'https://www.scss.tcd.ie/cgi-bin/webcal/sgmr/sgmr' url_ender = '.pl' url_booking = '.request' date_header_regex = '[0-9]{1,2} [A-Z][a-z]+ 20[0-9]{2,2} \\([A-Z][a-z]+\\):' booking_body_regex = '[0-9][0-9]:00-[0-9][0-9]:00 '
class TagsArgument(object): """Parse the tags argument""" def __init__(self): """ Initialize the class """ super(TagsArgument, self).__init__() def parse(self, configuration): """ Parse tags from the configuration file and return it formatted :param configuration: dict :return: dict """ return { 'Tags': [{'Key': tag, 'Value': configuration[tag]} for tag in configuration] }
class Tagsargument(object): """Parse the tags argument""" def __init__(self): """ Initialize the class """ super(TagsArgument, self).__init__() def parse(self, configuration): """ Parse tags from the configuration file and return it formatted :param configuration: dict :return: dict """ return {'Tags': [{'Key': tag, 'Value': configuration[tag]} for tag in configuration]}
#!/usr/bin/python3 def bubbleSort(arr, reverse=False): length = len(arr) for i in range(0, length-1): for j in range(0, length-i-1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] if reverse: arr.reverse() return arr
def bubble_sort(arr, reverse=False): length = len(arr) for i in range(0, length - 1): for j in range(0, length - i - 1): if arr[j] > arr[j + 1]: (arr[j], arr[j + 1]) = (arr[j + 1], arr[j]) if reverse: arr.reverse() return arr
# https://www.hackerrank.com/challenges/minimum-loss/problem def minimumLoss(price): min_loss = list() price = [(i,j) for i,j in zip(range(len(price)), price)] price = sorted(price,key=lambda x: x[1]) for i in range(len(price)-1): if(price[i][0]>price[i+1][0] and price[i][1]<price[i+1][1]): min_loss.append(price[i+1][1]-price[i][1]) min_loss.sort() return min_loss[0] if __name__ == '__main__': n = int(input()) price = list(map(int, input().rstrip().split())) print(minimumLoss(price))
def minimum_loss(price): min_loss = list() price = [(i, j) for (i, j) in zip(range(len(price)), price)] price = sorted(price, key=lambda x: x[1]) for i in range(len(price) - 1): if price[i][0] > price[i + 1][0] and price[i][1] < price[i + 1][1]: min_loss.append(price[i + 1][1] - price[i][1]) min_loss.sort() return min_loss[0] if __name__ == '__main__': n = int(input()) price = list(map(int, input().rstrip().split())) print(minimum_loss(price))
# recursive function # O(n) time | O(h) space def nodedepth(root, depth=0): if root is None: return 0 return depth + nodedepth(root.left, depth + 1) + nodedepth(root.right, depth+1) # iterative function # O(n) time | O(h) space def findtheddepth(root): stack = [{"node": root, "depth": 0}] sumOfDepth = 0 while len(stack) > 0: nodeInfo = stack.pop() node, depth = nodeInfo["node"], nodeInfo["depth"] if node in None: continue sumOfDepth += depth stack.append({"node": node.left, "depth": depth+1}) stack.append({"node": node.right, "depth": depth+1}) return sumOfDepth
def nodedepth(root, depth=0): if root is None: return 0 return depth + nodedepth(root.left, depth + 1) + nodedepth(root.right, depth + 1) def findtheddepth(root): stack = [{'node': root, 'depth': 0}] sum_of_depth = 0 while len(stack) > 0: node_info = stack.pop() (node, depth) = (nodeInfo['node'], nodeInfo['depth']) if node in None: continue sum_of_depth += depth stack.append({'node': node.left, 'depth': depth + 1}) stack.append({'node': node.right, 'depth': depth + 1}) return sumOfDepth
#!/usr/bin/env python3 # # Copyright (C) 2018 ETH Zurich and University of Bologna # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # class Condor_pool(object): def __init__(self): machines = [ 'fenga1.ee.ethz.ch', 'pisoc1.ee.ethz.ch', 'pisoc3.ee.ethz.ch', 'pisoc4.ee.ethz.ch', 'pisoc5.ee.ethz.ch', 'pisoc6.ee.ethz.ch' ] #'fenga2.ee.ethz.ch', 'fenga3.ee.ethz.ch', 'larain1.ee.ethz.ch', # 'larain2.ee.ethz.ch', 'larain3.ee.ethz.ch', # 'larain4.ee.ethz.ch', 'pisoc2.ee.ethz.ch', #machines_string = [] #for machine in machines: # machines_string.append('( TARGET.Machine == \"%s\" )' % (machine)) #self.env = {} #self.env['CONDOR_REQUIREMENTS'] = ' || '.join(machines_string) self.env = {} # TRY this command for the timeout # condor_run -a "periodic_remove = (RemoteWallClockTime - CumulativeSuspensionTime) > 1" self.env['CONDOR_REQUIREMENTS'] = '( TARGET.OpSysAndVer == \"CentOS7\" )' def get_cmd(self, cmd): return 'condor_run %s' % cmd def get_env(self): return self.env
class Condor_Pool(object): def __init__(self): machines = ['fenga1.ee.ethz.ch', 'pisoc1.ee.ethz.ch', 'pisoc3.ee.ethz.ch', 'pisoc4.ee.ethz.ch', 'pisoc5.ee.ethz.ch', 'pisoc6.ee.ethz.ch'] self.env = {} self.env['CONDOR_REQUIREMENTS'] = '( TARGET.OpSysAndVer == "CentOS7" )' def get_cmd(self, cmd): return 'condor_run %s' % cmd def get_env(self): return self.env
class Event: # TODO: This gonna abstract the concept of row data in traditional ML approach pass
class Event: pass
def parse(file_path): # Method to read the config file. # Using a custom function for parsing so that we have only one config for # both the scripts and the mapreduce tasks. config = {} with open(file_path) as f: for line in f: data = line.strip() if(data and not data.startswith("#")): (key, value) = data.split("=") config[key] = value return config
def parse(file_path): config = {} with open(file_path) as f: for line in f: data = line.strip() if data and (not data.startswith('#')): (key, value) = data.split('=') config[key] = value return config
# -*- coding: utf-8 -*- ############################################################################### # # Copyright (C) 2021-TODAY Prof-Dev Integrated(<http://www.prof-dev.com>). ############################################################################### { 'name': 'Prof-Dev School MGMT', 'version': '1.0', 'license': 'LGPL-3', 'category': 'Education', "sequence": 1, 'summary': 'Manage Students, School stages,levels, classes and fees', 'complexity': "easy", 'author': 'Prof-Dev Integrated Solutions', 'website': 'http://www.prof-dev.com', 'depends': [ 'hr'], 'data': [ 'views/students.xml', 'views/parent.xml', 'views/class.xml', 'views/level.xml', 'views/stage.xml', 'views/study_year.xml', 'views/enrollment.xml', 'security/ir.model.access.csv' ] }
{'name': 'Prof-Dev School MGMT', 'version': '1.0', 'license': 'LGPL-3', 'category': 'Education', 'sequence': 1, 'summary': 'Manage Students, School stages,levels, classes and fees', 'complexity': 'easy', 'author': 'Prof-Dev Integrated Solutions', 'website': 'http://www.prof-dev.com', 'depends': ['hr'], 'data': ['views/students.xml', 'views/parent.xml', 'views/class.xml', 'views/level.xml', 'views/stage.xml', 'views/study_year.xml', 'views/enrollment.xml', 'security/ir.model.access.csv']}
class Solution: def xorOperation(self, n: int, start: int) -> int: nums = [start + 2 * i for i in range(n)]; ret = 0; for val in nums: ret ^= val return ret
class Solution: def xor_operation(self, n: int, start: int) -> int: nums = [start + 2 * i for i in range(n)] ret = 0 for val in nums: ret ^= val return ret
text = '' with open('/home/reagan/code/proj/familienanlichkeiten/data/DeReKo-2014-II-MainArchive-STT.100000.freq', 'r+') as f: text = f.read() def process_line(line: str): parts = line.split('\t') return (parts[1], parts[2]) known = set() lemmas = [] for line in text.splitlines(): lemma = process_line(line) if lemma[0]+lemma[1] not in known: lemmas.append(lemma) known.add(lemma[0]+lemma[1]) print(known)
text = '' with open('/home/reagan/code/proj/familienanlichkeiten/data/DeReKo-2014-II-MainArchive-STT.100000.freq', 'r+') as f: text = f.read() def process_line(line: str): parts = line.split('\t') return (parts[1], parts[2]) known = set() lemmas = [] for line in text.splitlines(): lemma = process_line(line) if lemma[0] + lemma[1] not in known: lemmas.append(lemma) known.add(lemma[0] + lemma[1]) print(known)
EXCHANGE_COSMOS_BLOCKCHAIN = "cosmos_blockchain" CUR_ATOM = "ATOM" MILLION = 1000000.0 CURRENCIES = { "ibc/14F9BC3E44B8A9C1BE1FB08980FAB87034C9905EF17CF2F5008FC085218811CC": "OSMO" }
exchange_cosmos_blockchain = 'cosmos_blockchain' cur_atom = 'ATOM' million = 1000000.0 currencies = {'ibc/14F9BC3E44B8A9C1BE1FB08980FAB87034C9905EF17CF2F5008FC085218811CC': 'OSMO'}
''' Given an n-ary tree, return the level order traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples). Example: 1 / | \ 3 2 4 / \ 5 6 Input: root = [1,null,3,2,4,null,5,6] Output: [[1],[3,2,4],[5,6]] Approach: 1. Consider an 'ans' array (to store final answer) and a 'level' array to store all the nodes at one level. 2. Run an iterative approach where we keep adding the values of all nodes at that level to answer array and children of each node is added to another array 'temp'. 3. The new 'level' array for next iteration is the 'temp' array. ''' class Node(object): def __init__(self, val=None, children=None): self.val = val self.children = children class Solution(object): def levelOrder(self, root): """ :type root: Node :rtype: List[List[int]] """ if not root: return [] ans = [] level = [root] while(level): ans.append([node.val for node in level]) temp = [] for node in level: for child in node.children: if child: temp.append(child) level = temp return ans
""" Given an n-ary tree, return the level order traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples). Example: 1 / | 3 2 4 / 5 6 Input: root = [1,null,3,2,4,null,5,6] Output: [[1],[3,2,4],[5,6]] Approach: 1. Consider an 'ans' array (to store final answer) and a 'level' array to store all the nodes at one level. 2. Run an iterative approach where we keep adding the values of all nodes at that level to answer array and children of each node is added to another array 'temp'. 3. The new 'level' array for next iteration is the 'temp' array. """ class Node(object): def __init__(self, val=None, children=None): self.val = val self.children = children class Solution(object): def level_order(self, root): """ :type root: Node :rtype: List[List[int]] """ if not root: return [] ans = [] level = [root] while level: ans.append([node.val for node in level]) temp = [] for node in level: for child in node.children: if child: temp.append(child) level = temp return ans
class StoreDoesNotExist(Exception): def __init__(self): super(StoreDoesNotExist, self).__init__("Store with the given query does not exist")
class Storedoesnotexist(Exception): def __init__(self): super(StoreDoesNotExist, self).__init__('Store with the given query does not exist')
class Blend(GenericForm, IDisposable): """ A blend solid or void form. """ def Dispose(self): """ Dispose(self: Element,A_0: bool) """ pass def getBoundingBox(self, *args): """ getBoundingBox(self: Element,view: View) -> BoundingBoxXYZ """ pass def GetVertexConnectionMap(self): """ GetVertexConnectionMap(self: Blend) -> VertexIndexPairArray Gets the mapping between the vertices in the top and bottom profiles. """ pass def ReleaseUnmanagedResources(self, *args): """ ReleaseUnmanagedResources(self: Element,disposing: bool) """ pass def setElementType(self, *args): """ setElementType(self: Element,type: ElementType,incompatibleExceptionMessage: str) """ pass def SetVertexConnectionMap(self, vertexMap): """ SetVertexConnectionMap(self: Blend,vertexMap: VertexIndexPairArray) Sets the mapping between the vertices in the top and bottom profiles. """ pass def __enter__(self, *args): """ __enter__(self: IDisposable) -> object """ pass def __exit__(self, *args): """ __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """ pass def __init__(self, *args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass BottomOffset = property( lambda self: object(), lambda self, v: None, lambda self: None ) """The offset of the bottom end of the blend relative to the sketch plane. Get: BottomOffset(self: Blend) -> float Set: BottomOffset(self: Blend)=value """ BottomProfile = property( lambda self: object(), lambda self, v: None, lambda self: None ) """The curves which make up the bottom profile of the sketch. Get: BottomProfile(self: Blend) -> CurveArrArray """ BottomSketch = property( lambda self: object(), lambda self, v: None, lambda self: None ) """Returns the Bottom Sketch of the Blend. Get: BottomSketch(self: Blend) -> Sketch """ TopOffset = property(lambda self: object(), lambda self, v: None, lambda self: None) """The offset of the top end of the blend relative to the sketch plane. Get: TopOffset(self: Blend) -> float Set: TopOffset(self: Blend)=value """ TopProfile = property( lambda self: object(), lambda self, v: None, lambda self: None ) """The curves which make up the top profile of the sketch. Get: TopProfile(self: Blend) -> CurveArrArray """ TopSketch = property(lambda self: object(), lambda self, v: None, lambda self: None) """Returns the Top Sketch of the Blend. Get: TopSketch(self: Blend) -> Sketch """
class Blend(GenericForm, IDisposable): """ A blend solid or void form. """ def dispose(self): """ Dispose(self: Element,A_0: bool) """ pass def get_bounding_box(self, *args): """ getBoundingBox(self: Element,view: View) -> BoundingBoxXYZ """ pass def get_vertex_connection_map(self): """ GetVertexConnectionMap(self: Blend) -> VertexIndexPairArray Gets the mapping between the vertices in the top and bottom profiles. """ pass def release_unmanaged_resources(self, *args): """ ReleaseUnmanagedResources(self: Element,disposing: bool) """ pass def set_element_type(self, *args): """ setElementType(self: Element,type: ElementType,incompatibleExceptionMessage: str) """ pass def set_vertex_connection_map(self, vertexMap): """ SetVertexConnectionMap(self: Blend,vertexMap: VertexIndexPairArray) Sets the mapping between the vertices in the top and bottom profiles. """ pass def __enter__(self, *args): """ __enter__(self: IDisposable) -> object """ pass def __exit__(self, *args): """ __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """ pass def __init__(self, *args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass bottom_offset = property(lambda self: object(), lambda self, v: None, lambda self: None) 'The offset of the bottom end of the blend relative to the sketch plane.\n\n\n\nGet: BottomOffset(self: Blend) -> float\n\n\n\nSet: BottomOffset(self: Blend)=value\n\n' bottom_profile = property(lambda self: object(), lambda self, v: None, lambda self: None) 'The curves which make up the bottom profile of the sketch.\n\n\n\nGet: BottomProfile(self: Blend) -> CurveArrArray\n\n\n\n' bottom_sketch = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Returns the Bottom Sketch of the Blend.\n\n\n\nGet: BottomSketch(self: Blend) -> Sketch\n\n\n\n' top_offset = property(lambda self: object(), lambda self, v: None, lambda self: None) 'The offset of the top end of the blend relative to the sketch plane.\n\n\n\nGet: TopOffset(self: Blend) -> float\n\n\n\nSet: TopOffset(self: Blend)=value\n\n' top_profile = property(lambda self: object(), lambda self, v: None, lambda self: None) 'The curves which make up the top profile of the sketch.\n\n\n\nGet: TopProfile(self: Blend) -> CurveArrArray\n\n\n\n' top_sketch = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Returns the Top Sketch of the Blend.\n\n\n\nGet: TopSketch(self: Blend) -> Sketch\n\n\n\n'
class LexerFileWriter(): def __init__(self, tokens: dict, lexical_errors: dict, symbol_table: dict, token_filename="tokens.txt", lexical_error_filename="lexical_errors.txt", symbol_table_filename="symbol_table.txt"): self.tokens = tokens self.lexical_errors = lexical_errors self.symbol_table = symbol_table self.token_filename = token_filename self.lexical_error_filename = lexical_error_filename self.symbol_table_filename = symbol_table_filename def write_token_file(self): output_string = "" with open(self.token_filename, 'w') as f: for k in sorted(self.tokens.keys()): output_string += f"{k}.\t{self.tokens[k]}\n" f.write(output_string) def write_lexical_errors_file(self): output_string = "" with open(self.lexical_error_filename, 'w') as f: if self.lexical_errors: for k in sorted(self.lexical_errors.keys()): output_string += f"{k}.\t{self.lexical_errors[k]}\n" else: output_string = "There is no lexical error." f.write(output_string) def write_symbol_table_file(self): output_string = "" with open(self.symbol_table_filename, 'w') as f: for k in sorted(self.symbol_table.keys()): output_string += f"{k}.\t{self.symbol_table[k]}\n" f.write(output_string)
class Lexerfilewriter: def __init__(self, tokens: dict, lexical_errors: dict, symbol_table: dict, token_filename='tokens.txt', lexical_error_filename='lexical_errors.txt', symbol_table_filename='symbol_table.txt'): self.tokens = tokens self.lexical_errors = lexical_errors self.symbol_table = symbol_table self.token_filename = token_filename self.lexical_error_filename = lexical_error_filename self.symbol_table_filename = symbol_table_filename def write_token_file(self): output_string = '' with open(self.token_filename, 'w') as f: for k in sorted(self.tokens.keys()): output_string += f'{k}.\t{self.tokens[k]}\n' f.write(output_string) def write_lexical_errors_file(self): output_string = '' with open(self.lexical_error_filename, 'w') as f: if self.lexical_errors: for k in sorted(self.lexical_errors.keys()): output_string += f'{k}.\t{self.lexical_errors[k]}\n' else: output_string = 'There is no lexical error.' f.write(output_string) def write_symbol_table_file(self): output_string = '' with open(self.symbol_table_filename, 'w') as f: for k in sorted(self.symbol_table.keys()): output_string += f'{k}.\t{self.symbol_table[k]}\n' f.write(output_string)
classes = { # layout = ["name", [attacks],[item_drops], [changes]] 0: ["soldier", [0], [2, 4, 5, 11], ["h+10", "d+2"]], 1: ["mage", [0, 2], [3, 7], ["m+40"]], 2: ["tank", [0], [1, 2, 6, 11], ["h*2", "d*0.7"]], 3: ["archer", [0, 1], [0, 3, 4, 11], ["a+10"]], 100: ["boss", [], [], ["h*1.3", "d*1.5", "a*2", "m*2"]], 101: ["basic", [0], [], []] } def get_all_classes(name_only=False): ''' Gets all of the classes stored in classes. If name_only is true returns only the names ''' all_classes = [] if name_only: for i in classes.values(): all_classes.append(i[0]) return(all_classes) else: for i in classes.values(): all_classes.append(i) return(all_classes) def get_assignable_classes(as_list=False): ''' Gets all of the classes that can be either chosen or assigned. ''' assignable_classes = classes.copy() assignable_classes.pop(100) assignable_classes.pop(101) if as_list: assignable_classes_li = [] for i in assignable_classes.values(): assignable_classes_li.append(i) return assignable_classes_li else: return assignable_classes def is_class_valid(classe=""): for classes in get_assignable_classes(True): if classe.lower() in classes: return True return False
classes = {0: ['soldier', [0], [2, 4, 5, 11], ['h+10', 'd+2']], 1: ['mage', [0, 2], [3, 7], ['m+40']], 2: ['tank', [0], [1, 2, 6, 11], ['h*2', 'd*0.7']], 3: ['archer', [0, 1], [0, 3, 4, 11], ['a+10']], 100: ['boss', [], [], ['h*1.3', 'd*1.5', 'a*2', 'm*2']], 101: ['basic', [0], [], []]} def get_all_classes(name_only=False): """ Gets all of the classes stored in classes. If name_only is true returns only the names """ all_classes = [] if name_only: for i in classes.values(): all_classes.append(i[0]) return all_classes else: for i in classes.values(): all_classes.append(i) return all_classes def get_assignable_classes(as_list=False): """ Gets all of the classes that can be either chosen or assigned. """ assignable_classes = classes.copy() assignable_classes.pop(100) assignable_classes.pop(101) if as_list: assignable_classes_li = [] for i in assignable_classes.values(): assignable_classes_li.append(i) return assignable_classes_li else: return assignable_classes def is_class_valid(classe=''): for classes in get_assignable_classes(True): if classe.lower() in classes: return True return False
def common_settings(args, plt): # Common options if args['--title']: plt.title(args['--title']) plt.ylabel(args['--ylabel']) plt.xlabel(args['--xlabel']) if args['--xlog']: plt.xscale('log') if args['--ylog']: plt.yscale('log')
def common_settings(args, plt): if args['--title']: plt.title(args['--title']) plt.ylabel(args['--ylabel']) plt.xlabel(args['--xlabel']) if args['--xlog']: plt.xscale('log') if args['--ylog']: plt.yscale('log')
#This assignment will allow you to practice writing #Python Generator functions and a small GUI using tkinter #Title: Generator Function of Powers of Two #Author: Anthony Narlock #Prof: Lisa Minogue #Class: CSCI 2061 #Date: Nov 14, 2020 #Powers of two is a gen function that can take multiple parameters, 1 or 2, gives error for anything else def powers_of_twos(*args): number_of_parameters = len(args) if(number_of_parameters == 1): starting_pow = 1 num_of_pow = args[0] elif(number_of_parameters == 2): starting_pow = args[0] num_of_pow = args[1] else: raise TypeError("Expected either one or two parameters") for i in range(num_of_pow): yield 2 ** starting_pow starting_pow += 1 #main function for testing def main(): print("Printing the powers of two that yield from powers_of_two(5):") single_example = powers_of_twos(5) for powers in powers_of_twos(5): print(powers) print("\nPrinting the powers of two that yield from powers_of_two(3,5):") for powers in powers_of_twos(3,5): print(powers) #print("\n Showing error by typing powers_of_twos(1,2,3)") #for powers in powers_of_twos(1,2,3): # print(powers) print("\n Showing error by typing powers_of_twos(0)") for powers in powers_of_twos(): print(powers) if __name__ == '__main__': main()
def powers_of_twos(*args): number_of_parameters = len(args) if number_of_parameters == 1: starting_pow = 1 num_of_pow = args[0] elif number_of_parameters == 2: starting_pow = args[0] num_of_pow = args[1] else: raise type_error('Expected either one or two parameters') for i in range(num_of_pow): yield (2 ** starting_pow) starting_pow += 1 def main(): print('Printing the powers of two that yield from powers_of_two(5):') single_example = powers_of_twos(5) for powers in powers_of_twos(5): print(powers) print('\nPrinting the powers of two that yield from powers_of_two(3,5):') for powers in powers_of_twos(3, 5): print(powers) print('\n Showing error by typing powers_of_twos(0)') for powers in powers_of_twos(): print(powers) if __name__ == '__main__': main()
class FileNames(object): '''standardize and handle all file names/types encountered by pipeline''' def __init__(self, name): '''do everything upon instantiation''' # determine root file name self.root = name self.root = self.root.replace('_c.fit','') self.root = self.root.replace('_sobj.fit','') self.root = self.root.replace('_cobj.fit','') self.root = self.root.replace('_cnew.fit','') self.root = self.root.replace('_cwcs.fit','' ) self.root = self.root.replace('_ctwp.fit','' ) self.root = self.root.replace('_cfwp.fit','' ) self.root = self.root.replace('_ctcv.fit','' ) self.root = self.root.replace('_cfcv.fit','' ) self.root = self.root.replace('_ctsb.fit','' ) self.root = self.root.replace('_cfsb.fit','' ) self.root = self.root.replace('_cph.fit','' ) self.root = self.root.replace('_ctph.fit','' ) self.root = self.root.replace('_sbph.fit','' ) self.root = self.root.replace('_cand.fit','' ) self.root = self.root.replace('_fwhm.txt','' ) self.root = self.root.replace('_obj.txt','' ) self.root = self.root.replace('_psfstar.txt','' ) self.root = self.root.replace('_apt.txt','' ) self.root = self.root.replace('_apt.dat','' ) self.root = self.root.replace('_psf.txt','' ) self.root = self.root.replace('_standrd.txt','') self.root = self.root.replace('_standxy.txt','') self.root = self.root.replace('_objectrd.txt','') self.root = self.root.replace('_objectxy.txt','') self.root = self.root.replace('_sky.txt','') self.root = self.root.replace('_apass.dat','') self.root = self.root.replace('_zero.txt','') self.root = self.root.replace('.fit','') self.root = self.root.replace('.fts','') # generate all filenames from root self.cimg = self.root + '_c.fit' self.sobj = self.root + '_sobj.fit' self.cobj = self.root + '_cobj.fit' self.cnew = self.root + '_cnew.fit' self.cwcs = self.root + '_cwcs.fit' self.ctwp = self.root + '_ctwp.fit' self.cfwp = self.root + '_cfwp.fit' self.ctcv = self.root + '_ctcv.fit' self.cfcv = self.root + '_cfcv.fit' self.ctsb = self.root + '_ctsb.fit' self.cfsb = self.root + '_cfsb.fit' self.cph = self.root + '_cph.fit' self.ctph = self.root + '_ctph.fit' self.sbph = self.root + '_sbph.fit' self.cand = self.root + '_cand.fit' self.fwhm_fl = self.root + '_fwhm.txt' self.obj = self.root + '_obj.txt' self.psfstar = self.root + '_psfstar.txt' self.apt = self.root + '_apt.txt' self.aptdat = self.root + '_apt.dat' self.psf = self.root + '_psf.txt' self.psfsub = self.root + '_psfsub.txt' self.psffitarr = self.root + '_psffitarr.fit' self.psfdat = self.root + '_psf.dat' self.psfsubdat = self.root + '_psfsub.dat' self.standrd = self.root + '_standrd.txt' self.standxy = self.root + '_standxy.txt' self.objectrd = self.root + '_objectrd.txt' self.objectxy = self.root + '_objectxy.txt' self.skytxt = self.root + '_sky.txt' self.skyfit = self.root + '_sky.fit' self.apass = self.root + '_apass.dat' self.zerotxt = self.root + '_zero.txt'
class Filenames(object): """standardize and handle all file names/types encountered by pipeline""" def __init__(self, name): """do everything upon instantiation""" self.root = name self.root = self.root.replace('_c.fit', '') self.root = self.root.replace('_sobj.fit', '') self.root = self.root.replace('_cobj.fit', '') self.root = self.root.replace('_cnew.fit', '') self.root = self.root.replace('_cwcs.fit', '') self.root = self.root.replace('_ctwp.fit', '') self.root = self.root.replace('_cfwp.fit', '') self.root = self.root.replace('_ctcv.fit', '') self.root = self.root.replace('_cfcv.fit', '') self.root = self.root.replace('_ctsb.fit', '') self.root = self.root.replace('_cfsb.fit', '') self.root = self.root.replace('_cph.fit', '') self.root = self.root.replace('_ctph.fit', '') self.root = self.root.replace('_sbph.fit', '') self.root = self.root.replace('_cand.fit', '') self.root = self.root.replace('_fwhm.txt', '') self.root = self.root.replace('_obj.txt', '') self.root = self.root.replace('_psfstar.txt', '') self.root = self.root.replace('_apt.txt', '') self.root = self.root.replace('_apt.dat', '') self.root = self.root.replace('_psf.txt', '') self.root = self.root.replace('_standrd.txt', '') self.root = self.root.replace('_standxy.txt', '') self.root = self.root.replace('_objectrd.txt', '') self.root = self.root.replace('_objectxy.txt', '') self.root = self.root.replace('_sky.txt', '') self.root = self.root.replace('_apass.dat', '') self.root = self.root.replace('_zero.txt', '') self.root = self.root.replace('.fit', '') self.root = self.root.replace('.fts', '') self.cimg = self.root + '_c.fit' self.sobj = self.root + '_sobj.fit' self.cobj = self.root + '_cobj.fit' self.cnew = self.root + '_cnew.fit' self.cwcs = self.root + '_cwcs.fit' self.ctwp = self.root + '_ctwp.fit' self.cfwp = self.root + '_cfwp.fit' self.ctcv = self.root + '_ctcv.fit' self.cfcv = self.root + '_cfcv.fit' self.ctsb = self.root + '_ctsb.fit' self.cfsb = self.root + '_cfsb.fit' self.cph = self.root + '_cph.fit' self.ctph = self.root + '_ctph.fit' self.sbph = self.root + '_sbph.fit' self.cand = self.root + '_cand.fit' self.fwhm_fl = self.root + '_fwhm.txt' self.obj = self.root + '_obj.txt' self.psfstar = self.root + '_psfstar.txt' self.apt = self.root + '_apt.txt' self.aptdat = self.root + '_apt.dat' self.psf = self.root + '_psf.txt' self.psfsub = self.root + '_psfsub.txt' self.psffitarr = self.root + '_psffitarr.fit' self.psfdat = self.root + '_psf.dat' self.psfsubdat = self.root + '_psfsub.dat' self.standrd = self.root + '_standrd.txt' self.standxy = self.root + '_standxy.txt' self.objectrd = self.root + '_objectrd.txt' self.objectxy = self.root + '_objectxy.txt' self.skytxt = self.root + '_sky.txt' self.skyfit = self.root + '_sky.fit' self.apass = self.root + '_apass.dat' self.zerotxt = self.root + '_zero.txt'
# -*- coding: utf-8 -*- class Hero(object): def __init__(self, forename, surname, hero): self.forename = forename self.surname = surname self.heroname = hero def __repr__(self): return 'Hero({0}, {1}, {2})'.format( self.forename, self.surname, self.heroname)
class Hero(object): def __init__(self, forename, surname, hero): self.forename = forename self.surname = surname self.heroname = hero def __repr__(self): return 'Hero({0}, {1}, {2})'.format(self.forename, self.surname, self.heroname)
result = [] with open(FILE, mode='r') as file: reader = csv.reader(file, lineterminator='\n') for *features, label in reader: label = SPECIES[int(label)] row = tuple(features) + (label,) result.append(row)
result = [] with open(FILE, mode='r') as file: reader = csv.reader(file, lineterminator='\n') for (*features, label) in reader: label = SPECIES[int(label)] row = tuple(features) + (label,) result.append(row)
def spec(x, y, color="run ID"): def subfigure(params, x_kwargs, y_kwargs): return { "height": 400, "width": 600, "encoding": { "x": {"type": "quantitative", "field": x, **x_kwargs}, "y": {"type": "quantitative", "field": y, **y_kwargs}, "color": {"type": "nominal", "field": color}, "opacity": { "value": 0.1, "condition": { "test": { "and": [ {"param": "legend_selection"}, {"param": "hover"}, ] }, "value": 1, }, }, }, "layer": [ { "mark": "line", "params": params, } ], } params = [ { "bind": "legend", "name": "legend_selection", "select": { "on": "mouseover", "type": "point", "fields": ["run ID"], }, }, { "bind": "legend", "name": "hover", "select": { "on": "mouseover", "type": "point", "fields": ["run ID"], }, }, ] return { "$schema": "https://vega.github.io/schema/vega-lite/v5.json", "data": {"name": "data"}, "hconcat": [ subfigure( params=[*params, {"name": "selection", "select": "interval"}], x_kwargs={}, y_kwargs={}, ), subfigure( params=params, x_kwargs={"scale": {"domain": {"param": "selection", "encoding": "x"}}}, y_kwargs={"scale": {"domain": {"param": "selection", "encoding": "y"}}}, ), ], }
def spec(x, y, color='run ID'): def subfigure(params, x_kwargs, y_kwargs): return {'height': 400, 'width': 600, 'encoding': {'x': {'type': 'quantitative', 'field': x, **x_kwargs}, 'y': {'type': 'quantitative', 'field': y, **y_kwargs}, 'color': {'type': 'nominal', 'field': color}, 'opacity': {'value': 0.1, 'condition': {'test': {'and': [{'param': 'legend_selection'}, {'param': 'hover'}]}, 'value': 1}}}, 'layer': [{'mark': 'line', 'params': params}]} params = [{'bind': 'legend', 'name': 'legend_selection', 'select': {'on': 'mouseover', 'type': 'point', 'fields': ['run ID']}}, {'bind': 'legend', 'name': 'hover', 'select': {'on': 'mouseover', 'type': 'point', 'fields': ['run ID']}}] return {'$schema': 'https://vega.github.io/schema/vega-lite/v5.json', 'data': {'name': 'data'}, 'hconcat': [subfigure(params=[*params, {'name': 'selection', 'select': 'interval'}], x_kwargs={}, y_kwargs={}), subfigure(params=params, x_kwargs={'scale': {'domain': {'param': 'selection', 'encoding': 'x'}}}, y_kwargs={'scale': {'domain': {'param': 'selection', 'encoding': 'y'}}})]}
# Option for variable 'simulation_type': # 1: cylindrical roller bearing # 2: # 3: cylindrical roller thrust bearing # 4: ball on disk (currently not fully supported) # 5: pin on disk # 6: 4 ball # 7: ball on three plates # 8: ring on ring # global simulation setup simulation_type = 8 # one of the above type numbers simulation_name = 'RingOnRing' auto_print = True # True or False auto_plot = False auto_report = False # global test setup / bearing information tribo_system_name = 'bla' number_planets = 2 # Sun (CB1) e_cb1 = 210000 # young's modulus in MPa ny_cb1 = 0.3 # poisson number in MPa diameter_cb1 = 37.5 # in mm length_cb1 = 10 # in mm type_profile_cb1 = 'ISO' # 'None', 'ISO', 'Circle', 'File' path_profile_cb1 = 'tribology/p3can/BearingProfiles/NU206-RE-1.txt' # path to profile.txt file required if TypeProfile == 'File' profile_radius_cb1 = 6.35 # input required if TypeProfile == 'Circle' # Planet (CB2) e_cb2 = 210000 # young's modulus in MPa ny_cb2 = 0.3 # poisson number in MPa diameter_cb2 = 9 # in mm type_profile_cb2 = 'ISO' # 'None', 'File' profile_radius_cb2 = 20 length_cb2 = 10 path_profile_cb2 = "tribology/p3can/BearingProfiles/NU206-IR-2.txt" # path to profile.txt file required if TypeProfile == 'File' # Loads global_force = 300 # in N rot_velocity1 = 300 # in rpm rot_velocity2 = 2 # in rpm # Mesh res_x = 33 # data points along roller length res_y = 31 # data points along roller width
simulation_type = 8 simulation_name = 'RingOnRing' auto_print = True auto_plot = False auto_report = False tribo_system_name = 'bla' number_planets = 2 e_cb1 = 210000 ny_cb1 = 0.3 diameter_cb1 = 37.5 length_cb1 = 10 type_profile_cb1 = 'ISO' path_profile_cb1 = 'tribology/p3can/BearingProfiles/NU206-RE-1.txt' profile_radius_cb1 = 6.35 e_cb2 = 210000 ny_cb2 = 0.3 diameter_cb2 = 9 type_profile_cb2 = 'ISO' profile_radius_cb2 = 20 length_cb2 = 10 path_profile_cb2 = 'tribology/p3can/BearingProfiles/NU206-IR-2.txt' global_force = 300 rot_velocity1 = 300 rot_velocity2 = 2 res_x = 33 res_y = 31
class TestAuth: """ Test all functions relating to authentication in api.py. Logout is designed always to return success (even if user not logged in), since its job is to clear session data. """ def test_1(self, auth): # login and logout: correct input and method res = auth.login(uname="U1", password="111") assert res.headers.get("Set-Cookie") is not None assert res.json()["status"] == 1 # logout to clear session res = auth.logout() assert "session=; Expires=Thu, 01-Jan-1970 00:00:00 GMT; Max-Age=0;" in res.headers.get("Set-Cookie") assert res.json()["status"] == 1 def test_2(self, client): # login: wrong method res = client.get("/api/auth/login", data={"uname": "U1", "password": "111"}) assert res.status_code == 404 def test_3(self, auth): # login: non-existent username res = auth.login(uname="0.30000000000000004", password="111") assert b"Username does not exist." in res.content def test_4(self, auth): # login: wrong password res = auth.login(uname="U1", password="000") assert b"Incorrect password." in res.content def test_5(self, auth): # login: empty input res = auth.login(uname=None, password=None) assert b"Invalid input." in res.content def test_6(self, auth): # register: correct res = auth.register(uname="foobar", password="@123456a", nickname="Hook") assert res.json()["status"] == 1 auth.logout() # clear session res = auth.login(uname="foobar", password="@123456a") assert res.headers.get("Set-Cookie") is not None assert res.json()["status"] == 1 auth.logout() def test_7(self, auth): # register: invalid uname/password/nickname res = auth.register(uname="foo", password="@123456a", nickname="Hook") assert b"Username must be of length 5 ~ 20." in res.content res = auth.register(uname="foo123", password="12345678", nickname="Hook") assert b"Invalid password." in res.content res = auth.register(uname="foo123", password="@123456a", nickname="H" * 21) assert b"Invalid nickname." in res.content
class Testauth: """ Test all functions relating to authentication in api.py. Logout is designed always to return success (even if user not logged in), since its job is to clear session data. """ def test_1(self, auth): res = auth.login(uname='U1', password='111') assert res.headers.get('Set-Cookie') is not None assert res.json()['status'] == 1 res = auth.logout() assert 'session=; Expires=Thu, 01-Jan-1970 00:00:00 GMT; Max-Age=0;' in res.headers.get('Set-Cookie') assert res.json()['status'] == 1 def test_2(self, client): res = client.get('/api/auth/login', data={'uname': 'U1', 'password': '111'}) assert res.status_code == 404 def test_3(self, auth): res = auth.login(uname='0.30000000000000004', password='111') assert b'Username does not exist.' in res.content def test_4(self, auth): res = auth.login(uname='U1', password='000') assert b'Incorrect password.' in res.content def test_5(self, auth): res = auth.login(uname=None, password=None) assert b'Invalid input.' in res.content def test_6(self, auth): res = auth.register(uname='foobar', password='@123456a', nickname='Hook') assert res.json()['status'] == 1 auth.logout() res = auth.login(uname='foobar', password='@123456a') assert res.headers.get('Set-Cookie') is not None assert res.json()['status'] == 1 auth.logout() def test_7(self, auth): res = auth.register(uname='foo', password='@123456a', nickname='Hook') assert b'Username must be of length 5 ~ 20.' in res.content res = auth.register(uname='foo123', password='12345678', nickname='Hook') assert b'Invalid password.' in res.content res = auth.register(uname='foo123', password='@123456a', nickname='H' * 21) assert b'Invalid nickname.' in res.content
e={'Eid':100120,'name':'vijay','age':21} e1={'Eid':100121,'name':'vijay','age':21} e3={'Eid':100122,'name':'vijay','age':21} print(e) print(e.get('name')) e['age']=22; for i in e.keys(): print(e[i]) for i,j in e.items(): print(i,j)
e = {'Eid': 100120, 'name': 'vijay', 'age': 21} e1 = {'Eid': 100121, 'name': 'vijay', 'age': 21} e3 = {'Eid': 100122, 'name': 'vijay', 'age': 21} print(e) print(e.get('name')) e['age'] = 22 for i in e.keys(): print(e[i]) for (i, j) in e.items(): print(i, j)
class Solution(object): def islandPerimeter(self, grid): """ :type grid: List[List[int]] :rtype: int """ island_num = neighbor_num = 0 for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == 1: island_num += 1 if i < len(grid) - 1 and grid[i + 1][j] == 1: neighbor_num += 1 if j < len(grid[i]) - 1 and grid[i][j + 1] == 1: neighbor_num += 1 return island_num * 4 - neighbor_num * 2
class Solution(object): def island_perimeter(self, grid): """ :type grid: List[List[int]] :rtype: int """ island_num = neighbor_num = 0 for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == 1: island_num += 1 if i < len(grid) - 1 and grid[i + 1][j] == 1: neighbor_num += 1 if j < len(grid[i]) - 1 and grid[i][j + 1] == 1: neighbor_num += 1 return island_num * 4 - neighbor_num * 2
def all_doe_stake_transactions(): data = { 'module': 'account', 'action': 'txlist', 'address':'0x60C6b5DC066E33801F2D9F2830595490A3086B4e', 'startblock':'13554136', 'endblock':'99999999', # 'page': '1', # 'offset': '5', 'sort': 'asc', 'apikey': hidden_details.etherscan_key, } return requests.get("https://api.etherscan.io/api", data=data).json()['result'] def dump_all_stakers(): addresses = [] dump = all_doe_stake_transactions() for tx in dump: addr = tx['from'] if addr not in addresses: addresses.append(addr)
def all_doe_stake_transactions(): data = {'module': 'account', 'action': 'txlist', 'address': '0x60C6b5DC066E33801F2D9F2830595490A3086B4e', 'startblock': '13554136', 'endblock': '99999999', 'sort': 'asc', 'apikey': hidden_details.etherscan_key} return requests.get('https://api.etherscan.io/api', data=data).json()['result'] def dump_all_stakers(): addresses = [] dump = all_doe_stake_transactions() for tx in dump: addr = tx['from'] if addr not in addresses: addresses.append(addr)
# -*- coding: utf-8 -*- class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 last = 0 for i in range(1, len(nums)): if nums[i] != nums[last]: last += 1 nums[last] = nums[i] return last + 1 print(Solution().removeDuplicates([1,1,2]))
class Solution(object): def remove_duplicates(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 last = 0 for i in range(1, len(nums)): if nums[i] != nums[last]: last += 1 nums[last] = nums[i] return last + 1 print(solution().removeDuplicates([1, 1, 2]))
""" 53. How to get the last n rows of a dataframe with row sum > 100? """ """ Difficulty Level: L2 """ """ Get the last two rows of df whose row sum is greater than 100. """ """ df = pd.DataFrame(np.random.randint(10, 40, 60).reshape(-1, 4)) """
""" 53. How to get the last n rows of a dataframe with row sum > 100? """ '\nDifficulty Level: L2\n' '\nGet the last two rows of df whose row sum is greater than 100.\n' '\ndf = pd.DataFrame(np.random.randint(10, 40, 60).reshape(-1, 4))\n'
class Thinker: def __init__(self): self.velocity = 0 def viewDistance(self): return 20 def step(self, deltaTime): self.velocity = 30 def getVelocity(self): return self.velocity
class Thinker: def __init__(self): self.velocity = 0 def view_distance(self): return 20 def step(self, deltaTime): self.velocity = 30 def get_velocity(self): return self.velocity
__author__ = 'fernando' class BaseAuth(object): def has_data(self): raise NotImplementedError() def get_username(self): raise NotImplementedError() def get_password(self): raise NotImplementedError()
__author__ = 'fernando' class Baseauth(object): def has_data(self): raise not_implemented_error() def get_username(self): raise not_implemented_error() def get_password(self): raise not_implemented_error()
# -*- coding: utf-8 -*- def test_readuntil(monkey): pass
def test_readuntil(monkey): pass
class dotRebarSpacing_t(object): # no doc EndOffset = None EndOffsetIsAutomatic = None EndOffsetIsFixed = None NumberSpacingZones = None StartOffset = None StartOffsetIsAutomatic = None StartOffsetIsFixed = None Zones = None
class Dotrebarspacing_T(object): end_offset = None end_offset_is_automatic = None end_offset_is_fixed = None number_spacing_zones = None start_offset = None start_offset_is_automatic = None start_offset_is_fixed = None zones = None
# You can create a generator using a generator expression like a lambda function. # This function does not need or use a yield keyword. # Syntax : Y = ([ Expression ]) y = [1,2,3,4,5] print([x**2 for x in y]) print("\nDoing this without using the generator expressions :") length = len(y) print((x**2 for x in y).__next__()) input("Press any key to exit ")
y = [1, 2, 3, 4, 5] print([x ** 2 for x in y]) print('\nDoing this without using the generator expressions :') length = len(y) print((x ** 2 for x in y).__next__()) input('Press any key to exit ')
# Mock out starturls for ../spiders.py file class MockGenerator(object): def __init__(self, *args, **kwargs): pass def __call__(self, *args, **kwargs): return [] class FeedGenerator(MockGenerator): pass class FragmentGenerator(MockGenerator): pass
class Mockgenerator(object): def __init__(self, *args, **kwargs): pass def __call__(self, *args, **kwargs): return [] class Feedgenerator(MockGenerator): pass class Fragmentgenerator(MockGenerator): pass
class Time: def gettime(self): self.hour=int(input("Enter hour: ")) self.minute=int(input("Enter minute: ")) self.second=int(input("Enter seconds: ")) def display(self): print(f"Time is {self.hour}:{self.minute}:{self.second}\n") def __add__(self,other): sum=Time() sum.hour=self.hour+other.hour sum.minute=self.minute+other.minute if sum.minute>=60: sum.hour+=1 sum.minute-=60 sum.second=self.second+other.second if sum.second>=60: sum.minute+=1 sum.second-=60 return sum a=Time() a.gettime() a.display() b=Time() b.gettime() b.display() c=a+b c.display()
class Time: def gettime(self): self.hour = int(input('Enter hour: ')) self.minute = int(input('Enter minute: ')) self.second = int(input('Enter seconds: ')) def display(self): print(f'Time is {self.hour}:{self.minute}:{self.second}\n') def __add__(self, other): sum = time() sum.hour = self.hour + other.hour sum.minute = self.minute + other.minute if sum.minute >= 60: sum.hour += 1 sum.minute -= 60 sum.second = self.second + other.second if sum.second >= 60: sum.minute += 1 sum.second -= 60 return sum a = time() a.gettime() a.display() b = time() b.gettime() b.display() c = a + b c.display()
n = int(input()) for i in range(n): a = input() set1 = set(input().split()) b = input() set2 = set(input().split()) print(set1.issubset(set2))
n = int(input()) for i in range(n): a = input() set1 = set(input().split()) b = input() set2 = set(input().split()) print(set1.issubset(set2))
def estimator(data): reportedCases=data['reportedCases'] totalHospitalBeds=data['totalHospitalBeds'] output={"data": {},"impact": {},"severeImpact":{}} output['impact']['currentlyInfected']=reportedCases * 10 output['severeImpact']['currentlyInfected']=reportedCases * 50 days=28 if days: factor=int(days/3) estimate_impact=output['impact']['currentlyInfected'] *pow(2,factor) output['impact']['infectionsByRequestedTime']=estimate_impact estimate_severeimpact=output['severeImpact']['currentlyInfected']* pow(2,factor) output['severeImpact']['infectionsByRequestedTime']=estimate_severeimpact impact_=output['impact']['infectionsByRequestedTime'] *0.15 severimpact_=output['severeImpact']['infectionsByRequestedTime']*0.15 output['impact']['severeCasesByRequestedTime']=impact_ output['severeImpact']['severeCasesByRequestedTime']=severimpact_ beds_available =round(totalHospitalBeds*0.35,0) available_hospital_beds_impact=beds_available - output['impact']['severeCasesByRequestedTime'] available_hospital_beds_severeImpact= beds_available - output['severeImpact']['severeCasesByRequestedTime'] output['impact']['hospitalBedsByRequestedTime']=available_hospital_beds_impact output['severeImpact']['hospitalBedsByRequestedTime']=available_hospital_beds_severeImpact output['data']=data impact_icu=output['impact']['infectionsByRequestedTime'] *0.05 severimpact_icu=output['severeImpact']['infectionsByRequestedTime']*0.05 output['impact']['casesForICUByRequestedTime']=impact_icu output['severeImpact']['casesForICUByRequestedTime']=severimpact_icu impact_vetilator=output['impact']['infectionsByRequestedTime'] *0.02 severimpact_vetilator=output['severeImpact']['infectionsByRequestedTime']*0.02 output['impact']['casesForVentilatorsByRequestedTime']=impact_vetilator output['severeImpact']['casesForVentilatorsByRequestedTime']=severimpact_vetilator dollarsInFlight_1=output['impact']['infectionsByRequestedTime'] dollarsInFlight_2=output['severeImpact']['infectionsByRequestedTime'] estimated_money=dollarsInFlight_1*0.85*5*30 estimated_money1=dollarsInFlight_2*0.85*5*30 output['impact']['dollarsInFlight']=estimated_money output['severeImpact']['dollarsInFlight']=estimated_money1 final_output={"data":{}, "estimate":{}} final_output['data']=data final_output['estimate']["impact"]=output["impact"] final_output['estimate']["severeImpact"]=output["severeImpact"] return final_output elif data['weeks']: days=data['weeks']*7 factor=round(days/3,0) estimate_impact=output['impact']['currentlyInfected'] *pow(2,factor) output['impact']['infectionsByRequestedTime']=estimate_impact estimate_severeimpact=output['severeImpact']['currentlyInfected']* pow(2,factor) output['severeImpact']['infectionsByRequestedTime']=estimate_severeimpact impact_=output['impact']['infectionsByRequestedTime'] *0.15 severimpact_=output['severeImpact']['infectionsByRequestedTime']*0.15 output['impact']['severeCasesByRequestedTime']=impact_ output['severeImpact']['severeCasesByRequestedTime']=severimpact_ beds_available =round(totalHospitalBeds*0.35,0) available_hospital_beds_impact=beds_available - output['impact']['severeCasesByRequestedTime'] available_hospital_beds_severeImpact= beds_available - output['severeImpact']['severeCasesByRequestedTime'] output['impact']['hospitalBedsByRequestedTime']=available_hospital_beds_impact output['severeImpact']['hospitalBedsByRequestedTime']=available_hospital_beds_severeImpact output['data']=data impact_icu=output['impact']['infectionsByRequestedTime'] *0.05 severimpact_icu=output['severeImpact']['infectionsByRequestedTime']*0.05 output['impact']['casesForICUByRequestedTime']=impact_icu output['severeImpact']['casesForICUByRequestedTime']=severimpact_icu impact_vetilator=output['impact']['infectionsByRequestedTime'] *0.02 severimpact_vetilator=output['severeImpact']['infectionsByRequestedTime']*0.02 output['impact']['casesForVentilatorsByRequestedTime']=impact_vetilator output['severeImpact']['casesForVentilatorsByRequestedTime']=severimpact_vetilator dollarsInFlight_1=output['impact']['infectionsByRequestedTime'] dollarsInFlight_2=output['severeImpact']['infectionsByRequestedTime'] estimated_money=dollarsInFlight_1*0.85*5*30 estimated_money1=dollarsInFlight_2*0.85*5*30 output['impact']['dollarsInFlight']=estimated_money output['severeImpact']['dollarsInFlight']=estimated_money1 return output elif data['months']: days= data['months']*30 factor=round(days/3,0) estimate_impact=output['impact']['currentlyInfected'] *pow(2,factor) output['impact']['infectionsByRequestedTime']=estimate_impact estimate_severeimpact=output['severeImpact']['currentlyInfected']* pow(2,factor) output['severeImpact']['infectionsByRequestedTime']=estimate_severeimpact impact_=output['impact']['infectionsByRequestedTime'] *0.15 severimpact_=output['severeImpact']['infectionsByRequestedTime']*0.15 output['impact']['severeCasesByRequestedTime']=impact_ output['severeImpact']['severeCasesByRequestedTime']=severimpact_ beds_available =round(totalHospitalBeds*0.35,0) available_hospital_beds_impact=beds_available - output['impact']['severeCasesByRequestedTime'] available_hospital_beds_severeImpact= beds_available - output['severeImpact']['severeCasesByRequestedTime'] output['impact']['hospitalBedsByRequestedTime']=available_hospital_beds_impact output['severeImpact']['hospitalBedsByRequestedTime']=available_hospital_beds_severeImpact output['data']=data impact_icu=output['impact']['infectionsByRequestedTime'] *0.05 severimpact_icu=output['severeImpact']['infectionsByRequestedTime']*0.05 output['impact']['casesForICUByRequestedTime']=impact_icu output['severeImpact']['casesForICUByRequestedTime']=severimpact_icu impact_vetilator=output['impact']['infectionsByRequestedTime'] *0.02 severimpact_vetilator=output['severeImpact']['infectionsByRequestedTime']*0.02 output['impact']['casesForVentilatorsByRequestedTime']=impact_vetilator output['severeImpact']['casesForVentilatorsByRequestedTime']=severimpact_vetilator dollarsInFlight_1=output['impact']['infectionsByRequestedTime'] dollarsInFlight_2=output['severeImpact']['infectionsByRequestedTime'] estimated_money=dollarsInFlight_1*0.85*5*30 estimated_money1=dollarsInFlight_2*0.85*5*30 output['impact']['dollarsInFlight']=estimated_money output['severeImpact']['dollarsInFlight']=estimated_money1 return output else: return{'error':"no data "}
def estimator(data): reported_cases = data['reportedCases'] total_hospital_beds = data['totalHospitalBeds'] output = {'data': {}, 'impact': {}, 'severeImpact': {}} output['impact']['currentlyInfected'] = reportedCases * 10 output['severeImpact']['currentlyInfected'] = reportedCases * 50 days = 28 if days: factor = int(days / 3) estimate_impact = output['impact']['currentlyInfected'] * pow(2, factor) output['impact']['infectionsByRequestedTime'] = estimate_impact estimate_severeimpact = output['severeImpact']['currentlyInfected'] * pow(2, factor) output['severeImpact']['infectionsByRequestedTime'] = estimate_severeimpact impact_ = output['impact']['infectionsByRequestedTime'] * 0.15 severimpact_ = output['severeImpact']['infectionsByRequestedTime'] * 0.15 output['impact']['severeCasesByRequestedTime'] = impact_ output['severeImpact']['severeCasesByRequestedTime'] = severimpact_ beds_available = round(totalHospitalBeds * 0.35, 0) available_hospital_beds_impact = beds_available - output['impact']['severeCasesByRequestedTime'] available_hospital_beds_severe_impact = beds_available - output['severeImpact']['severeCasesByRequestedTime'] output['impact']['hospitalBedsByRequestedTime'] = available_hospital_beds_impact output['severeImpact']['hospitalBedsByRequestedTime'] = available_hospital_beds_severeImpact output['data'] = data impact_icu = output['impact']['infectionsByRequestedTime'] * 0.05 severimpact_icu = output['severeImpact']['infectionsByRequestedTime'] * 0.05 output['impact']['casesForICUByRequestedTime'] = impact_icu output['severeImpact']['casesForICUByRequestedTime'] = severimpact_icu impact_vetilator = output['impact']['infectionsByRequestedTime'] * 0.02 severimpact_vetilator = output['severeImpact']['infectionsByRequestedTime'] * 0.02 output['impact']['casesForVentilatorsByRequestedTime'] = impact_vetilator output['severeImpact']['casesForVentilatorsByRequestedTime'] = severimpact_vetilator dollars_in_flight_1 = output['impact']['infectionsByRequestedTime'] dollars_in_flight_2 = output['severeImpact']['infectionsByRequestedTime'] estimated_money = dollarsInFlight_1 * 0.85 * 5 * 30 estimated_money1 = dollarsInFlight_2 * 0.85 * 5 * 30 output['impact']['dollarsInFlight'] = estimated_money output['severeImpact']['dollarsInFlight'] = estimated_money1 final_output = {'data': {}, 'estimate': {}} final_output['data'] = data final_output['estimate']['impact'] = output['impact'] final_output['estimate']['severeImpact'] = output['severeImpact'] return final_output elif data['weeks']: days = data['weeks'] * 7 factor = round(days / 3, 0) estimate_impact = output['impact']['currentlyInfected'] * pow(2, factor) output['impact']['infectionsByRequestedTime'] = estimate_impact estimate_severeimpact = output['severeImpact']['currentlyInfected'] * pow(2, factor) output['severeImpact']['infectionsByRequestedTime'] = estimate_severeimpact impact_ = output['impact']['infectionsByRequestedTime'] * 0.15 severimpact_ = output['severeImpact']['infectionsByRequestedTime'] * 0.15 output['impact']['severeCasesByRequestedTime'] = impact_ output['severeImpact']['severeCasesByRequestedTime'] = severimpact_ beds_available = round(totalHospitalBeds * 0.35, 0) available_hospital_beds_impact = beds_available - output['impact']['severeCasesByRequestedTime'] available_hospital_beds_severe_impact = beds_available - output['severeImpact']['severeCasesByRequestedTime'] output['impact']['hospitalBedsByRequestedTime'] = available_hospital_beds_impact output['severeImpact']['hospitalBedsByRequestedTime'] = available_hospital_beds_severeImpact output['data'] = data impact_icu = output['impact']['infectionsByRequestedTime'] * 0.05 severimpact_icu = output['severeImpact']['infectionsByRequestedTime'] * 0.05 output['impact']['casesForICUByRequestedTime'] = impact_icu output['severeImpact']['casesForICUByRequestedTime'] = severimpact_icu impact_vetilator = output['impact']['infectionsByRequestedTime'] * 0.02 severimpact_vetilator = output['severeImpact']['infectionsByRequestedTime'] * 0.02 output['impact']['casesForVentilatorsByRequestedTime'] = impact_vetilator output['severeImpact']['casesForVentilatorsByRequestedTime'] = severimpact_vetilator dollars_in_flight_1 = output['impact']['infectionsByRequestedTime'] dollars_in_flight_2 = output['severeImpact']['infectionsByRequestedTime'] estimated_money = dollarsInFlight_1 * 0.85 * 5 * 30 estimated_money1 = dollarsInFlight_2 * 0.85 * 5 * 30 output['impact']['dollarsInFlight'] = estimated_money output['severeImpact']['dollarsInFlight'] = estimated_money1 return output elif data['months']: days = data['months'] * 30 factor = round(days / 3, 0) estimate_impact = output['impact']['currentlyInfected'] * pow(2, factor) output['impact']['infectionsByRequestedTime'] = estimate_impact estimate_severeimpact = output['severeImpact']['currentlyInfected'] * pow(2, factor) output['severeImpact']['infectionsByRequestedTime'] = estimate_severeimpact impact_ = output['impact']['infectionsByRequestedTime'] * 0.15 severimpact_ = output['severeImpact']['infectionsByRequestedTime'] * 0.15 output['impact']['severeCasesByRequestedTime'] = impact_ output['severeImpact']['severeCasesByRequestedTime'] = severimpact_ beds_available = round(totalHospitalBeds * 0.35, 0) available_hospital_beds_impact = beds_available - output['impact']['severeCasesByRequestedTime'] available_hospital_beds_severe_impact = beds_available - output['severeImpact']['severeCasesByRequestedTime'] output['impact']['hospitalBedsByRequestedTime'] = available_hospital_beds_impact output['severeImpact']['hospitalBedsByRequestedTime'] = available_hospital_beds_severeImpact output['data'] = data impact_icu = output['impact']['infectionsByRequestedTime'] * 0.05 severimpact_icu = output['severeImpact']['infectionsByRequestedTime'] * 0.05 output['impact']['casesForICUByRequestedTime'] = impact_icu output['severeImpact']['casesForICUByRequestedTime'] = severimpact_icu impact_vetilator = output['impact']['infectionsByRequestedTime'] * 0.02 severimpact_vetilator = output['severeImpact']['infectionsByRequestedTime'] * 0.02 output['impact']['casesForVentilatorsByRequestedTime'] = impact_vetilator output['severeImpact']['casesForVentilatorsByRequestedTime'] = severimpact_vetilator dollars_in_flight_1 = output['impact']['infectionsByRequestedTime'] dollars_in_flight_2 = output['severeImpact']['infectionsByRequestedTime'] estimated_money = dollarsInFlight_1 * 0.85 * 5 * 30 estimated_money1 = dollarsInFlight_2 * 0.85 * 5 * 30 output['impact']['dollarsInFlight'] = estimated_money output['severeImpact']['dollarsInFlight'] = estimated_money1 return output else: return {'error': 'no data '}
class Location(object): """ Represents a Location where an Action could be taken. """ def __init__(self, location_id: str): """ Create a new Location. :param location_id: The id of the Location. """ self._location_id: str = location_id @property def location_id(self) -> str: """ Return the id of the Location. """ return self._location_id def __repr__(self) -> str: return 'Location({})'.format(self._location_id) def __gt__(self, other: 'Location') -> bool: return self._location_id > other._location_id def __lt__(self, other: 'Location') -> bool: return self._location_id < other._location_id
class Location(object): """ Represents a Location where an Action could be taken. """ def __init__(self, location_id: str): """ Create a new Location. :param location_id: The id of the Location. """ self._location_id: str = location_id @property def location_id(self) -> str: """ Return the id of the Location. """ return self._location_id def __repr__(self) -> str: return 'Location({})'.format(self._location_id) def __gt__(self, other: 'Location') -> bool: return self._location_id > other._location_id def __lt__(self, other: 'Location') -> bool: return self._location_id < other._location_id
# The base class for all widgets class Widget: def __init__(self, name): self.name = name pass def press_on(self, key): """Called with the argument `key`""" pass def release_on(self, k): pass # Text related methods def start_text_on(self, k): pass def update_text_on(self, k): pass def end_text_on(self, k): pass def refresh(self): if self.window: self.window.noutrefresh()
class Widget: def __init__(self, name): self.name = name pass def press_on(self, key): """Called with the argument `key`""" pass def release_on(self, k): pass def start_text_on(self, k): pass def update_text_on(self, k): pass def end_text_on(self, k): pass def refresh(self): if self.window: self.window.noutrefresh()
""" Space : O(n) Time : O(n) Hackerrank competition """ def getMinimumUniqueSum(arr): ans = 0 dp = [0] * 7000 for i in arr: dp[i] += 1 n = len(dp) for i in range(n-1): if dp[i] > 1: dp[i+1] += dp[i] - 1 dp[i] = 1 for j in range(n): if dp[j] > 0: ans += j return ans
""" Space : O(n) Time : O(n) Hackerrank competition """ def get_minimum_unique_sum(arr): ans = 0 dp = [0] * 7000 for i in arr: dp[i] += 1 n = len(dp) for i in range(n - 1): if dp[i] > 1: dp[i + 1] += dp[i] - 1 dp[i] = 1 for j in range(n): if dp[j] > 0: ans += j return ans
num1=int(input('Enter the first number:')) num2=int(input('Enter the second number:')) sum=lambda num1,num2:num1+num2 diff=lambda num1,num2:num1-num2 mul=lambda num1,num2:num1*num2 div=lambda num1,num2:num1//num2 print("Sum is:",sum(num1,num2)) print("Difference is:",diff(num1,num2)) print("Multiply is",mul(num1,num2)) print("Division is:",div(num1,num2))
num1 = int(input('Enter the first number:')) num2 = int(input('Enter the second number:')) sum = lambda num1, num2: num1 + num2 diff = lambda num1, num2: num1 - num2 mul = lambda num1, num2: num1 * num2 div = lambda num1, num2: num1 // num2 print('Sum is:', sum(num1, num2)) print('Difference is:', diff(num1, num2)) print('Multiply is', mul(num1, num2)) print('Division is:', div(num1, num2))
""" command line function stuff @author: matt milunski """ def check_refresh(input): if input >= 1: return input else: return 1 def check_currency(input): assert len(input) > 0, "you forgot to specify the crypto to track" return input
""" command line function stuff @author: matt milunski """ def check_refresh(input): if input >= 1: return input else: return 1 def check_currency(input): assert len(input) > 0, 'you forgot to specify the crypto to track' return input
SECRET_KEY='development-key' MYSQL_DATABASE_USER='root' MYSQL_DATABASE_PASSWORD='classroom' MYSQL_DATABASE_DB='Ascott_InvMgmt' MYSQL_DATABASE_HOST='dogfood.coxb3venarbl.ap-southeast-1.rds.amazonaws.com' UPLOADS_DEFAULT_DEST = 'static/img/items/' UPLOADS_DEFAULT_URL = 'http://localhost:5000/static/img/items/' UPLOADED_IMAGES_DEST = 'static/img/items/' UPLOADED_IMAGES_URL = 'http://localhost:5000/static/img/items/' BABEL_LOCALES = ('en', 'zh', 'ms', 'ta') BABEL_DEFAULT_LOCALE = "en" # Property-specific info # Timezone string follows TZ format (see https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) TIMEZONE = "Asia/Singapore" PROP_NAME = "Capstone Room"
secret_key = 'development-key' mysql_database_user = 'root' mysql_database_password = 'classroom' mysql_database_db = 'Ascott_InvMgmt' mysql_database_host = 'dogfood.coxb3venarbl.ap-southeast-1.rds.amazonaws.com' uploads_default_dest = 'static/img/items/' uploads_default_url = 'http://localhost:5000/static/img/items/' uploaded_images_dest = 'static/img/items/' uploaded_images_url = 'http://localhost:5000/static/img/items/' babel_locales = ('en', 'zh', 'ms', 'ta') babel_default_locale = 'en' timezone = 'Asia/Singapore' prop_name = 'Capstone Room'
class ThreadModule(object): '''docstring for ThreadModule''' def __init__(self, ): super().__init__()
class Threadmodule(object): """docstring for ThreadModule""" def __init__(self): super().__init__()
# Copyright (c) 2014, MapR Technologies # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. OOZIE = 'Oozie' HIVE = 'Hive' HIVE_METASTORE = 'HiveMetastore' HIVE_SERVER2 = 'HiveServer2' CLDB = 'CLDB' FILE_SERVER = 'FileServer' ZOOKEEPER = 'ZooKeeper' RESOURCE_MANAGER = 'ResourceManager' HISTORY_SERVER = 'HistoryServer' IS_M7_ENABLED = 'Enable MapR-DB' GENERAL = 'general' JOBTRACKER = 'JobTracker' NODE_MANAGER = 'NodeManager' DATANODE = 'Datanode' TASK_TRACKER = 'TaskTracker' SECONDARY_NAMENODE = 'SecondaryNamenode' NFS = 'NFS' WEB_SERVER = 'Webserver' WAIT_OOZIE_INTERVAL = 300 WAIT_NODE_ALARM_NO_HEARTBEAT = 360 ecosystem_components = ['Oozie', 'Hive-Metastore', 'HiveServer2', 'HBase-Master', 'HBase-RegionServer', 'HBase-Client', 'Pig']
oozie = 'Oozie' hive = 'Hive' hive_metastore = 'HiveMetastore' hive_server2 = 'HiveServer2' cldb = 'CLDB' file_server = 'FileServer' zookeeper = 'ZooKeeper' resource_manager = 'ResourceManager' history_server = 'HistoryServer' is_m7_enabled = 'Enable MapR-DB' general = 'general' jobtracker = 'JobTracker' node_manager = 'NodeManager' datanode = 'Datanode' task_tracker = 'TaskTracker' secondary_namenode = 'SecondaryNamenode' nfs = 'NFS' web_server = 'Webserver' wait_oozie_interval = 300 wait_node_alarm_no_heartbeat = 360 ecosystem_components = ['Oozie', 'Hive-Metastore', 'HiveServer2', 'HBase-Master', 'HBase-RegionServer', 'HBase-Client', 'Pig']
def Analysis(cipherText): alphabet = dict(zip('ABCDEFGHIJKLMNOPQRSTUVWXYZ', [0] * 27)) for letter in cipherText: if letter.isalpha(): alphabet[letter] += 1 for key, value in alphabet.items(): alphabet[key] = value * (value - 1) IC = sum(alphabet.values()) / (len(cipherText) * len(cipherText) - 1) key_len = abs(((0.027 * len(cipherText)) / (len(cipherText) - 1) * IC - 0.038 * len(cipherText) + 0.065)) IC = "%.6f" % IC key_len = "%.2f" % key_len return float(IC), key_len
def analysis(cipherText): alphabet = dict(zip('ABCDEFGHIJKLMNOPQRSTUVWXYZ', [0] * 27)) for letter in cipherText: if letter.isalpha(): alphabet[letter] += 1 for (key, value) in alphabet.items(): alphabet[key] = value * (value - 1) ic = sum(alphabet.values()) / (len(cipherText) * len(cipherText) - 1) key_len = abs(0.027 * len(cipherText) / (len(cipherText) - 1) * IC - 0.038 * len(cipherText) + 0.065) ic = '%.6f' % IC key_len = '%.2f' % key_len return (float(IC), key_len)
# find nth fibonacci number using recursion. # sample output: # 21 def findnthfibnumber(n, map={1: 0, 2: 1}): if n in map: return map[n] else: map[n] = findnthfibnumber(n-1, map) + findnthfibnumber(n-2, map) return map[n] print (findnthfibnumber(9))
def findnthfibnumber(n, map={1: 0, 2: 1}): if n in map: return map[n] else: map[n] = findnthfibnumber(n - 1, map) + findnthfibnumber(n - 2, map) return map[n] print(findnthfibnumber(9))
class Solution: def countElements(self, arr: List[int]) -> int: d = {} count = 0 for i in arr: d[i] = 1 for x in arr: if x+1 in d.keys(): count += 1 return count
class Solution: def count_elements(self, arr: List[int]) -> int: d = {} count = 0 for i in arr: d[i] = 1 for x in arr: if x + 1 in d.keys(): count += 1 return count
def part_1() -> None: h_pos: int = 0 v_pos: int = 0 with open("../data/day2.txt", "r") as dFile: for row in dFile.readlines(): value: int = int(row.split(" ")[1]) match row.split(" ")[0]: case "forward": h_pos += value case "down": v_pos += value case "up": v_pos -= value case _: raise ValueError(f"Unsupported command {row.split(' ')[0]}") print("Day: 2 | Part: 1 | Result:", h_pos * v_pos) def part_2() -> None: h_pos: int = 0 v_pos: int = 0 aim : int = 0 with open("../data/day2.txt", "r") as dFile: for row in dFile.readlines(): value: int = int(row.split(" ")[1]) match row.split(" ")[0]: case "forward": h_pos += value v_pos += value * aim case "down": aim += value case "up": aim -= value case _: raise ValueError(f"Unsupported command {row.split(' ')[0]}") print("Day: 2 | Part: 2 | Result:", h_pos * v_pos) if __name__ == "__main__": part_1() part_2()
def part_1() -> None: h_pos: int = 0 v_pos: int = 0 with open('../data/day2.txt', 'r') as d_file: for row in dFile.readlines(): value: int = int(row.split(' ')[1]) match row.split(' ')[0]: case 'forward': h_pos += value case 'down': v_pos += value case 'up': v_pos -= value case _: raise value_error(f"Unsupported command {row.split(' ')[0]}") print('Day: 2 | Part: 1 | Result:', h_pos * v_pos) def part_2() -> None: h_pos: int = 0 v_pos: int = 0 aim: int = 0 with open('../data/day2.txt', 'r') as d_file: for row in dFile.readlines(): value: int = int(row.split(' ')[1]) match row.split(' ')[0]: case 'forward': h_pos += value v_pos += value * aim case 'down': aim += value case 'up': aim -= value case _: raise value_error(f"Unsupported command {row.split(' ')[0]}") print('Day: 2 | Part: 2 | Result:', h_pos * v_pos) if __name__ == '__main__': part_1() part_2()
pkgname = "libffi8" pkgver = "3.4.2" pkgrel = 0 build_style = "gnu_configure" configure_args = [ "--includedir=/usr/include", "--disable-multi-os-directory", "--with-pic" ] hostmakedepends = ["pkgconf"] # actually only on x86 and arm (tramp.c code) but it does not hurt makedepends = ["linux-headers"] checkdepends = ["dejagnu"] pkgdesc = "Library supporting Foreign Function Interfaces" maintainer = "q66 <q66@chimera-linux.org>" license = "MIT" url = "http://sourceware.org/libffi" source = f"https://github.com/libffi/libffi/releases/download/v{pkgver}/libffi-{pkgver}.tar.gz" sha256 = "540fb721619a6aba3bdeef7d940d8e9e0e6d2c193595bc243241b77ff9e93620" # missing checkdepends for now options = ["!check"] def post_install(self): self.install_license("LICENSE") @subpackage("libffi-devel") def _devel(self): return self.default_devel(man = True, extra = ["usr/share/info"])
pkgname = 'libffi8' pkgver = '3.4.2' pkgrel = 0 build_style = 'gnu_configure' configure_args = ['--includedir=/usr/include', '--disable-multi-os-directory', '--with-pic'] hostmakedepends = ['pkgconf'] makedepends = ['linux-headers'] checkdepends = ['dejagnu'] pkgdesc = 'Library supporting Foreign Function Interfaces' maintainer = 'q66 <q66@chimera-linux.org>' license = 'MIT' url = 'http://sourceware.org/libffi' source = f'https://github.com/libffi/libffi/releases/download/v{pkgver}/libffi-{pkgver}.tar.gz' sha256 = '540fb721619a6aba3bdeef7d940d8e9e0e6d2c193595bc243241b77ff9e93620' options = ['!check'] def post_install(self): self.install_license('LICENSE') @subpackage('libffi-devel') def _devel(self): return self.default_devel(man=True, extra=['usr/share/info'])
# # PySNMP MIB module HPN-ICF-L2VPN-PWE3-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-L2VPN-PWE3-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:27:17 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ValueSizeConstraint, ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection") hpnicfCommon, = mibBuilder.importSymbols("HPN-ICF-OID-MIB", "hpnicfCommon") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Gauge32, Bits, MibIdentifier, Counter64, ModuleIdentity, Counter32, Unsigned32, ObjectIdentity, IpAddress, NotificationType, iso, TimeTicks, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "Bits", "MibIdentifier", "Counter64", "ModuleIdentity", "Counter32", "Unsigned32", "ObjectIdentity", "IpAddress", "NotificationType", "iso", "TimeTicks", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn") DisplayString, RowStatus, TextualConvention, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "RowStatus", "TextualConvention", "TruthValue") hpnicfL2VpnPwe3 = ModuleIdentity((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78)) if mibBuilder.loadTexts: hpnicfL2VpnPwe3.setLastUpdated('200703310000Z') if mibBuilder.loadTexts: hpnicfL2VpnPwe3.setOrganization('') class HpnicfL2VpnVcEncapsType(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 255)) namedValues = NamedValues(("frameRelayDlciMartini", 1), ("atmAal5SduVccTransport", 2), ("atmTransparentCellTransport", 3), ("ethernetTagged", 4), ("ethernet", 5), ("hdlc", 6), ("ppp", 7), ("cem", 8), ("atmN2OneVccCellTransport", 9), ("atmN2OneVpcCellTransport", 10), ("ipLayer2Transport", 11), ("atmOne2OneVccCellMode", 12), ("atmOne2OneVpcCellMode", 13), ("atmAal5PduVccTransport", 14), ("frameRelayPortMode", 15), ("cep", 16), ("saE1oP", 17), ("saT1oP", 18), ("saE3oP", 19), ("saT3oP", 20), ("cESoPsnBasicMode", 21), ("tDMoIPbasicMode", 22), ("l2VpnCESoPSNTDMwithCAS", 23), ("l2VpnTDMoIPTDMwithCAS", 24), ("frameRelayDlci", 25), ("ipInterworking", 64), ("unknown", 255)) hpnicfL2VpnPwe3ScalarGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 1)) hpnicfPwVcTrapOpen = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 1, 1), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfPwVcTrapOpen.setStatus('current') hpnicfL2VpnPwe3Table = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2)) hpnicfPwVcTable = MibTable((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1), ) if mibBuilder.loadTexts: hpnicfPwVcTable.setStatus('current') hpnicfPwVcEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1), ).setIndexNames((0, "HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcIndex")) if mibBuilder.loadTexts: hpnicfPwVcEntry.setStatus('current') hpnicfPwVcIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 1), Integer32()) if mibBuilder.loadTexts: hpnicfPwVcIndex.setStatus('current') hpnicfPwVcID = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 2), Unsigned32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hpnicfPwVcID.setStatus('current') hpnicfPwVcType = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 3), HpnicfL2VpnVcEncapsType()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hpnicfPwVcType.setStatus('current') hpnicfPwVcPeerAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 4), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hpnicfPwVcPeerAddr.setStatus('current') hpnicfPwVcMtu = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 5), Unsigned32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hpnicfPwVcMtu.setStatus('current') hpnicfPwVcCfgType = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("primary", 1), ("backup", 2), ("multiPort", 3)))).setMaxAccess("readcreate") if mibBuilder.loadTexts: hpnicfPwVcCfgType.setStatus('current') hpnicfPwVcInboundLabel = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 7), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hpnicfPwVcInboundLabel.setStatus('current') hpnicfPwVcOutboundLabel = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 8), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hpnicfPwVcOutboundLabel.setStatus('current') hpnicfPwVcIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 9), Unsigned32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hpnicfPwVcIfIndex.setStatus('current') hpnicfPwVcAcStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("down", 1), ("up", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: hpnicfPwVcAcStatus.setStatus('current') hpnicfPwVcStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("down", 1), ("up", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: hpnicfPwVcStatus.setStatus('current') hpnicfPwVcRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 12), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hpnicfPwVcRowStatus.setStatus('current') hpnicfL2VpnPwe3Notifications = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3)) hpnicfPwVcSwitchWtoP = NotificationType((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3, 1)).setObjects(("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcID"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcType"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcPeerAddr"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcID"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcType"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcPeerAddr")) if mibBuilder.loadTexts: hpnicfPwVcSwitchWtoP.setStatus('current') hpnicfPwVcSwitchPtoW = NotificationType((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3, 2)).setObjects(("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcID"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcType"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcPeerAddr"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcID"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcType"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcPeerAddr")) if mibBuilder.loadTexts: hpnicfPwVcSwitchPtoW.setStatus('current') hpnicfPwVcDown = NotificationType((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3, 3)).setObjects(("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcID"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcType"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcPeerAddr")) if mibBuilder.loadTexts: hpnicfPwVcDown.setStatus('current') hpnicfPwVcUp = NotificationType((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3, 4)).setObjects(("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcID"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcType"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcPeerAddr")) if mibBuilder.loadTexts: hpnicfPwVcUp.setStatus('current') hpnicfPwVcDeleted = NotificationType((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3, 5)).setObjects(("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcID"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcType"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcPeerAddr")) if mibBuilder.loadTexts: hpnicfPwVcDeleted.setStatus('current') mibBuilder.exportSymbols("HPN-ICF-L2VPN-PWE3-MIB", hpnicfPwVcEntry=hpnicfPwVcEntry, hpnicfPwVcOutboundLabel=hpnicfPwVcOutboundLabel, hpnicfPwVcID=hpnicfPwVcID, hpnicfL2VpnPwe3Table=hpnicfL2VpnPwe3Table, hpnicfL2VpnPwe3=hpnicfL2VpnPwe3, hpnicfPwVcTable=hpnicfPwVcTable, hpnicfPwVcSwitchPtoW=hpnicfPwVcSwitchPtoW, PYSNMP_MODULE_ID=hpnicfL2VpnPwe3, hpnicfPwVcAcStatus=hpnicfPwVcAcStatus, hpnicfPwVcDeleted=hpnicfPwVcDeleted, hpnicfPwVcStatus=hpnicfPwVcStatus, hpnicfL2VpnPwe3Notifications=hpnicfL2VpnPwe3Notifications, hpnicfPwVcMtu=hpnicfPwVcMtu, hpnicfPwVcSwitchWtoP=hpnicfPwVcSwitchWtoP, hpnicfPwVcIndex=hpnicfPwVcIndex, hpnicfPwVcUp=hpnicfPwVcUp, hpnicfPwVcDown=hpnicfPwVcDown, hpnicfPwVcIfIndex=hpnicfPwVcIfIndex, hpnicfPwVcType=hpnicfPwVcType, hpnicfPwVcCfgType=hpnicfPwVcCfgType, hpnicfPwVcInboundLabel=hpnicfPwVcInboundLabel, HpnicfL2VpnVcEncapsType=HpnicfL2VpnVcEncapsType, hpnicfPwVcRowStatus=hpnicfPwVcRowStatus, hpnicfL2VpnPwe3ScalarGroup=hpnicfL2VpnPwe3ScalarGroup, hpnicfPwVcTrapOpen=hpnicfPwVcTrapOpen, hpnicfPwVcPeerAddr=hpnicfPwVcPeerAddr)
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, value_size_constraint, constraints_union, single_value_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ValueSizeConstraint', 'ConstraintsUnion', 'SingleValueConstraint', 'ConstraintsIntersection') (hpnicf_common,) = mibBuilder.importSymbols('HPN-ICF-OID-MIB', 'hpnicfCommon') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (gauge32, bits, mib_identifier, counter64, module_identity, counter32, unsigned32, object_identity, ip_address, notification_type, iso, time_ticks, integer32, mib_scalar, mib_table, mib_table_row, mib_table_column) = mibBuilder.importSymbols('SNMPv2-SMI', 'Gauge32', 'Bits', 'MibIdentifier', 'Counter64', 'ModuleIdentity', 'Counter32', 'Unsigned32', 'ObjectIdentity', 'IpAddress', 'NotificationType', 'iso', 'TimeTicks', 'Integer32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn') (display_string, row_status, textual_convention, truth_value) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'RowStatus', 'TextualConvention', 'TruthValue') hpnicf_l2_vpn_pwe3 = module_identity((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78)) if mibBuilder.loadTexts: hpnicfL2VpnPwe3.setLastUpdated('200703310000Z') if mibBuilder.loadTexts: hpnicfL2VpnPwe3.setOrganization('') class Hpnicfl2Vpnvcencapstype(TextualConvention, Integer32): status = 'current' subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 255)) named_values = named_values(('frameRelayDlciMartini', 1), ('atmAal5SduVccTransport', 2), ('atmTransparentCellTransport', 3), ('ethernetTagged', 4), ('ethernet', 5), ('hdlc', 6), ('ppp', 7), ('cem', 8), ('atmN2OneVccCellTransport', 9), ('atmN2OneVpcCellTransport', 10), ('ipLayer2Transport', 11), ('atmOne2OneVccCellMode', 12), ('atmOne2OneVpcCellMode', 13), ('atmAal5PduVccTransport', 14), ('frameRelayPortMode', 15), ('cep', 16), ('saE1oP', 17), ('saT1oP', 18), ('saE3oP', 19), ('saT3oP', 20), ('cESoPsnBasicMode', 21), ('tDMoIPbasicMode', 22), ('l2VpnCESoPSNTDMwithCAS', 23), ('l2VpnTDMoIPTDMwithCAS', 24), ('frameRelayDlci', 25), ('ipInterworking', 64), ('unknown', 255)) hpnicf_l2_vpn_pwe3_scalar_group = mib_identifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 1)) hpnicf_pw_vc_trap_open = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 1, 1), truth_value().clone('false')).setMaxAccess('readwrite') if mibBuilder.loadTexts: hpnicfPwVcTrapOpen.setStatus('current') hpnicf_l2_vpn_pwe3_table = mib_identifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2)) hpnicf_pw_vc_table = mib_table((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1)) if mibBuilder.loadTexts: hpnicfPwVcTable.setStatus('current') hpnicf_pw_vc_entry = mib_table_row((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1)).setIndexNames((0, 'HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcIndex')) if mibBuilder.loadTexts: hpnicfPwVcEntry.setStatus('current') hpnicf_pw_vc_index = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 1), integer32()) if mibBuilder.loadTexts: hpnicfPwVcIndex.setStatus('current') hpnicf_pw_vc_id = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 2), unsigned32()).setMaxAccess('readcreate') if mibBuilder.loadTexts: hpnicfPwVcID.setStatus('current') hpnicf_pw_vc_type = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 3), hpnicf_l2_vpn_vc_encaps_type()).setMaxAccess('readcreate') if mibBuilder.loadTexts: hpnicfPwVcType.setStatus('current') hpnicf_pw_vc_peer_addr = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 4), ip_address()).setMaxAccess('readcreate') if mibBuilder.loadTexts: hpnicfPwVcPeerAddr.setStatus('current') hpnicf_pw_vc_mtu = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 5), unsigned32()).setMaxAccess('readcreate') if mibBuilder.loadTexts: hpnicfPwVcMtu.setStatus('current') hpnicf_pw_vc_cfg_type = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('primary', 1), ('backup', 2), ('multiPort', 3)))).setMaxAccess('readcreate') if mibBuilder.loadTexts: hpnicfPwVcCfgType.setStatus('current') hpnicf_pw_vc_inbound_label = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 7), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hpnicfPwVcInboundLabel.setStatus('current') hpnicf_pw_vc_outbound_label = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 8), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hpnicfPwVcOutboundLabel.setStatus('current') hpnicf_pw_vc_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 9), unsigned32()).setMaxAccess('readcreate') if mibBuilder.loadTexts: hpnicfPwVcIfIndex.setStatus('current') hpnicf_pw_vc_ac_status = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 10), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('down', 1), ('up', 2)))).setMaxAccess('readonly') if mibBuilder.loadTexts: hpnicfPwVcAcStatus.setStatus('current') hpnicf_pw_vc_status = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 11), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('down', 1), ('up', 2)))).setMaxAccess('readonly') if mibBuilder.loadTexts: hpnicfPwVcStatus.setStatus('current') hpnicf_pw_vc_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 12), row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: hpnicfPwVcRowStatus.setStatus('current') hpnicf_l2_vpn_pwe3_notifications = mib_identifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3)) hpnicf_pw_vc_switch_wto_p = notification_type((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3, 1)).setObjects(('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcID'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcType'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcPeerAddr'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcID'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcType'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcPeerAddr')) if mibBuilder.loadTexts: hpnicfPwVcSwitchWtoP.setStatus('current') hpnicf_pw_vc_switch_pto_w = notification_type((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3, 2)).setObjects(('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcID'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcType'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcPeerAddr'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcID'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcType'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcPeerAddr')) if mibBuilder.loadTexts: hpnicfPwVcSwitchPtoW.setStatus('current') hpnicf_pw_vc_down = notification_type((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3, 3)).setObjects(('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcID'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcType'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcPeerAddr')) if mibBuilder.loadTexts: hpnicfPwVcDown.setStatus('current') hpnicf_pw_vc_up = notification_type((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3, 4)).setObjects(('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcID'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcType'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcPeerAddr')) if mibBuilder.loadTexts: hpnicfPwVcUp.setStatus('current') hpnicf_pw_vc_deleted = notification_type((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3, 5)).setObjects(('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcID'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcType'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcPeerAddr')) if mibBuilder.loadTexts: hpnicfPwVcDeleted.setStatus('current') mibBuilder.exportSymbols('HPN-ICF-L2VPN-PWE3-MIB', hpnicfPwVcEntry=hpnicfPwVcEntry, hpnicfPwVcOutboundLabel=hpnicfPwVcOutboundLabel, hpnicfPwVcID=hpnicfPwVcID, hpnicfL2VpnPwe3Table=hpnicfL2VpnPwe3Table, hpnicfL2VpnPwe3=hpnicfL2VpnPwe3, hpnicfPwVcTable=hpnicfPwVcTable, hpnicfPwVcSwitchPtoW=hpnicfPwVcSwitchPtoW, PYSNMP_MODULE_ID=hpnicfL2VpnPwe3, hpnicfPwVcAcStatus=hpnicfPwVcAcStatus, hpnicfPwVcDeleted=hpnicfPwVcDeleted, hpnicfPwVcStatus=hpnicfPwVcStatus, hpnicfL2VpnPwe3Notifications=hpnicfL2VpnPwe3Notifications, hpnicfPwVcMtu=hpnicfPwVcMtu, hpnicfPwVcSwitchWtoP=hpnicfPwVcSwitchWtoP, hpnicfPwVcIndex=hpnicfPwVcIndex, hpnicfPwVcUp=hpnicfPwVcUp, hpnicfPwVcDown=hpnicfPwVcDown, hpnicfPwVcIfIndex=hpnicfPwVcIfIndex, hpnicfPwVcType=hpnicfPwVcType, hpnicfPwVcCfgType=hpnicfPwVcCfgType, hpnicfPwVcInboundLabel=hpnicfPwVcInboundLabel, HpnicfL2VpnVcEncapsType=HpnicfL2VpnVcEncapsType, hpnicfPwVcRowStatus=hpnicfPwVcRowStatus, hpnicfL2VpnPwe3ScalarGroup=hpnicfL2VpnPwe3ScalarGroup, hpnicfPwVcTrapOpen=hpnicfPwVcTrapOpen, hpnicfPwVcPeerAddr=hpnicfPwVcPeerAddr)
""" This file contains misc functions that are used throughout the project... """ def print_dict(d, level=0): # Prints a dictionary for k, v in d.items(): if isinstance(v, dict): print(level * '\t', k, ':') print_dict(v, level + 1) else: print(level * '\t', k, '-', v)
""" This file contains misc functions that are used throughout the project... """ def print_dict(d, level=0): for (k, v) in d.items(): if isinstance(v, dict): print(level * '\t', k, ':') print_dict(v, level + 1) else: print(level * '\t', k, '-', v)
{ "targets": [ { "target_name": "gameLauncher", "conditions": [ ["OS==\"win\"", { "sources": [ "srcs/windows/GameLauncher.cpp" ] }], ["OS==\"linux\"", { "sources": [ "srcs/linux/GameLauncher.cpp" ] }] ] } ] }
{'targets': [{'target_name': 'gameLauncher', 'conditions': [['OS=="win"', {'sources': ['srcs/windows/GameLauncher.cpp']}], ['OS=="linux"', {'sources': ['srcs/linux/GameLauncher.cpp']}]]}]}
# pylint: disable=undefined-variable ## Whether to include output from clients other than this one sharing the same # kernel. # Required for jupyter-vim, see: # https://github.com/jupyter-vim/jupyter-vim#jupyter-configuration c.ZMQTerminalInteractiveShell.include_other_output = True ## Text to display before the first prompt. Will be formatted with variables # {version} and {kernel_banner}. c.ZMQTerminalInteractiveShell.banner = 'Jupyter console {version}' ## Shortcut style to use at the prompt. 'vi' or 'emacs'. #c.ZMQTerminalInteractiveShell.editing_mode = 'emacs' ## The name of a Pygments style to use for syntax highlighting c.ZMQTerminalInteractiveShell.highlighting_style = 'solarized-dark' ## How many history items to load into memory c.ZMQTerminalInteractiveShell.history_load_length = 1000 ## Use 24bit colors instead of 256 colors in prompt highlighting. If your # terminal supports true color, the following command should print 'TRUECOLOR' # in orange: printf "\x1b[38;2;255;100;0mTRUECOLOR\x1b[0m\n" c.ZMQTerminalInteractiveShell.true_color = True
c.ZMQTerminalInteractiveShell.include_other_output = True c.ZMQTerminalInteractiveShell.banner = 'Jupyter console {version}' c.ZMQTerminalInteractiveShell.highlighting_style = 'solarized-dark' c.ZMQTerminalInteractiveShell.history_load_length = 1000 c.ZMQTerminalInteractiveShell.true_color = True
# Function to count number of substrings # with exactly k unique characters def countkDist(str1, k): n = len(str1) # Initialize result res = 0 # Consider all substrings beginning # with str[i] for i in range(0, n): dist_count = 0 # Initializing array with 0 cnt = [0] * 27 # Consider all substrings between str[i..j] for j in range(i, n): # If this is a new character for this # substring, increment dist_count. if(cnt[ord(str1[j]) - 97] == 0): dist_count += 1 # Increment count of current character cnt[ord(str1[j]) - 97] += 1 # If distinct character count becomes k, # then increment result. if(dist_count == k): res += 1 if(dist_count > k): break return res
def countk_dist(str1, k): n = len(str1) res = 0 for i in range(0, n): dist_count = 0 cnt = [0] * 27 for j in range(i, n): if cnt[ord(str1[j]) - 97] == 0: dist_count += 1 cnt[ord(str1[j]) - 97] += 1 if dist_count == k: res += 1 if dist_count > k: break return res
def check_order(scale_list): ascending_list = sorted(scale_list) descending_list = sorted(scale_list, reverse=True) if scale_list == ascending_list: return "ascending" elif scale_list == descending_list: return "descending" else: return "mixed" def main(): scale_list = input().split() result_value = check_order(scale_list) print(result_value) if __name__ == "__main__": main()
def check_order(scale_list): ascending_list = sorted(scale_list) descending_list = sorted(scale_list, reverse=True) if scale_list == ascending_list: return 'ascending' elif scale_list == descending_list: return 'descending' else: return 'mixed' def main(): scale_list = input().split() result_value = check_order(scale_list) print(result_value) if __name__ == '__main__': main()
#! /usr/bin/env python3 # -*- coding: UTF-8 -*- #------------------------------------------------------------------------------ def asSeparator () : return "//" + ("-" * 78) + "\n" #------------------------------------------------------------------------------ def generateInterruptSection (interruptSectionName) : sCode = asSeparator () sCode += "// INTERRUPT - SECTION: " + interruptSectionName + "\n" sCode += asSeparator () + "\n" sCode += " .section .text.interrupt." + interruptSectionName + ", \"ax\", %progbits\n\n" sCode += " .align 1\n" sCode += " .global interrupt." + interruptSectionName + "\n" sCode += " .type interrupt." + interruptSectionName + ", %function\n\n" sCode += "interrupt." + interruptSectionName + ":\n" sCode += "//----------------------------------------- R2 <- CPU INDEX\n" sCode += " ldr r3, = 0xD0000000 + 0x000 // Address of SIO CPUID control register\n" sCode += " ldr r2, [r3] // R2 <- 0 for CPU0, 1 for CPU 1\n" sCode += "//----------------------------------------- Activity led On\n" sCode += " MACRO_ACTIVITY_LED_0_OR_1_ON // R2 should contain CPU index\n" sCode += "//--- Save registers\n" sCode += " push {r4, lr}\n" sCode += "//--- R4 <- Address of SPINLOCK 0 (rp2040 datasheet, 2.3.1.7, page 42)\n" sCode += " ldr r4, = 0xD0000000 + 0x100\n" sCode += "//--- Read: attempt to claim the lock. Read value is nonzero if the lock was\n" sCode += "// successfully claimed, or zero if the lock had already been claimed\n" sCode += "// by a previous read (rp2040 datasheet, section 2.3.1.3 page 30).\n" sCode += interruptSectionName +".spinlock.busy.wait:\n" sCode += " ldr r0, [r4]\n" sCode += " cmp r0, #0\n" sCode += " beq " + interruptSectionName +".spinlock.busy.wait\n" sCode += "//--- Call section, interrupts disabled, spinlock successfully claimed\n" sCode += " bl interrupt.section." + interruptSectionName + "\n" sCode += "//--- Write (any value): release the lock (rp2040 datasheet, section 2.3.1.3 page 30).\n" sCode += "// The next attempt to claim the lock will be successful.\n" sCode += " str r0, [r4]\n" sCode += "//--- Return\n" sCode += " pop {r4, pc}\n\n" return ("", sCode) #------------------------------------------------------------------------------ # ENTRY POINT #------------------------------------------------------------------------------ def buildSectionInterruptCode (interruptSectionList): #------------------------------ Destination file strings cppFile = "" sFile = "" #------------------------------ Iterate on section sectionList for interruptSectionName in interruptSectionList : (cppCode, sCode) = generateInterruptSection (interruptSectionName) cppFile += cppCode sFile += sCode #------------------------------ Return return (cppFile, sFile) #------------------------------------------------------------------------------
def as_separator(): return '//' + '-' * 78 + '\n' def generate_interrupt_section(interruptSectionName): s_code = as_separator() s_code += '// INTERRUPT - SECTION: ' + interruptSectionName + '\n' s_code += as_separator() + '\n' s_code += ' .section .text.interrupt.' + interruptSectionName + ', "ax", %progbits\n\n' s_code += ' .align 1\n' s_code += ' .global interrupt.' + interruptSectionName + '\n' s_code += ' .type interrupt.' + interruptSectionName + ', %function\n\n' s_code += 'interrupt.' + interruptSectionName + ':\n' s_code += '//----------------------------------------- R2 <- CPU INDEX\n' s_code += ' ldr r3, = 0xD0000000 + 0x000 // Address of SIO CPUID control register\n' s_code += ' ldr r2, [r3] // R2 <- 0 for CPU0, 1 for CPU 1\n' s_code += '//----------------------------------------- Activity led On\n' s_code += ' MACRO_ACTIVITY_LED_0_OR_1_ON // R2 should contain CPU index\n' s_code += '//--- Save registers\n' s_code += ' push {r4, lr}\n' s_code += '//--- R4 <- Address of SPINLOCK 0 (rp2040 datasheet, 2.3.1.7, page 42)\n' s_code += ' ldr r4, = 0xD0000000 + 0x100\n' s_code += '//--- Read: attempt to claim the lock. Read value is nonzero if the lock was\n' s_code += '// successfully claimed, or zero if the lock had already been claimed\n' s_code += '// by a previous read (rp2040 datasheet, section 2.3.1.3 page 30).\n' s_code += interruptSectionName + '.spinlock.busy.wait:\n' s_code += ' ldr r0, [r4]\n' s_code += ' cmp r0, #0\n' s_code += ' beq ' + interruptSectionName + '.spinlock.busy.wait\n' s_code += '//--- Call section, interrupts disabled, spinlock successfully claimed\n' s_code += ' bl interrupt.section.' + interruptSectionName + '\n' s_code += '//--- Write (any value): release the lock (rp2040 datasheet, section 2.3.1.3 page 30).\n' s_code += '// The next attempt to claim the lock will be successful.\n' s_code += ' str r0, [r4]\n' s_code += '//--- Return\n' s_code += ' pop {r4, pc}\n\n' return ('', sCode) def build_section_interrupt_code(interruptSectionList): cpp_file = '' s_file = '' for interrupt_section_name in interruptSectionList: (cpp_code, s_code) = generate_interrupt_section(interruptSectionName) cpp_file += cppCode s_file += sCode return (cppFile, sFile)
class Solution(object): # Empty list + join (Accepted + Top Voted), O(n) space and time def restoreString(self, s, indices): """ :type s: str :type indices: List[int] :rtype: str """ ret = [None] * len(s) for i in range(len(s)): ret[indices[i]] = s[i] return "".join(ret)
class Solution(object): def restore_string(self, s, indices): """ :type s: str :type indices: List[int] :rtype: str """ ret = [None] * len(s) for i in range(len(s)): ret[indices[i]] = s[i] return ''.join(ret)
''' File name: jr_utils.py Author: Tyche Analytics Co. Note: truncated file, suitable for model inference, but not development ''' """Collect various utility functions for JR model""" def mean(xs): if hasattr(xs,"__len__"): return sum(xs)/float(len(xs)) else: acc = 0 n = 0 for x in xs: acc += x n += 1 return acc/float(n) def variance(xs,correct=True): n = len(xs) correction = n/float(n-1) if correct else 1 mu = mean(xs) return correction * mean([(x-mu)**2 for x in xs]) def se(xs,correct=True): return sd(xs,correct)/sqrt(len(xs))
""" File name: jr_utils.py Author: Tyche Analytics Co. Note: truncated file, suitable for model inference, but not development """ 'Collect various utility functions for JR model' def mean(xs): if hasattr(xs, '__len__'): return sum(xs) / float(len(xs)) else: acc = 0 n = 0 for x in xs: acc += x n += 1 return acc / float(n) def variance(xs, correct=True): n = len(xs) correction = n / float(n - 1) if correct else 1 mu = mean(xs) return correction * mean([(x - mu) ** 2 for x in xs]) def se(xs, correct=True): return sd(xs, correct) / sqrt(len(xs))
def two_fer(name="you"): """Returns a string in the two-fer format.""" return "One for " + name + ", one for me."
def two_fer(name='you'): """Returns a string in the two-fer format.""" return 'One for ' + name + ', one for me.'
in_str = list(str(input())) str_len = len(in_str) # letters set set_letters = set(in_str) set_len = len(set_letters) if str_len == set_len: print("Unique") else: print("Deja Vu")
in_str = list(str(input())) str_len = len(in_str) set_letters = set(in_str) set_len = len(set_letters) if str_len == set_len: print('Unique') else: print('Deja Vu')
# Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. # # Use of this source code is governed by a BSD-style license # that can be found in the LICENSE file in the root of the source # tree. An additional intellectual property rights grant can be found # in the file PATENTS. All contributing project authors may # be found in the AUTHORS file in the root of the source tree. { 'includes': [ '../build/common.gypi', ], 'targets': [ { 'target_name': 'peerconnection_unittests', 'type': '<(gtest_target_type)', 'dependencies': [ '<(DEPTH)/testing/gmock.gyp:gmock', '<(webrtc_root)/api/api.gyp:libjingle_peerconnection', '<(webrtc_root)/base/base_tests.gyp:rtc_base_tests_utils', '<(webrtc_root)/common.gyp:webrtc_common', '<(webrtc_root)/media/media.gyp:rtc_unittest_main', '<(webrtc_root)/pc/pc.gyp:rtc_pc', ], 'direct_dependent_settings': { 'include_dirs': [ '<(DEPTH)/testing/gmock/include', ], }, 'defines': [ # Feature selection. 'HAVE_SCTP', ], 'sources': [ 'datachannel_unittest.cc', 'dtlsidentitystore_unittest.cc', 'dtmfsender_unittest.cc', 'fakemetricsobserver.cc', 'fakemetricsobserver.h', 'jsepsessiondescription_unittest.cc', 'localaudiosource_unittest.cc', 'mediaconstraintsinterface_unittest.cc', 'mediastream_unittest.cc', 'peerconnection_unittest.cc', 'peerconnectionendtoend_unittest.cc', 'peerconnectionfactory_unittest.cc', 'peerconnectioninterface_unittest.cc', 'proxy_unittest.cc', 'rtpsenderreceiver_unittest.cc', 'statscollector_unittest.cc', 'test/fakeaudiocapturemodule.cc', 'test/fakeaudiocapturemodule.h', 'test/fakeaudiocapturemodule_unittest.cc', 'test/fakeconstraints.h', 'test/fakedatachannelprovider.h', 'test/fakedtlsidentitystore.h', 'test/fakeperiodicvideocapturer.h', 'test/fakevideotrackrenderer.h', 'test/mockpeerconnectionobservers.h', 'test/peerconnectiontestwrapper.h', 'test/peerconnectiontestwrapper.cc', 'test/testsdpstrings.h', 'videocapturertracksource_unittest.cc', 'videotrack_unittest.cc', 'webrtcsdp_unittest.cc', 'webrtcsession_unittest.cc', ], # TODO(kjellander): Make the code compile without disabling these flags. # See https://bugs.chromium.org/p/webrtc/issues/detail?id=3307 'cflags': [ '-Wno-sign-compare', ], 'cflags!': [ '-Wextra', ], 'cflags_cc!': [ '-Woverloaded-virtual', ], 'msvs_disabled_warnings': [ 4245, # conversion from 'int' to 'size_t', signed/unsigned mismatch. 4267, # conversion from 'size_t' to 'int', possible loss of data. 4389, # signed/unsigned mismatch. ], 'conditions': [ ['clang==1', { # TODO(kjellander): Make the code compile without disabling these flags. # See https://bugs.chromium.org/p/webrtc/issues/detail?id=3307 'cflags!': [ '-Wextra', ], 'xcode_settings': { 'WARNING_CFLAGS!': ['-Wextra'], }, }], ['OS=="android"', { 'sources': [ 'test/androidtestinitializer.cc', 'test/androidtestinitializer.h', ], 'dependencies': [ '<(DEPTH)/testing/android/native_test.gyp:native_test_native_code', '<(webrtc_root)/api/api.gyp:libjingle_peerconnection_jni', ], }], ['OS=="win" and clang==1', { 'msvs_settings': { 'VCCLCompilerTool': { 'AdditionalOptions': [ # Disable warnings failing when compiling with Clang on Windows. # https://bugs.chromium.org/p/webrtc/issues/detail?id=5366 '-Wno-sign-compare', '-Wno-unused-function', ], }, }, }], ['use_quic==1', { 'dependencies': [ '<(DEPTH)/third_party/libquic/libquic.gyp:libquic', ], 'sources': [ 'quicdatachannel_unittest.cc', 'quicdatatransport_unittest.cc', ], 'export_dependent_settings': [ '<(DEPTH)/third_party/libquic/libquic.gyp:libquic', ], }], ], # conditions }, # target peerconnection_unittests ], # targets 'conditions': [ ['OS=="android"', { 'targets': [ { 'target_name': 'libjingle_peerconnection_android_unittest', 'type': 'none', 'dependencies': [ '<(webrtc_root)/api/api.gyp:libjingle_peerconnection_java', ], 'variables': { 'apk_name': 'libjingle_peerconnection_android_unittest', 'java_in_dir': 'androidtests', 'resource_dir': 'androidtests/res', 'native_lib_target': 'libjingle_peerconnection_so', 'is_test_apk': 1, 'test_type': 'instrumentation', 'tested_apk_path': '', 'never_lint': 1, }, 'includes': [ '../../build/java_apk.gypi', '../../build/android/test_runner.gypi', ], }, ], # targets }], # OS=="android" ['OS=="android"', { 'targets': [ { 'target_name': 'peerconnection_unittests_apk_target', 'type': 'none', 'dependencies': [ '<(apk_tests_path):peerconnection_unittests_apk', ], }, ], 'conditions': [ ['test_isolation_mode != "noop"', { 'targets': [ { 'target_name': 'peerconnection_unittests_apk_run', 'type': 'none', 'dependencies': [ '<(apk_tests_path):peerconnection_unittests_apk', ], 'includes': [ '../build/isolate.gypi', ], 'sources': [ 'peerconnection_unittests_apk.isolate', ], }, ] } ], ], }], # OS=="android" ['test_isolation_mode != "noop"', { 'targets': [ { 'target_name': 'peerconnection_unittests_run', 'type': 'none', 'dependencies': [ 'peerconnection_unittests', ], 'includes': [ '../build/isolate.gypi', ], 'sources': [ 'peerconnection_unittests.isolate', ], }, ], # targets }], # test_isolation_mode != "noop" ], # conditions }
{'includes': ['../build/common.gypi'], 'targets': [{'target_name': 'peerconnection_unittests', 'type': '<(gtest_target_type)', 'dependencies': ['<(DEPTH)/testing/gmock.gyp:gmock', '<(webrtc_root)/api/api.gyp:libjingle_peerconnection', '<(webrtc_root)/base/base_tests.gyp:rtc_base_tests_utils', '<(webrtc_root)/common.gyp:webrtc_common', '<(webrtc_root)/media/media.gyp:rtc_unittest_main', '<(webrtc_root)/pc/pc.gyp:rtc_pc'], 'direct_dependent_settings': {'include_dirs': ['<(DEPTH)/testing/gmock/include']}, 'defines': ['HAVE_SCTP'], 'sources': ['datachannel_unittest.cc', 'dtlsidentitystore_unittest.cc', 'dtmfsender_unittest.cc', 'fakemetricsobserver.cc', 'fakemetricsobserver.h', 'jsepsessiondescription_unittest.cc', 'localaudiosource_unittest.cc', 'mediaconstraintsinterface_unittest.cc', 'mediastream_unittest.cc', 'peerconnection_unittest.cc', 'peerconnectionendtoend_unittest.cc', 'peerconnectionfactory_unittest.cc', 'peerconnectioninterface_unittest.cc', 'proxy_unittest.cc', 'rtpsenderreceiver_unittest.cc', 'statscollector_unittest.cc', 'test/fakeaudiocapturemodule.cc', 'test/fakeaudiocapturemodule.h', 'test/fakeaudiocapturemodule_unittest.cc', 'test/fakeconstraints.h', 'test/fakedatachannelprovider.h', 'test/fakedtlsidentitystore.h', 'test/fakeperiodicvideocapturer.h', 'test/fakevideotrackrenderer.h', 'test/mockpeerconnectionobservers.h', 'test/peerconnectiontestwrapper.h', 'test/peerconnectiontestwrapper.cc', 'test/testsdpstrings.h', 'videocapturertracksource_unittest.cc', 'videotrack_unittest.cc', 'webrtcsdp_unittest.cc', 'webrtcsession_unittest.cc'], 'cflags': ['-Wno-sign-compare'], 'cflags!': ['-Wextra'], 'cflags_cc!': ['-Woverloaded-virtual'], 'msvs_disabled_warnings': [4245, 4267, 4389], 'conditions': [['clang==1', {'cflags!': ['-Wextra'], 'xcode_settings': {'WARNING_CFLAGS!': ['-Wextra']}}], ['OS=="android"', {'sources': ['test/androidtestinitializer.cc', 'test/androidtestinitializer.h'], 'dependencies': ['<(DEPTH)/testing/android/native_test.gyp:native_test_native_code', '<(webrtc_root)/api/api.gyp:libjingle_peerconnection_jni']}], ['OS=="win" and clang==1', {'msvs_settings': {'VCCLCompilerTool': {'AdditionalOptions': ['-Wno-sign-compare', '-Wno-unused-function']}}}], ['use_quic==1', {'dependencies': ['<(DEPTH)/third_party/libquic/libquic.gyp:libquic'], 'sources': ['quicdatachannel_unittest.cc', 'quicdatatransport_unittest.cc'], 'export_dependent_settings': ['<(DEPTH)/third_party/libquic/libquic.gyp:libquic']}]]}], 'conditions': [['OS=="android"', {'targets': [{'target_name': 'libjingle_peerconnection_android_unittest', 'type': 'none', 'dependencies': ['<(webrtc_root)/api/api.gyp:libjingle_peerconnection_java'], 'variables': {'apk_name': 'libjingle_peerconnection_android_unittest', 'java_in_dir': 'androidtests', 'resource_dir': 'androidtests/res', 'native_lib_target': 'libjingle_peerconnection_so', 'is_test_apk': 1, 'test_type': 'instrumentation', 'tested_apk_path': '', 'never_lint': 1}, 'includes': ['../../build/java_apk.gypi', '../../build/android/test_runner.gypi']}]}], ['OS=="android"', {'targets': [{'target_name': 'peerconnection_unittests_apk_target', 'type': 'none', 'dependencies': ['<(apk_tests_path):peerconnection_unittests_apk']}], 'conditions': [['test_isolation_mode != "noop"', {'targets': [{'target_name': 'peerconnection_unittests_apk_run', 'type': 'none', 'dependencies': ['<(apk_tests_path):peerconnection_unittests_apk'], 'includes': ['../build/isolate.gypi'], 'sources': ['peerconnection_unittests_apk.isolate']}]}]]}], ['test_isolation_mode != "noop"', {'targets': [{'target_name': 'peerconnection_unittests_run', 'type': 'none', 'dependencies': ['peerconnection_unittests'], 'includes': ['../build/isolate.gypi'], 'sources': ['peerconnection_unittests.isolate']}]}]]}
txtFile=open("/Users/chenchaoyang/Desktop/python/Python/content/content.txt","r") while True: line=txtFile.readline() if not line: break else: print(line) txtFile.close()
txt_file = open('/Users/chenchaoyang/Desktop/python/Python/content/content.txt', 'r') while True: line = txtFile.readline() if not line: break else: print(line) txtFile.close()
class DatabaseException(Exception): """Base exception for this package.""" pass class NoDataFoundException(DatabaseException): """Should be used when no data has been found.""" pass class BadDataException(DatabaseException): """Should be used when incorrect data is being submitted.""" pass
class Databaseexception(Exception): """Base exception for this package.""" pass class Nodatafoundexception(DatabaseException): """Should be used when no data has been found.""" pass class Baddataexception(DatabaseException): """Should be used when incorrect data is being submitted.""" pass
def beautify_parameter_name(s: str) -> str: """Make a parameter name look better. Good for parameter names that have words separated by _ . 1. change _ by spaces. 2. First letter is uppercased. """ new_s = " ".join(s.split("_")) return new_s.capitalize()
def beautify_parameter_name(s: str) -> str: """Make a parameter name look better. Good for parameter names that have words separated by _ . 1. change _ by spaces. 2. First letter is uppercased. """ new_s = ' '.join(s.split('_')) return new_s.capitalize()
# Extra parsing for markdown (Highlighting and alert boxes) def parse(rtxt, look, control): txtl = rtxt.split(look) i, j = 0, 0 ret_text = "" while i < len(txtl): if j == 0: # This is the start before the specified tag, add it normally ret_text += control.start(txtl[i]) j+=1 elif j == 1: # This is the text we actually want to parse ret_text += control.inner(txtl[i]) j+=1 else: ret_text += control.end(txtl[i]) j = 1 i+=1 return ret_text class Control(): def start(self, s): return s def inner(self, s): return s def end(self, s): return s class HighlightControl(Control): def inner(self, s): return "<span class='highlight'>" + s + "</span>" class BoxControl(Control): def inner(self, s): style = s.split("\n")[0].strip().replace("<br />", "") # This controls info, alert, danger, warning, error etc... if style == "info": # info box return "<div class='alert-info white' style='color: white !important;'><i class='fa fa-info-circle i-m3' aria-hidden='true'></i><span class='bold'>Info</span>" + s.replace("info", "", 1) + "</div>" return s # This adds the == highlighter and ::: boxes def emd(txt: str) -> str: # == highlighting ret_text = parse(txt, "==", HighlightControl()) # ::: boxes ret_text = parse(ret_text, ":::", BoxControl()) return ret_text # Test cases #emd.emd("Hi ==Highlight== We love you == meow == What about you? == mew == ::: info\nHellow world:::")
def parse(rtxt, look, control): txtl = rtxt.split(look) (i, j) = (0, 0) ret_text = '' while i < len(txtl): if j == 0: ret_text += control.start(txtl[i]) j += 1 elif j == 1: ret_text += control.inner(txtl[i]) j += 1 else: ret_text += control.end(txtl[i]) j = 1 i += 1 return ret_text class Control: def start(self, s): return s def inner(self, s): return s def end(self, s): return s class Highlightcontrol(Control): def inner(self, s): return "<span class='highlight'>" + s + '</span>' class Boxcontrol(Control): def inner(self, s): style = s.split('\n')[0].strip().replace('<br />', '') if style == 'info': return "<div class='alert-info white' style='color: white !important;'><i class='fa fa-info-circle i-m3' aria-hidden='true'></i><span class='bold'>Info</span>" + s.replace('info', '', 1) + '</div>' return s def emd(txt: str) -> str: ret_text = parse(txt, '==', highlight_control()) ret_text = parse(ret_text, ':::', box_control()) return ret_text
# Copyright 2021, Google LLC # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # returns fullfillment response for dialogflow detect_intent call # [START dialogflow_webhook] # TODO: change the default Entry Point text to handleWebhook def handleWebhook(request): req = request.get_json() responseText = "" intent = req["queryResult"]["intent"]["displayName"] if intent == "Default Welcome Intent": responseText = "Hello from a GCF Webhook" elif intent == "get-agent-name": responseText = "My name is Flowhook" else: responseText = f"There are no fulfillment responses defined for Intent {intent}" # You can also use the google.cloud.dialogflowcx_v3.types.WebhookRequest protos instead of manually writing the json object res = {"fulfillmentMessages": [{"text": {"text": [responseText]}}]} return res # [END dialogflow_webhook]
def handle_webhook(request): req = request.get_json() response_text = '' intent = req['queryResult']['intent']['displayName'] if intent == 'Default Welcome Intent': response_text = 'Hello from a GCF Webhook' elif intent == 'get-agent-name': response_text = 'My name is Flowhook' else: response_text = f'There are no fulfillment responses defined for Intent {intent}' res = {'fulfillmentMessages': [{'text': {'text': [responseText]}}]} return res
class TxtReader: def __init__(self, f): self.f = f def parse(self): file = open(self.f) line = file.readline() while line: print(line) line = file.readline() file.close #t = TxtReader('sample.txt') #t.parse()
class Txtreader: def __init__(self, f): self.f = f def parse(self): file = open(self.f) line = file.readline() while line: print(line) line = file.readline() file.close
#!/usr/bin/env python # encoding: utf-8 """ search_in_2d_matrix.py Created by Shengwei on 2014-07-24. """ # https://oj.leetcode.com/problems/search-a-2d-matrix/ # tags: easy / medium, matrix, search, edge cases """ Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous row. For example, Consider the following matrix: [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] Given target = 3, return true. """ # https://oj.leetcode.com/discuss/6201/compare-some-of-solutions-witch-is-most-effective class Solution: # @param matrix, a list of lists of integers # @param target, an integer # @return a boolean def searchMatrix(self, matrix, target): # look for the row where target locates up, down = 0, len(matrix) while up < down: mid = (up + down) / 2 if matrix[mid][0] == target: return True if matrix[mid][0] > target: down = mid else: up = mid + 1 # up == down == i+1 where target is in # row i if it exists; i.e., # matrix[up][0] > target > matrix[up-1][0] if up == 0: return False row = up - 1 # search in the row left, right = 0, len(matrix[row]) while left < right: mid = (left + right) / 2 if matrix[row][mid] == target: return True if matrix[row][mid] > target: right = mid else: left = mid + 1 return False
""" search_in_2d_matrix.py Created by Shengwei on 2014-07-24. """ '\nWrite an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:\n\nIntegers in each row are sorted from left to right.\nThe first integer of each row is greater than the last integer of the previous row.\nFor example,\n\nConsider the following matrix:\n\n[\n [1, 3, 5, 7],\n [10, 11, 16, 20],\n [23, 30, 34, 50]\n]\nGiven target = 3, return true.\n' class Solution: def search_matrix(self, matrix, target): (up, down) = (0, len(matrix)) while up < down: mid = (up + down) / 2 if matrix[mid][0] == target: return True if matrix[mid][0] > target: down = mid else: up = mid + 1 if up == 0: return False row = up - 1 (left, right) = (0, len(matrix[row])) while left < right: mid = (left + right) / 2 if matrix[row][mid] == target: return True if matrix[row][mid] > target: right = mid else: left = mid + 1 return False
# -*- coding: utf-8 -*- def greet(name): i =0 # while True: # i +=1 first_name, surname = name.split(' ') return 'Hello {0}, {1}'.format(surname, first_name) def suggest_travel(distance): if distance > 5: return 'You should take the train.' elif distance > 2: return 'You should cycle.' else: return 'Stop being lazy and walk!' def fizz_buzz(n): if n%3==0 and n%5==0: return 'FizzBuzz' elif n%3==0: return 'Fizz' elif n%5==0: return 'Buzz' else: return n def sum_odd_numbers(n): my_sum=0 for i in range(1,n): if i%2!=0: my_sum = my_sum + i return my_sum def double_char(word): double_word = "" # initialise double_word as an empty string for character in word: double_word = double_word + character*2 return double_word def sum_div3_numbers(n): my_sum=0 for i in range(1,n): if i%3==0: my_sum = my_sum + i return my_sum def sum_numbers(n): my_sum=0 for i in range(1,n): my_sum = my_sum + i return my_sum
def greet(name): i = 0 (first_name, surname) = name.split(' ') return 'Hello {0}, {1}'.format(surname, first_name) def suggest_travel(distance): if distance > 5: return 'You should take the train.' elif distance > 2: return 'You should cycle.' else: return 'Stop being lazy and walk!' def fizz_buzz(n): if n % 3 == 0 and n % 5 == 0: return 'FizzBuzz' elif n % 3 == 0: return 'Fizz' elif n % 5 == 0: return 'Buzz' else: return n def sum_odd_numbers(n): my_sum = 0 for i in range(1, n): if i % 2 != 0: my_sum = my_sum + i return my_sum def double_char(word): double_word = '' for character in word: double_word = double_word + character * 2 return double_word def sum_div3_numbers(n): my_sum = 0 for i in range(1, n): if i % 3 == 0: my_sum = my_sum + i return my_sum def sum_numbers(n): my_sum = 0 for i in range(1, n): my_sum = my_sum + i return my_sum
# Para criar uma lista com 5 elementos '_' # ex. ['_', '_', '_', '_', '_'] print("Lista com elementos iguais") lista = [] for i in range(5): lista.append('_') print("Lista: ", lista) # Alternativa lista_alternativa = ['_' for i in range(5)] print("Modo Alternativdo de criar lista: ", lista_alternativa) # Para criar uma lista com 6 numeros # ex. [0, 1, 2, 3, 4, 5] print("Lista com numeros na sequencia") lista = [] for i in range(6): lista.append(i) print("Lista: ", lista) # Alternativa lista_alternativa = [i for i in range(6)] print("Modo Alternativdo de criar lista: ", lista_alternativa) # Para criar uma lista com 6 numeros pares # ex. [0, 2, 4, 6, 8, 10] print("Lista com 6 numeros pares na sequencia") lista = [] for i in range(6): lista.append(i * 2) print("Lista: ", lista) # Alternativa lista_alternativa = [i * 2 for i in range(6)] print("Modo Alternativdo de criar lista: ", lista_alternativa) # Para criar uma matriz com elementos repetidos # ex. [ ['_', '_', '_'], # ['_', '_', '_'], # ['_', '_', '_'] # ] print("Matriz 3x3 com elementos repetidos") matriz = [] for l in range(3): linha = [] for c in range(6): linha.append('_') matriz.append(linha) print("Matriz: ", matriz) # Alternativa matriz_alternativa = [['_' for c in range(3)] for l in range(3)] print("Modo Alternativdo de criar matriz: ", matriz_alternativa)
print('Lista com elementos iguais') lista = [] for i in range(5): lista.append('_') print('Lista: ', lista) lista_alternativa = ['_' for i in range(5)] print('Modo Alternativdo de criar lista: ', lista_alternativa) print('Lista com numeros na sequencia') lista = [] for i in range(6): lista.append(i) print('Lista: ', lista) lista_alternativa = [i for i in range(6)] print('Modo Alternativdo de criar lista: ', lista_alternativa) print('Lista com 6 numeros pares na sequencia') lista = [] for i in range(6): lista.append(i * 2) print('Lista: ', lista) lista_alternativa = [i * 2 for i in range(6)] print('Modo Alternativdo de criar lista: ', lista_alternativa) print('Matriz 3x3 com elementos repetidos') matriz = [] for l in range(3): linha = [] for c in range(6): linha.append('_') matriz.append(linha) print('Matriz: ', matriz) matriz_alternativa = [['_' for c in range(3)] for l in range(3)] print('Modo Alternativdo de criar matriz: ', matriz_alternativa)
#hack RSA, caluclate the p,q,d in order by given t,n,e def finitePrimeHack(t, n, e): res_list = [] # find p & q for i in range(2, t): if n % i == 0: p = i q = n//p res_list.append(p) res_list.append(q) #sort the list as p <= q res_list.sort() # find the d which is modular inverse of e d = 0 y = 1 far = (p-1)*(q-1) while (((far * y) + 1) % e) != 0: y += 1 d = (far * y + 1) // e res_list.append(d) # print(res_list) return res_list def blockSizeHack(blocks, n, e): SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.' string = [] p = 0 q = 0 for i in range(2, n): if n % i == 0: p = i q = n//p break x = (p-1)*(q-1) y = 1 d = 0 while (((x * y) + 1) % e) != 0: y += 1 d = (x * y + 1) // e for i in range(len(blocks)): blockInt = pow(blocks[i], d, n) if blockInt < len(SYMBOLS)**i and blockInt != 0: blockInt = blockInt % (len(SYMBOLS)**i) else: blockInt = blockInt // (len(SYMBOLS)**i) string.append(SYMBOLS[blockInt]) return ''.join(string) def main(): # # question1 t = 100 n = 493 e = 5 print(finitePrimeHack(t, n, e)) # question3 blocks = [2361958428825, 564784031984, 693733403745, 693733403745, 2246930915779, 1969885380643] n = 3328101456763 e = 1827871 print(blockSizeHack(blocks, n, e)) if __name__ == "__main__": main()
def finite_prime_hack(t, n, e): res_list = [] for i in range(2, t): if n % i == 0: p = i q = n // p res_list.append(p) res_list.append(q) res_list.sort() d = 0 y = 1 far = (p - 1) * (q - 1) while (far * y + 1) % e != 0: y += 1 d = (far * y + 1) // e res_list.append(d) return res_list def block_size_hack(blocks, n, e): symbols = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.' string = [] p = 0 q = 0 for i in range(2, n): if n % i == 0: p = i q = n // p break x = (p - 1) * (q - 1) y = 1 d = 0 while (x * y + 1) % e != 0: y += 1 d = (x * y + 1) // e for i in range(len(blocks)): block_int = pow(blocks[i], d, n) if blockInt < len(SYMBOLS) ** i and blockInt != 0: block_int = blockInt % len(SYMBOLS) ** i else: block_int = blockInt // len(SYMBOLS) ** i string.append(SYMBOLS[blockInt]) return ''.join(string) def main(): t = 100 n = 493 e = 5 print(finite_prime_hack(t, n, e)) blocks = [2361958428825, 564784031984, 693733403745, 693733403745, 2246930915779, 1969885380643] n = 3328101456763 e = 1827871 print(block_size_hack(blocks, n, e)) if __name__ == '__main__': main()
d1 = {0:1, 1:1, 2:2, 3:3} pent_nums = [] for i in range(1, 100): val1 = ((3*(i**2))-i)/2 val2 = ((3*((-i)**2))+i)/2 pent_nums.append(val1) pent_nums.append(val2) for n in range(4, 101): ite = 0 p_t = d1[n-pent_nums[ite]] step = 1 stop = False rolling_sum = 0 while not stop: if step == 1 or step == 2: rolling_sum += p_t step += 1 elif step==3: rolling_sum -= p_t step += 1 else: rolling_sum -= p_t step = 1 ite += 1 try: if d1[n-pent_nums[ite]] > 0: p_t = d1[n-pent_nums[ite]] except: stop = True d1[n] = rolling_sum print(d1[100]-1) # 190569291 """ Using a recurrence relation for the partitions of n based on generalized pentagonal numbers... """
d1 = {0: 1, 1: 1, 2: 2, 3: 3} pent_nums = [] for i in range(1, 100): val1 = (3 * i ** 2 - i) / 2 val2 = (3 * (-i) ** 2 + i) / 2 pent_nums.append(val1) pent_nums.append(val2) for n in range(4, 101): ite = 0 p_t = d1[n - pent_nums[ite]] step = 1 stop = False rolling_sum = 0 while not stop: if step == 1 or step == 2: rolling_sum += p_t step += 1 elif step == 3: rolling_sum -= p_t step += 1 else: rolling_sum -= p_t step = 1 ite += 1 try: if d1[n - pent_nums[ite]] > 0: p_t = d1[n - pent_nums[ite]] except: stop = True d1[n] = rolling_sum print(d1[100] - 1) '\n\nUsing a recurrence relation for the partitions of n\nbased on generalized pentagonal numbers...\n\n'
n1 = int(input()) n2 = int(input()) n3 = int(input()) if n1 > n2 > n3: print(n3) print(n2) print(n1) elif n2 > n1 > n3: print(n3) print(n1) print(n2) elif n1 > n3 > n2: print(n2) print(n3) print(n1) elif n2 > n3 > n1: print(n1) print(n3) print(n2) elif n3 > n2 > n1: print(n1) print(n2) print(n3) elif n3 > n1 > n2: print(n2) print(n1) print(n3)
n1 = int(input()) n2 = int(input()) n3 = int(input()) if n1 > n2 > n3: print(n3) print(n2) print(n1) elif n2 > n1 > n3: print(n3) print(n1) print(n2) elif n1 > n3 > n2: print(n2) print(n3) print(n1) elif n2 > n3 > n1: print(n1) print(n3) print(n2) elif n3 > n2 > n1: print(n1) print(n2) print(n3) elif n3 > n1 > n2: print(n2) print(n1) print(n3)
RBNF = r""" NEWLINE := '' ENDMARKER := '' NAME := '' INDENT := '' DEDENT := '' NUMBER := '' STRING := '' single_input ::= it=NEWLINE | seq=simple_stmt | it=compound_stmt NEWLINE file_input ::= (NEWLINE | seqs<<stmt)* [ENDMARKER] -> mod=Module(sum(seqs or [], [])); fix_missing_locations(mod); return mod eval_input ::= it=testlist NEWLINE* ENDMARKER -> Expression(it) # the restrictions of decorator syntax are released here for the sake of convenience. decorator ::= '@' exp=test NEWLINE -> exp decorated ::= decorators=decorator+ it=(classdef | funcdef | async_funcdef) -> it.decorator_list = list(decorators); return it async_funcdef ::= mark='async' 'def' name=NAME args=parameters ['->' ret=test] ':' body=suite -> def_rewrite(mark, name, args, ret, body, is_async=True) funcdef ::= mark='def' name=NAME args=parameters ['->' ret=test] ':' body=suite -> def_rewrite(mark, name, args, ret, body) parameters ::= '(' [args=typedargslist] ')' -> args if args else arguments([], None, [], [], None, []) lam_args ::= [args=varargslist] -> args if args else arguments([], None, [], [], None, []) default_fp ::= '=' expr=test -> expr kw_default_fp ::= ['=' expr=test] -> expr tfpdef ::= name=NAME [':' annotation=test] -> arg(name.value, annotation, **loc @ name) vfpdef ::= name=NAME -> arg(name.value, None, **loc @ name) typedargslist ::= args << tfpdef [defaults<<default_fp] (',' args<<tfpdef [defaults<<default_fp])* [',' [ '*' [vararg=tfpdef] (',' kwonlyargs<<tfpdef kw_defaults<<kw_default_fp)* [',' ['**' kwarg=tfpdef [',']]] | '**' kwarg=tfpdef [',']]] | '*' [vararg=tfpdef] (',' kwonlyargs<<tfpdef kw_defaults<<kw_default_fp)* [',' ['**' kwarg=tfpdef [',']]] | '**' kwarg=tfpdef [','] -> arguments(args or [], vararg, kwonlyargs or [], kw_defaults or [], kwarg, defaults or []) varargslist ::= args << vfpdef [defaults<<default_fp] (',' args<<vfpdef [defaults<<default_fp])* [',' [ '*' [vararg=vfpdef] (',' kwonlyargs<<vfpdef kw_defaults<<kw_default_fp)* [',' ['**' kwarg=vfpdef [',']]] | '**' kwarg=vfpdef [',']]] | '*' [vararg=vfpdef] (','kwonlyargs<<vfpdef kw_defaults<<kw_default_fp)* [',' ['**' kwargs=vfpdef [',']]] | '**' kwargs=vfpdef [','] -> arguments(args or [], vararg, kwonlyargs or [], kw_defaults or [], kwarg, defaults or []) stmt ::= seq=simple_stmt | it=compound_stmt -> [it] if it else seq simple_stmt ::= seq<<small_stmt (';' seq<<small_stmt)* [';'] NEWLINE -> seq small_stmt ::= it=(expr_stmt | del_stmt | pass_stmt | flow_stmt | # ------------------------------ import_stmt | global_stmt | nonlocal_stmt | assert_stmt) -> it expr_stmt ::= lhs=testlist_star_expr (ann=annassign | aug=augassign aug_exp=(yield_expr|testlist) | # ------------------------------ ('=' rhs<<(yield_expr|testlist_star_expr))*) -> expr_stmt_rewrite(lhs, ann, aug, aug_exp, rhs) annassign ::= ':' anno=test ['=' value=test] -> (anno, value) testlist_star_expr ::= seq<<(test|star_expr) (',' seq<<(test|star_expr))* [force_tuple=','] -> Tuple(seq, Load()) if len(seq) > 1 or force_tuple else seq[0] augassign ::= it=('+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' | # ------------------------------ '<<=' | '>>=' | '**=' | '//=') -> augassign_rewrite(it) # For normal and annotated assignments, additional restrictions enforced by the interpreter ------------------------------- del_stmt ::= mark='del' lst=exprlist -> Delete([as_del(lst)], **loc @ mark) pass_stmt ::= mark='pass' -> Pass(**loc @ mark) flow_stmt ::= it=(break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt) -> it break_stmt ::= mark='break' -> Break(**loc @ mark) continue_stmt ::= mark='continue' -> Continue(**loc @ mark) return_stmt ::= mark='return' [value=testlist_star_expr] -> Return(value, **loc @ mark) yield_stmt ::= exp=yield_expr -> Expr(exp) raise_stmt ::= mark='raise' [exc=test ['from' cause=test]] -> Raise(exc, cause, **loc @ mark) import_stmt ::= it=(import_name | import_from) -> it import_name ::= mark='import' names=dotted_as_names -> Import(names, **loc @ mark) # note below::= the ('.' | '...') is necessary because '...' is tokenized as ELLIPSIS -------------------------------- import_level::= (_1='.' | '...') -> 1 if _1 else 3 wild ::= '*' -> [alias(name='*', asname=None)] import_from ::= (mark='from' (levels=import_level* module=dotted_name | levels=import_level+) # ------------------------------ 'import' (wild=wild | '(' names=import_as_names ')' | names=import_as_names)) -> ImportFrom(module or '', wild or names, sum(levels or []), **loc @ mark) NAMESTR ::= n=NAME -> n.value import_as_name ::= name=NAMESTR ['as' asname=NAMESTR] -> alias(name, asname) dotted_as_name ::= name=dotted_name ['as' asname=NAMESTR] -> alias(name, asname) import_as_names::= seq<<import_as_name (',' seq<<import_as_name)* [','] -> seq dotted_as_names::= seq<<dotted_as_name (',' seq<<dotted_as_name)* -> seq dotted_name ::= xs=(NAME ('.' NAME)*) -> ''.join(c.value for c in xs) global_stmt ::= mark='global' names<<NAMESTR (',' name<<NAMESTR)* -> Global(names, **loc @ mark) nonlocal_stmt ::= mark='nonlocal' names<<NAMESTR (',' name<<NAMESTR)* -> Nonlocal(names, **loc @ mark) assert_stmt ::= mark='assert' test=test [',' msg=test] -> Assert(test, msg, **loc @ mark) compound_stmt ::= it=(if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated # ------------------------------ | async_stmt) -> it async_stmt ::= it=(async_funcdef | async_with_stmt | async_for_stmt) -> it if_stmt ::= marks<<'if' tests<<test ':' # ------------------------------ bodies<<suite # ------------------------------ (marks<<'elif' tests<<test ':' bodies<<suite)* # ------------------------------ ['else' ':' orelse=suite] -> if_stmt_rewrite(marks, tests, bodies, orelse) while_stmt ::= 'while' test=test ':' body=suite ['else' ':' orelse=suite] -> while_stmt_rewrite(test, body, orelse) async_for_stmt ::= 'async' 'for' target=exprlist 'in' iter=testlist ':' body=suite ['else' ':' orelse=suite] -> for_stmt_rewrite(target, iter, body, orelse, is_async=True) for_stmt ::= 'for' target=exprlist 'in' iter=testlist ':' body=suite ['else' ':' orelse=suite] -> for_stmt_rewrite(target, iter, body, orelse) try_stmt ::= (mark='try' ':' # --------------------------- body=suite # --------------------------- ((excs<<except_clause ':' rescues<<suite)+ # --------------------------- ['else' ':' orelse=suite] # --------------------------- ['finally' ':' final=suite] | # --------------------------- 'finally' ':' final=suite)) -> try_stmt_rewrite(mark, body, excs, rescues, orelse, final) async_with_stmt::= mark='async' 'with' items<<with_item (',' items<<with_item)* ':' body=suite -> with_stmt_rewrite(mark, items, body, is_async=True) with_stmt ::= mark='with' items<<with_item (',' items<<with_item)* ':' body=suite -> with_stmt_rewrite(mark, items, body) with_item ::= context_expr=test ['as' optional_vars=expr] -> withitem(context_expr, as_store(optional_vars)) except_clause ::= 'except' [type=test ['as' name=NAMESTR]] -> (type, name) suite ::= seqs<<simple_stmt | NEWLINE INDENT (seqs<<stmt)+ DEDENT -> sum(seqs, []) test ::= it=(ifexp| lambdef) -> it ifexp ::= body=or_test ['if' test=or_test 'else' orelse=test] -> IfExp(test, body, orelse) if orelse else body test_nocond ::= it=(or_test | lambdef_nocond) -> it lambdef ::= m='lambda' args=lam_args ':' body=test -> Lambda(args, body) lambdef_nocond ::= m='lambda' args=lam_args ':' body=test_nocond -> Lambda(args, body) or_test ::= head=and_test ('or' tail<<and_test)* -> BoolOp(Or(), [head, *tail]) if tail else head and_test ::= head=not_test ('and' tail<<not_test)* -> BoolOp(And(), [head, *tail]) if tail else head not_test ::= mark='not' expr=not_test | comp=comparison -> UnaryOp(Not(), expr, **loc @ mark) if mark else comp comparison ::= left=expr (ops<<comp_op comparators<<expr)* -> Compare(left, ops, comparators) if ops else left comp_op ::= op=('<'|'>'|'=='|'>='|'<='|'<>'|'!=' |'in'|'not' 'in'|'is'|'is' 'not') -> comp_op_rewrite(op) star_expr ::= mark='*' expr=expr -> Starred(expr, Load(), **loc @ mark) expr_tr ::= op='|' expr=xor_expr -> (op, expr) expr ::= head=xor_expr tail=expr_tr* -> expr_rewrite(head, tail) xor_expr_tr ::= op='^' expr=and_expr -> (op, expr) xor_expr ::= head=and_expr tail=xor_expr_tr* -> xor_expr_rewrite(head, tail) and_expr_tr ::= op = '&' expr=shift_expr -> (op, expr) and_expr ::= head=shift_expr tail=and_expr_tr* -> and_expr_rewrite(head, tail) shift_expr_tr ::= op=('<<'|'>>') expr=arith_expr -> (op, expr) shift_expr ::= head=arith_expr tail=shift_expr_tr* -> shift_expr_rewrite(head, tail) arith_expr_tr ::= op=('+'|'-') expr=term -> (op, expr) arith_expr ::= head=term tail=arith_expr_tr* -> arith_expr_rewrite(head, tail) term_tr ::= op=('*'|'@'|'/'|'%'|'//') expr=factor -> (op, expr) term ::= head=factor tail=term_tr* -> term_rewrite(head, tail) factor ::= mark=('+'|'-'|'~') factor=factor | power=power -> factor_rewrite(mark, factor, power) power ::= atom_expr=atom_expr ['**' factor=factor] -> BinOp(atom_expr, Pow(), factor) if factor else atom_expr atom_expr ::= [a='await'] atom=atom trailers=trailer* -> atom_expr_rewrite(a, atom, trailers) atom ::= (is_gen ='(' [yield_expr=yield_expr|comp=testlist_comp] ')' | is_list='[' [comp=testlist_comp] ']' | head='{' [dict=dictorsetmaker] is_dict='}' | name=NAME | number=NUMBER | strs=STRING+ | ellipsis='...' | namedc='None' | namedc='True' | namedc='False') -> atom_rewrite(loc, name, number, strs, namedc, ellipsis, dict, is_dict, is_gen, is_list, comp, yield_expr) testlist_comp ::= values<<(test|star_expr) ( comp=comp_for | (',' values<<(test|star_expr))* [force_tuple=','] ) -> def app(is_tuple=None, is_list=None): if is_list and comp: return ListComp(*values, comp) elif is_list: return List(values, Load()) elif comp: return GeneratorExp(*values, comp) else: return values[0] if len(values) is 1 and not force_tuple else Tuple(values, Load()) app # `ExtSlice` is ignored here. We don't need this optimization for this project. trailer ::= arglist=arglist | mark='[' subscr=subscriptlist ']' | mark='.' attr=NAMESTR -> (lambda value: Subscript(value, subscr, Load(), **loc @ mark)) if subscr is not None else\ (lambda value: Call(value, *split_args_helper(arglist))) if arglist is not None else\ (lambda value: Attribute(value, attr, Load(), **loc @ mark)) # `Index` will be deprecated in Python3.8. # See https://github.com/python/cpython/pull/9605#issuecomment-425381990 subscriptlist ::= head=subscript (',' tail << subscript)* [','] -> Index(head if not tail else Tuple([head, *tail], Load())) subscript3 ::= [lower=test] subscr=[':' [upper=test] [':' [step=test]]] -> Slice(lower, upper, step) if subscr else lower subscript ::= it=(subscript3 | test) -> it exprlist ::= seq << (expr|star_expr) (',' seq << (expr|star_expr))* [force_tuple=','] -> Tuple(seq, Load()) if force_tuple or len(seq) > 1 else seq[0] testlist ::= seq << test (',' seq << test)* [force_tuple=','] -> Tuple(seq, Load()) if force_tuple or len(seq) > 1 else seq[0] dict_unpack_s ::= '**' -> None dictorsetmaker ::= (((keys<<test ':' values<<test | keys<<dict_unpack_s values<<expr) (comp=comp_for | (',' (keys<<test ':' values<<test | keys<<dict_unpack_s values<<expr))* [','])) | (values<<(test | star_expr) (comp=comp_for | (',' values<<(test | star_expr))* [','])) ) -> if not comp: return ExDict(keys, values, Load()) if keys else Set(values) DictComp(*keys, *values, comp) if keys else SetComp(*values, comp) classdef ::= mark='class' name=NAME [arglist=arglist]':' suite=suite -> ClassDef(name.value, *split_args_helper(arglist or []), suite, [], **loc @ mark) arglist ::= mark='(' [seq<<argument (',' seq<<argument)* [',']] ')' -> check_call_args(loc @ mark, seq or []) argument ::= ( key=NAME '=' value=test | arg=test [comp=comp_for] | mark='**' kwargs=test | mark='*' args=test ) -> Starred(**(loc @ mark), value=args, ctx=Load()) if args else \ keyword(**(loc @ mark), arg=None, value=kwargs) if kwargs else\ keyword(**(loc @ key), arg=key.value, value=value) if key else \ GeneratorExp(arg, comp) if comp else \ arg comp_for_item ::= [is_async='async'] 'for' target=exprlist 'in' iter=or_test ('if' ifs<<test_nocond)* -> comprehension(as_store(target), iter, ifs, bool(is_async)) comp_for ::= generators=comp_for_item+ -> list(generators) encoding_decl ::= NAME yield_expr ::= mark='yield' [is_yield_from='from' expr=test | expr=testlist_star_expr] -> YieldFrom(**(loc @ mark), value=expr) if is_yield_from else Yield(**(loc @ mark), value=expr) """
rbnf = "\nNEWLINE := ''\nENDMARKER := ''\nNAME := ''\nINDENT := ''\nDEDENT := ''\nNUMBER := ''\nSTRING := ''\n\nsingle_input ::= it=NEWLINE | seq=simple_stmt | it=compound_stmt NEWLINE\nfile_input ::= (NEWLINE | seqs<<stmt)* [ENDMARKER] -> mod=Module(sum(seqs or [], [])); fix_missing_locations(mod); return mod\neval_input ::= it=testlist NEWLINE* ENDMARKER -> Expression(it)\n\n# the restrictions of decorator syntax are released here for the sake of convenience.\ndecorator ::= '@' exp=test NEWLINE -> exp\ndecorated ::= decorators=decorator+ it=(classdef | funcdef | async_funcdef) -> it.decorator_list = list(decorators); return it\n \nasync_funcdef ::= mark='async' \n 'def' name=NAME args=parameters ['->' ret=test] ':' body=suite -> def_rewrite(mark, name, args, ret, body, is_async=True) \nfuncdef ::= mark='def' name=NAME args=parameters ['->' ret=test] ':' body=suite -> def_rewrite(mark, name, args, ret, body)\n\n\nparameters ::= '(' [args=typedargslist] ')' -> args if args else arguments([], None, [], [], None, [])\nlam_args ::= [args=varargslist] -> args if args else arguments([], None, [], [], None, [])\n\ndefault_fp ::= '=' expr=test -> expr\nkw_default_fp ::= ['=' expr=test] -> expr \ntfpdef ::= name=NAME [':' annotation=test] -> arg(name.value, annotation, **loc @ name) \nvfpdef ::= name=NAME -> arg(name.value, None, **loc @ name)\n\ntypedargslist ::= args << tfpdef [defaults<<default_fp] (',' args<<tfpdef [defaults<<default_fp])* [',' [\n '*' [vararg=tfpdef] (',' kwonlyargs<<tfpdef kw_defaults<<kw_default_fp)* [',' ['**' kwarg=tfpdef [',']]]\n | '**' kwarg=tfpdef [',']]]\n | '*' [vararg=tfpdef] (',' kwonlyargs<<tfpdef kw_defaults<<kw_default_fp)* [',' ['**' kwarg=tfpdef [',']]]\n | '**' kwarg=tfpdef [','] \n -> arguments(args or [], vararg, kwonlyargs or [], kw_defaults or [], kwarg, defaults or [])\n\n\nvarargslist ::= args << vfpdef [defaults<<default_fp] (',' args<<vfpdef [defaults<<default_fp])* [',' [\n '*' [vararg=vfpdef] (',' kwonlyargs<<vfpdef kw_defaults<<kw_default_fp)* [',' ['**' kwarg=vfpdef [',']]]\n | '**' kwarg=vfpdef [',']]]\n | '*' [vararg=vfpdef] (','kwonlyargs<<vfpdef kw_defaults<<kw_default_fp)* [',' ['**' kwargs=vfpdef [',']]]\n | '**' kwargs=vfpdef [','] \n -> arguments(args or [], vararg, kwonlyargs or [], kw_defaults or [], kwarg, defaults or [])\n\nstmt ::= seq=simple_stmt | it=compound_stmt -> [it] if it else seq\nsimple_stmt ::= seq<<small_stmt (';' seq<<small_stmt)* [';'] NEWLINE -> seq\nsmall_stmt ::= it=(expr_stmt | del_stmt | pass_stmt | flow_stmt | # ------------------------------\n import_stmt | global_stmt | nonlocal_stmt | assert_stmt) -> it\nexpr_stmt ::= lhs=testlist_star_expr (ann=annassign | aug=augassign aug_exp=(yield_expr|testlist) | # ------------------------------\n ('=' rhs<<(yield_expr|testlist_star_expr))*) -> expr_stmt_rewrite(lhs, ann, aug, aug_exp, rhs)\nannassign ::= ':' anno=test ['=' value=test] -> (anno, value)\ntestlist_star_expr ::= seq<<(test|star_expr) (',' seq<<(test|star_expr))* [force_tuple=','] -> Tuple(seq, Load()) if len(seq) > 1 or force_tuple else seq[0] \naugassign ::= it=('+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' | # ------------------------------\n '<<=' | '>>=' | '**=' | '//=') -> augassign_rewrite(it)\n# For normal and annotated assignments, additional restrictions enforced by the interpreter -------------------------------\ndel_stmt ::= mark='del' lst=exprlist -> Delete([as_del(lst)], **loc @ mark)\npass_stmt ::= mark='pass' -> Pass(**loc @ mark)\nflow_stmt ::= it=(break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt) -> it\nbreak_stmt ::= mark='break' -> Break(**loc @ mark)\ncontinue_stmt ::= mark='continue' -> Continue(**loc @ mark)\nreturn_stmt ::= mark='return' [value=testlist_star_expr] -> Return(value, **loc @ mark)\nyield_stmt ::= exp=yield_expr -> Expr(exp) \nraise_stmt ::= mark='raise' [exc=test ['from' cause=test]] -> Raise(exc, cause, **loc @ mark) \nimport_stmt ::= it=(import_name | import_from) -> it \nimport_name ::= mark='import' names=dotted_as_names -> Import(names, **loc @ mark)\n# note below::= the ('.' | '...') is necessary because '...' is tokenized as ELLIPSIS --------------------------------\nimport_level::= (_1='.' | '...') -> 1 if _1 else 3 \nwild ::= '*' -> [alias(name='*', asname=None)]\nimport_from ::= (mark='from' (levels=import_level* module=dotted_name | levels=import_level+) # ------------------------------\n 'import' (wild=wild | '(' names=import_as_names ')' | names=import_as_names)) -> ImportFrom(module or '', wild or names, sum(levels or []), **loc @ mark) \nNAMESTR ::= n=NAME -> n.value \nimport_as_name ::= name=NAMESTR ['as' asname=NAMESTR] -> alias(name, asname)\ndotted_as_name ::= name=dotted_name ['as' asname=NAMESTR] -> alias(name, asname) \nimport_as_names::= seq<<import_as_name (',' seq<<import_as_name)* [','] -> seq\ndotted_as_names::= seq<<dotted_as_name (',' seq<<dotted_as_name)* -> seq\ndotted_name ::= xs=(NAME ('.' NAME)*) -> ''.join(c.value for c in xs)\nglobal_stmt ::= mark='global' names<<NAMESTR (',' name<<NAMESTR)* -> Global(names, **loc @ mark) \nnonlocal_stmt ::= mark='nonlocal' names<<NAMESTR (',' name<<NAMESTR)* -> Nonlocal(names, **loc @ mark)\nassert_stmt ::= mark='assert' test=test [',' msg=test] -> Assert(test, msg, **loc @ mark)\ncompound_stmt ::= it=(if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated # ------------------------------\n | async_stmt) -> it\nasync_stmt ::= it=(async_funcdef | async_with_stmt | async_for_stmt) -> it\nif_stmt ::= marks<<'if' tests<<test ':' # ------------------------------\n bodies<<suite # ------------------------------\n (marks<<'elif' tests<<test ':' bodies<<suite)* # ------------------------------\n ['else' ':' orelse=suite] -> if_stmt_rewrite(marks, tests, bodies, orelse)\nwhile_stmt ::= 'while' test=test ':' body=suite ['else' ':' orelse=suite] -> while_stmt_rewrite(test, body, orelse)\nasync_for_stmt ::= 'async' 'for' target=exprlist 'in' iter=testlist ':' body=suite ['else' ':' orelse=suite] -> for_stmt_rewrite(target, iter, body, orelse, is_async=True) \nfor_stmt ::= 'for' target=exprlist 'in' iter=testlist ':' body=suite ['else' ':' orelse=suite] -> for_stmt_rewrite(target, iter, body, orelse)\ntry_stmt ::= (mark='try' ':' # ---------------------------\n body=suite # ---------------------------\n ((excs<<except_clause ':' rescues<<suite)+ # ---------------------------\n ['else' ':' orelse=suite] # ---------------------------\n ['finally' ':' final=suite] | # ---------------------------\n 'finally' ':' final=suite)) -> try_stmt_rewrite(mark, body, excs, rescues, orelse, final)\nasync_with_stmt::= mark='async' 'with' items<<with_item (',' items<<with_item)* ':' body=suite -> with_stmt_rewrite(mark, items, body, is_async=True)\nwith_stmt ::= mark='with' items<<with_item (',' items<<with_item)* ':' body=suite -> with_stmt_rewrite(mark, items, body)\nwith_item ::= context_expr=test ['as' optional_vars=expr] -> withitem(context_expr, as_store(optional_vars)) \nexcept_clause ::= 'except' [type=test ['as' name=NAMESTR]] -> (type, name) \nsuite ::= seqs<<simple_stmt | NEWLINE INDENT (seqs<<stmt)+ DEDENT -> sum(seqs, [])\ntest ::= it=(ifexp| lambdef) -> it\nifexp ::= body=or_test ['if' test=or_test 'else' orelse=test] -> IfExp(test, body, orelse) if orelse else body \ntest_nocond ::= it=(or_test | lambdef_nocond) -> it \n\nlambdef ::= m='lambda' args=lam_args ':' body=test -> Lambda(args, body) \nlambdef_nocond ::= m='lambda' args=lam_args ':' body=test_nocond -> Lambda(args, body)\n\nor_test ::= head=and_test ('or' tail<<and_test)* -> BoolOp(Or(), [head, *tail]) if tail else head \nand_test ::= head=not_test ('and' tail<<not_test)* -> BoolOp(And(), [head, *tail]) if tail else head\nnot_test ::= mark='not' expr=not_test | comp=comparison -> UnaryOp(Not(), expr, **loc @ mark) if mark else comp \n\ncomparison ::= left=expr (ops<<comp_op comparators<<expr)* -> Compare(left, ops, comparators) if ops else left\n\ncomp_op ::= op=('<'|'>'|'=='|'>='|'<='|'<>'|'!='\n |'in'|'not' 'in'|'is'|'is' 'not') -> comp_op_rewrite(op)\n\nstar_expr ::= mark='*' expr=expr -> Starred(expr, Load(), **loc @ mark)\nexpr_tr ::= op='|' expr=xor_expr -> (op, expr)\nexpr ::= head=xor_expr tail=expr_tr* -> expr_rewrite(head, tail)\n\nxor_expr_tr ::= op='^' expr=and_expr -> (op, expr) \nxor_expr ::= head=and_expr tail=xor_expr_tr* -> xor_expr_rewrite(head, tail)\n\nand_expr_tr ::= op = '&' expr=shift_expr -> (op, expr)\nand_expr ::= head=shift_expr tail=and_expr_tr* -> and_expr_rewrite(head, tail)\n\nshift_expr_tr ::= op=('<<'|'>>') expr=arith_expr -> (op, expr)\nshift_expr ::= head=arith_expr tail=shift_expr_tr* -> shift_expr_rewrite(head, tail)\n\narith_expr_tr ::= op=('+'|'-') expr=term -> (op, expr)\narith_expr ::= head=term tail=arith_expr_tr* -> arith_expr_rewrite(head, tail) \n\nterm_tr ::= op=('*'|'@'|'/'|'%'|'//') expr=factor -> (op, expr)\nterm ::= head=factor tail=term_tr* -> term_rewrite(head, tail)\n\nfactor ::= mark=('+'|'-'|'~') factor=factor | power=power -> factor_rewrite(mark, factor, power) \n\npower ::= atom_expr=atom_expr ['**' factor=factor] -> BinOp(atom_expr, Pow(), factor) if factor else atom_expr\natom_expr ::= [a='await'] atom=atom trailers=trailer* -> atom_expr_rewrite(a, atom, trailers)\n\natom ::= (is_gen ='(' [yield_expr=yield_expr|comp=testlist_comp] ')' |\n is_list='[' [comp=testlist_comp] ']' |\n head='{' [dict=dictorsetmaker] is_dict='}' |\n name=NAME |\n number=NUMBER | \n strs=STRING+ | \n ellipsis='...' | \n namedc='None' | \n namedc='True' | \n namedc='False')\n -> atom_rewrite(loc, name, number, strs, namedc, ellipsis, dict, is_dict, is_gen, is_list, comp, yield_expr)\n \ntestlist_comp ::= values<<(test|star_expr) ( comp=comp_for | (',' values<<(test|star_expr))* [force_tuple=','] )\n ->\n def app(is_tuple=None, is_list=None):\n if is_list and comp:\n return ListComp(*values, comp)\n elif is_list:\n return List(values, Load())\n elif comp:\n return GeneratorExp(*values, comp)\n else:\n return values[0] if len(values) is 1 and not force_tuple else Tuple(values, Load())\n app\n\n# `ExtSlice` is ignored here. We don't need this optimization for this project.\ntrailer ::= arglist=arglist | mark='[' subscr=subscriptlist ']' | mark='.' attr=NAMESTR\n -> (lambda value: Subscript(value, subscr, Load(), **loc @ mark)) if subscr is not None else\\\n (lambda value: Call(value, *split_args_helper(arglist))) if arglist is not None else\\\n (lambda value: Attribute(value, attr, Load(), **loc @ mark)) \n \n# `Index` will be deprecated in Python3.8. \n# See https://github.com/python/cpython/pull/9605#issuecomment-425381990 \nsubscriptlist ::= head=subscript (',' tail << subscript)* [',']\n -> Index(head if not tail else Tuple([head, *tail], Load())) \nsubscript3 ::= [lower=test] subscr=[':' [upper=test] [':' [step=test]]] -> Slice(lower, upper, step) if subscr else lower \nsubscript ::= it=(subscript3 | test) -> it\nexprlist ::= seq << (expr|star_expr) (',' seq << (expr|star_expr))* [force_tuple=','] -> Tuple(seq, Load()) if force_tuple or len(seq) > 1 else seq[0]\ntestlist ::= seq << test (',' seq << test)* [force_tuple=','] -> Tuple(seq, Load()) if force_tuple or len(seq) > 1 else seq[0]\n\ndict_unpack_s ::= '**' -> None \ndictorsetmaker ::= (((keys<<test ':' values<<test | keys<<dict_unpack_s values<<expr)\n (comp=comp_for | (',' (keys<<test ':' values<<test | keys<<dict_unpack_s values<<expr))* [','])) |\n (values<<(test | star_expr)\n (comp=comp_for | (',' values<<(test | star_expr))* [','])) )\n -> if not comp: return ExDict(keys, values, Load()) if keys else Set(values)\n DictComp(*keys, *values, comp) if keys else SetComp(*values, comp)\n\nclassdef ::= mark='class' name=NAME [arglist=arglist]':' suite=suite\n -> ClassDef(name.value, *split_args_helper(arglist or []), suite, [], **loc @ mark)\n\narglist ::= mark='(' [seq<<argument (',' seq<<argument)* [',']] ')' -> check_call_args(loc @ mark, seq or [])\n\nargument ::= ( \n key=NAME '=' value=test |\n arg=test [comp=comp_for] |\n mark='**' kwargs=test |\n mark='*' args=test )\n -> \n Starred(**(loc @ mark), value=args, ctx=Load()) if args else \\\n keyword(**(loc @ mark), arg=None, value=kwargs) if kwargs else\\\n keyword(**(loc @ key), arg=key.value, value=value) if key else \\\n GeneratorExp(arg, comp) if comp else \\\n arg\n\ncomp_for_item ::= [is_async='async'] 'for' target=exprlist 'in' iter=or_test ('if' ifs<<test_nocond)* \n -> comprehension(as_store(target), iter, ifs, bool(is_async))\n \ncomp_for ::= generators=comp_for_item+ -> list(generators)\n\nencoding_decl ::= NAME\n\nyield_expr ::= mark='yield' [is_yield_from='from' expr=test | expr=testlist_star_expr]\n -> YieldFrom(**(loc @ mark), value=expr) if is_yield_from else Yield(**(loc @ mark), value=expr)\n"
# https://codeforces.com/problemset/problem/959/A n = int(input()) print('Mahmoud' if n%2 == 0 else 'Ehab')
n = int(input()) print('Mahmoud' if n % 2 == 0 else 'Ehab')
# # Copyright (c) 2017-2018 Joy Diamond. All rights reserved. # @gem('Sapphire.Parse1Atom') def gem(): show = 7 @share def parse1_map_element(): if qk() is not none: #my_line('qk: %r', qk()) raise_unknown_line() token = parse1_atom() if token.is_right_brace: return token if token.is_special_operator: raise_unknown_line() operator = qk() if operator is none: if qn() is not none: raise_unknown_line() operator = tokenize_operator() else: wk(none) if not operator.is_colon: token = parse1_ternary_expression__X__any_expression(token, operator) operator = qk() if operator is none: raise_unknown_line() wk(none) if not operator.is_colon: raise_unknown_line() return conjure_map_element(token, operator, parse1_ternary_expression()) @share def parse1_map__left_brace(left_brace): # # 1 # left = parse1_map_element() if left.is_right_brace: return conjure_empty_map(left_brace, left) operator = qk() if operator is none: operator = tokenize_operator() else: wk(none) if operator.is_keyword_for: left = parse1_comprehension_expression__X__any_expression(left, operator) operator = qk() if operator is none: operator = tokenize_operator() else: wk(none) if operator.is_right_brace: return conjure_map_expression_1(left_brace, left, operator) if not operator.is_comma: raise_unknown_line() token = parse1_map_element() if token.is_right_brace: return conjure_map_expression_1(left_brace, left, conjure__comma__right_brace(operator, token)) many = [left, token] many_frill = [operator] while 7 is 7: operator = qk() if operator is none: raise_unknown_line() wk(none) if operator.is_right_brace: return conjure_map_expression_many(left_brace, many, many_frill, operator) if not operator.is_comma: raise_unknown_line() token = parse1_map_element() if token.is_right_brace: return conjure_map_expression_many( left_brace, many, many_frill, conjure__comma__right_brace(operator, token), ) many_frill.append(operator) many.append(token) @share def parse1__parenthesized_expression__left_parenthesis(left_parenthesis): # # 1 # # # TODO: # Replace this with 'parse1__parenthesis__first_atom' & handle a right-parenthesis as an empty tuple # middle_1 = parse1_atom() if middle_1.is_right_parenthesis: return conjure_empty_tuple(left_parenthesis, middle_1) if middle_1.is_special_operator: raise_unknown_line() operator_1 = qk() if operator_1 is none: operator_1 = tokenize_operator() else: wk(none) #my_line('operator_1: %r', operator_1) if not operator_1.is_end_of_ternary_expression: middle_1 = parse1_ternary_expression__X__any_expression(middle_1, operator_1) operator_1 = qk() wk(none) if operator_1.is_right_parenthesis: return conjure_parenthesized_expression(left_parenthesis, middle_1, operator_1) if operator_1.is_comma__right_parenthesis: return conjure_parenthesized_tuple_expression_1(left_parenthesis, middle_1, operator_1) if not operator_1.is_comma: raise_unknown_line() # # 2 # middle_2 = parse1_atom() if middle_2.is_right_parenthesis: return conjure_parenthesized_tuple_expression_1( left_parenthesis, middle_1, conjure_comma__right_parenthesis(operator_1, middle_2), ) if middle_2.is_special_operator: raise_unknown_line() operator_2 = tokenize_operator() if not operator_2.is_end_of_ternary_expression: middle_2 = parse1_ternary_expression__X__any_expression(middle_2, operator_2) operator_2 = qk() wk(none) if operator_2.is__optional_comma__right_parenthesis: return conjure_tuple_expression_2(left_parenthesis, middle_1, operator_1, middle_2, operator_2) if not operator_2.is_comma: raise_unknown_line() # # 3 # middle_3 = parse1_atom() if middle_3.is_right_parenthesis: return conjure_tuple_expression_2( left_parenthesis, middle_1, operator_1, middle_2, conjure_comma__right_parenthesis(operator_2, middle_3), ) if middle_3.is_special_operator: raise_unknown_line() many = [middle_1, middle_2] many_frill = [operator_1, operator_2] while 7 is 7: operator_7 = tokenize_operator() if not operator_7.is_end_of_ternary_expression: middle_3 = parse1_ternary_expression__X__any_expression(middle_3, operator_7) operator_7 = qk() wk(none) many.append(middle_3) if operator_7.is__optional_comma__right_parenthesis: return conjure_tuple_expression_many(left_parenthesis, many, many_frill, operator_7) if not operator_7.is_comma: raise_unknown_line() middle_3 = parse1_atom() if middle_3.is_right_parenthesis: return conjure_tuple_expression_many( left_parenthesis, many, many_frill, conjure_comma__right_parenthesis(operator_7, middle_3), ) if middle_3.is_special_operator: raise_unknown_line() many_frill.append(operator_7) @share def parse1__list_expression__left_square_bracket(left_square_bracket): # # 1 # middle_1 = parse1_atom() if middle_1.is_right_square_bracket: return conjure_empty_list(left_square_bracket, middle_1) if middle_1.is_special_operator: raise_unknown_line() operator_1 = tokenize_operator() if not operator_1.is_end_of_comprehension_expression: middle_1 = parse1_comprehension_expression__X__any_expression(middle_1, operator_1) operator_1 = qk() wk(none) if operator_1.is__optional_comma__right_square_bracket: return conjure_list_expression_1(left_square_bracket, middle_1, operator_1) if not operator_1.is_comma: #my_line('line: %d; middle_1: %r; operator_1: %r', ql(), middle_1, operator_1) raise_unknown_line() # # 2 # middle_2 = parse1_atom() if middle_2.is_right_square_bracket: return conjure_list_expression_1( left_square_bracket, middle_1, conjure_comma__right_square_bracket(operator_1, middle_2), ) if middle_2.is_special_operator: raise_unknown_line() operator_2 = tokenize_operator() if not operator_2.is_end_of_ternary_expression: middle_2 = parse1_ternary_expression__X__any_expression(middle_2, operator_2) operator_2 = qk() wk(none) if operator_2.is__optional_comma__right_square_bracket: return conjure_list_expression_2(left_square_bracket, middle_1, operator_1, middle_2, operator_2) if not operator_2.is_comma: raise_unknown_line() # # 3 # middle_3 = parse1_atom() if middle_3.is_right_square_bracket: return conjure_list_expression_2( left_square_bracket, middle_1, operator_1, middle_2, conjure_comma__right_square_bracket(operator_2, middle_3), ) if middle_3.is_special_operator: raise_unknown_line() many = [middle_1, middle_2] many_frill = [operator_1, operator_2] while 7 is 7: operator_7 = tokenize_operator() if not operator_7.is_end_of_ternary_expression: middle_3 = parse1_ternary_expression__X__any_expression(middle_3, operator_7) operator_7 = qk() wk(none) many.append(middle_3) if operator_7.is__optional_comma__right_square_bracket: return conjure_list_expression_many(left_square_bracket, many, many_frill, operator_7) if not operator_7.is_comma: raise_unknown_line() middle_3 = parse1_atom() if middle_3.is_right_square_bracket: return conjure_list_expression_many( left_square_bracket, many, many_frill, conjure_comma__right_square_bracket(operator_7, middle_3), ) if middle_3.is_special_operator: raise_unknown_line() many_frill.append(operator_7) @share def parse1_atom(): assert qk() is none assert qn() is none m = atom_match(qs(), qj()) if m is none: #my_line('full: %r; s: %r', portray_string(qs()), portray_string(qs()[qj() :])) raise_unknown_line() token = analyze_atom(m) if token.is__atom__or__special_operator: return token if token.is_left_parenthesis: return parse1__parenthesized_expression__left_parenthesis(token) if token.is_left_square_bracket: return parse1__list_expression__left_square_bracket(token) if token.is_left_brace: return parse1_map__left_brace(token) if token.is_keyword_not: return parse1_not_expression__operator(token) if token.is_minus_sign: return parse1_negative_expression__operator(token) if token.is_tilde_sign: return parse1_twos_complement_expression__operator(token) if token.is_star_sign: return conjure_star_argument(token, parse1_ternary_expression()) my_line('token: %r', token) assert 0 raise_unknown_line()
@gem('Sapphire.Parse1Atom') def gem(): show = 7 @share def parse1_map_element(): if qk() is not none: raise_unknown_line() token = parse1_atom() if token.is_right_brace: return token if token.is_special_operator: raise_unknown_line() operator = qk() if operator is none: if qn() is not none: raise_unknown_line() operator = tokenize_operator() else: wk(none) if not operator.is_colon: token = parse1_ternary_expression__x__any_expression(token, operator) operator = qk() if operator is none: raise_unknown_line() wk(none) if not operator.is_colon: raise_unknown_line() return conjure_map_element(token, operator, parse1_ternary_expression()) @share def parse1_map__left_brace(left_brace): left = parse1_map_element() if left.is_right_brace: return conjure_empty_map(left_brace, left) operator = qk() if operator is none: operator = tokenize_operator() else: wk(none) if operator.is_keyword_for: left = parse1_comprehension_expression__x__any_expression(left, operator) operator = qk() if operator is none: operator = tokenize_operator() else: wk(none) if operator.is_right_brace: return conjure_map_expression_1(left_brace, left, operator) if not operator.is_comma: raise_unknown_line() token = parse1_map_element() if token.is_right_brace: return conjure_map_expression_1(left_brace, left, conjure__comma__right_brace(operator, token)) many = [left, token] many_frill = [operator] while 7 is 7: operator = qk() if operator is none: raise_unknown_line() wk(none) if operator.is_right_brace: return conjure_map_expression_many(left_brace, many, many_frill, operator) if not operator.is_comma: raise_unknown_line() token = parse1_map_element() if token.is_right_brace: return conjure_map_expression_many(left_brace, many, many_frill, conjure__comma__right_brace(operator, token)) many_frill.append(operator) many.append(token) @share def parse1__parenthesized_expression__left_parenthesis(left_parenthesis): middle_1 = parse1_atom() if middle_1.is_right_parenthesis: return conjure_empty_tuple(left_parenthesis, middle_1) if middle_1.is_special_operator: raise_unknown_line() operator_1 = qk() if operator_1 is none: operator_1 = tokenize_operator() else: wk(none) if not operator_1.is_end_of_ternary_expression: middle_1 = parse1_ternary_expression__x__any_expression(middle_1, operator_1) operator_1 = qk() wk(none) if operator_1.is_right_parenthesis: return conjure_parenthesized_expression(left_parenthesis, middle_1, operator_1) if operator_1.is_comma__right_parenthesis: return conjure_parenthesized_tuple_expression_1(left_parenthesis, middle_1, operator_1) if not operator_1.is_comma: raise_unknown_line() middle_2 = parse1_atom() if middle_2.is_right_parenthesis: return conjure_parenthesized_tuple_expression_1(left_parenthesis, middle_1, conjure_comma__right_parenthesis(operator_1, middle_2)) if middle_2.is_special_operator: raise_unknown_line() operator_2 = tokenize_operator() if not operator_2.is_end_of_ternary_expression: middle_2 = parse1_ternary_expression__x__any_expression(middle_2, operator_2) operator_2 = qk() wk(none) if operator_2.is__optional_comma__right_parenthesis: return conjure_tuple_expression_2(left_parenthesis, middle_1, operator_1, middle_2, operator_2) if not operator_2.is_comma: raise_unknown_line() middle_3 = parse1_atom() if middle_3.is_right_parenthesis: return conjure_tuple_expression_2(left_parenthesis, middle_1, operator_1, middle_2, conjure_comma__right_parenthesis(operator_2, middle_3)) if middle_3.is_special_operator: raise_unknown_line() many = [middle_1, middle_2] many_frill = [operator_1, operator_2] while 7 is 7: operator_7 = tokenize_operator() if not operator_7.is_end_of_ternary_expression: middle_3 = parse1_ternary_expression__x__any_expression(middle_3, operator_7) operator_7 = qk() wk(none) many.append(middle_3) if operator_7.is__optional_comma__right_parenthesis: return conjure_tuple_expression_many(left_parenthesis, many, many_frill, operator_7) if not operator_7.is_comma: raise_unknown_line() middle_3 = parse1_atom() if middle_3.is_right_parenthesis: return conjure_tuple_expression_many(left_parenthesis, many, many_frill, conjure_comma__right_parenthesis(operator_7, middle_3)) if middle_3.is_special_operator: raise_unknown_line() many_frill.append(operator_7) @share def parse1__list_expression__left_square_bracket(left_square_bracket): middle_1 = parse1_atom() if middle_1.is_right_square_bracket: return conjure_empty_list(left_square_bracket, middle_1) if middle_1.is_special_operator: raise_unknown_line() operator_1 = tokenize_operator() if not operator_1.is_end_of_comprehension_expression: middle_1 = parse1_comprehension_expression__x__any_expression(middle_1, operator_1) operator_1 = qk() wk(none) if operator_1.is__optional_comma__right_square_bracket: return conjure_list_expression_1(left_square_bracket, middle_1, operator_1) if not operator_1.is_comma: raise_unknown_line() middle_2 = parse1_atom() if middle_2.is_right_square_bracket: return conjure_list_expression_1(left_square_bracket, middle_1, conjure_comma__right_square_bracket(operator_1, middle_2)) if middle_2.is_special_operator: raise_unknown_line() operator_2 = tokenize_operator() if not operator_2.is_end_of_ternary_expression: middle_2 = parse1_ternary_expression__x__any_expression(middle_2, operator_2) operator_2 = qk() wk(none) if operator_2.is__optional_comma__right_square_bracket: return conjure_list_expression_2(left_square_bracket, middle_1, operator_1, middle_2, operator_2) if not operator_2.is_comma: raise_unknown_line() middle_3 = parse1_atom() if middle_3.is_right_square_bracket: return conjure_list_expression_2(left_square_bracket, middle_1, operator_1, middle_2, conjure_comma__right_square_bracket(operator_2, middle_3)) if middle_3.is_special_operator: raise_unknown_line() many = [middle_1, middle_2] many_frill = [operator_1, operator_2] while 7 is 7: operator_7 = tokenize_operator() if not operator_7.is_end_of_ternary_expression: middle_3 = parse1_ternary_expression__x__any_expression(middle_3, operator_7) operator_7 = qk() wk(none) many.append(middle_3) if operator_7.is__optional_comma__right_square_bracket: return conjure_list_expression_many(left_square_bracket, many, many_frill, operator_7) if not operator_7.is_comma: raise_unknown_line() middle_3 = parse1_atom() if middle_3.is_right_square_bracket: return conjure_list_expression_many(left_square_bracket, many, many_frill, conjure_comma__right_square_bracket(operator_7, middle_3)) if middle_3.is_special_operator: raise_unknown_line() many_frill.append(operator_7) @share def parse1_atom(): assert qk() is none assert qn() is none m = atom_match(qs(), qj()) if m is none: raise_unknown_line() token = analyze_atom(m) if token.is__atom__or__special_operator: return token if token.is_left_parenthesis: return parse1__parenthesized_expression__left_parenthesis(token) if token.is_left_square_bracket: return parse1__list_expression__left_square_bracket(token) if token.is_left_brace: return parse1_map__left_brace(token) if token.is_keyword_not: return parse1_not_expression__operator(token) if token.is_minus_sign: return parse1_negative_expression__operator(token) if token.is_tilde_sign: return parse1_twos_complement_expression__operator(token) if token.is_star_sign: return conjure_star_argument(token, parse1_ternary_expression()) my_line('token: %r', token) assert 0 raise_unknown_line()
def calculateFuel(weight): return int(weight / 3)-2 # Part 1 total = 0 with open("/Users/a318196/Code/AdventOfCode2020/20191201/input.txt") as file: for line in file: total += calculateFuel(int(line)) print ('Total part 1: ' + str(total)) # Part 2 total = 0 with open("/Users/a318196/Code/AdventOfCode2020/20191201/input.txt") as file: for line in file: fuel = calculateFuel(int(line)) additionalFuel = calculateFuel(fuel) while additionalFuel > 0: fuel += additionalFuel additionalFuel = calculateFuel(additionalFuel) total += fuel print ('Total part 2: ' + str(total))
def calculate_fuel(weight): return int(weight / 3) - 2 total = 0 with open('/Users/a318196/Code/AdventOfCode2020/20191201/input.txt') as file: for line in file: total += calculate_fuel(int(line)) print('Total part 1: ' + str(total)) total = 0 with open('/Users/a318196/Code/AdventOfCode2020/20191201/input.txt') as file: for line in file: fuel = calculate_fuel(int(line)) additional_fuel = calculate_fuel(fuel) while additionalFuel > 0: fuel += additionalFuel additional_fuel = calculate_fuel(additionalFuel) total += fuel print('Total part 2: ' + str(total))
class FLAG_OPTIONS: MUTLIPLE_SEGMENTS_EXIST = 0x1 ALL_PROPERLY_ALIGNED = 0x2 SEG_UNMAPPED = 0x4 NEXT_SEG_UNMAPPED = 0x8 SEQ_REV_COMP = 0x10 NEXT_SEQ_REV_COMP = 0x20 FIRST_SEQ_IN_TEMP = 0x40 LAST_SEQ_IN_TEMP = 0x80 SECONDARY_ALG = 0x100 POOR_QUALITY = 0x200 DUPLICATE_READ = 0x400 SUPPLEMENTARY_ALG = 0x800
class Flag_Options: mutliple_segments_exist = 1 all_properly_aligned = 2 seg_unmapped = 4 next_seg_unmapped = 8 seq_rev_comp = 16 next_seq_rev_comp = 32 first_seq_in_temp = 64 last_seq_in_temp = 128 secondary_alg = 256 poor_quality = 512 duplicate_read = 1024 supplementary_alg = 2048
secure_log_path = "/var/log/secure"; secure_log_score_tokens = \ { "Invalid user": 3, "User root": 5, "Failed password": 2 }; secure_log_score_limit = 10; #firewall-cmd --permanent --ipset=some_set --add-entry=xxx.xxx.xxx.xxx firewalld_ipset_name = "ips2drop"; ##################################################### # technical section # ##################################################### # time_stamp_pattern = ""; ip_address_pattern = r"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"; abuse_report_mail_pattern = r"abuse@[a-zA-Z]+\.[a-zA-Z]+"; #####################################################
secure_log_path = '/var/log/secure' secure_log_score_tokens = {'Invalid user': 3, 'User root': 5, 'Failed password': 2} secure_log_score_limit = 10 firewalld_ipset_name = 'ips2drop' ip_address_pattern = '[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}' abuse_report_mail_pattern = 'abuse@[a-zA-Z]+\\.[a-zA-Z]+'
a, b, c, d = map(int, input().split()) s = a + b + c + d a, b, c, d = map(int, input().split()) t = a + b + c + d print(max(s, t))
(a, b, c, d) = map(int, input().split()) s = a + b + c + d (a, b, c, d) = map(int, input().split()) t = a + b + c + d print(max(s, t))