content
stringlengths
7
1.05M
{ '%Y-%m-%d':'%Y-%m-%d', '%Y-%m-%d %H:%M:%S':'%Y-%m-%d %H:%M:%S', '%s rows deleted':'%s records cancellati', '%s rows updated':'*** %s records modificati', 'Hello World':'Salve Mondo', 'Invalid Query':'Query invalida', 'Sure you want to delete this object?':'Sicuro che vuoi cancellare questo oggetto?', 'Welcome to web2py':'Ciao da wek2py', 'click here for online examples':'clicca per vedere gli esempi', 'click here for the administrative interface':'clicca per l\'interfaccia administrativa', 'data uploaded':'dati caricati', 'db':'db', 'design':'progetta', 'done!':'fatto!', 'invalid request':'richiesta invalida!', 'new record inserted':'nuovo record inserito', 'record does not exist':'il record non esiste', 'state':'stato', 'unable to parse csv file':'non so leggere questo csv file' }
def clean_split(text, delim=','): text = text.strip() return map(lambda o: o.strip(), text.split(delim)) def read_notes(file): notes = {} for line in file: split = clean_split(line, ',')[:-1] if split[-1] == '': continue notes[(split[0], int(split[1]))] = float(split[2]) return notes # Map notes to frequencies notes = read_notes(open('notes.txt')) # Map frequencies to note tuples inv_notes = {v: k for k, v in notes.items()} if __name__ == '__main__': path = 'notes.txt' with open(path) as f: read_notes(f)
# Game Objects class Space(object): def __init__(self,name): self.name = name def get_name(self): return self.name class Property(Space): set_houses = { "Violet":2, "Light blue":3, "Purple":3, "Orange":3, "Red":3, "Yellow":3, "Green":3, "Blue":2 } def __init__(self, name, color, price, rent, one_house_rent, two_house_rent, three_house_rent, four_house_rent, hotel_rent, house_cost): super(Property,self).__init__(name) self.price = price self.color = color self.house_count = 0 #5 means hotel self.rents = {0:rent, 1:one_house_rent, 2:two_house_rent, 3:three_house_rent, 4:four_house_rent, 5:hotel_rent} self.house_cost = house_cost def get_house_cost(self): return self.house_cost def info(self): information = [ self.name+" is a "+self.color+" property that costs "+str(self.price)+".", "It currently has "+str(self.house_count)+" houses.", "With no houses rent is "+str(self.rents[0])+".", "With 1 house rent is "+str(self.rents[1])+".", "With 2 houses rent is "+str(self.rents[2])+".", "With 3 houses rent is "+str(self.rents[3])+".", "With 4 houses rent is "+str(self.rents[4])+".", "With a hotel rent is "+str(self.rents[5])+".", "A house costs "+str(self.house_cost)+" to build." ] return " ".join(information) class Railroad(Space): def __init__(self,name): super(Railroad, self).__init__(name) self.price = 200 self.rents = {1:25, 2:50, 3:100, 4:200} def info(self): information = [ self.name+" is a railroad that costs "+str(self.price)+".", "If a player has one railroad only the rent is "+str(self.rents[1])+".", "If a player has two railroads the rent is "+str(self.rents[2])+".", "If a player has three railroads only the rent is "+str(self.rents[3])+".", "If a player has four railroads only the rent is "+str(self.rents[4])+"." ] return " ".join(information) class Utility(Space): def __init__(self,name): super(Utility,self).__init__(name) self.price = 150 self.rents = {1:"4 *", 2:"10 *"} def info(self): return self.name+" is a utility that costs "+str(self.price)+". If you have " +\ "one utility rent is four times the amount the player rolled on the dice or "+\ "if you have two utilities the rent is ten times!" board_spaces = [ Space("GO"), Property("Mediterranean Ave.","Violet",60,2,10,30,90,160,250,50), Space("Community Card"), Property("Baltic Ave.","Violet",60,4,20,60,180,320,450,50), Space("Income Tax"), Railroad("Reading Railroad"), Property("Oriental Ave.","Light blue",100,6,30,90,270,400,550,50), Space("Chance Card"), Property("Vermont Ave.","Light blue",100,6,30,90,270,400,550,50), Property("Conneticut Ave.","Light blue",120,8,40,100,300,450,600,50), Space("Jail"), Property("St. Charles Pl.","Purple",140,10,50,150,450,625,750,100), Utility("Electric Company"), Property("States Ave.","Purple",140,10,50,150,450,625,750,100), Property("Virginia Ave.","Purple",160,12,60,180,500,700,900,100), Railroad("Pennsylvania Railroad"), Property("St. James Pl.","Orange",180,14,70,200,550,750,950,100), Space("Community Card"), Property("Tennessee Ave.","Orange",180,14,70,200,550,750,950,100), Property("New York Ave.","Orange",200,16,80,220,600,800,1000,100), Space("Free Parking"), Property("Kentucky Ave.","Red",220,18,90,250,700,875,1050,150), Space("Chance Card"), Property("Indiana Ave.","Red",220,18,90,250,700,875,1050,150), Property("Illinois Ave.","Red",240,20,100,300,750,925,1100,150), Railroad("B. & O. Railroad"), Property("Atlantic Ave.","Yellow",260,22,110,330,800,975,1150,150), Property("Ventnor Ave.","Yellow",260,22,110,330,800,975,1150,150), Utility("Water Works"), Property("Marvin Gardens","Yellow",280,24,120,360,850,1025,1200,150), Space("Go to Jail"), Property("Pacific Ave.","Green",300,26,130,390,900,1100,1275,200), Property("No. Carolina Ave.","Green",300,26,130,390,900,1100,1275,200), Space("Community Card"), Property("Pennsylvania Ave.","Green",320,28,150,450,1000,1200,1400,200), Railroad("Short Line Railroad"), Space("Chance Card"), Property("Park Place","Blue",350,35,175,500,1100,1300,1500,200), Space("Luxury Tax"), Property("Boardwalk","Blue",400,50,200,600,1400,1700,2000,200) ] #chance_methods = [pay_all,reading_rail,move_to,go,railroad,get_outta_jail,jail,earn,fine,repairs,util,move_back_three] #in the following decks, the second value of the dictionaries in the array must be an iterable and not an int, #hence why you will see things like (50,) so that python keeps it as a tuple chance_deck = [ {"You have been elected chairman of the board, pay each player $50":[0,(50,)]}, {"Take a ride on the reading, if you pass GO collect $200":[1,()]}, {"Take a walk on the board walk, advance token to board walk":[2,(board_spaces[39],)]}, {"Advance to go, collect $200":[3,()]}, {"Advance token to the nearest Railroad and pay owner Twice the Rental owed. If Railroad is unowned you may buy it from the bank":[4,()]}, {"Advance token to the nearest Railroad and pay owner Twice the Rental owed. If Railroad is unowned you may buy it from the bank":[4,()]}, {"Get out of jail free. This card may be kept until needed or sold":[5,()]}, {"Go directly to jail. Do not pass Go, do not collect $200":[6,()]}, {"Bank pays you dividend of $50":[7,(50,)]}, {"Advance to Illinois Ave":[2,(board_spaces[24],)]}, {"Pay poor tax of $15":[8,(15,)]}, {"Make general repairs on all your property. For each house pay $25, for each hotel $100":[9,(25,100)]}, {"Advance to St. Charles Place. If you pass Go, collect $200":[2,(board_spaces[11],)]}, {"Your building and loan matures. Collect $150":[7,(150,)]}, {"Advance token to nearest utility. If Unowned you may buy it from the bank. If owned throw dice and pay owner ten times the amount thrown.":[10,()]}, {"Go back 3 spaces":[11,()]} ] #cc methods = [earn,get_outta_jail,collect,go,jail,repairs,fine] community_deck = [ {"Get out of jail free.":[1,()]}, {"From sale of stock, you get $45":[0,(45,)]}, {"Grand opera opening. Collect $50 from every player for opening night seats":[2,(50,)]}, {"Advance to Go, collect $200":[3,()]}, {"Xmas fund matures, collect $100":[0,(100,)]}, {"Go directly to jail. Do not pass Go. Do not collect $200":[4,()]}, {"Life insurance matures, collect $200":[0,(200,)]}, {"You are assessed for street repairs. $40 per house, $115 per hotel":[5,(40,115)]}, {"Pay hospital $100":[6,(100,)]}, {"Income tax refund, collect $20":[0,(20,)]}, {"Doctor's fee, pay $50":[6,(50,)]}, {"You inherit $100":[0,(100,)]}, {"Pay school tax of $150":[6,(150,)]}, {"Receive for services $25":[0,(25,)]}, {"Bank error in your favor, collect $200":[0,(200,)]}, {"You have won second prize in a beauty contest, collect $10":[0,(10,)]} ]
class Hourly: def __init__(self, temp, feels_like, pressure, humidity, wind_speed, date, city, weather): self.temp=temp; self.feels_like=feels_like; self.pressure=pressure; self.humidity=humidity; self.wind_speed=wind_speed; self.date=date; self.city=city; self.weather=weather;
class InvalidQNameError(RuntimeError): def __init__(self, qname): message = "Invalid qname: " + qname super(InvalidQNameError, self).__init__(message)
# selection sort algorithm # time complexity O(n^2) # space complexity O(1) def selectionsort(list, comp): for x in range(len(list)): curr = x for y in range(x, len(list)): if (comp(list[curr], list[y]) > 0): curr = y swap = list[x] list[x] = list[curr] list[curr] = swap return list
def rpn_eval(tokens): def op(symbol, a, b): return { '+': lambda a, b: a + b, '-': lambda a, b: a - b, '*': lambda a, b: a * b, '/': lambda a, b: a / b }[symbol](a, b) stack = [] for token in tokens: if isinstance(token, float): stack.append(token) else: a = stack.pop() b = stack.pop() stack.append( op(token, a, b) ) return stack.pop() """ Reverse Polish Notation Four-function calculator with input given in Reverse Polish Notation (RPN). Input: A list of values and operators encoded as floats and strings Precondition: all( isinstance(token, float) or token in ('+', '-', '*', '/') for token in tokens ) Example: >>> rpn_eval([3.0, 5.0, '+', 2.0, '/']) 4.0 """
#coding=utf-8 #使用递归计算n的阶乘(5!=5*4*3*2*1) def factorial(n): if n==1: return n else: return n*factorial(n-1) print(factorial(5))
class Solution: def oddEvenList(self, head: ListNode) -> ListNode: odd = head even = head.next even_head = head.next while even and even.next: odd.next = odd.next.next even.next = even.next.next odd = odd.next even = even.next odd.next = even_head return head """ Runtime: O(N) Space: O(1) Runtime: 32 ms, faster than 98.43% of Python3 online submissions for Odd Even Linked List. Memory Usage: 14.6 MB, less than 100.00% of Python3 online submissions for Odd Even Linked List. """
# Represents a single space within the board. class Tile(): # Initializes the tile. # By default, each tile is a wall until a board is built def __init__(self): self.isWall = True # Renders the object character in this tile def render(self): if self.isWall == True: return '0'; # Represents the game board for the PC to explore class Board(): # Initializes the board with a rectangle of Tiles # # @width - the number of tiles wide the board is # @height - the number of tiles tall the board is def __init__(self, width, height): self.width = width # width of the max play area self.height = height # height of the max play area self.board = []; # collection of all tiles that make up the board # Loop through each row & column to initialize the tile for y in range(0, self.height): row = []; for x in range(0, self.width): tile = Tile(); row.append(tile); self.board.append(row); # Renders each tile in the board def render(self): for y in range(0, self.height): row = ''; for x in range(0, self.width): row += self.board[y][x].render(); print(row)
__title__ = 'dtanys' __description__ = 'Python structured data parser.' __url__ = 'https://github.com/luxuncang/dtanys' __version__ = '1.0.5' __author__ = 'ShengXin Lu' __author_email__ = 'luxuncang@qq.com' __license__ = 'MIT' __copyright__ = 'Copyright 2021 ShengXin Lu'
class Clock: def __init__(self, hour, minute): self.total: int = hour * 60 + minute # in minutes def __repr__(self): hour, minute = (self.total // 60) % 24, self.total % 60 return '{:02d}:{:02d}'.format(hour, minute) def __eq__(self, other): return repr(self) == repr(other) def __add__(self, minutes: int): self.total += minutes return self def __sub__(self, minutes: int): self.total -= minutes return self
file=open("circulations.txt") data=[] date=int(input()) for line in file: [book,member,due]=line.strip().split() if date>int(due): data.append([book,member,due]) i=0 while i<len(data)-1: j=0 while j<len(data)-1: if int(data[j][2])>int(data[j+1][2]): data[j], data[j+1] = data[j+1], data[j] j+=1 i+=1 if len(data)>0: for d in data: print(" ".join(d)) else: print("Not Found") file.close
BASE_URL = "https://api.stlouisfed.org" SERIES_ENDPOINT = "fred/series/observations" SERIES = ["GDPC1", "UMCSENT", "UNRATE"] FILE_TYPE = "json"
""" Module: 'uasyncio.__init__' on micropython-rp2-1.15 """ # MCU: {'family': 'micropython', 'sysname': 'rp2', 'version': '1.15.0', 'build': '', 'mpy': 5637, 'port': 'rp2', 'platform': 'rp2', 'name': 'micropython', 'arch': 'armv7m', 'machine': 'Raspberry Pi Pico with RP2040', 'nodename': 'rp2', 'ver': '1.15', 'release': '1.15.0'} # Stubber: 1.3.9 class CancelledError: '' class Event: '' def clear(): pass def is_set(): pass def set(): pass wait = None class IOQueue: '' def _dequeue(): pass def _enqueue(): pass def queue_read(): pass def queue_write(): pass def remove(): pass def wait_io_event(): pass class Lock: '' acquire = None def locked(): pass def release(): pass class Loop: '' _exc_handler = None def call_exception_handler(): pass def close(): pass def create_task(): pass def default_exception_handler(): pass def get_exception_handler(): pass def run_forever(): pass def run_until_complete(): pass def set_exception_handler(): pass def stop(): pass class SingletonGenerator: '' class StreamReader: '' aclose = None awrite = None awritestr = None def close(): pass drain = None def get_extra_info(): pass read = None readexactly = None readline = None wait_closed = None def write(): pass class StreamWriter: '' aclose = None awrite = None awritestr = None def close(): pass drain = None def get_extra_info(): pass read = None readexactly = None readline = None wait_closed = None def write(): pass class Task: '' class TaskQueue: '' def peek(): pass def pop_head(): pass def push_head(): pass def push_sorted(): pass def remove(): pass class ThreadSafeFlag: '' def ioctl(): pass def set(): pass wait = None class TimeoutError: '' _attrs = None def create_task(): pass def current_task(): pass gather = None def get_event_loop(): pass def new_event_loop(): pass open_connection = None def run(): pass def run_until_complete(): pass select = None def sleep(): pass def sleep_ms(): pass start_server = None sys = None def ticks(): pass def ticks_add(): pass def ticks_diff(): pass wait_for = None def wait_for_ms(): pass
f90 = {} cxx = {} cc = {} is_arch_valid = 1 flags_arch = '-g -pg -O3 -Wall' # -lpthread: not needed? # -rdynamic: required for backtraces balancer = 'RotateLB' flags_prec_single = '-fdefault-real-4 -fdefault-double-8' flags_prec_double = '-fdefault-real-8 -fdefault-double-8' flags_cxx_charm = '-balancer ' + balancer flags_link_charm = '-rdynamic -module ' + balancer cc = 'gcc' f90 = 'gfortran' libpath_fortran = '' libs_fortran = ['gfortran'] home = os.environ['HOME'] charm_path = home + '/Charm/charm' papi_path = '/usr/local' hdf5_path = '/usr'
"""Holds cerberus validation schemals for each yml parsed by any of the sheetwork system.""" config_schema = { "sheets": { "required": True, "type": "list", "schema": { "type": "dict", "schema": { "sheet_name": {"required": True, "type": "string"}, "sheet_key": {"required": True, "type": "string"}, "worksheet": {"required": False, "type": "string"}, "target_schema": {"required": False, "type": "string"}, "target_table": {"required": True, "type": "string"}, "snake_case_camel": {"required": False, "type": "boolean"}, "columns": { "type": "list", "required": False, "schema": { "type": "dict", "schema": { "name": { "required": True, "type": "string", "maxlength": 255, }, "datatype": { "required": True, "type": "string", "regex": "(?i)^(int|varchar|numeric|boolean|date|timestamp_ntz)$", }, "identifier": {"required": False, "type": "string"}, }, }, }, "excluded_columns": { "anyof_type": ["list", "string"], "required": False, "schema": {"type": "string"}, }, "included_columns": { "anyof_type": ["list", "string"], "required": False, "schema": {"type": "string"}, }, "custom_column_name_cleanup": { "type": "dict", "required": False, "schema": { "default_replacement": {"type": "string", "required": False}, "characters_to_replace": { "anyof_type": ["list", "string"], "required": False, "schema": {"type": "string"}, }, }, }, }, }, }, } profiles_schema = { "profiles": { "required": True, "type": "dict", "valuesrules": { "type": "dict", "schema": { "target": {"required": True, "type": "string"}, "outputs": { "required": True, "type": "dict", "valuesrules": { "type": "dict", "schema": { "db_type": {"required": True, "type": "string"}, "account": {"required": False, "type": "string"}, "user": {"required": True, "type": "string"}, "password": {"required": True, "type": "string"}, "host": {"required": False, "type": "string"}, "port": {"required": False, "type": "string"}, "role": {"required": False, "type": "string"}, "database": {"required": False, "type": "string"}, "warehouse": {"required": False, "type": "string"}, "schema": {"required": False, "type": "string"}, # ! new and prefered from v1.1.0 "target_schema": {"required": False, "type": "string"}, "guser": {"required": True, "type": "string"}, "is_service_account": {"required": False, "type": "boolean"}, }, }, }, }, }, } } project_schema = { "name": {"required": True, "type": "string"}, "target_schema": {"required": False, "type": "string"}, "always_create": {"required": False, "type": "boolean"}, "always_create_table": {"required": False, "type": "boolean"}, "always_create_schema": {"required": False, "type": "boolean"}, "always_create_objects": {"required": False, "type": "boolean"}, "destructive_create_table": {"required": False, "type": "boolean"}, "paths": { "type": "dict", "required": False, "schema": { "profile_dir": {"required": False, "type": "string"}, "sheet_config_dir": {"required": False, "type": "string"}, }, }, }
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def removeZeroSumSublists(self, head: ListNode) -> ListNode: ptr = ListNode(-1) ptr.next = head current = head head = ptr while head: s = 0 while current: s += current.val if s == 0: head.next = current.next current = current.next head = head.next if head: current = head.next return ptr.next
#!/usr/bin/env python """ Library of functions to help output data in reStructuredText format """ ## functions def print_rest_table_contents(columns,items,withTrailing=True): """ function needs to be turned into a class """ row = "+" head = "+" for col in columns: row += "-"*col+"-+" head += "="*col+"=+" if len(columns) != len(items): raise Exception("Dimension mismatch %s %s"%(len(columns),len(items))) toPrint = "| " for i,item in enumerate(items): item = str(item) if len(item) >= columns[i]: raise Exception("col %s not large enough min = %s"%(i,len(item)+2)) toPrint += item+" "*(columns[i]-len(item))+"| " print(toPrint[:-1]) if withTrailing: print(row)
add_library('opencv_processing') src = loadImage("test.jpg") size(src.width, src.height, P2D) opencv = OpenCV(this, src) opencv.findCannyEdges(20, 75) canny = opencv.getSnapshot() opencv.loadImage(src) opencv.findScharrEdges(OpenCV.HORIZONTAL) scharr = opencv.getSnapshot() opencv.loadImage(src) opencv.findSobelEdges(1, 0) sobel = opencv.getSnapshot() with pushMatrix(): scale(0.5) image(src, 0, 0) image(canny, src.width, 0) image(scharr, 0, src.height) image(sobel, src.width, src.height) text("Source", 10, 25) text("Canny", src.width / 2 + 10, 25) text("Scharr", 10, src.height / 2 + 25) text("Sobel", src.width / 2 + 10, src.height / 2 + 25)
# # PySNMP MIB module RAPID-HA-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RAPID-HA-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:51:59 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ConstraintsIntersection, SingleValueConstraint, ValueSizeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsUnion") rapidstream, = mibBuilder.importSymbols("RAPID-MIB", "rapidstream") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") MibIdentifier, Bits, Integer32, Unsigned32, NotificationType, enterprises, Counter64, iso, Counter32, ModuleIdentity, TimeTicks, IpAddress, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, Gauge32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "Bits", "Integer32", "Unsigned32", "NotificationType", "enterprises", "Counter64", "iso", "Counter32", "ModuleIdentity", "TimeTicks", "IpAddress", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "Gauge32") DateAndTime, TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "DateAndTime", "TextualConvention", "DisplayString") rsInfoModule = ModuleIdentity((1, 3, 6, 1, 4, 1, 4355, 6)) rsInfoModule.setRevisions(('2002-11-01 12:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: rsInfoModule.setRevisionsDescriptions(('Initial revision.',)) if mibBuilder.loadTexts: rsInfoModule.setLastUpdated('0211011200Z') if mibBuilder.loadTexts: rsInfoModule.setOrganization('WatchGuard Technologies, Inc.') if mibBuilder.loadTexts: rsInfoModule.setContactInfo(' Ella Yu WatchGuard Technologies, Inc. 1841 Zanker Road San Jose, CA 95112 USA 408-519-4888 ella.yu@watchguard.com ') if mibBuilder.loadTexts: rsInfoModule.setDescription('The MIB module describes general information of RapidStream system. Mainly, the information obtained from this MIB is used by rsInfoSystemMIB, rsClientMIB, rsSystemStatisticsMIB, rsIpsecTunnelMIB, rsHAMIB.') rsHAMIB = ObjectIdentity((1, 3, 6, 1, 4, 1, 4355, 6, 6)) if mibBuilder.loadTexts: rsHAMIB.setStatus('current') if mibBuilder.loadTexts: rsHAMIB.setDescription('This is the base object identifier for all HA related branches.') rsHALocal = ObjectIdentity((1, 3, 6, 1, 4, 1, 4355, 6, 6, 1)) if mibBuilder.loadTexts: rsHALocal.setStatus('current') if mibBuilder.loadTexts: rsHALocal.setDescription('This is the base object identifier for all objects which are belong to local appliance.') rsHAPeer = ObjectIdentity((1, 3, 6, 1, 4, 1, 4355, 6, 6, 2)) if mibBuilder.loadTexts: rsHAPeer.setStatus('current') if mibBuilder.loadTexts: rsHAPeer.setDescription('This is the base object identifier for all objects which are belong to peer appliance.') rsHAStatus = MibScalar((1, 3, 6, 1, 4, 1, 4355, 6, 6, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11))).clone(namedValues=NamedValues(("disabled", 0), ("unknown", 1), ("as-primary-active", 2), ("as-secondary-active", 3), ("aa-primary-ative", 4), ("aa-secondary-active", 5), ("aa-primary-takeover", 6), ("aa-secondary-takeover", 7), ("standby", 8), ("admin", 9), ("failed", 10), ("unavailable", 11)))).setMaxAccess("readonly") if mibBuilder.loadTexts: rsHAStatus.setStatus('current') if mibBuilder.loadTexts: rsHAStatus.setDescription("Indicates current status of local appliance. disabled: The local appliance of HA system is not enabled. unknown: The local appliance of HA system is in initialization as-primary-active: The local appliance that is the primary appliance of HA/AS system is in active mode. This status is also called MASTER in some systems. as-secondary-active: The local appliance that is the secondary appliance of HA/AS system is in active mode. This status is also called BACKUP in some systems. aa-primary-ative: The local appliance that is the primary appliance of HA/AA system is in active mode. aa-secondary-active: The local appliance that is the secondary appliance of HA/AA system is in active mode. aa-primary-takeover: The local appliance that is the primary appliance of HA/AA system has taken over the peer's duty. aa-secondary-takeover: The local appliance of the secondary appliance of HA/AA system has taken over the peer's duty. standby: The local appliance of HA/AS system is in standby mode. admin: The local appliance of HA system detects an mismatched configuration and waits for system administrator to reslove the conflict. failed: The local appliance of the HA system is down due to forced failover or other reasons. unavailable: It's reported when local appliance of HA system is unabled to get status information. ") rsHAPeerStatus = MibScalar((1, 3, 6, 1, 4, 1, 4355, 6, 6, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("unavailable", 0), ("active", 1), ("standby", 2), ("admin", 3), ("failed", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: rsHAPeerStatus.setStatus('current') if mibBuilder.loadTexts: rsHAPeerStatus.setDescription("Indicates current status of peer appliance. unavailable: It's reported when peer appliance of HA system is unabled to get status information. active: The peer applicance of HA system is in active mode. standby: The peer applicance of HA system is in standby mode. admin: The peer applicance of HA system dectects an mismatched configuration and waits for system administrator to reslove the conflict. failed: The peer appliance of HA system is down due to forced failover or other reasons. ") rsHALastDBSyncTime = MibScalar((1, 3, 6, 1, 4, 1, 4355, 6, 6, 1, 3), DateAndTime()).setMaxAccess("readonly") if mibBuilder.loadTexts: rsHALastDBSyncTime.setStatus('current') if mibBuilder.loadTexts: rsHALastDBSyncTime.setDescription('The last DB synchronized time of local appliance.') rsHAError = MibScalar((1, 3, 6, 1, 4, 1, 4355, 6, 6, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14))).clone(namedValues=NamedValues(("no-error", 0), ("mismatched-ha-id", 1), ("mismatched-software", 2), ("mismatched-database", 3), ("mismatched-hardware", 4), ("forced-fail", 5), ("invalid-ha-role", 6), ("link-down", 7), ("lost-mia-heartbeat", 8), ("mia-not-responding", 9), ("admin-command-failed", 10), ("detect-ha-error", 11), ("unavailable", 12), ("hotsync-failed", 13), ("config-sync-failed", 14)))).setMaxAccess("readonly") if mibBuilder.loadTexts: rsHAError.setStatus('current') if mibBuilder.loadTexts: rsHAError.setDescription('Reports the current error that occurred in local appliance .') rsHAPeerError = MibScalar((1, 3, 6, 1, 4, 1, 4355, 6, 6, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14))).clone(namedValues=NamedValues(("no-error", 0), ("mismatched-ha-id", 1), ("mismatched-software", 2), ("mismatched-database", 3), ("mismatched-hardware", 4), ("forced-fail", 5), ("invalid-ha-role", 6), ("link-down", 7), ("lost-mia-heartbeat", 8), ("mia-not-responding", 9), ("admin-command-failed", 10), ("detect-ha-error", 11), ("unavailable", 12), ("hotsync-failed", 13), ("config-sync-failed", 14)))).setMaxAccess("readonly") if mibBuilder.loadTexts: rsHAPeerError.setStatus('current') if mibBuilder.loadTexts: rsHAPeerError.setDescription('Reports the current error that occurred in peer appliance.') rsHAPeerSerialNumber = MibScalar((1, 3, 6, 1, 4, 1, 4355, 6, 6, 2, 1), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: rsHAPeerSerialNumber.setStatus('current') if mibBuilder.loadTexts: rsHAPeerSerialNumber.setDescription('The serial number of peer appliance.') rsHAPeerLastDBSyncTime = MibScalar((1, 3, 6, 1, 4, 1, 4355, 6, 6, 2, 2), DateAndTime()).setMaxAccess("readonly") if mibBuilder.loadTexts: rsHAPeerLastDBSyncTime.setStatus('current') if mibBuilder.loadTexts: rsHAPeerLastDBSyncTime.setDescription('The last DB synchronized time of peer appliance.') rsHAPeerDevice = ObjectIdentity((1, 3, 6, 1, 4, 1, 4355, 6, 6, 2, 3)) if mibBuilder.loadTexts: rsHAPeerDevice.setStatus('current') if mibBuilder.loadTexts: rsHAPeerDevice.setDescription('This is the base object for parameters and configuration data of devices in this entity.') rsHAPeerCounters = ObjectIdentity((1, 3, 6, 1, 4, 1, 4355, 6, 6, 2, 4)) if mibBuilder.loadTexts: rsHAPeerCounters.setStatus('current') if mibBuilder.loadTexts: rsHAPeerCounters.setDescription('This is the base object for parameters and configuration data of devices in this entity.') rsHAPeerIfNumber = MibScalar((1, 3, 6, 1, 4, 1, 4355, 6, 6, 2, 3, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rsHAPeerIfNumber.setStatus('current') if mibBuilder.loadTexts: rsHAPeerIfNumber.setDescription('The number of RapidCard installed in this entity.') rsHAPeerIfTable = MibTable((1, 3, 6, 1, 4, 1, 4355, 6, 6, 2, 3, 2), ) if mibBuilder.loadTexts: rsHAPeerIfTable.setStatus('current') if mibBuilder.loadTexts: rsHAPeerIfTable.setDescription('A list of RapidCard entries. The number of entries is given by the value of rsHAPeerDeviceNumber.') rsHAPeerIfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4355, 6, 6, 2, 3, 2, 1), ).setIndexNames((0, "RAPID-HA-MIB", "rsHAPeerIfIndex")) if mibBuilder.loadTexts: rsHAPeerIfEntry.setStatus('current') if mibBuilder.loadTexts: rsHAPeerIfEntry.setDescription('A RapidCard entry containing objects for a particular RapidCard.') rsHAPeerIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 4355, 6, 6, 2, 3, 2, 1, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rsHAPeerIfIndex.setStatus('current') if mibBuilder.loadTexts: rsHAPeerIfIndex.setDescription('The unique value for each interface.') rsHAPeerIfIpAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 4355, 6, 6, 2, 3, 2, 1, 4), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: rsHAPeerIfIpAddr.setStatus('current') if mibBuilder.loadTexts: rsHAPeerIfIpAddr.setDescription('The ip address of the interface.') rsHAPeerIfLinkStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 4355, 6, 6, 2, 3, 2, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("down", 0), ("up", 1), ("other", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: rsHAPeerIfLinkStatus.setStatus('current') if mibBuilder.loadTexts: rsHAPeerIfLinkStatus.setDescription('The current state of the interface.') rsHAPeerSystemCpuUtil = MibScalar((1, 3, 6, 1, 4, 1, 4355, 6, 6, 2, 4, 1), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rsHAPeerSystemCpuUtil.setStatus('current') if mibBuilder.loadTexts: rsHAPeerSystemCpuUtil.setDescription('The CPU utilization of the peer system in last 5 seconds.') rsHAPeerSystemTotalSendBytes = MibScalar((1, 3, 6, 1, 4, 1, 4355, 6, 6, 2, 4, 2), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: rsHAPeerSystemTotalSendBytes.setStatus('current') if mibBuilder.loadTexts: rsHAPeerSystemTotalSendBytes.setDescription('The total number of bytes sent since peer system is up.') rsHAPeerSystemTotalRecvBytes = MibScalar((1, 3, 6, 1, 4, 1, 4355, 6, 6, 2, 4, 3), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: rsHAPeerSystemTotalRecvBytes.setStatus('current') if mibBuilder.loadTexts: rsHAPeerSystemTotalRecvBytes.setDescription('The total number of bytes received since peer system is up.') rsHAPeerSystemTotalSendPackets = MibScalar((1, 3, 6, 1, 4, 1, 4355, 6, 6, 2, 4, 4), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: rsHAPeerSystemTotalSendPackets.setStatus('current') if mibBuilder.loadTexts: rsHAPeerSystemTotalSendPackets.setDescription('The total number of packets sent since peer system is up.') rsHAPeerSystemTotalRecvPackets = MibScalar((1, 3, 6, 1, 4, 1, 4355, 6, 6, 2, 4, 5), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: rsHAPeerSystemTotalRecvPackets.setStatus('current') if mibBuilder.loadTexts: rsHAPeerSystemTotalRecvPackets.setDescription('The total number of packets received since peer system is up.') rsHAPeerSystemStreamReqTotal = MibScalar((1, 3, 6, 1, 4, 1, 4355, 6, 6, 2, 4, 6), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: rsHAPeerSystemStreamReqTotal.setStatus('current') if mibBuilder.loadTexts: rsHAPeerSystemStreamReqTotal.setDescription('The total number of the connection requests since system is up.') rsHAPeerSystemStreamReqDrop = MibScalar((1, 3, 6, 1, 4, 1, 4355, 6, 6, 2, 4, 7), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: rsHAPeerSystemStreamReqDrop.setStatus('current') if mibBuilder.loadTexts: rsHAPeerSystemStreamReqDrop.setDescription('The total number of the connection requests being dropped since system is up.') rsHAPeerSystemCurrIpsecTunnels = MibScalar((1, 3, 6, 1, 4, 1, 4355, 6, 6, 2, 4, 8), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: rsHAPeerSystemCurrIpsecTunnels.setStatus('current') if mibBuilder.loadTexts: rsHAPeerSystemCurrIpsecTunnels.setDescription('The number of ipsec tunnels in the peer system currently.') rsHAPeerSystemCpuUtil1 = MibScalar((1, 3, 6, 1, 4, 1, 4355, 6, 6, 2, 4, 9), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rsHAPeerSystemCpuUtil1.setStatus('current') if mibBuilder.loadTexts: rsHAPeerSystemCpuUtil1.setDescription('The CPU utilization of the peer system in last 1 minute.') rsHAPeerSystemCpuUtil5 = MibScalar((1, 3, 6, 1, 4, 1, 4355, 6, 6, 2, 4, 10), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rsHAPeerSystemCpuUtil5.setStatus('current') if mibBuilder.loadTexts: rsHAPeerSystemCpuUtil5.setDescription('The CPU utilization of the peer system in last 5 minutes.') rsHAPeerSystemCpuUtil15 = MibScalar((1, 3, 6, 1, 4, 1, 4355, 6, 6, 2, 4, 11), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rsHAPeerSystemCpuUtil15.setStatus('current') if mibBuilder.loadTexts: rsHAPeerSystemCpuUtil15.setDescription('The CPU utilization of the peer system in last 15 minutes.') mibBuilder.exportSymbols("RAPID-HA-MIB", rsHAPeerIfNumber=rsHAPeerIfNumber, rsHALocal=rsHALocal, rsHAPeerIfIndex=rsHAPeerIfIndex, rsHAError=rsHAError, rsHAPeerLastDBSyncTime=rsHAPeerLastDBSyncTime, rsInfoModule=rsInfoModule, rsHALastDBSyncTime=rsHALastDBSyncTime, rsHAPeerDevice=rsHAPeerDevice, rsHAPeerSystemStreamReqTotal=rsHAPeerSystemStreamReqTotal, rsHAPeerSystemCpuUtil1=rsHAPeerSystemCpuUtil1, rsHAPeerSystemCpuUtil5=rsHAPeerSystemCpuUtil5, rsHAPeerSystemCpuUtil=rsHAPeerSystemCpuUtil, rsHAPeerStatus=rsHAPeerStatus, rsHAPeer=rsHAPeer, rsHAPeerSystemCurrIpsecTunnels=rsHAPeerSystemCurrIpsecTunnels, rsHAMIB=rsHAMIB, rsHAPeerSystemTotalSendBytes=rsHAPeerSystemTotalSendBytes, rsHAPeerCounters=rsHAPeerCounters, rsHAPeerIfIpAddr=rsHAPeerIfIpAddr, rsHAPeerIfEntry=rsHAPeerIfEntry, rsHAStatus=rsHAStatus, rsHAPeerError=rsHAPeerError, rsHAPeerIfLinkStatus=rsHAPeerIfLinkStatus, PYSNMP_MODULE_ID=rsInfoModule, rsHAPeerSystemCpuUtil15=rsHAPeerSystemCpuUtil15, rsHAPeerSystemTotalRecvBytes=rsHAPeerSystemTotalRecvBytes, rsHAPeerSystemStreamReqDrop=rsHAPeerSystemStreamReqDrop, rsHAPeerSerialNumber=rsHAPeerSerialNumber, rsHAPeerSystemTotalSendPackets=rsHAPeerSystemTotalSendPackets, rsHAPeerSystemTotalRecvPackets=rsHAPeerSystemTotalRecvPackets, rsHAPeerIfTable=rsHAPeerIfTable)
test = { 'name': 'q1c', 'points': 3, 'suites': [ { 'cases': [ { 'code': r""" >>> manhattan_taxi.shape (82800, 9) """, 'hidden': False, 'locked': False }, { 'code': r""" >>> sum(manhattan_taxi['duration']) 54551565 """, 'hidden': False, 'locked': False }, { 'code': r""" >>> manhattan_taxi.iloc[0,:]['duration'] 981 """, 'hidden': False, 'locked': False } ], 'scored': True, 'setup': '', 'teardown': '', 'type': 'doctest' } ] }
# Ex056.2 """Develop a program that reads the name, age and sex of for people. At the end of the program, show: The average age of the group, What's the name of the older man, How many women are under 20""" total_age = 0 older_man = 0 name_over_man = '' women20_cont = 0 for n in range(1, 4 + 1): print(f'\033[32mPerson number {n}\033[m') name = str(input('What is the name?: ')).title() age = int(input('What is the age?: ')) sex = str(input('What is the sex? [M /F]: ')).upper() total_age += age if sex == 'M' and age > older_man: older_man = age name_older_man = name if sex == 'F' and age < 20: women20_cont += 1 print('\033[31m-\033[m' * 30) average_age = total_age / 4 print(f'The average age of the group is \033[32m{average_age}\033[m') print(f'The name of the older man is \033[32m{name_older_man}\033[m with \033[32m{older_man}\033[m years old') print(f'Women under 20: \033[32m{women20_cont}\033[m')
# -*- encoding: utf-8 -*- # auto-learner v0.1.0 # my machine learning project # Copyright © 2018, Arash Eghtesadi. # See /LICENSE for licensing information. """ Main routine of auto-learner. :Copyright: © 2018, Arash Eghtesadi. :License: BSD (see /LICENSE). """ __all__ = ('main',) def main(): """Main routine of auto-learner.""" print("Hello, world!") print("This is auto-learner.") print("You should customize __main__.py to your liking (or delete it).") if __name__ == '__main__': main()
def get_date_from_zip(zip_name: str) -> str: """ Helper function to parse a date from a ROM zip's name """ return zip_name.split("-")[-1].split(".")[0] def get_metadata_from_zip(zip_name: str) -> (str, str, str, str): """ Helper function to parse some data from ROM zip's name """ data = zip_name.replace(".zip", "").split("-") return data[1], data[2], data[3], data[4]
filt_dict = { 'db': [['Emissions', '(Kyoto Gases|co2)$', '(|Energy and Industrial Processes|AFOLU)$', '', '(world|r5.*)'], ['Policy cost', '(Additional Total Energy System Cost|consumption Loss|gdp Loss)', '', '', '(world|r5.*)'], ['Price', 'Carbon', '$', '', '(world|r5.*)'], ], }
# https://leetcode.com/problems/insert-interval/ # Given a set of non-overlapping intervals, insert a new interval into the # intervals (merge if necessary). # You may assume that the intervals were initially sorted according to their start # times. ################################################################################ # loop over intervals -> merge with newIntercal if overlap # append to ans if no overlap class Solution: def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: if not intervals: return [newInterval] ans = [] inserted = False for interval in intervals: if interval[1] < newInterval[0]: # no overlap ans.append(interval) elif interval[0] > newInterval[1]: # no overlap if not inserted: ans.append(newInterval) inserted = True ans.append(interval) else: # overlap, merge intervals newInterval[0] = min(newInterval[0], interval[0]) newInterval[1] = max(newInterval[1], interval[1]) if not inserted: ans.append(newInterval) return ans
#!/usr/bin/env python3 def merge(L1, L2): L3 = L1+L2 for j in range(len(L3)): for i in range(0, len(L3)-j-1): if L3[i]> L3[i+1]: L3[i],L3[i+1] = L3[i+1] , L3[i] return (L3) def main(): print((merge([1,2,3],[1,6,7]))) pass if __name__ == "__main__": main()
class ControllerBase: @staticmethod def base(): return True
__author__ = 'fatih' class SQL(): """ This class includes all using database commands such as insert, remove, select etc. Only need to do is you will write your sql command and format it into running command by given values """ #insert commands SQL_INSERT_CONFIG = "INSERT INTO apc_config(name, description, ip, radius_config_id, ssid, vlan_id, channel, channel_freq, date_added, date_modified) "\ "VALUES('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}') RETURNING id;" #(config_name, description, ip, radius_config_id, ssid, vlan_id, channel, channel_freq, date_added, date_modified) SQL_INSERT_DEVICE = "INSERT INTO apc_device(name, ip, config_id, username, password, date_added, date_modified) "\ "VALUES('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}') RETURNING id;" #(nick, ip, config_id, username, password, date_added, date_modified) SQL_INSERT_GROUP = "INSERT INTO apc_groups(name, config_id) VALUES('{0}','{1}') RETURNING id;" #insert group to the database SQL_INSERT_VLAN_CONFIG = "INSERT INTO apc_vlan(name, ip, subnet, number, interface) " \ "VALUES('{0}','{1}','{2}','{3}','{4}')" #insert vlan config values to the database #remove commands SQL_REMOVE_CONFIG = "DELETE FROM apc_config WHERE name = '{0}';" SQL_REMOVE_DEVICE = "DELETE FROM apc_device WHERE name = '{0}' AND id = {1};" SQL_REMOVE_GROUP = "DELETE FROM apc_groups WHERE name = '{0}' AND id = {1};" SQL_REMOVE_VLAN = "DELETE FROM apc_vlan WHERE name = '{0}' AND id = {1};" SQL_REMOVE_DEVICE_FROM_GROUP = "DELETE FROM apc_device_group WHERE device_id = {0} AND group_id = {1};" #select queries #select device records SQL_SELECT_DEVICE = "SELECT * FROM apc_device d WHERE d.name IS NOT NULL AND d.id = {0};" SQL_SELECT_DEVICE_CONFIG = "SELECT * FROM apc_device d LEFT JOIN apc_config c ON d.config_id = c.id WHERE d.id = {0};" SQL_SELECT_DEVICE_ALL = "SELECT * FROM apc_device AS d WHERE d.name IS NOT NULL ORDER BY DATE(date_added) ASC;" #select config records SQL_SELECT_CONFIG = "SELECT * FROM apc_config c WHERE c.name IS NOT NULL ORDER BY date_added ASC;" SQL_SELECT_CONFIG_DETAIL = "SELECT * FROM apc_config AS c WHERE c.name IS NOT NULL AND c.name IS '{0}';" SQL_SELECT_GROUP_DETAIL = "SELECT * FROM apc_groups g WHERE g.name IS NOT NULL AND g.id = {0};" SQL_SELECT_GROUP_ALL = "SELECT * FROM apc_groups d WHERE d.name IS NOT NULL ORDER BY date_added ASC;" SQL_SELECT_GROUP_DEVICE = "SELECT * FROM apc_device d LEFT JOIN apc_group g ON d.config_id = g.id WHERE d.id = {0};" SQL_SELECT_VLAN = "SELECT * FROM apc_vlan v WHERE v.id IS NOT NULL ORDER BY date_added ASC;" SQL_SELECT_VLAN_DETAIL = "SELECT * FROM apc_config AS c WHERE c.name IS NOT NULL AND c.name IS '{0}';"
''' You are given an array of length n which only contains the elements 0,1 and 2. You are supposed to sort the array in ascending order without the use of any sorting algorithms. Minimize time complexity. Input Format: The first line of input contains the value of n i.e. size of array. The next line contains n space separated integers, each representing an element of the array (0/1/2) Output Format: Print the sorted array as n space separated integers. Constraints: All array elements and n are within integer value limits. Example input: 8 1 0 2 1 2 1 0 0 Example output: [0, 0, 0, 1, 1, 1, 2, 2] Explanation: There are 3 zeroes, 3 ones and 2 twos. Sorted array is printed as space separated integers. ********************************************************************************************************************* ''' #Solution presented here has a time complexity of O(n) and uses a dictionary def arraySort(n, array): mappings = {0:0, 1:0, 2:0} for element in array: count = mappings.get(element) count = count+1 mappings.update({element:count}) arrayIndex = 0 count = mappings.get(0) for i in range(0, count): array[arrayIndex]=0 arrayIndex = arrayIndex+1 count = mappings.get(1) for i in range(0, count): array[arrayIndex]=1 arrayIndex = arrayIndex+1 count = mappings.get(2) for i in range(0, count): array[arrayIndex]=2 arrayIndex = arrayIndex+1 return array #Take input and call the function n = int(input()) array = [int(item) for item in input().split(' ')] array = arraySort(n, array) print(array)
""" author: Akshay Chawla (https://github.com/akshaychawla) TEST:rs Test convert.py's ability to handle Deconvolution and Crop laye by converting voc-fcn8s .prototxt and .caffemodel present in the caffe/models/segmentation folder """ # import os # import inspect # import numpy as np # import keras.caffe.convert as convert # from scipy import misc # import matplotlib.pyplot as plt # from subprocess import call # check whether files are present in folder """ path = os.path.dirname(inspect.getfile(inspect.currentframe())) assert os.path.exists(path + "/deploy.prototxt"), "Err. Couldn't find the debug.prototxt file" assert os.path.exists(path + "/horse.png"), "Err. Couldn't find the horse.png image file" if not os.path.exists(path + "/fcn8s-heavy-pascal.caffemodel"): call(["wget http://dl.caffe.berkeleyvision.org/fcn8s-heavy-pascal.caffemodel -O " + "./" + path + "/fcn8s-heavy-pascal.caffemodel"], shell=True) assert os.path.exists(path + "/fcn8s-heavy-pascal.caffemodel"), "Err. Cannot find .caffemodel file. \ please download file using command : wget http://dl.caffe.berkeleyvision.org/fcn8s-heavy-pascal.caffemodel " model = convert.caffe_to_keras(path + "/deploy.prototxt", path + "/fcn8s-heavy-pascal.caffemodel", debug=1) print ("Yay!") # 1. load image img = misc.imread(path + "/horse.png") # modify it img = np.rollaxis(img, 2) img = np.expand_dims(img, 0) # 2. run forward pass op = model.predict(img) # 3. reshape output op = op[0] op = op.reshape((500, 500, 21)) op_arg = np.argmax(op, axis=2) # 4. plot output plt.imshow(op_arg) plt.show() print ("..done") """
class BlocoMemoria: palavra: list endBlock: int atualizado: bool custo: int cacheHit: int ultimoUso: int def __init__(self): self.endBlock = -1 self.atualizado = False self.custo = 0 self.cacheHit = 0 ultimoUso: 2**31-1
AzToolchainInfo = provider( doc = "Azure toolchain rule parameters", fields = [ "az_tool_path", "az_tool_target", "azure_extension_dir", "az_extensions_installed", "jq_tool_path", ], ) AzConfigInfo = provider( fields = [ "debug", "global_args", "subscription", "verbose" ], )
# Copyright 2018- The Pixie Authors. # # 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. # # SPDX-License-Identifier: Apache-2.0 def _fetch_licenses_impl(ctx): args = ctx.actions.args() args.add("--github_token", ctx.file.oauth_token) args.add("--modules", ctx.file.src) if ctx.attr.use_pkg_dev_go: args.add("--try_pkg_dev_go") if ctx.attr.disallow_missing: args.add("--fatal_if_missing") args.add("--json_manual_input", ctx.file.manual_licenses) args.add("--json_output", ctx.outputs.out_found) args.add("--json_missing_output", ctx.outputs.out_missing) ctx.actions.run( executable = ctx.file.fetch_tool, inputs = [ctx.file.src, ctx.file.oauth_token, ctx.file.manual_licenses], outputs = [ctx.outputs.out_found, ctx.outputs.out_missing], arguments = [args], progress_message = "Fetching licenses %s" % ctx.outputs.out_found, ) fetch_licenses = rule( implementation = _fetch_licenses_impl, attrs = dict({ "disallow_missing": attr.bool(), "fetch_tool": attr.label(mandatory = True, allow_single_file = True), "manual_licenses": attr.label(mandatory = True, allow_single_file = True), "oauth_token": attr.label(mandatory = True, allow_single_file = True), "out_found": attr.output(mandatory = True), "out_missing": attr.output(), "src": attr.label(mandatory = True, allow_single_file = True), "use_pkg_dev_go": attr.bool(), }), )
package(default_visibility = [ "//visibility:public" ]) load("@io_bazel_rules_dotnet//dotnet:defs.bzl", "net_import_library", "core_import_library") net_import_library( name = "net45", src = "lib/netstandard1.0/System.Threading.Tasks.Extensions.dll", ) core_import_library( name = "netcore", src = "lib/netstandard2.0/System.Threading.Tasks.Extensions.dll" )
class Solution: def repeatedStringMatch(self, A: str, B: str) -> int: if B in A: return 0 counter = 1 repeatedA = A while len(repeatedA) < len(B)*2: repeatedA += A if B in repeatedA: return counter counter += 1 return -1 a = 'abc' b = 'abcs' if find('c', a): print('yes') else: print('no') # print(not a.index('s'))
# File03.py user = 'Ali' f1 = open('./Users/users01.txt', mode = 'a+', encoding = 'cp949') # a+ : 읽기와 쓰기 같이 users1 = f1.write('\n' + user) f1.seek(0) # 커서의 위치변경 users1 = f1.read() print("닫힘" if f1.closed else "안닫힘") f1.close() print("닫힘" if f1.closed else "안닫힘") print(users1)
WIDTH = 50 HEIGHT = 10 MAX_WIDTH = WIDTH - 2 MAX_HEIGHT = HEIGHT - 2
# coding: utf-8 class CorpusInterface(object): def load_corpus(self, corpus): pass def read_corpus(self, filename): pass class Corpus(object): def load_corpus(self, corpus): raise NotImplementedError() def read_corpus(self, filename): raise NotImplementedError()
x = int(input()) for i in range(1, 11): resultado = i * x print("{} x {} = {}".format(i, x, resultado))
patches = [ # Rename AWS::Lightsail::Instance.Disk to AWS::Lightsail::Instance.DiskProperty { "op": "move", "from": "/PropertyTypes/AWS::Lightsail::Instance.Disk", "path": "/PropertyTypes/AWS::Lightsail::Instance.DiskProperty", }, { "op": "replace", "path": "/PropertyTypes/AWS::Lightsail::Instance.Hardware/Properties/Disks/ItemType", "value": "DiskProperty", }, # Remove Location and State attribute properties { "op": "remove", "path": "/PropertyTypes/AWS::Lightsail::Instance.Location", }, { "op": "remove", "path": "/PropertyTypes/AWS::Lightsail::Instance.State", }, ]
maximum = float("-inf") def max_path_sum(root): helper(root) return maximum def helper(root): if not root: return 0 left = helper(root.left) right = helper(root.right) maximum = max(maximum, left+right+root.val) return root.val + max(left, right)
fruit = input() size_set = input() count_sets = float(input()) price_set = 0 if fruit == 'Watermelon': if size_set == 'small': price_set = count_sets * 56 * 2 elif size_set == 'big': price_set = count_sets * 28.7 * 5 elif fruit == 'Mango': if size_set == 'small': price_set = count_sets * 36.66 * 2 elif size_set == 'big': price_set = count_sets * 19.60 * 5 elif fruit == 'Pineapple': if size_set == 'small': price_set = count_sets * 42.1 * 2 elif size_set == 'big': price_set = count_sets * 24.8 * 5 elif fruit == 'Raspberry': if size_set == 'small': price_set = count_sets * 20 * 2 elif size_set == 'big': price_set = count_sets * 15.2 * 5 if 400 <= price_set <= 1000: price_set = price_set * 0.85 elif price_set > 1000: price_set = price_set * 0.5 print(f'{price_set:.2f} lv.')
def test_socfaker_timestamp_in_the_past(socfaker_fixture): assert socfaker_fixture.timestamp.in_the_past() def test_socfaker_timestamp_in_the_future(socfaker_fixture): assert socfaker_fixture.timestamp.in_the_future() def test_socfaker_timestamp_current(socfaker_fixture): assert socfaker_fixture.timestamp.current def test_socfaker_timestamp_date_string(socfaker_fixture): assert socfaker_fixture.timestamp.date_string
""" NewsTrader - a framework of news trading for individual investors This package is inspired by many other awesome Python packages """ # Shortcuts for key modules or functions __VERSION__ = "0.0.1"
releases = [ { "ocid": "A", "id": "1", "date": "2014-01-01", "tag": ["tender"], "tender": { "items": [ { "id": "1", "description": "Item 1", "quantity": 1 }, { "id": "2", "description": "Item 2", "quantity": 1 } ] } }, { "ocid": "A", "id": "2", "date": "2014-01-02", "tag": ["tender"], "tender": { "items": [ { "id": "1", "description": "Item 1", "quantity": 2 }, { "id": "3", "description": "Item 3", "quantity": 1 } ] } } ] compiledRelease = { "ocid": "A", "id": "2", "date": "2014-01-02", "tag": ["compiled"], "tender": { "items": [ { "id": "1", "description": "Item 1", "quantity": 2 }, { "id": "2", "description": "Item 2", "quantity": 1 }, { "id": "3", "description": "Item 3", "quantity": 1 } ] } } versionedRelease = { "ocid": "A", "tender": { "items": [ { "id": "1", "description": [ { "value": "Item 1", "releaseDate": "2014-01-01", "releaseTag": ["tender"], "releaseID": "1" } ], "quantity": [ { "value": 1, "releaseDate": "2014-01-01", "releaseTag": ["tender"], "releaseID": "1" }, { "value": 2, "releaseDate": "2014-01-02", "releaseTag": ["tender"], "releaseID": "2" } ] }, { "id": "2", "description": [ { "value": "Item 2", "releaseDate": "2014-01-01", "releaseTag": ["tender"], "releaseID": "1" } ], "quantity": [ { "value": 1, "releaseDate": "2014-01-01", "releaseTag": ["tender"], "releaseID": "1" }, ] }, { "id": "3", "description": [ { "value": "Item 3", "releaseDate": "2014-01-02", "releaseTag": ["tender"], "releaseID": "2" } ], "quantity": [ { "value": 1, "releaseDate": "2014-01-02", "releaseTag": ["tender"], "releaseID": "2" }, ] } ] } }
# -*- coding: utf-8 -*- """ exceptions.py Exceptions raised by the Kite Connect client. :copyright: (c) 2017 by Zerodha Technology. :license: see LICENSE for details. """ class KiteException(Exception): """ Base exception class representing a Kite client exception. Every specific Kite client exception is a subclass of this and exposes two instance variables `.code` (HTTP error code) and `.message` (error text). """ def __init__(self, message, code=500): """Initialize the exception.""" super(KiteException, self).__init__(message) self.code = code class GeneralException(KiteException): """An unclassified, general error. Default code is 500.""" def __init__(self, message, code=500): """Initialize the exception.""" super(GeneralException, self).__init__(message, code) class TokenException(KiteException): """Represents all token and authentication related errors. Default code is 403.""" def __init__(self, message, code=403): """Initialize the exception.""" super(TokenException, self).__init__(message, code) class PermissionException(KiteException): """Represents permission denied exceptions for certain calls. Default code is 403.""" def __init__(self, message, code=403): """Initialize the exception.""" super(PermissionException, self).__init__(message, code) class OrderException(KiteException): """Represents all order placement and manipulation errors. Default code is 500.""" def __init__(self, message, code=500): """Initialize the exception.""" super(OrderException, self).__init__(message, code) class InputException(KiteException): """Represents user input errors such as missing and invalid parameters. Default code is 400.""" def __init__(self, message, code=400): """Initialize the exception.""" super(InputException, self).__init__(message, code) class DataException(KiteException): """Represents a bad response from the backend Order Management System (OMS). Default code is 502.""" def __init__(self, message, code=502): """Initialize the exception.""" super(DataException, self).__init__(message, code) class NetworkException(KiteException): """Represents a network issue between Kite and the backend Order Management System (OMS). Default code is 503.""" def __init__(self, message, code=503): """Initialize the exception.""" super(NetworkException, self).__init__(message, code)
__title__ = "PyMatting" __version__ = "1.1.3" __author__ = "The PyMatting Developers" __email__ = "pymatting@gmail.com" __license__ = "MIT" __uri__ = "https://pymatting.github.io" __summary__ = "Python package for alpha matting."
"""Chapter 12 - Be a pythonista""" # vars def dump(func): """Print input arguments and output value(s)""" def wrapped(*args, **kwargs): print("Function name: %s" % func.__name__) print("Input arguments: %s" % ' '.join(map(str, args))) print("Input keyword arguments: %s" % kwargs.items()) output = func(*args, **kwargs) print("Output:", output) return output return wrapped @dump def double(*args, **kwargs): """Double every argument""" output_list = [2 * arg for arg in args] output_dict = {k: 2*v for k, v in kwargs.items()} return output_list, output_dict # pdb def process_cities(filename): with open(filename, 'rt') as file: for line in file: line = line.strip() if 'quit' == line.lower(): return country, city = line.split(',') city = city.strip() country = country.strip() print(city.title(), country.title(), sep=',') def func(*arg, **kwargs): print('vars:', vars()) def main(): """ # working with vars() function func(1, 2, 3) func(['a', 'b', 'argh']) double(3, 5, first=100, next=98.6, last=-40) """ # working with pdb process_cities("cities.csv") if __name__ == '__main__': main()
class Matrix: def __init__(self, mat): l_size = len(mat[0]) for line in mat: if l_size != len(line): raise ValueError('invalid matrix sizes') self._raw = mat @property def raw(self): return self._raw @property def trace(self): if self.size[0] == self.size[1]: return sum([ self[i][j] for j in range(self.size[0]) for i in range(self.size[1]) ]) else: print('nb lines != nb columns') @property def size(self): return self._raw.__len__(), self._raw[0].__len__() def __str__(self): s = "\n" for l in self._raw: s +='| ' for c in l: s += '{:6.2f} '.format( round(float(c), 3)) s += '|\n' return s def __call__(self, index): return self.col(self, index) @classmethod def col(cls, matrix, index, raw = False): col = [ line[index] for line in matrix._raw ] if raw: return col else: return Vector(col) def transpose(self): return Matrix([ self.col(self, i, True) for i in range(self.size[1]) ]) def __setitem__(self, key, item): if not type(item).__name__ == 'list' or len(item) != self.size[0]: print('invalid assignement') else: self._raw[key] = item def __getitem__(self, key): return Vector(self._raw[key], transpose = True) def __add__(self, other): if type(other).__name__ == 'Matrix' or type(other).__name__ == 'Vector': if self.size[0] == other.size[0] and self.size[1] == other.size[1]: return Matrix([ [ self._raw[i][j] + other._raw[i][j] for j in range(self.size[1])] for i in range(self.size[0])]) else: try: return Matrix([ [ self._raw[i][j] + other for j in range(self.size[1])] for i in range(self.size[0])]) except: print('cannot add') def __sub__(self, other): if type(other).__name__ == 'Matrix' or type(other).__name__ == 'Vector': if self.size[0] == other.size[0] and self.size[1] == other.size[1]: return Matrix([ [ self._raw[i][j] - other._raw[i][j] for j in range(self.size[1])] for i in range(self.size[0])]) else: try: return Matrix([ [ self._raw[i][j] - other for j in range(self.size[1])] for i in range(self.size[0])]) except: print('cannot substract') def __mul__(self, other): if type(other).__name__ == 'Matrix' or type(other).__name__ == 'Vector': if self.size[1] == other.size[0]: # nb c == nb l res = [] for i in range(self.size[0]): res += [[]] for j in range(other.size[1]): res[i] += [sum([m*n for m,n in zip(self._raw[i], self.col(other, j, True))])] return Matrix(res) else: try: return Matrix([ [ self[i][j] * other for j in range(self.size[1])] for i in range(self.size[0])]) except: print('cannot substract') @classmethod def gen(cls, l, c, fill = 0): mat = [[fill for j in range(c)] for i in range(l)] return Matrix(mat) class Vector(Matrix): def __init__(self, vect, transpose = False): self.transposed = transpose super().__init__([vect] if transpose else [ [elem] for elem in vect ] ) @property def raw(self): if self.transposed: return self._raw[0] else: return self.col(self, 0, True) @property def gravity(self): return sum(self.raw) / len(self.raw) def __setitem__(self, key, item): if self.transposed: self._raw[0][key] = item else: self._raw[key][0] = item def __getitem__(self, key): if self.transposed: if type(self._raw[0][key]).__name__ == 'list': return Vector(self._raw[0][key]) else: return self._raw[0][key] else: if type(self._raw[key][0]).__name__ == 'list': return Vector(self._raw[key][0]) else: return self._raw[key][0] @classmethod def gen(cls, l, fill = 0): mat = super().gen(l, 1, fill) return mat(0) # ================================================================== # m = [[1,2,3],[4,5,6],[7,8,9]] # mt = Matrix(m) # print(mt) # print(mt.transpose()) # print(mt.trace) # print(mt.size) # mt2 = mt.transpose() # mt3 = Matrix.gen(3,3,9) # print(mt3) # print(mt2 + mt,mt2 - mt, mt2 * mt)
# todo remove in next major release as we no longer support django < 3.2 anyway. Note this would make dj-stripe unuseable for djang0 < 3.2 # for django < 3.2 default_app_config = "djstripe.apps.DjstripeAppConfig"
valores = [] index = 0 for c in range(0, 5): valor = int(input(f'Digite um valor para a posição {index}: ')) valores.append(valor) index += 1 print('-=-' * 15) print(f'Você digitou os valores {valores}.') print(f'O maior valor digitado foi {max(valores)} nas posições ', end='') for i, v in enumerate(valores): if v == max(valores): print(f'{i}', end='.. ') print(f'\nO menor valor digitado foi {min(valores)} na posições ', end='') for i, v in enumerate(valores): if v == min(valores): print(f'{i}', end='.. ') '''Para achar o indice do maior valor poderia ser usado valores.index(max(valores))'''
with open("mynewtextfile.txt","w+") as f: f.writelines("\nOtus we are learning python\nOtus we are learning python\nOtus we are learning python") f.seek(0) print(f.readlines()) print("Is readable:", f.readable()) print("Is writeable:", f.writable()) print("File no:", f.fileno()) print("Is connected to tty-like device:", f.isatty()) f.truncate(20) f.flush() f.seek(0) print(f.readline()) print(f.readline()) print(f.readline()) print(f.readline()) print(f.readline()) f.close()
class Solution: def traverse(self, node: TreeNode, deep: int): if node is None: return deep deep += 1 if node.left is None: return self.traverse(node.right, deep) elif node.right is None: return self.traverse(node.left, deep) else: left_deep = self.traverse(node.left, deep) right_deep = self.traverse(node.right, deep) return min(left_deep, right_deep) def XXX(self, root: TreeNode) -> int: return self.traverse(root, 0)
def rotation_saxs(t = 1): #sample = ['Hopper2_AGIB_AuPd_top', 'Hopper2_AGIB_AuPd_mid', 'Hopper2_AGIB_AuPd_bot'] #Change filename sample = ['AGIB3N_1top', 'AGIB3N_1mid', 'AGIB3N_1cen'] #Change filename #y_list = [-6.06, -6.04, -6.02] #hexapod is in mm #y_list = [-10320, -10300, -10280] #SmarAct is um y_list = [4760, 4810, 4860]#, 5210] #SmarAct is um assert len(y_list) == len(sample), f'Number of X coordinates ({len(x_list)}) is different from number of samples ({len(samples)})' # Detectors, motors: #dets = [pil1M, rayonix, pil300KW] dets = [pil1M, pil300KW] prs_range = [-90, 90, 91] waxs_range = [0, 26, 5] #step of 6.5 degrees det_exposure_time(t,t) #pil_pos_x = [-0.4997, -0.4997 + 4.3, -0.4997 + 4.3, -0.4997] #pil_pos_y = [-59.9987, -59.9987, -59.9987 + 4.3, -59.9987] #waxs_po = np.linspace(20.95, 2.95, 4) for sam, y in zip(sample, y_list): #yield from bps.mv(stage.y, y) #hexapod yield from bps.mv(piezo.y, y) #SmarAct name_fmt = '{sam}' sample_name = name_fmt.format(sam=sam) sample_id(user_name='MK', sample_name=sample_name) print(f'\n\t=== Sample: {sample_name} ===\n') yield from bp.grid_scan(dets, prs, *prs_range, waxs, *waxs_range, 1) sample_id(user_name='test', sample_name='test') det_exposure_time(0.3, 0.3) def rotation_saxs_fast(t = 1): sample = ['AGIB3DR_2fast_top', 'AGIB3DR_2fast_mid', 'AGIB3DR_2fast_cen'] #Change filename y_list = [5150, 5230, 5310] #SmarAct is um assert len(y_list) == len(sample), f'Number of X coordinates ({len(x_list)}) is different from number of samples ({len(samples)})' # Detectors, motors: dets = [pil1M, pil300KW] prs_range = np.linspace(-90, 90, 91) waxs_range = np.linspace(0, 26, 5) det_exposure_time(t,t) for sam, y in zip(sample, y_list): yield from bps.mv(piezo.y, y) for wa in waxs_range: yield from bps.mv(waxs, wa) for pr in prs_range: yield from bps.mv(prs, pr) name_fmt = '{sam}_wa{waxs}deg_{prs}deg' sample_name = name_fmt.format(sam=sam, waxs='%2.1f'%wa, prs='%3.3d'%pr) sample_id(user_name='MK', sample_name=sample_name) print(f'\n\t=== Sample: {sample_name} ===\n') yield from bp.count(dets, num=1) sample_id(user_name='test', sample_name='test') det_exposure_time(0.3, 0.3) def rotation_saxs_att(t = 1): #attenuated WAXS, so SAXS recorded separately first #sample = ['Disc3_AuPd_top-3', 'Disc3_AuPd_mid-3', 'Disc3_AuPd_bot-3'] #Change filename sample = ['Hopper1_AGIB_AuPd_top','Hopper1_AGIB_AuPd_mid', 'Hopper1_AGIB_AuPd_bot'] #Change filename #y_list = [-6.06, -6.04, -6.02] #hexapod is in mm #y_list = [-10320, -10300, -10280] #SmarAct is um y_list = [-9540, -9520, -9500] #SmarAct is um assert len(y_list) == len(sample), f'Number of X coordinates ({len(x_list)}) is different from number of samples ({len(samples)})' # Detectors, motors: #dets = [pil1M, rayonix, pil300KW] dets0 = [pil1M] dets = [pil300KW] det_exposure_time(t,t) pil_pos_x = [-0.4997, -0.4997 + 4.3, -0.4997 + 4.3, -0.4997] pil_pos_y = [-59.9987, -59.9987, -59.9987 + 4.3, -59.9987] waxs_po = np.linspace(20.95, 2.95, 4) for sam, y in zip(sample, y_list): #yield from bps.mv(stage.y, y) #hexapod yield from bps.mv(piezo.y, y) #SmarAct yield from bps.mv(waxs, 70) for angle in range(-90, 91, 1): yield from bps.mv(prs, angle) name_fmt = '{sam}_phi{angle}deg' sample_name = name_fmt.format(sam=sam, angle=angle) sample_id(user_name='MK', sample_name=sample_name) print(f'\n\t=== Sample: {sample_name} ===\n') yield from bp.count(dets0, num = 1) yield from bps.mv(att1_5, 'Insert') yield from bps.sleep(1) yield from bps.mv(att1_6, 'Insert') yield from bps.sleep(1) for sam, y in zip(sample, y_list): #yield from bps.mv(stage.y, y) #hexapod yield from bps.mv(piezo.y, y) #SmarAct for i, waxs_pos in enumerate(waxs_po): yield from bps.mv(waxs, waxs_pos) yield from bps.mv(pil1m_pos.x, pil_pos_x[i]) yield from bps.mv(pil1m_pos.y, pil_pos_y[i]) for angle in range(-90, 91, 1): yield from bps.mv(prs, angle) name_fmt = '{sam}_phi{angle}deg_{waxs_pos}deg' sample_name = name_fmt.format(sam=sam, angle=angle, waxs_pos = waxs_pos) sample_id(user_name='MK', sample_name=sample_name) print(f'\n\t=== Sample: {sample_name} ===\n') yield from bp.count(dets, num = 1) sample_id(user_name='test', sample_name='test') det_exposure_time(0.5, 0.5) yield from bps.mv(att1_5, 'Retract') yield from bps.sleep(1) yield from bps.mv(att1_6, 'Retract') yield from bps.sleep(1) yield from bps.mv(pil1m_pos.x, -0.4997) yield from bps.mv(pil1m_pos.y, -59.9987)
def factory(classToInstantiate): def f(*arg): def g(): return classToInstantiate(*arg) return g return f
class EmailBuilder: def __init__(self): self.message = {} def set_from_email(self, email): self.message['from'] = email return self def set_receiver_email(self, email): self.message['receiver'] = email def set_cc_emails(self, emails): self.message['cc'] = emails return self def set_attachaments(self, attachments): self.message['attachments'] = attachments return self def set_subject(self, subject): self.message['subject'] = subject return self def set_msg(self, message): self.message['message'] = message return self def set_priority(self, priority): self.message['priority'] = priority return self def build(self): return self.message
# -*- coding: utf-8 -*- # Copyright 2018 ICON Foundation # # 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. TEST_REQUEST_TRANSFER_ICX = { "jsonrpc": "2.0", "method": "icx_sendTransaction", "id": 1234, "params": { "version": "0x3", "from": "hxbe258ceb872e08851f1f59694dac2558708ece11", "to": "hx5bfdb090f43a808005ffc27c25b213145e80b7cd", "value": "0xde0b6b3a7640000", "stepLimit": "0x12345", "timestamp": "0x563a6cf330136", "nid": "0x3f", "nonce": "0x1", "signature": "VAia7YZ2Ji6igKWzjR2YsGa2m53nKPrfK7uXYW78QLE+ATehAVZPC40szvAiA6NEU5gCYB4c4qaQzqDh2ugcHgA=" } } TEST_REQUEST_SCORE_FUNCTION_CALL = { "jsonrpc": "2.0", "method": "icx_sendTransaction", "id": 1234, "params": { "version": "0x3", "from": "hxbe258ceb872e08851f1f59694dac2558708ece11", "to": "cxb0776ee37f5b45bfaea8cff1d8232fbb6122ec32", "stepLimit": "0x12345", "timestamp": "0x563a6cf330136", "nid": "0x3f", "nonce": "0x1", "signature": "VAia7YZ2Ji6igKWzjR2YsGa2m53nKPrfK7uXYW78QLE+ATehAVZPC40szvAiA6NEU5gCYB4c4qaQzqDh2ugcHgA=", "dataType": "call", "data": { "method": "transfer", "params": { "to": "hxab2d8215eab14bc6bdd8bfb2c8151257032ecd8b", "value": "0x1" } } } } TEST_REQUEST_SCORE_ISNTALL = { "jsonrpc": "2.0", "method": "icx_sendTransaction", "id": 1234, "params": { "version": "0x3", "from": "hxbe258ceb872e08851f1f59694dac2558708ece11", "to": "cx0000000000000000000000000000000000000000", "stepLimit": "0x12345", "timestamp": "0x563a6cf330136", "nid": "0x3f", "nonce": "0x1", "signature": "VAia7YZ2Ji6igKWzjR2YsGa2m53nKPrfK7uXYW78QLE+ATehAVZPC40szvAiA6NEU5gCYB4c4qaQzqDh2ugcHgA=", "dataType": "deploy", "data": { "contentType": "application/zip", "content": "0x1867291283973610982301923812873419826abcdef91827319263187263a7326e...", "params": { "name": "ABCToken", "symbol": "abc", "decimals": "0x12" } } } } TEST_REQUEST_SCORE_UPDATE = { "jsonrpc": "2.0", "method": "icx_sendTransaction", "id": 1234, "params": { "version": "0x3", "from": "hxbe258ceb872e08851f1f59694dac2558708ece11", "to": "cxb0776ee37f5b45bfaea8cff1d8232fbb6122ec32", "stepLimit": "0x12345", "timestamp": "0x563a6cf330136", "nid": "0x3f", "nonce": "0x1", "signature": "VAia7YZ2Ji6igKWzjR2YsGa2m53nKPrfK7uXYW78QLE+ATehAVZPC40szvAiA6NEU5gCYB4c4qaQzqDh2ugcHgA=", "dataType": "deploy", "data": { "contentType": "application/zip", "content": "0x1867291283973610982301923812873419826abcdef91827319263187263a7326e...", "params": { "amount": "0x1234" } } } } TEST_REQUEST_SEND_MESSAGE = { "jsonrpc": "2.0", "method": "icx_sendTransaction", "id": 1234, "params": { "version": "0x3", "from": "hxbe258ceb872e08851f1f59694dac2558708ece11", "to": "hxbe258ceb872e08851f1f59694dac2558708ece11", "stepLimit": "0x12345", "timestamp": "0x563a6cf330136", "nid": "0x3f", "nonce": "0x1", "signature": "VAia7YZ2Ji6igKWzjR2YsGa2m53nKPrfK7uXYW78QLE+ATehAVZPC40szvAiA6NEU5gCYB4c4qaQzqDh2ugcHgA=", "dataType": "message", "data": "0x4c6f72656d20697073756d20646f6c6f722073697420616d65742c20636f6e7365637465747572206164697069736963696e6720656c69742c2073656420646f20656975736d6f642074656d706f7220696e6369646964756e74207574206c61626f726520657420646f6c6f7265206d61676e6120616c697175612e20557420656e696d206164206d696e696d2076656e69616d2c2071756973206e6f737472756420657865726369746174696f6e20756c6c616d636f206c61626f726973206e69736920757420616c697175697020657820656120636f6d6d6f646f20636f6e7365717561742e2044756973206175746520697275726520646f6c6f7220696e20726570726568656e646572697420696e20766f6c7570746174652076656c697420657373652063696c6c756d20646f6c6f726520657520667567696174206e756c6c612070617269617475722e204578636570746575722073696e74206f6363616563617420637570696461746174206e6f6e2070726f6964656e742c2073756e7420696e2063756c706120717569206f666669636961206465736572756e74206d6f6c6c697420616e696d20696420657374206c61626f72756d2e" } }
#! /usr/bin/env python3 def main(): try: name = input('\nHello! What is your name? ') if name: print(f'\nWell, {name}, it is nice to meet you!\n') except: print('\n\nSorry. Something went wrong, please try again.\n') if __name__ == '__main__': main()
def binary_search(element, some_list): # 코드를 작성하세요. start_index = 0 end_index = len(some_list) - 1 while (start_index <= end_index): mid_index = (end_index + start_index) // 2 if(some_list[mid_index] == element): return mid_index elif(some_list[mid_index] < element): start_index = mid_index + 1 else: end_index = mid_index - 1 return None print(binary_search(2, [2, 3, 5, 7, 11])) # 0 print(binary_search(0, [2, 3, 5, 7, 11])) # None print(binary_search(5, [2, 3, 5, 7, 11])) # 2 print(binary_search(3, [2, 3, 5, 7, 11])) # err print(binary_search(11, [2, 3, 5, 7, 11]))
#for循环方法 a=1 for i in range(0,101): if i%2!=0: print(i,end=' ') #换行打印 print('') while a<=100: if a % 2!=0: print(a,end=' ') a+=1
meta_pickups={ 'aux_domains': lambda r, common, data: { 'pos': r['head_pos'], 'head': r['head'], 'head_word': r['head_word'], **common, **data}, 'root_domains': lambda r, common, data: {'pos': r['upos'], 'rel': r['rel'], **common, **data}, 'verb_domains': lambda r, common, data: {'pos': r['upos'], 'rel': r['rel'], **common, **data}, 'predicate': lambda r, common, data: { 'pos': r['pos'], 'rel': r['rel'], 'segments':r['segments'] if 'segments' in r else [], **common, **data}, 'subj_domains': lambda r, common, data: { 'pos': r['head_pos'], 'head': r['head'], 'head_word': r['head_word'], **common, **data}, } def build_meta(r, data): # from sagas.conf.conf import cf type_name = r['type'] common = {'lemma': r['lemma'], 'word': r['word'], 'index': r['index'], 'stems': r['stems'], 'domain_type': type_name, } # if 'engine' not in data: # data['engine']=cf.engine(data['lang']) if type_name in meta_pickups: return meta_pickups[type_name](r, common, data) else: return {'rel': r['rel'], **common, **data}
# # PySNMP MIB module CISCO-WAN-BBIF-ATM-CONN-STAT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-WAN-BBIF-ATM-CONN-STAT-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:03:57 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") SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ConstraintsIntersection, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsIntersection", "ConstraintsUnion") bbChanCntGrp, = mibBuilder.importSymbols("BASIS-MIB", "bbChanCntGrp") ciscoWan, = mibBuilder.importSymbols("CISCOWAN-SMI", "ciscoWan") ModuleCompliance, ObjectGroup, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup", "NotificationGroup") MibIdentifier, Counter64, iso, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, Counter32, NotificationType, Unsigned32, TimeTicks, Gauge32, ObjectIdentity, Bits, ModuleIdentity, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "Counter64", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "Counter32", "NotificationType", "Unsigned32", "TimeTicks", "Gauge32", "ObjectIdentity", "Bits", "ModuleIdentity", "Integer32") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") ciscoWanBbifAtmConnStatMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 351, 150, 36)) ciscoWanBbifAtmConnStatMIB.setRevisions(('2002-10-18 00:00',)) if mibBuilder.loadTexts: ciscoWanBbifAtmConnStatMIB.setLastUpdated('200210180000Z') if mibBuilder.loadTexts: ciscoWanBbifAtmConnStatMIB.setOrganization('Cisco Systems, Inc.') bbChanCntGrpTable = MibTable((1, 3, 6, 1, 4, 1, 351, 110, 5, 2, 7, 3, 1), ) if mibBuilder.loadTexts: bbChanCntGrpTable.setStatus('current') bbChanCntGrpEntry = MibTableRow((1, 3, 6, 1, 4, 1, 351, 110, 5, 2, 7, 3, 1, 1), ).setIndexNames((0, "CISCO-WAN-BBIF-ATM-CONN-STAT-MIB", "bbChanCntNum")) if mibBuilder.loadTexts: bbChanCntGrpEntry.setStatus('current') bbChanCntNum = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 2, 7, 3, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(16, 4111))).setMaxAccess("readonly") if mibBuilder.loadTexts: bbChanCntNum.setStatus('current') bbChanRcvClp0Cells = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 2, 7, 3, 1, 1, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: bbChanRcvClp0Cells.setStatus('current') bbChanRcvClp1Cells = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 2, 7, 3, 1, 1, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: bbChanRcvClp1Cells.setStatus('current') bbChanNonConformCellsAtGcra1Policer = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 2, 7, 3, 1, 1, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: bbChanNonConformCellsAtGcra1Policer.setStatus('current') bbChanNonConformCellsAtGcra2Policer = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 2, 7, 3, 1, 1, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: bbChanNonConformCellsAtGcra2Policer.setStatus('current') bbChanRcvEOFCells = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 2, 7, 3, 1, 1, 6), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: bbChanRcvEOFCells.setStatus('current') bbChanDscdClp0Cells = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 2, 7, 3, 1, 1, 7), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: bbChanDscdClp0Cells.setStatus('current') bbChanDscdClp1Cells = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 2, 7, 3, 1, 1, 8), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: bbChanDscdClp1Cells.setStatus('current') bbChanRcvCellsSent = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 2, 7, 3, 1, 1, 9), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: bbChanRcvCellsSent.setStatus('current') bbChanXmtClp0Cells = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 2, 7, 3, 1, 1, 10), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: bbChanXmtClp0Cells.setStatus('current') bbChanXmtClp1Cells = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 2, 7, 3, 1, 1, 11), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: bbChanXmtClp1Cells.setStatus('current') bbChanDscdClpZeroCellsToPort = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 2, 7, 3, 1, 1, 12), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: bbChanDscdClpZeroCellsToPort.setStatus('current') bbChanDscdClpOneCellsToPort = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 2, 7, 3, 1, 1, 13), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: bbChanDscdClpOneCellsToPort.setStatus('current') bbChanCntClrButton = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 2, 7, 3, 1, 1, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("noAction", 1), ("resetCounters", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: bbChanCntClrButton.setStatus('current') cwbAtmConnStatMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 351, 150, 36, 2)) cwbAtmConnStatMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 351, 150, 36, 2, 1)) cwbAtmConnStatMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 351, 150, 36, 2, 2)) cwbAtmConnStatCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 351, 150, 36, 2, 2, 1)).setObjects(("CISCO-WAN-BBIF-ATM-CONN-STAT-MIB", "cwbAtmConnStatsGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cwbAtmConnStatCompliance = cwbAtmConnStatCompliance.setStatus('current') cwbAtmConnStatsGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 351, 150, 36, 2, 1, 1)).setObjects(("CISCO-WAN-BBIF-ATM-CONN-STAT-MIB", "bbChanCntNum"), ("CISCO-WAN-BBIF-ATM-CONN-STAT-MIB", "bbChanRcvClp0Cells"), ("CISCO-WAN-BBIF-ATM-CONN-STAT-MIB", "bbChanRcvClp1Cells"), ("CISCO-WAN-BBIF-ATM-CONN-STAT-MIB", "bbChanNonConformCellsAtGcra1Policer"), ("CISCO-WAN-BBIF-ATM-CONN-STAT-MIB", "bbChanNonConformCellsAtGcra2Policer"), ("CISCO-WAN-BBIF-ATM-CONN-STAT-MIB", "bbChanRcvEOFCells"), ("CISCO-WAN-BBIF-ATM-CONN-STAT-MIB", "bbChanDscdClp0Cells"), ("CISCO-WAN-BBIF-ATM-CONN-STAT-MIB", "bbChanDscdClp1Cells"), ("CISCO-WAN-BBIF-ATM-CONN-STAT-MIB", "bbChanRcvCellsSent"), ("CISCO-WAN-BBIF-ATM-CONN-STAT-MIB", "bbChanXmtClp0Cells"), ("CISCO-WAN-BBIF-ATM-CONN-STAT-MIB", "bbChanXmtClp1Cells"), ("CISCO-WAN-BBIF-ATM-CONN-STAT-MIB", "bbChanDscdClpZeroCellsToPort"), ("CISCO-WAN-BBIF-ATM-CONN-STAT-MIB", "bbChanDscdClpOneCellsToPort"), ("CISCO-WAN-BBIF-ATM-CONN-STAT-MIB", "bbChanCntClrButton")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cwbAtmConnStatsGroup = cwbAtmConnStatsGroup.setStatus('current') mibBuilder.exportSymbols("CISCO-WAN-BBIF-ATM-CONN-STAT-MIB", bbChanRcvCellsSent=bbChanRcvCellsSent, bbChanRcvClp1Cells=bbChanRcvClp1Cells, bbChanDscdClp0Cells=bbChanDscdClp0Cells, PYSNMP_MODULE_ID=ciscoWanBbifAtmConnStatMIB, bbChanDscdClpOneCellsToPort=bbChanDscdClpOneCellsToPort, bbChanNonConformCellsAtGcra1Policer=bbChanNonConformCellsAtGcra1Policer, cwbAtmConnStatMIBCompliances=cwbAtmConnStatMIBCompliances, bbChanXmtClp1Cells=bbChanXmtClp1Cells, cwbAtmConnStatMIBGroups=cwbAtmConnStatMIBGroups, bbChanRcvEOFCells=bbChanRcvEOFCells, bbChanRcvClp0Cells=bbChanRcvClp0Cells, cwbAtmConnStatsGroup=cwbAtmConnStatsGroup, cwbAtmConnStatMIBConformance=cwbAtmConnStatMIBConformance, bbChanCntClrButton=bbChanCntClrButton, bbChanXmtClp0Cells=bbChanXmtClp0Cells, bbChanCntNum=bbChanCntNum, bbChanDscdClpZeroCellsToPort=bbChanDscdClpZeroCellsToPort, bbChanDscdClp1Cells=bbChanDscdClp1Cells, bbChanCntGrpTable=bbChanCntGrpTable, ciscoWanBbifAtmConnStatMIB=ciscoWanBbifAtmConnStatMIB, bbChanCntGrpEntry=bbChanCntGrpEntry, cwbAtmConnStatCompliance=cwbAtmConnStatCompliance, bbChanNonConformCellsAtGcra2Policer=bbChanNonConformCellsAtGcra2Policer)
things = ['a', 'b', 'c', 'd'] print(things) print(things[1]) things[1] = 'z' print(things[1]) print(things) things = ['a', 'b', 'c', 'd'] print("=" * 50) stuff = {'name' : 'Jinkyu', 'age' : 40, 'height' : 6 * 12 + 2} print(stuff) print(stuff['name']) print(stuff['age']) print(stuff['height']) stuff['city'] = "SF" print(stuff['city']) stuff[1] = "Wow" stuff[2] = "Neato" print(stuff) print(stuff[1]) print(stuff[2]) del stuff['city'] del stuff[1] del stuff[2] print(stuff)
class Solution(object): def canVisitAllRooms(self, rooms): """ :type rooms: List[List[int]] :rtype: bool """ seen = [False] * len(rooms) seen[0] = True stack = [0, ] while stack: roomIdx = stack.pop() for key in rooms[roomIdx]: if not seen[key]: seen[key] = True stack.append(key) return all(seen)
# https://leetcode.com/problems/surface-area-of-3d-shapes class Solution: def surfaceArea(self, grid): N = len(grid) ans = 0 for i in range(N): for j in range(N): if grid[i][j] == 0: continue height = grid[i][j] ans += 2 for h in range(1, height + 1): adj = [[i + 1, j], [i - 1, j], [i, j + 1], [i, j - 1]] for a, b in adj: if a < 0 or N <= a or b < 0 or N <= b: ans += 1 else: if h <= grid[a][b]: ans += 0 else: ans += 1 return ans
USERDV = [ "USER_NAME", "USER_USERNAME", "USER_ID", "USER_PIC", "USER_BIO" ] class UserConfig(object): def UserName(self): """returns name of user""" return self.getdv("USER_NAME") or self.USER_NAME or self.name or None def UserUsername(self): """returns username of user""" return self.getdv("USER_USERNAME") or self.USER_USERNAME or self.username or None def UserMention(self): """returns mention of user""" return self.MentionMarkdown(self.UserId(), self.UserName()) if self.UserName() and self.UserId() else None def UserId(self): """returns telegram id of user""" return self.getdv("USER_ID") or self.USER_ID or self.id or None def UserDc(self): """returns telegram dc id of user""" return self.getdv("DC_ID") or self.dc_id or None def UserPic(self): """returns pic of user""" return self.getdv("USER_PIC") or self.USER_PIC or self.pic or None def UserBio(self): """returns bio of user""" return self.getdv("USER_BIO") or self.USER_BIO or self.bio or None
tempo = int(input()) velocida_media = int(input()) gasto_carro = 12 distancia = velocida_media * tempo print(f'{distancia / 12:.3f}')
rows, cols = [int(n) for n in input().split(", ")] matrix = [] for _ in range(rows): matrix.append([int(n) for n in input().split(" ")]) for j in range(cols): total = 0 for row in matrix: total += row[j] print(total)
# Available methods METHODS = { # Dummy for HF "hf": ["hf"], "ricc2": ["rimp2", "rimp3", "rimp4", "ricc2"], # Hardcoded XC-functionals that can be selected from the dft submenu # of define. "dft_hardcoded": [ # Hardcoded in V7.3 "s-vwn", "s-vwn_Gaussian", "pwlda", "b-lyp", "b-vwn", "b-p", "pbe", "tpss", "bh-lyp", "b3-lyp", "b3-lyp_Gaussian", "pbe0", "tpssh", "pw6b95", "m06", "m06-l", "m06-2x", "lhf", "oep", "b97-d", "pbeh-3c", "b97-3c", "lh07t-svwn", "lh07s-svwn", "lh12ct-ssirpw92", "lh12ct-ssifpw92", "lh14t-calpbe", # Hardcoded in V7.4 "cam-b3lyp", # B2PLYP his is not easily supported right now as we would need an # additional MP2 calculation from rimp2/ricc2. # "b2-plyp", ], # Shorctus for XC functionals in V7.4 using LibXC "dft_libxc": [ "wb97", "wb97x", "sogga11", "sogga-11x", "mn12-l", "mn12-sx", "mn15", "mn15-l", "m06-libxc", "cam-b3lyp-libxc", "hse06-libxc", ], } # Available keywords KEYWORDS = { # Resolution of identity "ri": ["rijk", "ri", "marij"], # Dispersion correction "dsp": ["d3", "d3bj"], }
def sumValues(a, b, *others): retValue = a + b # Tham số 'others' giống như một mảng. for other in others: retValue = retValue + other return retValue
class Config: ''' General configuration parent class ''' NEWS_API_BASE_URL ='https://newsapi.org/v2/sources?apiKey={}' ARTICLE_API_BASE_URL = 'https://newsapi.org/v2/everything?sources={}&apiKey={}' class ProdConfig(Config): ''' Production configuration child class Args: Config: The parent configuration class with general configuration settings ''' pass class DevConfig(Config): ''' Development configuration child class Args: Config: The parent configuration class with general configuration settings ''' DEBUG = True
def main() -> None: K, X = map(int, input().split()) assert 1 <= K <= 100 assert 1 <= X <= 10**5 if __name__ == '__main__': main()
# Copyright (c) The PyAMF Project. # See LICENSE.txt for details. """ Remoting tests. @since: 0.1.0 """
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def sumNumsR(self, root, s): if root is None: return 0 s = s * 10 + root.val if not root.left and not root.right: return s return self.sumNumsR(root.left, s) + self.sumNumsR(root.right, s) def sumNumbers0(self, root: TreeNode) -> int: if root is None: return 0 return self.sumNumsR(root, 0) def sumNumbersF(self, root: TreeNode) -> int: def sumNumsInR(root, s): if not root: return 0 s = s + root.val if not root.left and not root.right: return s return sumNumsInR(root.left, s * 10) + \ sumNumsInR(root.right, s * 10) return sumNumsInR(root, 0) def sumNumbers(self, root): """ :type root: TreeNode :rtype: int """ self.sum = 0 def dfs(root, pathsum): if root: pathsum += root.val left = dfs(root.left, pathsum * 10) right = dfs(root.right, pathsum * 10) if not left and not right: self.sum += pathsum return True dfs(root, 0) return self.sum
# Copyright 2018 Google Inc. All rights reserved. # # 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. """ This template creates a Runtime Configurator with the associated resources. """ def generate_config(context): """ Entry point for the deployment resources. """ resources = [] properties = context.properties project_id = properties.get('projectId', context.env['project']) name = properties.get('config', context.env['name']) parent = 'projects/{}/configs/{}'.format(project_id, name) # The runtimeconfig resource. runtime_config = { 'name': name, 'type': 'runtimeconfig.v1beta1.config', 'properties': { 'config': name, 'description': properties['description'] } } resources.append(runtime_config) # The runtimeconfig variable resources. for variable in properties.get('variables', []): variable['parent'] = parent variable['config'] = name variable_res = { 'name': variable['variable'], 'type': 'variable.py', 'properties': variable } resources.append(variable_res) # The runtimeconfig waiter resources. for waiter in properties.get('waiters', []): waiter['parent'] = parent waiter['config'] = name waiter_res = { 'name': waiter['waiter'], 'type': 'waiter.py', 'properties': waiter } resources.append(waiter_res) outputs = [{'name': 'configName', 'value': '$(ref.{}.name)'.format(name)}] return {'resources': resources, 'outputs': outputs}
__all__ = ('ascii_art_title_4client', 'ascii_art_title_4server') ascii_art_title_4client = r""" /$$$$$$ /$$ /$$ /$$__ $$| $$ | $$ /$$$$$$ /$$$$$$$ /$$$$$$ /$$$$$$$ /$$ /$$ /$$$$$$/$$$$ | $$ \__/| $$$$$$$ /$$$$$$ /$$$$$$ |____ $$| $$__ $$ /$$__ $$| $$__ $$| $$ | $$| $$_ $$_ $$| $$ | $$__ $$ |____ $$|_ $$_/ /$$$$$$$| $$ \ $$| $$ \ $$| $$ \ $$| $$ | $$| $$ \ $$ \ $$| $$ | $$ \ $$ /$$$$$$$ | $$ /$$__ $$| $$ | $$| $$ | $$| $$ | $$| $$ | $$| $$ | $$ | $$| $$ $$| $$ | $$ /$$__ $$ | $$ /$$ | $$$$$$$| $$ | $$| $$$$$$/| $$ | $$| $$$$$$$| $$ | $$ | $$| $$$$$$/| $$ | $$| $$$$$$$ | $$$$/ \_______/|__/ |__/ \______/ |__/ |__/ \____ $$|__/ |__/ |__/ \______/ |__/ |__/ \_______/ \___/ /$$ | $$ | $$$$$$/ \______/ """ ascii_art_title_4server = r""" _____ _ _ _____ / __ \ | | | / ___| __ _ _ __ ___ _ __ _ _ _ __ ___ | / \/ |__ __ _| |_ \ `--. ___ _ ____ _____ _ __ / _` | '_ \ / _ \| '_ \| | | | '_ ` _ \| | | '_ \ / _` | __| `--. \/ _ \ '__\ \ / / _ \ '__| | (_| | | | | (_) | | | | |_| | | | | | | \__/\ | | | (_| | |_ /\__/ / __/ | \ V / __/ | \__,_|_| |_|\___/|_| |_|\__, |_| |_| |_|\____/_| |_|\__,_|\__| \____/ \___|_| \_/ \___|_| __/ | |___/ """
# -*- coding: utf-8 -*- description = "Setup for the LakeShore 340 temperature controller" group = "optional" includes = ["alias_T"] tango_base = "tango://phys.kws3.frm2:10000/kws3" tango_ls340 = tango_base + "/ls340" devices = dict( T_ls340 = device("nicos.devices.entangle.TemperatureController", description = "Temperature regulation", tangodevice = tango_ls340 + "/t_control1", pollinterval = 2, maxage = 5, abslimits = (0, 300), precision = 0.01, ), ls340_heaterrange = device("nicos.devices.entangle.DigitalOutput", description = "Temperature regulation", tangodevice = tango_ls340 + "/t_range1", unit = '', fmtstr = '%d', ), T_ls340_A = device("nicos.devices.entangle.Sensor", description = "Sensor A", tangodevice = tango_ls340 + "/t_sensor1", pollinterval = 2, maxage = 5, ), T_ls340_B = device("nicos.devices.entangle.Sensor", description = "Sensor B", tangodevice = tango_ls340 + "/t_sensor2", pollinterval = 2, maxage = 5, ), T_ls340_C = device("nicos.devices.entangle.Sensor", description = "Sensor C", tangodevice = tango_ls340 + "/t_sensor3", pollinterval = 2, maxage = 5, ), T_ls340_D = device("nicos.devices.entangle.Sensor", description = "Sensor D", tangodevice = tango_ls340 + "/t_sensor4", pollinterval = 2, maxage = 5, ), ) alias_config = { "T": { "T_%s" % setupname: 100 }, "Ts": { "T_%s_A" % setupname: 110, "T_%s_B" % setupname: 100, "T_%s_C" % setupname: 90, "T_%s_D" % setupname: 80, "T_%s" % setupname: 120, }, }
def response(status, message, data, status_code=200): return { "status": status, "message": message, "data": data, }, status_code
""" Blocks TODO: * Avoid newline/indent on certain tags, like Blank/Pre: self.__class__.__name__ != "Pre" (necessary?) * Fixed: () popped len(token) twice """ ## +block def indented_block(self): print(f"Indent-dependent {self.tag} block started") start_O_line = self.O.line_number block_indent = self.I.indent_count + 1 if self.offset: self.O.offset -= block_indent #Opening block self.opening_tag() #Main block loop while 1: loop_line = self.I.line_number index, token = self.next_token() if index > 0: self.O.indents(count = self.I.indent_count) self.O.write(self.I.popto(index)) self.I.popto(len(token)) if token: self.routine(token) #refill line if self.I.line == '': try: self.I.readline() except: break #check if next line is in block if loop_line != self.I.line_number: if block_indent > self.I.indent_count: break else: self.O.newline() #check if preceding line was empty: if self.I.empty_line: self.I.empty_line = False self.O.indents(count = 0) self.O.newline() #Closing block if start_O_line != self.O.line_number: self.O.newline() self.O.indents(count = block_indent - 1) self.closing_tag() if self.offset: self.O.offset += block_indent ## @wrapper: def wrapping_block(self): print(f"Wrapping {self.tag} block started") start_O_line = self.O.line_number block_indent = self.I.indent_count if self.offset: self.O.offset -= block_indent #Opening block self.opening_tag() #Main block loop FIX while 1: loop_line = self.I.line_number index, token = self.next_token() if not token and index: self.O.indents(count = self.I.indent_count) self.O.write(self.I.popto(index)) self.I.popto(len(token)) if token: self.routine(token) #refill line if self.I.line == '': try: self.I.readline() except: break #check if next line is in block if loop_line != self.I.line_number: if block_indent > self.I.indent_count: break else: self.O.newline() #check if preceding line was empty: if self.I.empty_line: self.I.empty_line = False self.O.indents(count = 0) self.O.newline() #Closing block if start_O_line != self.O.line_number and self.__class__.__name__ != "Blank": self.O.newline() self.O.indents(count = block_indent) self.closing_tag() if self.offset: self.O.offset += block_indent ## +block() def bracketed_block(self): print(f"Bracketed {self.tag} block started") start_O_line = self.O.line_number block_indent = self.I.indent_count if self.offset: self.O.offset -= block_indent #Opening block self.opening_tag() #Main block loop FIX level = 0 #number of brackets must match while 1: loop_line = self.I.line_number index, token = self.next_token('(', ')') if not token or token == '(' or token == ')': #indent will be added in the token's routine, if needed self.O.indents(count = self.I.indent_count) self.O.write(self.I.popto(index)) self.I.popto(len(token)) if token == '(': self.O.write('(') level += 1 elif token == ')': if level == 0: break #end of block self.O.write(')') level -= 1 else: if token: self.routine(token) if self.I.line.isspace() or self.I.line == '': self.I.readline() #refill line if self.I.line == '': try: self.I.readline() except: break #check if next line is in block REMOVE?! + indent_count?? if loop_line != self.I.line_number: if block_indent > self.I.indent_count: break else: self.O.newline() #check if preceding line was empty: if self.I.empty_line: self.I.empty_line = False self.O.indents(count = 0) self.O.newline() #Closing block self.closing_tag() if self.offset: self.O.offset += block_indent #Selfclosing pseudo-block def selfclosing_block(self): print(f"Selfclosing {self.tag} tag started") self.opening_tag()
def leiaInt(msg): while True: try: n = int(input(msg)) except (ValueError, TypeError): print('\033[31mErro:Por favor, digite um número inteiro válido\033[m') continue except (keyboardInterrupt): print('\n\033[31mUsuário preferiu não digitar esse número\033[m') return 0 else: return n def leiafloat(msg): while True: try: n = float(input(msg)) except (ValueError, TypeError): print('\033[31mErro:Por favor, digite um número real válido.\033[m') continue except (keyboardInterrupt): print('\n\033[31mUsuario preferiu não digitar esse número.\033[m') return 0 else: return n n1 = leiaInt('Digite um Inteiro: ') n2 = leiafloat('Digite um Real: ') print(f'O valor inteiro digitado foi {n1} eo real foi {n2}')
x = 0 for n in range(10): x = x + 1 assert x == 10
# Aula 016: '''Nessa aula, vamos aprender o que são TUPLAS e como utilizar tuplas em Python. As tuplas são variáveis compostas e imutáveis que permitem armazenar vários valores em uma mesma estrutura, acessíveis por chaves individuais.''' # Variáveis compostas (Tuplas): lanche = ('Hamburger', 'Suco', 'Pizza', 'Pudim') print(lanche) # Obs: Os parênteses para marcar a tupla são opcionais no Python. O comando funciona simplesmente com a enumeração: lanche = 'Hamburger', 'Suco', 'Pizza', 'Pudim' print(lanche) # A estrutura de Tupla aceita o fatiamento do mesmo modo que a string: print(lanche[1]) # segundo termo print(lanche[-1]) # primeiro termo de trás pra frente print(lanche[0]) # primeiro termo print(lanche[-0]) # primeiro termo print(lanche[1:3]) # do segundo termo (inclusive) até o quarto termo (exclusive) print(lanche[2:]) # do terceiro termo em diante print(lanche[:2]) # do primeiro termo até o terceiro (exclusive) print(lanche[::]) # tudo # Tuplas são IMUTÁVEIS print(lanche[1]) # lanche[1] = 'refrigerante' # comando vai gerar erro # Também podemos usar estruturas de repetição com a tupla: # lanche = 'Hamburger', 'Suco', 'Pizza', 'Pudim' for comida in lanche: print(f'Eu vou comer {comida}!') print('Comi para caramba!') # Também podemos combinar o "range" com o "len" para as estruturas de repetição: lanche = ('Hamburger', 'Suco', 'Pizza', 'Pudim', 'Batata Frita') for contador in range(0, len(lanche)): print(f'Eu vou comer {lanche[contador]}!') print('Comi para caramba!') # O resultado dos dois exemplos acima é o mesmo. # Também podemos descobrir a posição relativa de cada elemento com o "enumerate" ou com o "renge". lanche = ('Hamburger', 'Suco', 'Pizza', 'Pudim', 'Batata Frita') for contador, comida in enumerate(lanche): print(f'Eu vou comer {comida} na posição {contador}!') print('Comi para caramba!') for contador in range(0, len(lanche)): print(f'Eu vou comer {lanche[contador]} na posição {contador}!') print('Comi para caramba!') # Podemos ordenar a apresentação dos itens da tupla (Embora a ordem seja imutável, o "print" vai ser ordenado). # Interessante notar que o Python cria uma lista para fazer essa ordenação. lanche = ('Hamburger', 'Suco', 'Pizza', 'Pudim', 'Batata Frita') print(sorted(lanche)) print(sorted(lanche[0])) # criou uma lista ordenada com as letras do primeiro elemento na ordem normal!!! print(lanche) # Também podemos fazer operações com tuplas: a = (2, 5, 4) b = (5, 8, 1, 2) c = a + b d = b + a # A ordem é importante. Os elementos não são somados, são concatenados. print(a) print(b) print(c) print(d) # Existem algumas funções internas: print(c.count(5)) # Conta quantas vezes o elemento aparece repetido na tupla. # Podemos saber a posição do elemento na tupla: print(c.index(8)) # Se o elemento aparecer mais de uma vez o "index" retorna a primeira ocorrência: print(d.index(2)) # Você pode usar o deslocamento para saber quala próxima posição do elemento repetido: print(d.index(5, 1)) # No exemplo acima, como eu sei que existe um número cinco na posição "0", eu desloco o início da busca para a # posição "1" e descubro onde existe outro elemento "5". # Tuplas aceitam elementos de diversos tipos: pessoa = ('Gustavo', 39, 'M', 99.88) print(pessoa) # Por fim, podemos deletar uma tupla inteira: del(pessoa) print(pessoa) # Fim!
#Queue.py #20 Oct 2017 #Written By Amin Dehghan #DS & Algorithms With Python class Queue: def __init__(self): self.items=[] self.fronIdx=0 def __compress(self): newlst=[] for i in range(self.frontIdx,len(self.items)): newlst.append(self.items[i]) self.items=newlst self.frontIdx=0 def dequeue(self): if self.isEmpty(): raise RuntimeError("Attempt to dequeue an empty queue") if self.froniIdx*2< len(self.items): self.__compress() item=self.items[self.frontIdx] self.frontIdx+=1 return item def enqueue(self,val): self.items.append(val) def front(self): if self.isEmpty(): raise RuntimeError("Attempt to access front of empty queue") return self.items[frontIdx] def isEmpty(self): return len(self.items)==frontIdx
patches = [ { "op": "move", "from": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/ItemType", "path": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/PrimitiveItemType", }, { "op": "replace", "path": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/PrimitiveItemType", "value": "String", }, { "op": "move", "from": "/ResourceTypes/AWS::Transfer::User/Properties/SshPublicKeys/ItemType", "path": "/ResourceTypes/AWS::Transfer::User/Properties/SshPublicKeys/PrimitiveItemType", }, { "op": "replace", "path": "/ResourceTypes/AWS::Transfer::User/Properties/SshPublicKeys/PrimitiveItemType", "value": "String", }, ]
def foo(x): if x == 0: return 1 elif x % 2 == 0: return 2 * x * foo(x - 2) else: return (x -3) * x * foo(x + 1) print(foo(4))
def goGame(): persAcc = 0.0 history=[] # [покупка, сумма, счет] while True: print('1. пополнение счета') print('2. покупка') print('3. история покупок') print('4. выход') choice = input('Выберите пункт меню: ') if choice == '1': s = float( input( 'Введите сумму пополнения счёта (руб):') ) persAcc += s print() elif choice == '2': t = float( input( 'Введите сумму покупки (руб):' ) ) if t > persAcc: print( 'На счету мало средств!\n') else: p = input( 'Введите, что покупаете:') persAcc -= t history.append( [p,t, persAcc] ) print() elif choice == '3': print( 'История покупок: ') for v in history: print( v[0] +', '+str( v[1] )+'р., Осталось на счете:'+str( v[2] ) +'р.\n' ) elif choice == '4': break else: print('Неверный пункт меню') if __name__ == '__main__': goGame()
def diff(n, mid) : if (n > (mid * mid * mid)) : return (n - (mid * mid * mid)) else : return ((mid * mid * mid) - n) # Returns cube root of a no n def cubicRoot(n) : # Set start and end for binary # search start = 0 end = n # Set precision e = 0.0000001 while (True) : mid = (start + end) / 2 error = diff(n, mid) # If error is less than e # then mid is our answer # so return mid if (error <= e) : return mid # If mid*mid*mid is greater # than n set end = mid if ((mid * mid * mid) > n) : end = mid # If mid*mid*mid is less # than n set start = mid else : start = mid # Driver code n = 3 print("Cubic root of", n, "is", round(cubicRoot(n),6))
# Base Parameters assets = asset_list('FX') # Trading Parameters horizon = 'H1' pair = 0 # Mass Imports my_data = mass_import(pair, horizon) # Parameters long_ema = 26 short_ema = 12 signal_ema = 9 def ma(Data, lookback, close, where): Data = adder(Data, 1) for i in range(len(Data)): try: Data[i, where] = (Data[i - lookback + 1:i + 1, close].mean()) except IndexError: pass # Cleaning Data = jump(Data, lookback) return Data def ema(Data, alpha, lookback, what, where): alpha = alpha / (lookback + 1.0) beta = 1 - alpha # First value is a simple SMA Data = ma(Data, lookback, what, where) # Calculating first EMA Data[lookback + 1, where] = (Data[lookback + 1, what] * alpha) + (Data[lookback, where] * beta) # Calculating the rest of EMA for i in range(lookback + 2, len(Data)): try: Data[i, where] = (Data[i, what] * alpha) + (Data[i - 1, where] * beta) except IndexError: pass return Data def macd(Data, what, long_ema, short_ema, signal_ema, where): Data = adder(Data, 1) Data = ema(Data, 2, long_ema, what, where) Data = ema(Data, 2, short_ema, what, where + 1) Data[:, where + 2] = Data[:, where + 1] - Data[:, where] Data = jump(Data, long_ema) Data = ema(Data, 2, signal_ema, where + 2, where + 3) Data = deleter(Data, where, 2) Data = jump(Data, signal_ema) return Data def indicator_plot_double_macd(Data, MACD_line, MACD_signal, window = 250): fig, ax = plt.subplots(2, figsize = (8, 5)) Chosen = Data[-window:, ] for i in range(len(Chosen)): ax[0].vlines(x = i, ymin = Chosen[i, 2], ymax = Chosen[i, 1], color = 'black', linewidth = 1) ax[0].grid() for i in range(len(Chosen)): if Chosen[i, MACD_line] > 0: ax[1].vlines(x = i, ymin = 0, ymax = Chosen[i, MACD_line], color = 'green', linewidth = 1) if Chosen[i, MACD_line] < 0: ax[1].vlines(x = i, ymin = Chosen[i, MACD_line], ymax = 0, color = 'red', linewidth = 1) if Chosen[i, MACD_line] == 0: ax[1].vlines(x = i, ymin = Chosen[i, MACD_line], ymax = 0, color = 'black', linewidth = 1) ax[1].grid() ax[1].axhline(y = 0, color = 'black', linewidth = 0.5, linestyle = '--') ax[1].plot(Data[-window:, MACD_signal], color = 'blue', linewidth = 0.75, linestyle = 'dashed') my_data = macd(my_data, 3, 26, 12, 9, 4) indicator_plot_double_macd(my_data, 4, 5, window = 250)
x = 'heLLo world' print("Swap the case: " + x.swapcase()) print("Set all cast to upper: " + x.upper()) print("Set all cast to lower: " + x.lower()) print("Set all cast to lower aggresivly: " + x.casefold()) print("Set every word\'s first letter to upper: " + x.title()) print("Set the first word\'s first letter to upper in a sentence: " + x.capitalize()) x = x.split() y = '--'.join(x) print(y)
''' constants for the project ''' TRAIN_LOSS = 0 TRAIN_ACCURACY = 1 VAL_LOSS = 2 VAL_ACCURACY = 3
# -*- coding: utf-8 -*- STATSD_ENABLED = False STATSD_HOST = "localhost" STATSD_PORT = 8125 STATSD_LOG_PERIODIC = True STATSD_LOG_EVERY = 5 STATSD_HANDLER = "scrapy_statsd_extension.handlers.StatsdBase" STATSD_PREFIX = "scrapy" STATSD_LOG_ONLY = [] STATSD_TAGGING = False STATSD_TAGS = {"spider_name": True} STATSD_IGNORE = []
N, r = map(int, input().split()) for i in range(N): R = int(input()) if R>=r: print('Good boi') else: print('Bad boi')
# WRITE YOUR SOLUTION HERE: class Employee: def __init__(self, name: str): self.name = name self.subordinates = [] def add_subordinate(self, employee: 'Employee'): self.subordinates.append(employee) def count_subordinates(employee: Employee): count = len(employee.subordinates) if len(employee.subordinates) != 0: for sub_employee in employee.subordinates: count += count_subordinates(sub_employee) return count if __name__ == "__main__": t1 = Employee("Sally") t2 = Employee("Eric") t3 = Employee("Matthew") t4 = Employee("Emily") t5 = Employee("Adele") t6 = Employee("Claire") t1.add_subordinate(t4) t1.add_subordinate(t6) t4.add_subordinate(t2) t4.add_subordinate(t3) t4.add_subordinate(t5) print(count_subordinates(t1)) print(count_subordinates(t4)) print(count_subordinates(t5))
jogador = dict() golList = list() cadastro = list() while True: print('°~~'*15) jogador['nome'] = str(input('Nome do jogador: ')).strip().title() partidas = int(input(f'Quantas partidas {jogador["nome"]} jogou? ')) print('°~~'*15) for g in range(0, partidas): golList.append(int(input(f'Quantos gols na partida {g+1}? '))) jogador['total'] = sum(golList) jogador['gols'] = golList[:] golList.clear() cadastro.append(jogador.copy()) resposta = ' ' while resposta not in 'SN': print('-=-'*10) resposta = str(input('Deseja continuar? [S/N]: ')).strip().upper()[0] if resposta == 'N': break print('°~~'*20) print(f'{"cod":<} {"Nome":<15} {"Gols":<20} {"Total":<5}') print('-'*50) for i, reg in enumerate(cadastro): print(f'{i:>3} {reg["nome"]:<15} {str(reg["gols"]):<20} {reg["total"]:<5}') while True: print('°~~'*20) cod = int(input('Escolha um jogador para detalhes: ')) while (cod >= len(cadastro) or cod < 0) and cod != 999: print('°~~'*20) print('Código incorreto! Tente novamente') cod = int(input('Escolha um jogador para detalhes: ')) if cod == 999: break detalhe = cadastro[cod] print('°~~'*20) print(f'-==Levantamento do jogador {detalhe["nome"].upper()}==-') for i, g in enumerate(detalhe['gols']): print(f'No jogo {i+1} fez {g} gols.') print('-=-'*15) print('>FIM DO PROGRAMA<')
#!/usr/bin/env python3 def palindrome(x): return str(x) == str(x)[::-1] def number_palindrome(n, base): if base == 2: binary = bin(n)[2:] return palindrome(binary) if base == 10: return palindrome(n) return False def double_base_palindrome(x): return number_palindrome(x, 10) and number_palindrome(x, 2) def sum_double_palindrome_numbers_below(limit): return sum((x for x in range(1, limit) if double_base_palindrome(x))) def solve(): return sum_double_palindrome_numbers_below(1000000) if __name__ == '__main__': result = solve() print(result)
#for request headers headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Max-Age': '3600', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0' }
# Create an array for the points of the line line_points = [ {"x":5, "y":5}, {"x":70, "y":70}, {"x":120, "y":10}, {"x":180, "y":60}, {"x":240, "y":10}] # Create style style_line = lv.style_t() style_line.init() style_line.set_line_width(8) style_line.set_line_color(lv.palette_main(lv.PALETTE.BLUE)) style_line.set_line_rounded(True) # Create a line and apply the new style line1 = lv.line(lv.scr_act()) line1.set_points(line_points, 5) # Set the points line1.add_style(style_line, 0) line1.center()
# In case it's not obvious, a list comprehension produces a list, but # it doesn't have to be given a list to iterate over. # # You can use a list comprehension with any iterable type, so we'll # write a comprehension to convert dimensions from inches to centimetres. # # Our dimensions will be represented by a tuple, for the length, width and height. # # There are 2.54 centimetres to 1 inch. inch_measurement = (3, 8, 20) cm_measurement = [x * 2.54 for x in inch_measurement] print(cm_measurement) # Once you've got the correct values, change the code to produce a tuple, rather than a list. cm_measurement = [(x, x * 2.54) for x in inch_measurement] print(cm_measurement) cm_measurement = tuple(x * 2.54 for x in inch_measurement) print(cm_measurement)