content
stringlengths
7
1.05M
# This program gets a numberic test score from the # user and displays the corresponding letter grade. # Named constants to represent the grade thresholds A_SCORE = 90 B_SCORE = 80 C_SCORE = 70 D_SCORE = 60 # Get a test score from the user. score = int(input('Enter your test score: ')) # Determine the grade. if score >= A_SCORE: print('Your grade is A.') else: if score >= B_SCORE: print('Your grade is B.') else: if score >= C_SCORE: print('Your grade is C.') else: if score >= D_SCORE: print('Your grade is D.') else: print('Your grade is F.')
{ 'target_defaults': { 'variables': { 'deps': [ 'libbrillo-<(libbase_ver)', 'libchrome-<(libbase_ver)', 'libndp', 'libshill-client', 'protobuf-lite', ], }, }, 'targets': [ { 'target_name': 'protos', 'type': 'static_library', 'variables': { 'proto_in_dir': '.', 'proto_out_dir': 'include/arc-networkd', }, 'sources': ['<(proto_in_dir)/ipc.proto'], 'includes': ['../common-mk/protoc.gypi'], }, { 'target_name': 'arc-networkd', 'type': 'executable', 'dependencies': ['protos'], 'sources': [ 'arc_ip_config.cc', 'helper_process.cc', 'ip_helper.cc', 'main.cc', 'manager.cc', 'multicast_forwarder.cc', 'multicast_socket.cc', 'ndp_handler.cc', 'neighbor_finder.cc', 'router_finder.cc', 'shill_client.cc', ], }, ], }
class ApplicationException(Exception): def __init__(self, java_exception): self.java_exception = java_exception def message(self): return self.java_exception.getMessage()
EXPECTED_TABULATED_HTML = """ <table> <thead> <tr> <th>category</th> <th>date</th> <th>downloads</th> </tr> </thead> <tbody> <tr> <td align="left">2.6</td> <td align="left">2018-08-15</td> <td align="right">51</td> </tr> <tr> <td align="left">2.7</td> <td align="left">2018-08-15</td> <td align="right">63,749</td> </tr> <tr> <td align="left">3.2</td> <td align="left">2018-08-15</td> <td align="right">2</td> </tr> <tr> <td align="left">3.3</td> <td align="left">2018-08-15</td> <td align="right">40</td> </tr> <tr> <td align="left">3.4</td> <td align="left">2018-08-15</td> <td align="right">6,095</td> </tr> <tr> <td align="left">3.5</td> <td align="left">2018-08-15</td> <td align="right">20,358</td> </tr> <tr> <td align="left">3.6</td> <td align="left">2018-08-15</td> <td align="right">35,274</td> </tr> <tr> <td align="left">3.7</td> <td align="left">2018-08-15</td> <td align="right">6,595</td> </tr> <tr> <td align="left">3.8</td> <td align="left">2018-08-15</td> <td align="right">3</td> </tr> <tr> <td align="left">null</td> <td align="left">2018-08-15</td> <td align="right">1,019</td> </tr> </tbody> </table> """ EXPECTED_TABULATED_MD = """ | category | date | downloads | | -------- | ---------- | --------: | | 2.6 | 2018-08-15 | 51 | | 2.7 | 2018-08-15 | 63,749 | | 3.2 | 2018-08-15 | 2 | | 3.3 | 2018-08-15 | 40 | | 3.4 | 2018-08-15 | 6,095 | | 3.5 | 2018-08-15 | 20,358 | | 3.6 | 2018-08-15 | 35,274 | | 3.7 | 2018-08-15 | 6,595 | | 3.8 | 2018-08-15 | 3 | | null | 2018-08-15 | 1,019 | """ EXPECTED_TABULATED_RST = """ .. table:: ========== ============ =========== category date downloads ========== ============ =========== 2.6 2018-08-15 51 2.7 2018-08-15 63,749 3.2 2018-08-15 2 3.3 2018-08-15 40 3.4 2018-08-15 6,095 3.5 2018-08-15 20,358 3.6 2018-08-15 35,274 3.7 2018-08-15 6,595 3.8 2018-08-15 3 null 2018-08-15 1,019 ========== ============ =========== """ # noqa: W291 EXPECTED_TABULATED_TSV = """ "category"\t"date"\t"downloads" "2.6"\t"2018-08-15"\t51 "2.7"\t"2018-08-15"\t63,749 "3.2"\t"2018-08-15"\t2 "3.3"\t"2018-08-15"\t40 "3.4"\t"2018-08-15"\t6,095 "3.5"\t"2018-08-15"\t20,358 "3.6"\t"2018-08-15"\t35,274 "3.7"\t"2018-08-15"\t6,595 "3.8"\t"2018-08-15"\t3 "null"\t"2018-08-15"\t1,019 """ # noqa: W291
# def t1(): # l = [] # for i in range(10000): # l = l + [i] # def t2(): # l = [] # for i in range(10000): # l.append(i) # def t3(): # l = [i for i in range(10000)] # def t4(): # l = list(range(10000)) # # from timeit import Timer # # timer1 = Timer("t1()", "from __main__ import t1") # print("concat ",timer1.timeit(number=100), "seconds") # timer2 = Timer("t2()", "from __main__ import t2") # print("append ",timer2.timeit(number=100), "seconds") # timer3 = Timer("t3()", "from __main__ import t3") # print("comprehension ",timer3.timeit(number=100), "seconds") # timer4 = Timer("t4()", "from __main__ import t4") # print("list range ",timer4.timeit(number=100), "seconds") # I = [] for i in range(4): I.append({"num": i}) print(I) I = [] a = {"num": 0} for i in range(4): a["num"] = i I.append(a) print(I)
#!/usr/bin/env python3 class ProjectNameException(Exception): pass class MissingEnv(ProjectNameException): pass class CreateDirectoryException(ProjectNameException): pass class ConfigError(ProjectNameException): pass
# Задача 4. Вариант 28. # Напишите программу, которая выводит имя, # под которым скрывается Эмиль Эрзог. # Дополнительно необходимо вывести область интересов указанной личности, # место рождения, годы рождения и смерти (если человек умер), # вычислить возраст на данный момент (или момент смерти). # Для хранения всех необходимых данных требуется использовать переменные. # После вывода информации программа должна дожидаться пока пользователь # нажмет Enter для выхода. #Чинкиров.В.В. # 28.03.2016 name = "Эмиль Эрзог" city = "Эльбёф,Франция" rod = int (1895) dead = int (1934) age = int (dead - rod) interest = "Писатель" print(name+" наиболее известен как Андреа Моруа - Французский писатель и член Французской академии. ") print("Место рождения: "+city) print("Год рождения: "+str(rod)) print("Год смерти: "+str(dead)) print("Возраст смерти: "+str(age)) print("Область интересов: "+interest) input("Нажмите Enter для закрытия")
# Here go your api methods. def get_prod_list(): prod_list = db(db.products).select( db.products.id, db.products.name, db.products.description, db.products.price, orderby=~db.products.price ).as_list() return response.json(dict(prod_list=prod_list)) def get_rev_list(): review_list = db(db.reviews).select( db.reviews.usr, db.reviews.product, db.reviews.cont, db.reviews.num, ).as_list() return response.json(dict(review_list=review_list)) @auth.requires_signature() def add_review(): rev_id = db.reviews.update_or_insert( (db.reviews.product == request.vars.product) & (db.reviews.usr == auth.user.email), usr=auth.user.email, cont=request.vars.cont, product=request.vars.product, num=request.vars.num, ) # We return the id of the new post, so we can insert it along all the others. return response.json(dict(rev_id=rev_id))
######## # BASE # ######## # Registration NICK = 'NICK' PASS = 'PASS' QUIT = 'QUIT' USER = 'USER' # Sent when registering a new user. # Channel ops INVITE = 'INVITE' JOIN = 'JOIN' KICK = 'KICK' LIST = 'LIST' MODE = 'MODE' NAMES = 'NAMES' PART = 'PART' TOPIC = 'TOPIC' # Server ops ADMIN = 'ADMIN' CONNECT = 'CONNECT' INFO = 'INFO' LINKS = 'LINKS' OPER = 'OPER' REHASH = 'REHASH' RESTART = 'RESTART' SERVER = 'SERVER' # Sent when registering as a server. SQUIT = 'SQUIT' STATS = 'STATS' SUMMON = 'SUMMON' TIME = 'TIME' TRACE = 'TRACE' VERSION = 'VERSION' WALLOPS = 'WALLOPS' # Sending messages NOTICE = 'NOTICE' PRIVMSG = 'PRIVMSG' # User queries WHO = 'WHO' WHOIS = 'WHOIS' WHOWAS = 'WHOWAS' # Misc ERROR = 'ERROR' KILL = 'KILL' PING = 'PING' PONG = 'PONG' # Optional AWAY = 'AWAY' USERS = 'USERS' USERHOST = 'USERHOST' ISON = 'ISON' # "Is on" ########### # REPLIES # ########### # 001 to 004 are sent to a user upon successful registration. RPL_WELCOME = '001' RPL_YOURHOST = '002' RPL_CREATED = '003' RPL_MYINFO = '004' # Sent by the server to suggest an alternative server when full or refused. RPL_BOUNCE = '005' # Reply to the USERHOST command. RPL_USERHOST = '302' # Reply to the ISON command (to see if a user "is on"). RPL_ISON = '303' # Sent to any client sending a PRIVMSG to a client which is away. RPL_AWAY = '301' # Acknowledgements of the AWAY command. RPL_UNAWAY = '305' RPL_NOWAWAY = '306' # Replies to a WHOIS message. RPL_WHOISUSER = '311' RPL_WHOISSERVE = '312' RPL_WHOISOPERATOR = '313' RPL_WHOISIDLE = '317' RPL_ENDOFWHOIS = '318' RPL_WHOISCHANNELS = '319' # Replies to WHOWAS command. See also ERR_WASNOSUCHNICK. RPL_WHOWASUSER = '314' RPL_ENDOFWHOWAS = '369' # Replies to LIST command. Note that 321 is obsolete and unused. RPL_LISTSTART = '321' RPL_LIST = '322' RPL_LISTEND = '323' # Replies to MODE. I don't understand the spec of 325! RPL_CHANNELMODEIS = '324' RPL_UNIQOPIS = '325' RPL_INVITELIST = '346' RPL_ENDOFINVITELIST = '347' RPL_EXCEPTLIST = '348' RPL_ENDOFEXCEPTLIST = '349' RPL_BANLIST = '367' RPL_ENDOFBANLIST = '368' RPL_UMODEIS = '221' # Replies to TOPIC. RPL_NOTOPIC = '331' RPL_TOPIC = '332' # Acknowledgement of INVITE command. RPL_INVITING = '341' # Acknowledgement of SUMMON command. RPL_SUMMONING = '342' # Reply to VERSION. RPL_VERSION = '351' # Reply to WHO. RPL_WHOREPLY = '352' RPL_ENDOFWHO = '315' # Reply to NAMES. RPL_NAMREPLY = '353' RPL_ENDOFNAMES = '366' # Reply to LINKS. RPL_LINKS = '364' RPL_ENDOFLINKS = '365' # Reply to INFO. RPL_INFO = '371' RPL_ENDOFINFO = '374' # Reply to MOTD. Also usually sent upon successful registration. RPL_MOTDSTART = '375' RPL_MOTD = '372' RPL_ENDOFMOTD = '376' # Acknowledgement of OPER. RPL_YOUREOPER = '381' # Acknowledgement of REHASH. RPL_REHASHING = '382' # Reply to SERVICE upon successful registration. RPL_YOURESERVICE = '383' # Reply to TIME. RPL_TIME = '391' # Replies to USERS. RPL_USERSSTART = '392' RPL_USERS = '393' RPL_ENDOFUSERS = '394' RPL_NOUSERS = '395' # Replies to TRACE. RPL_TRACELINK = '200' RPL_TRACECONNECTING = '201' RPL_TRACEHANDSHAKE = '202' RPL_TRACEUNKNOWN = '203' RPL_TRACEOPERATOR = '204' RPL_TRACEUSER = '205' RPL_TRACESERVER = '206' RPL_TRACESERVICE = '207' RPL_TRACENEWTYPE = '208' RPL_TRACECLASS = '209' RPL_TRACERECONNECT = '210' RPL_TRACELOG = '261' RPL_TRACEEND = '262' # Reply to STATS. See also ERR_NOSUCHSERVER. RPL_STATSLINKINFO = '211' RPL_STATSCOMMANDS = '212' RPL_ENDOFSTATS = '219' RPL_STATSUPTIME = '242' RPL_STATSOLINE = '243' # Reply to SERVLIST. RPL_SERVLIST = '234' RPL_SERVLISTEND = '235' # Reply to LUSERS. RPL_LUSERCLIENT = '251' RPL_LUSEROP = '252' RPL_LUSERUNKNOWN = '253' RPL_LUSERCHANNELS = '254' RPL_LUSERME = '255' # Reply to ADMIN. RPL_ADMINME = '256' RPL_ADMINLOC1 = '257' RPL_ADMINLOC2 = '258' RPL_ADMINEMAIL = '259' # Sent when a server drops a command without processing it. RPL_TRYAGAIN = '263' ########## # ERRORS # ########## ERR_NOSUCHNICK = '401' ERR_NOSUCHSERVER = '402' ERR_NOSUCHCHANNEL = '403' ERR_CANNOTSENDTOCHAN = '404' ERR_TOOMANYCHANNELS = '405' ERR_WASNOSUCHNICK = '406' ERR_TOOMANYTARGETS = '407' ERR_NOSUCHSERVICE = '408' ERR_NOORIGIN = '409' ERR_NORECIPIENT = '411' ERR_NOTEXTTOSEND = '412' ERR_NOTOPLEVEL = '413' ERR_WILDTOPLEVEL = '414' ERR_BADMASK = '415' ERR_UNKNOWNCOMMAND = '421' ERR_NOMOTD = '422' ERR_NOADMININFO = '423' ERR_FILEERROR = '424' ERR_NONICKNAMEGIVEN = '431' ERR_ERRONEUSNICKNAME = '432' ERR_NICKNAMEINUSE = '433' ERR_NICKCOLLISION = '436' ERR_UNAVAILRESOURCE = '437' ERR_USERNOTINCHANNEL = '441' ERR_NOTONCHANNEL = '442' ERR_USERONCHANNEL = '443' ERR_NOLOGIN = '444' ERR_SUMMONDISABLED = '445' ERR_USERSDISABLED = '446' ERR_NOTREGISTERED = '451' ERR_NEEDMOREPARAMS = '461' ERR_ALREADYREGISTRED = '462' ERR_NOPERMFORHOST = '463' ERR_PASSWDMISMATCH = '464' ERR_YOUREBANNEDCREEP = '465' ERR_YOUWILLBEBANNED = '466' ERR_KEYSET = '467' ERR_CHANNELISFULL = '471' ERR_UNKNOWNMODE = '472' ERR_INVITEONLYCHAN = '473' ERR_BANNEDFROMCHAN = '474' ERR_BADCHANNELKEY = '475' ERR_BADCHANMASK = '476' ERR_NOCHANMODES = '477' ERR_BANLISTFULL = '478' ERR_NOPRIVILEGES = '481' ERR_CHANOPRIVSNEEDED = '482' ERR_CANTKILLSERVER = '483' ERR_RESTRICTED = '484' ERR_UNIQOPPRIVSNEEDED = '485' ERR_NOOPERHOST = '491' ERR_UMODEUNKNOWNFLAG = '501' ERR_USERSDONTMATCH = '502' ######### # Other # ######### # Found in responses from freenode # Names from https://www.alien.net.au/irc/irc2numerics.html # Could not find in a spec. RPL_STATSCONN = '250' RPL_LOCALUSERS = '265' RPL_GLOBALUSERS = '266' RPL_CHANNEL_URL = '328'
# -*- coding: utf-8 -*- if __name__ == '__main__': Plant = lambda x: x + 2 FFC = lambda x: 1.1 * x + 1.9 FBC = lambda y: 0.9*y - 1.8 x = 5 x_ = x y = Plant(x) for k in range(100): ypre = FFC(x_) x_ = FFC(ypre) x_ = (x + x_) / 2 print(y, ypre)
""" Chaos 'probes' module. This module contains *probes* that collect state from an indy-node pool. By design, chaostoolkit runs an experiment if and only if 'steady state' is met. Steady state is composed of one or more '*probes*'. *Probes* gather and return system state data. An experiment defines a 'tolerance' (predicate) for each *probe* that must be true before the next *probe* is executed. All *probes* must pass the tolerance test before the system is considered to be in a steady state. When the steady state is met, the 'method' of the experiment will execute. An experiment's 'method' is composed of a list of one or more 'actions' that introduce 'chaos' (change state, impede traffic, induce faults, etc.) into the distributed system. Actions are executed in the order they are declared. Faults, failures, and exceptions encountered while executing an action do NOT cause an experiment to fail. All chaostoolkit cares about is if the steady state hypothesis is met before and after the method executes. However, a chaos engineer may consider a 'succeeded' result a failure if one or more of the actions encountered an exception, failure, etc. Each action's results are logged in the experiment's 'journal'. Manually or programmatically inspecting an experiment's journal may be required to decide if an experiment truely 'succeeded' or 'failed'. Actions applied to a system (changes, faults, etc.) should not cause predicatable failure. The purpose of an experiment is to introduce chaos to expose weakness/vulnerability, bottlenecks/inefficiency, etc. without causing systemic failure. If systemic failure is the result, either a bug exists or the experiment is too aggressive. Things to consider when adding or modifying probes: 1. Actions and *probes* could/may be used outside of Chaos experiments for other kinds of integration or systems testing. Therefore, *probes* should be written in a way they can reused outside of the context of the chaostoolkit. """
def gcdIter(a, b): ''' a, b: positive integers returns: a positive integer, the greatest common divisor of a & b. ''' # Your code here gcd = 1 if a > b: for i in range(b, 0, -1): if a % i == 0 and b % i == 0: gcd = i break else: for i in range(a, 0, -1): if a % i == 0 and b % i == 0: gcd = i break return gcd print(gcdIter(2, 12))
#English alphabet to be used in #decipher/encipher calculations. Alpha=['a','b','c','d','e','f','g', 'h','i','j','k','l','m','n', 'o','p','q','r','s','t','u', 'v','w','x','y','z'] def v_cipher(mode, text): if(mode == "encipher"): plainTxt = text cipher = "" key = input("Key:") key = key.upper() if(len(key) > len(plainTxt.strip())): print("Error key is larger than the message") exit() keyIndex = 0 for c in plainTxt: if(ord(c) >= 65 and ord(c) <= 90): m = ord(key[keyIndex]) - 65 k = ord(c) - 65 cipherCharNum = (m + k) % 26 cipherChar = Alpha[cipherCharNum].upper() cipher += cipherChar keyIndex += 1 keyIndex %= len(key) elif(ord(c) >= 97 and ord(c) <= 122): m = ord(key[keyIndex]) - 65 k = ord(c) - 97 cipherCharNum = (m + k) % 26 cipherChar = Alpha[cipherCharNum] cipher += cipherChar keyIndex += 1 keyIndex %= len(key) else: cipher += c print("Cipher:", cipher) elif(mode == "decipher"): cipher = text plainTxt = "" key = input("Key:") key = key.upper() if(len(key) > len(cipher.strip())): print("Error key is larger than the cipher") exit() keyIndex = 0 for c in cipher: if(ord(c) >= 65 and ord(c) <= 90): k = ord(key[keyIndex]) - 65 cNum = ord(c) - 65 plainCharNum =(26 + cNum - k) % 26 plainTxtChar = Alpha[plainCharNum].upper() plainTxt += plainTxtChar keyIndex += 1 keyIndex %= len(key) elif(ord(c) >= 97 and ord(c) <= 122): k=ord(key[keyIndex]) - 65 cNum=ord(c) - 97 plainCharNum = (26 + cNum - k ) %26 plainTxtChar=Alpha[plainCharNum] plainTxt += plainTxtChar keyIndex += 1 keyIndex %= len(key) else: plainTxt += c print("Message:", plainTxt)
class Match: def __init__(self, first_team, second_team, first_team_score, second_team_score): self.first_team = first_team self.second_team = second_team self.first_team_score = first_team_score self.second_team_score = second_team_score self.commentary = [] def __repr__(self): return str(self.__dict__)
def millis_interval(start, end): diff = end - start millis = diff.days * 24 * 60 * 60 * 1000 millis += diff.seconds * 1000 millis += diff.microseconds / 1000 return int(round(millis))
langversion = 1 langname = "Français" ##updater # text construct: "Version "+version+available+changelog #example: Version 3 available, click here to download, or for changelog click here available = "disponibles, cliquez pour télécharger" changelog = ", ou pour la liste des changements cliquez ici" ##world gen worldify = "depuis l'image" planetoids = "Planetoïds & Terra" arena = "Donjon Arena" flat = "Monde plat" new = "Nouveau monde :" ##mainmenu #omnitool settings = "Réglages" report_issue = "Reporter un bug" exit = "Sortir" #start start = "Démarrer" terraria = "Terraria" steamfree = "Terraria sans-Steam" #open open = "Ouvrez" imagefolder = "Images du monde" backupfolder = "Les sauvegardes du Monde" themes = "Thèmes Omnitool" #visit visit = "Visiter" donate = "Faire un don" homepage = "Omnitool" TO = "Terraria Online" wiki = "Terraria Wiki" ##world thumbnail label = "Monde : " ##settings menu warning = "Toutes les modifications nécessitent un redémarrage pour prendre effet" #out of date - not all changes require a restart now none = "Aucune" tiny = "Minuscule" #unused small = "Petite" medium = "Medium" large = "Grand" very_large = "XXL" theme_select = "Sélectionner un thème :" thumbsize = "Taille de la miniature du monde :" mk_backups = "Faire des sauvegardes :" world_columns = "Monde Colonnes :" ##world interaction menu wa_worldactionmenu = "Action pour {} :" wa_imageopen = "Ouvrir l'image" wa_renderopen = "Faire le rendu du monde" wa_teditopen = "Ouvrir dans TEdit" wa_update = "Mette à jour l'image" wa_super = "Generer une Super-Image" ##planetoids & terra pt_start = 'Démarrer génération !' pt_name = "Nom : " pt_mode = "Mode : " pt_small = "petites planetoïdes" pt_medium = "planetoïdes moyennes" pt_large = "grandes planetoïdes" pt_square = " planetoïdes carrées" pt_both = "grandes planetoïdes & Terra" pt_square_terra = "Terra carrés" pt_start_sel = "Démarrer : " pt_morning = "Matin" pt_day = "Jour" pt_night = "Nuit" pt_bloodmoon = "Lune de Sang" pt_extras = "Extras : " pt_sun = "Soleil : " pt_atlantis = "Atlantis : " pt_merchant = "Marchand : " pt_lloot = "Moins de butin : " pt_mirror = " Mode miroir : " pt_pre = "Préfixes des objets : " ##worldify w_start = "Démarrer la construction du monde !" w_cont = "Continuer" w_name = "Nom: " w_rgb = "RGB" w_hsv = "HSV pondéré" w_method = "Méthode : " w_priority = "Choix prioritaire" w_hue = "Teinte : " w_saturation = "Saturation : " w_brightness = "Luminosité : " ##arena a_start = "Démarrer génération!" a_name = "Nom : " a_rooms = "Cabines : " a_sidelen = "Longueur des côtés de cabines : " a_corlen = "Longueur corridor : " a_chest = "Coffre : " a_itemchest = "Objet par coffre : " a_light = "Eclairage : " a_chances = "Chances de cabine : " a_standard = "Standard : " a_cross = "Couloir de la croix : " ##torch at_chances = "Changement de couleur:" at_full = "Spectre complet" at_blue = "Bleu" at_red = "Rouge" at_green = "Vert" at_pink = "Rose" at_white = "Blanc" at_yellow = "Jaune" at_purple = "Mauve" at_lime = "Citron" ##plugins pl_start = "Démarrer le plugin" pl_rec = "Sélectionnez un monde qui sera reçu" pl_mod = "Sélectionnez un monde qui sera modifié" pl_trans = "Sélectionnez deux mondes pour le transfert" pl_trans_source = "Source" pl_trans_target = "Cible" ##flatworld fw_size = "Taille du monde :" fw_tiny = "minuscule" fw_square = "carré" fw_small = "petit" fw_medium = "moyen" fw_large = "grand" fw_tile = "Type de bloc :" fw_wall = "Type de mur :" fw_surf = "Type de surface :"
class Node(object): """docstring for Node""" def __init__(self, value): self.value = value self.edges = [] class Edge(object): """docstring for Edge""" def __init__(self, value, node_from, node_to): self.value = value self.node_from = node_from self.node_to = node_to class Graph(object): """docstring for Graph""" def __init__(self, nodes=[], edges=[]): self.nodes = nodes self.edges = edges def insert_node(self, new_node_value): """Creates a new node with the given value and inserts it into the graph's list of nodes""" new_node = Node(new_node_value) self.nodes.append(new_node) def insert_edge(self, new_edge_value, node_from_val, node_to_val): """Creates a new edge with a given value between nodes with the specified values. If no nodes exist with the given values, new nodes are created. The new edge is then added to the graph's list of edges, as well as the individual node's list of edges""" from_found = None to_found = None for node in self.nodes: if node_from_val == node.value: from_found = node if node_to_val == node.value: to_found = node if from_found is None: from_found = Node(node_from_val) self.nodes.append(from_found) if to_found is None: to_found = Node(node_to_val) self.nodes.append(to_found) new_edge = Edge(new_edge_value, from_found, to_found) from_found.edges.append(new_edge) to_found.edges.append(new_edge) self.edges.append(new_edge) def get_edge_list(self): """Returns a list of tuples, each representing an edge, that contain the edge value, the value of the origin node, and the value of the destination node""" edge_list = [] for edge in self.edges: edge_list.append((edge.value, edge.node_from.value, edge.node_to.value)) return edge_list def get_adjacency_list(self): """Returns a list of lists, list indices represent each node in the graph. Each sublist contains tuples for each outbound edge from the node. The tuples store the value of the connected node, and the value of the edge.""" adjacency_list = [] for node in self.nodes: sublist = [] for edge in node.edges: if edge.node_to != node: sublist.append((edge.node_to.value, edge.value)) if sublist: adjacency_list.append(sublist) else: adjacency_list.append(None) return adjacency_list def get_adjacenty_matrix(self): """Returns a list of lists, forming a matrix where the row represents the origin node and the column represents the destination node. If an edge exists between the origin and the destination, it's value is added to the appropriate position within the matrix""" adjacency_matrix = [] for node in self.nodes: matrix_row = [] counter = 1 for subnode in self.nodes: for edge in node.edges: if edge.node_to == subnode and edge.node_from == node: matrix_row.append(edge.value) if len(matrix_row) < counter: matrix_row.append(0) counter += 1 adjacency_matrix.append(matrix_row) return adjacency_matrix def dfs(self, start_node_num): """Outputs a list of numbers corresponding to the traversed nodes in a Depth First Search. ARGUMENTS: start_node_num is the starting node number (integer) RETURN: a list of the node values (integers).""" start_node = self.find_node(start_node_num) return self.dfs_helper(start_node, visited=[]) def bfs(self, start_node_num): """TODO: Create an iterative implementation of Breadth First Search iterating through a node's edges. The output should be a list of numbers corresponding to the traversed nodes. ARGUMENTS: start_node_num is the node number (integer) RETURN: a list of the node values (integers).""" ret_list = [start_node_num] for node_value in ret_list: node = self.find_node(node_value) for edge in node.edges: if edge.node_from == node and edge.node_to.value not in ret_list: ret_list.append(edge.node_to.value) return ret_list def dfs_helper(self, start_node, visited): """TODO: Write the helper function for a recursive implementation of Depth First Search iterating through a node's edges. The output should be a list of numbers corresponding to the values of the traversed nodes. ARGUMENTS: start_node is the starting Node Because this is recursive, we pass in the set of visited node values. RETURN: a list of the traversed node values (integers). """ if start_node: visited.append(start_node.value) for edge in start_node.edges: if edge.node_from == start_node and edge.node_to.value not in visited: visited = self.dfs_helper(edge.node_to, visited) return visited def find_node(self, node_value): """input: value output: first node in the graph with given value""" for node in self.nodes: if node_value == node.value: return node return None
''' Stepik001146PyBeginсh11p04st05TASK04_20210204_lists_methods.py Без дубликатов На вход программе подается натуральное число nn, а затем nn строк. Напишите программу, которая выводит только уникальные строки, в том же порядке, в котором они были введены. Формат входных данных На вход программе подаются натуральное число nn, а затем nn строк, каждая на отдельной строке. Формат выходных данных Программа должна вывести текст в соответствии с условием задачи. Примечание. Считайте, что все строки состоят из строчных символов. Sample Input: 5 first second first third second Sample Output: first second third ''' n = int(input()) wlist = [] wlist.append(input()) for i in range(n - 1): new_item = input() wlist.append(new_item) for j in range(len(wlist) - 1): if wlist[j] == new_item: del wlist[-1] for i in wlist: print(i)
''' module for calculating factorials of large numbers efficiently ''' def factorial(n: int): ''' Calculating factorial using prime decomposition ''' prime = [True] * (n + 1) result = 1 for i in range (2, n + 1): if (prime[i]): j = 2 * i while (j <= n): prime[j] = False j += i sum = 0 num = i while (num <= n): sum += n // num num *= i result *= i ** sum return result ''' PyAlgo Devansh Singh, 2021 '''
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Oct 6 16:29:07 2017 @author: Young """ # Placeholder
class Solution: def frequencySort(self, s: str) -> str: freq_dict = dict() output = "" for x in s: if x in freq_dict: freq_dict[x] += 1 else: freq_dict[x] = 1 refined_freq = sorted(freq_dict.items(), key=operator.itemgetter(1), reverse=True) for x in refined_freq: output += x[0] * x[1] return output
class Solution: def minMeetingRooms(self, intervals: List[List[int]]) -> int: time = [] for i in intervals: time.append((i[0], 1)) time.append((i[1], 0)) time.sort() count = maxCount = 0 for t in time: if t[1] == 1: count += 1 maxCount = max(maxCount, count) else: count -= 1 return maxCount
class Company(object): def __init__(self, name, title, start_date): self.name = name self.title = title self.start_date = start_date def getName(self): return self.name def getTitle(self): return self.title def getStartDate(self): return self.start_date
class FastSort2(): def __init__(self, elems = []): self._elems = elems def FS2(self, low, high): if low >= high: return i = low pivot = self._elems[low] for m in range(low + 1, high + 1): if self._elems[m] < pivot: i += 1 self._elems[i], self._elems[m] = self._elems[m], self._elems[i] self._elems[low], self._elems[i] = self._elems[i], self._elems[low] self.FS2(low, i-1) self.FS2(i+1, high) def get_res(self): return self._elems if __name__ == '__main__': test = [1, 5, 8, 2, 9, 26, 98, 34, 101, 76, 34, 26] k1 = FastSort2(test) k1.FS2(0, len(test) - 1) print(k1.get_res())
descriptor = ' {:<30} {}' message_help_required_tagname = descriptor.format('', 'required: provide a tag to scrape') message_help_required_login_username = descriptor.format('', 'required: add a login username') message_help_required_login_password = descriptor.format('', 'required: add a login password') message_help_required_users_to_remove = descriptor.format('', 'required: add users to remove') message_help_required_users_n_to_remove = descriptor.format('', 'required: add user numbers to remove') message_help_required_tags_to_remove = descriptor.format('', 'required: add tags to remove') message_help_required_tags_n_to_remove = descriptor.format('', 'required: add tag numbers to remove') message_help_required_max = descriptor.format('', 'required: provide a max number of posts to scrape') message_help_recommended_max = descriptor.format('', 'recommended: provide a max number of posts to scrape') message_help_required_logged_in = descriptor.format('', 'required: you need to be logged in') args_options = [ ['--login-username', 'the login username' + '\n' + message_help_required_login_username], ['--login-password', 'the login password' + '\n' + message_help_required_login_password], ['--update-users', 'Check all previously scraped users for new posts' + '\n' + message_help_recommended_max], ['--top-tags', 'scrape top tags' + '\n' + message_help_required_tagname], ['--recent-tags', 'scrape recent tags' + '\n' + message_help_required_tagname], ['--max', 'maximum number of posts to scrape' + '\n' + message_help_required_max], ['--stories', 'scrape stories also' + '\n' + message_help_required_logged_in], ['--headful', 'display the browser'], ['--list-users', 'list all scraped users'], ['--list-tags', 'list all scraped tags'], ['--remove-users', 'remove user(s)' + '\n' + message_help_required_users_to_remove], ['--remove-users-n', 'remove user(s) by number' + '\n' + message_help_required_users_n_to_remove], ['--remove-all-users', 'remove all users'], ['--remove-tags', 'remove tag(s)' + '\n' + message_help_required_tags_to_remove], ['--remove-tags-n', 'remove tag(s) by number' + '\n' + message_help_required_tags_n_to_remove], ['--remove-all-tags', 'remove all tags'], ['--version', 'program version'], ['--log', 'create log file'], ['--help', 'show help'] ] def print_help(): print('usage: ' + 'igscraper' + ' [username] [options]') print('') print('options: ') for i, argument in enumerate(args_options): print(descriptor.format(argument[0], argument[1]))
# # PySNMP MIB module Juniper-TSM-CONF (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-TSM-CONF # Produced by pysmi-0.3.4 at Mon Apr 29 19:53:51 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, ConstraintsIntersection, SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion") juniAgents, = mibBuilder.importSymbols("Juniper-Agents", "juniAgents") AgentCapabilities, ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "AgentCapabilities", "ModuleCompliance", "NotificationGroup") Counter32, Counter64, IpAddress, Bits, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, Unsigned32, ObjectIdentity, TimeTicks, ModuleIdentity, Integer32, MibIdentifier, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "Counter64", "IpAddress", "Bits", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "Unsigned32", "ObjectIdentity", "TimeTicks", "ModuleIdentity", "Integer32", "MibIdentifier", "NotificationType") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") juniTsmAgent = ModuleIdentity((1, 3, 6, 1, 4, 1, 4874, 5, 2, 67)) juniTsmAgent.setRevisions(('2003-10-27 22:50',)) if mibBuilder.loadTexts: juniTsmAgent.setLastUpdated('200310272250Z') if mibBuilder.loadTexts: juniTsmAgent.setOrganization('Juniper Networks, Inc.') juniTsmAgentV1 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 67, 1)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniTsmAgentV1 = juniTsmAgentV1.setProductRelease('Version 1 of the Terminal Server Management (TSM) component of the\n JUNOSe SNMP agent. This version of the TSM component is supported in\n JUNOSe 5.3 and subsequent system releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniTsmAgentV1 = juniTsmAgentV1.setStatus('current') mibBuilder.exportSymbols("Juniper-TSM-CONF", juniTsmAgent=juniTsmAgent, PYSNMP_MODULE_ID=juniTsmAgent, juniTsmAgentV1=juniTsmAgentV1)
def ready_jobs_dict_to_key(ready_jobs_list_dict): ready_jobs_list_key = ( "ready_jobs" + "_cpu_credits_" + str(ready_jobs_list_dict["cpu_credits"]) + "_gpu_credits_" + str(ready_jobs_list_dict["gpu_credits"]) ) return ready_jobs_list_key
{'application':{'type':'Application', 'name':'Template', 'backgrounds': [ {'type':'Background', 'name':'standaloneBuilder', 'title':u'PythonCard standaloneBuilder', 'size':(800, 610), 'statusBar':1, 'menubar': {'type':'MenuBar', 'menus': [ {'type':'Menu', 'name':'menuFile', 'label':'&File', 'items': [ {'type':'MenuItem', 'name':'menuFileNew', 'label':'&New\tCtrl+N', 'command':'newBtn', }, {'type':'MenuItem', 'name':'menuFileOpen', 'label':'&Open\tCtrl+O', 'command':'openBtn', }, {'type':'MenuItem', 'name':'menuFileSave', 'label':'&Save\tCtrl+S', 'command':'saveBtn', }, {'type':'MenuItem', 'name':'menuFileSaveAs', 'label':'Save &As...', }, {'type':'MenuItem', 'name':'fileSep2', 'label':'-', }, {'type':'MenuItem', 'name':'menuFileExit', 'label':'E&xit\tAlt+X', 'command':'menuFileExit', }, ] }, {'type':'Menu', 'name':'Edit', 'label':'&Edit', 'items': [ {'type':'MenuItem', 'name':'menuEditMainScript', 'label':u'&Main script...', 'command':'EditMainScript', }, {'type':'MenuItem', 'name':'menuEditChglog', 'label':u'&Changelog...', 'command':'editChgLog', }, {'type':'MenuItem', 'name':'menuEditReadme', 'label':u'&README...', 'command':'editReadme', }, {'type':'MenuItem', 'name':'menuEditSpecfile', 'label':u'&Spec file...', 'command':'editSpecFile', }, {'type':'MenuItem', 'name':'menuEditInnoFile', 'label':u'&Inno script...', 'command':'editInnoFile', }, {'type':'MenuItem', 'name':'menuEditProps', 'label':u'&Project properties...', 'command':'editProps', }, {'type':'MenuItem', 'name':'editSep1', 'label':'-', }, {'type':'MenuItem', 'name':'menuEditPrefs', 'label':u'&Preferences...', 'command':'editPrefs', }, ] }, {'type':'Menu', 'name':'menuTools', 'label':'&Tools', 'items': [ {'type':'MenuItem', 'name':'menuToolsLogAdd', 'label':u'A&dd changelog entry...\tShift++', 'command':'menuToolsLogAdd', }, {'type':'MenuItem', 'name':'menuToolsChkImport', 'label':u'&Check component imports', 'command':'menuToolsChkImport', }, {'type':'MenuItem', 'name':'toolSep1', 'label':'-', }, {'type':'MenuItem', 'name':'menuToolsAddScript', 'label':u'Add &script...', 'command':'addScript', }, {'type':'MenuItem', 'name':'menuToolsAddResource', 'label':u'Add &resource...', 'command':'addResource', }, {'type':'MenuItem', 'name':'menuToolsAddPixmap', 'label':u'Add &pixmap...', 'command':'addPixmap', }, {'type':'MenuItem', 'name':'menuToolsAddOther', 'label':u'Add &other...', 'command':'addOther', }, {'type':'MenuItem', 'name':'toolSep2', 'label':u'-', }, {'type':'MenuItem', 'name':'menuToolsRunMain', 'label':u'Run &main script', 'command':'runMainScript', }, {'type':'MenuItem', 'name':'toolSep3', 'label':u'-', }, {'type':'MenuItem', 'name':'menuToolsRebuild', 'label':'R&ebuild\tCtrl+R', 'command':'rebuildCmd', }, {'type':'MenuItem', 'name':'menuToolsRelease', 'label':u'&Release\tCtrl+M', 'command':'releaseCmd', }, ] }, {'type':'Menu', 'name':'menuHelp', 'label':'&Help', 'items': [ {'type':'MenuItem', 'name':'menuHelpManual', 'label':u'&Manual', 'command':'menuHelpManual', }, {'type':'MenuItem', 'name':'menuHelpAbout', 'label':u'&About standaloneBuilder...', 'command':'menuHelpAbout', }, ] }, ] }, 'strings': { u'testString':u'This is a test string', }, 'components': [ {'type':'Button', 'name':'mainScriptEditBtn', 'position':(375, 120), 'size':(52, 25), 'actionBindings':{}, 'command':'EditMainScript', 'font':{'faceName': u'Sans', 'size': 8}, 'label':'Edit...', 'toolTip':'Edit the main script', }, {'type':'StaticText', 'name':'versionString', 'position':(560, 125), 'actionBindings':{}, 'text':'n/a', }, {'type':'ImageButton', 'name':'newBtn', 'position':(5, 5), 'size':(38, 38), 'actionBindings':{}, 'backgroundColor':(255, 255, 255), 'border':'3d', 'command':'newBtn', 'file':'pixmaps/new.png', 'toolTip':'Create a new project', 'userdata':'frozen', }, {'type':'ImageButton', 'name':'openBtn', 'position':(40, 5), 'size':(38, 38), 'actionBindings':{}, 'backgroundColor':(255, 255, 255), 'border':'3d', 'command':'openBtn', 'file':'pixmaps/open.png', 'toolTip':'Open an existing project', 'userdata':'frozen', }, {'type':'ImageButton', 'name':'saveBtn', 'position':(75, 5), 'size':(38, 38), 'actionBindings':{}, 'backgroundColor':(255, 255, 255), 'border':'3d', 'command':'saveBtn', 'file':'pixmaps/save.png', 'toolTip':'Save the current project', 'userdata':'frozen', }, {'type':'ImageButton', 'name':'prefsBtn', 'position':(705, 5), 'size':(38, 38), 'actionBindings':{}, 'backgroundColor':(255, 255, 255), 'border':'3d', 'command':'editPrefs', 'file':'pixmaps/prefs.png', 'toolTip':'standaloneBuilder preferences', 'userdata':'frozen', }, {'type':'ImageButton', 'name':'quitBtn', 'position':(750, 5), 'size':(38, 38), 'actionBindings':{}, 'backgroundColor':(255, 255, 255), 'border':'3d', 'command':'quitBtn', 'file':'pixmaps/exit.png', 'toolTip':'Quit the program', 'userdata':'frozen', }, {'type':'TextField', 'name':'projectName', 'position':(95, 60), 'size':(250, -1), 'actionBindings':{}, }, {'type':'TextField', 'name':'projectIcon', 'position':(500, 60), 'size':(250, -1), 'actionBindings':{}, }, {'type':'Button', 'name':'iconBtn', 'position':(755, 60), 'size':(25, 25), 'actionBindings':{}, 'label':'...', }, {'type':'TextField', 'name':'baseDir', 'position':(95, 90), 'size':(250, -1), 'actionBindings':{}, }, {'type':'Button', 'name':'baseDirBtn', 'position':(350, 90), 'size':(25, 25), 'actionBindings':{}, 'label':'...', }, {'type':'TextField', 'name':'projectDesc', 'position':(500, 90), 'size':(250, -1), 'actionBindings':{}, }, {'type':'TextField', 'name':'mainScript', 'position':(95, 120), 'size':(250, -1), 'actionBindings':{}, }, {'type':'Button', 'name':'mainScriptBtn', 'position':(350, 120), 'size':(25, 25), 'actionBindings':{}, 'label':'...', }, {'type':'StaticBox', 'name':'StaticBox2', 'position':(5, 165), 'size':(380, 160), 'actionBindings':{}, 'label':'Script files:', }, {'type':'List', 'name':'scriptList', 'position':(15, 180), 'size':(360, 100), 'actionBindings':{}, 'items':[], }, {'type':'Button', 'name':'scriptAddBtn', 'position':(15, 285), 'actionBindings':{}, 'command':'addScript', 'label':'Add...', }, {'type':'Button', 'name':'scriptDelBtn', 'position':(100, 285), 'actionBindings':{}, 'label':'Remove', }, {'type':'Button', 'name':'scriptEditBtn', 'position':(185, 285), 'actionBindings':{}, 'label':'Edit...', }, {'type':'Button', 'name':'scriptDelAllBtn', 'position':(295, 285), 'actionBindings':{}, 'label':'Clear all', }, {'type':'StaticBox', 'name':'StaticBox3', 'position':(405, 165), 'size':(380, 160), 'actionBindings':{}, 'label':'Resource files:', }, {'type':'List', 'name':'resList', 'position':(415, 180), 'size':(360, 100), 'actionBindings':{}, 'items':[], }, {'type':'Button', 'name':'resAddBtn', 'position':(415, 285), 'actionBindings':{}, 'command':'addResource', 'label':'Add..', }, {'type':'Button', 'name':'resDelBtn', 'position':(500, 285), 'actionBindings':{}, 'label':'Remove', }, {'type':'Button', 'name':'resEditBtn', 'position':(585, 285), 'actionBindings':{}, 'label':'Edit...', }, {'type':'Button', 'name':'resDelAllBtn', 'position':(695, 285), 'actionBindings':{}, 'label':'Clear all', }, {'type':'StaticBox', 'name':'StaticBox4', 'position':(5, 325), 'size':(380, 160), 'actionBindings':{}, 'label':'Pixmap files:', }, {'type':'List', 'name':'pixmapList', 'position':(15, 340), 'size':(360, 100), 'actionBindings':{}, 'items':[], }, {'type':'Button', 'name':'pixmapAddBtn', 'position':(15, 445), 'actionBindings':{}, 'command':'addPixmap', 'label':'Add...', }, {'type':'Button', 'name':'pixmapDelBtn', 'position':(100, 445), 'actionBindings':{}, 'label':'Remove', }, {'type':'Button', 'name':'pixmapEditBtn', 'position':(185, 445), 'actionBindings':{}, 'label':'Edit...', }, {'type':'Button', 'name':'pixmapDelAllBtn', 'position':(295, 445), 'actionBindings':{}, 'label':'Clear all', }, {'type':'StaticBox', 'name':'StaticBox5', 'position':(405, 325), 'size':(380, 160), 'actionBindings':{}, 'label':'Other files:', }, {'type':'List', 'name':'otherList', 'position':(415, 340), 'size':(360, 100), 'actionBindings':{}, 'items':[], }, {'type':'Button', 'name':'docAddBtn', 'position':(415, 445), 'actionBindings':{}, 'command':'addOther', 'label':'Add...', }, {'type':'Button', 'name':'docDelBtn', 'position':(500, 445), 'actionBindings':{}, 'label':'Remove', }, {'type':'Button', 'name':'docEditBtn', 'position':(585, 445), 'actionBindings':{}, 'label':'Edit...', }, {'type':'Button', 'name':'docDelAllBtn', 'position':(695, 445), 'actionBindings':{}, 'label':'Clear all', }, {'type':'Button', 'name':'propertiesBtn', 'position':(15, 490), 'size':(85, -1), 'actionBindings':{}, 'command':'editProps', 'label':'Properties...', 'toolTip':'Change your projects properties', }, {'type':'Button', 'name':'changelogBtn', 'position':(100, 490), 'size':(85, -1), 'actionBindings':{}, 'command':'editChgLog', 'label':'Changelog...', 'toolTip':'Edit the changelog file', }, {'type':'Button', 'name':'readmeBtn', 'position':(100, 525), 'actionBindings':{}, 'command':'editReadme', 'label':'README...', 'toolTip':'Edit the README file', }, {'type':'Button', 'name':'specBtn', 'position':(185, 490), 'actionBindings':{}, 'command':'editSpecFile', 'label':'Spec file...', 'toolTip':'Edit the applications spec file', }, {'type':'Button', 'name':'innoBtn', 'position':(185, 525), 'size':(85, -1), 'actionBindings':{}, 'command':'editInnoFile', 'label':'Inno script...', 'toolTip':'Edit the Inno setup script for your application', }, {'type':'Button', 'name':'runBtn', 'position':(295, 490), 'actionBindings':{}, 'command':'runMainScript', 'label':'Run...', 'toolTip':'Run the application', }, {'type':'Button', 'name':'rebuildBtn', 'position':(695, 490), 'actionBindings':{}, 'command':'rebuildCmd', 'label':'Rebuild', 'toolTip':'Rebuild the standalone version of your application', 'userdata':'frozen', }, {'type':'Button', 'name':'releaseBtn', 'position':(695, 525), 'actionBindings':{}, 'command':'releaseCmd', 'label':'Release', 'toolTip':'Make a release of your finished application', 'userdata':'frozen', }, {'type':'StaticBox', 'name':'StaticBox1', 'position':(5, 45), 'size':(780, 115), 'actionBindings':{}, 'label':'Project:', }, {'type':'StaticText', 'name':'StaticText5', 'position':(15, 125), 'actionBindings':{}, 'text':'Main script', }, {'type':'StaticText', 'name':'StaticText4', 'position':(420, 95), 'actionBindings':{}, 'text':'Description', }, {'type':'StaticText', 'name':'StaticText9', 'position':(430, 65), 'actionBindings':{}, 'text':'Icon (Win)', }, {'type':'StaticText', 'name':'StaticText8', 'position':(500, 125), 'actionBindings':{}, 'text':'Version', }, {'type':'StaticText', 'name':'StaticText7', 'position':(15, 95), 'actionBindings':{}, 'text':'Directory', }, {'type':'StaticText', 'name':'StaticText6', 'position':(15, 65), 'actionBindings':{}, 'text':'Name', }, ] # end components } # end background ] # end backgrounds } }
class Error(Exception): def __init__(self, typ, start_pos, end_pos, details) -> None: self.typ = typ self.details = details self.start_pos = start_pos self.end_pos = end_pos def __repr__(self) -> str: return f"{self.typ} : {self.details} ({self.start_pos.idx}, {self.end_pos.idx})" class InvalidIdentifier(Error): def __init__(self, start_pos, end_pos, details) -> None: super().__init__("Invalid Identifier", start_pos, end_pos, details)
class PathAnalyzerStore: """ Maps extensions to analyzers. To be used for storing the analyzers that should be used for specific extensions in a directory. """ #################################################################################################################### # Constructor. #################################################################################################################### def __init__(self): # This dictionary stores the corresponding analyzer for each extension. self._analyzers_by_extensions = {} #################################################################################################################### # Public methods. #################################################################################################################### def add_analyzer(self, extensions, analyzer): for extension in extensions: if extension in self._analyzers_by_extensions: raise Exception( F'Invalid configuration, an analyzer is already registered for the extension "{extension}". Do not ' 'register multiple rules for the same extensions in a directory.') self._analyzers_by_extensions[extension] = analyzer def find_analyzer(self, extension): return self._analyzers_by_extensions.get(extension, None)
class ListNode: def __init__(self, x): self.val = x self.next = None def insert(head, x): new_node = ListNode(x) if head is None: head = new_node return last_node = head while last_node.next: last_node = last_node.next last_node.next = new_node def printList(head): curr_node = head while curr_node: print(f'{curr_node.val}', "->", end=" ") curr_node = curr_node.next print() def deleteNode(head, position): prev_node = None curr_node = head i = 1 while curr_node and i != position: prev_node = curr_node curr_node = curr_node.next i += 1 if curr_node is None: return prev_node.next = curr_node.next def removeNthFromEnd(head, n): dummy_head = ListNode(0) dummy_head.next = head fast = slow = dummy_head for i in range(n): fast = fast.next while fast and fast.next: fast = fast.next slow = slow.next slow.next = slow.next.next return dummy_head.next node = ListNode(8) insert(node, 1) insert(node, 7) insert(node, 3) insert(node, 9) printList(node) removeNthFromEnd(node, 2) printList(node)
class Client(): def __init__(self, player): #self.clientSocket pass def connect(self): pass def sending(self): pass def getting(self): pass def serverHandling(self): pass
""" Monthly Backups Description: This script is run weekly on Sunday at 2 AM and generates weekly backups. On Rojo we keep weekly backups going back 1 month, we keep monthly backups going back 6 months, and we put older backups into cold storage. Directory Stucture: junkinthetrunk/ backups/ weekly/ weekly.4.tar.gz --> weekly.2018-01-28.tar.gz weekly.3.tar.gz --> weekly.2018-01-21.tar.gz weekly.2.tar.gz --> weekly.2018-01-14.tar.gz weekly.1.tar.gz --> weekly.2018-01-07.tar.gz monthly/ monthly.6.tar.gz --> monthly.2018-01-07.tar.gz monthly.5.tar.gz --> monthly.2017-12-03.tar.gz monthly.4.tar.gz --> monthly.2017-11-05.tar.gz monthly.3.tar.gz --> monthly.2017-10-01.tar.gz monthly.2.tar.gz --> monthly.2017-09-03.tar.gz monthly.1.tar.gz --> monthly.2017-08-06.tar.gz """
# -*- coding: utf-8 -*- # Scrapy settings for state_scrapper project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://docs.scrapy.org/en/latest/topics/settings.html # https://docs.scrapy.org/en/latest/topics/downloader-middleware.html # https://docs.scrapy.org/en/latest/topics/spider-middleware.html BOT_NAME = 'state_scrapper' SPIDER_MODULES = ['state_scrapper.spiders'] NEWSPIDER_MODULE = 'state_scrapper.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent USER_AGENT = 'state_scrapper (+http://www.mobicrol.com)' # Obey robots.txt rules ROBOTSTXT_OBEY = True # Configure maximum concurrent requests performed by Scrapy (default: 16) #CONCURRENT_REQUESTS = 32 # Configure a delay for requests for the same website (default: 0) # See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs DOWNLOAD_DELAY = 3.0 # The download delay setting will honor only one of: CONCURRENT_REQUESTS_PER_DOMAIN = 16 #CONCURRENT_REQUESTS_PER_IP = 16 # Disable cookies (enabled by default) #COOKIES_ENABLED = False # Disable Telnet Console (enabled by default) #TELNETCONSOLE_ENABLED = False # Override the default request headers: #DEFAULT_REQUEST_HEADERS = { # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', # 'Accept-Language': 'en', #} # Enable or disable spider middlewares # See https://docs.scrapy.org/en/latest/topics/spider-middleware.html #SPIDER_MIDDLEWARES = { # 'state_scrapper.middlewares.StateScrapperSpiderMiddleware': 543, #} # Enable or disable downloader middlewares # See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html #DOWNLOADER_MIDDLEWARES = { # 'state_scrapper.middlewares.StateScrapperDownloaderMiddleware': 543, #} # Enable or disable extensions # See https://docs.scrapy.org/en/latest/topics/extensions.html #EXTENSIONS = { # 'scrapy.extensions.telnet.TelnetConsole': None, #} # Configure item pipelines # See https://docs.scrapy.org/en/latest/topics/item-pipeline.html ITEM_PIPELINES = { #'state_scrapper.pipelines.StateScrapperPipeline': 100, 'state_scrapper.pipelines.DuplicatesPipeline': 200, 'state_scrapper.pipelines.DatabasePipeline': 300 } # Enable and configure the AutoThrottle extension (disabled by default) # See https://docs.scrapy.org/en/latest/topics/autothrottle.html #AUTOTHROTTLE_ENABLED = True # The initial download delay AUTOTHROTTLE_START_DELAY = 3 # The maximum download delay to be set in case of high latencies #AUTOTHROTTLE_MAX_DELAY = 60 # The average number of requests Scrapy should be sending in parallel to # each remote server #AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0 # Enable showing throttling stats for every response received: #AUTOTHROTTLE_DEBUG = False # Enable and configure HTTP caching (disabled by default) # See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings HTTPCACHE_ENABLED = False #HTTPCACHE_EXPIRATION_SECS = 0 #HTTPCACHE_DIR = 'httpcache' #HTTPCACHE_IGNORE_HTTP_CODES = [] #HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage' DB_SETTINGS = { 'database': 'mobicrol_DB', 'user': 'mobicrol_admin', 'password': "X->e^QW%K{|v12~#", 'host': 'mobicrol.heliohost.org', } APIMAPS_SETTINGS ={ 'endpoint': 'https://reverse.geocoder.ls.hereapi.com/6.2/reversegeocode.json', #?apiKey=w0AqGhEuRk7POniPcharjnQ7uKIWgvFhJZbbaAe2hOw&mode=retrieveAddresses&prox=4.724455,-74.03006 'apiKey': 'w0AqGhEuRk7POniPcharjnQ7uKIWgvFhJZbbaAe2hOw' }
__author__ = 'Robbert Harms' __date__ = "2015-05-04" __maintainer__ = "Robbert Harms" __email__ = "[email protected]" class ScannerSettingsParser(object): def get_value(self, key): """Read a value for a given key for all sessions in settings file. The settings file is supposed to be given in the constructor. Args: key (str): The name of the key to read Returns: dict: A dictionary with as keys the session names and as values the requested value for the key. """ class InfoReader(object): def get_read_out_time(self): """Get the read out time from the settings file. The settings file is supposed to be given to the constructor. Returns: float: The read out time in seconds. """
# -*- coding: utf-8 -*- CATEGORIES = ( (u'dania-miesne', u'Dania mięsne'), (u'dania-rybne', u'Dania rybne'), (u'dania-wegetarianskie', u'Dania wegetariańskie'), (u'inne', u'Inne'), (u'kolacje', u'Kolacje'), (u'przekaski', u'Przekąski'), (u'salatki-surowki', u'Sałatki i surówki'), (u'sniadania', u'Śniadania'), (u'wypieki', u'Wypieki'), (u'zupy', u'Zupy'), ) CATEGORIES_SV = dict(CATEGORIES) CATEGORIES_VS = dict(((v, k) for k, v in CATEGORIES)) PHASES = (u'Faza I i II' ,u'Faza II', u'Odstępstwo') TYPES = (u'Tłuszczowy', u'Węglowodanowy', u'Mieszany') TIMES = ( (u'15',u'Do 15 min.'), (u'30',u'Do pół godziny'), (u'60',u'Do godziny'), (u'90',u'Do półtorej godziny'), (u'120',u'Do dwóch godzin'), (u'240',u'Ponad dwie godziny'), ) TIMES_KEYS = (15, 30, 60, 90, 120, 240) TIMES_SV = dict(TIMES) PORTION_WEIGHTS = (u'g', u'kg', u'ml', u'l', u'sztuka', u'łyżeczka płaska', u'łyż. stołowa płaska', u'szklanka', u'szczypta', u'kropla') VISIBILITY = (u'Mnie', u'Znajomych', u'Wszystkich') SHARD_RECIPE_KEY = 'recipe|%s' ORDERINGS = { 'nowe': '-created', 'popularne': '-views', 'tytul': 'title', }
n = int(input()) a = sorted(list(map(int, input().split(" ")))) while len(a) > 0: print(len(a)) a = sorted(list(filter(lambda x: x > 0, map(lambda x: x - a[0], a))))
config = dict( agent=dict(), algo=dict(), env=dict( game="pong", num_img_obs=1, ), model=dict(), optim=dict(), runner=dict( n_steps=5e6, # log_interval_steps=1e5, ), sampler=dict( batch_T=20, batch_B=32, max_decorrelation_steps=1000, ), ) configs = dict( default=config )
class Solution: def findGoodStrings(self, n, s1, s2, evil): M = 10 ** 9 + 7 m = len(evil) memo = {} # KMP dfa = self.failure(evil) def dfs(i, x, bound): if x == m: return 0 if i == n: return 1 if (i, x, bound) not in memo: cnt = 0 lo = ord('a' if bound & 1 else s1[i]) # "be*" -> {"be*", "ca*", ..}, 'b' when bound bit = ?0 hi = ord('z' if bound & 2 else s2[i]) # "do*" -> {"cz*", "do*", ..}, 'd' when bound bit = 0? for j, c in enumerate(chr(o) for o in range(lo, hi + 1)): y = x while y and evil[y] != c: y = dfa[y - 1] y += evil[y] == c cnt = (cnt + dfs(i + 1, y, bound | (j > 0) | (j < hi - lo) << 1)) % M memo[i, x, bound] = cnt return memo[i, x, bound] return dfs(0, 0, 0) def failure(self, evil): res = [0] * len(evil) i, j = 1, 0 while i < len(evil): if evil[i] == evil[j]: res[i] = j + 1 j += 1 i += 1 elif j != 0: j = res[j - 1] else: res[i] = 0 i += 1 return res
""" RANGE: 3 parameters [start,stop,step] Code to print the odd integers in the specified range from 5 to -10 by assigning negative step value """ start = 5 stop = -10 step = -2 print("Odd numbers from 5 to -10 are: ") for num in range(start,stop,step): print(num) ''' OUTPUT: Odd numbers from 5 to -10 are: 5 3 1 -1 -3 -5 -7 -9 '''
# -*- coding: utf-8 -*- """ Created on Thu Jun 23 00:20:58 2016 @author: DrCollins The merging procedure is an essential part of “Merge Sort” (which is considered in one of the next problems). Given: A positive integer n ≤ 10**5 and a sorted array A[1..n] of integers from −10**5 to 10**5, a positive integer m ≤ 10**5 and a sorted array B[1..m] of integers from −10**5 to 10**5. Return: A sorted array C[1..n+m] containing all the elements of A and B. Sample Dataset 4 2 4 10 18 3 -5 11 12 Sample Output -5 2 4 10 11 12 18 """ def merge_arrays(): with open("rosalind_mer.txt") as input_file: A_size = int(input_file.readline().strip()) A_arr = [int(x) for x in input_file.readline().split()] B_size = int(input_file.readline().strip()) B_arr = [int(x) for x in input_file.readline().split()] merged_list = [] while (B_arr or A_arr): if not A_arr: merged_list.extend(B_arr) return merged_list elif not B_arr: merged_list.extend(A_arr) return merged_list elif A_arr[0] <= B_arr[0]: merged_list.append(A_arr.pop(0)) else: merged_list.append(B_arr.pop(0)) return merged_list merged = (merge_arrays()) with open("merge_arrays_output.txt", "w") as out_file: out_file.write(' '.join([str(x) for x in merged]))
# 给定一个正整数 rows,生成rows行杨辉三角 # C(rows,cols) = C(rows-1,cols-1) + C(rows-1,cols) rows = 8 triangle = [] for i in range(rows): tmp = [1] * (i + 1) triangle.append(tmp) for j in range(1, i): triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j] for row in triangle: print(row)
#!/usr/bin/env python xlist = [1, 3, 5, 7, 1] ylist = [1, 1, 1, 1, 2] totaltrees = 1 with open('input.txt', 'r', encoding='utf-8') as input: all_lines = input.readlines() for i in range(5): x = xlist[i] y = ylist[i] trees = 0 posx = 0 posy = 0 iterations = 1 for line in all_lines: if y == 2 and posy % 2 == 1: posy = posy + 1 else: curline = '' line = line.rstrip() for iter in range(iterations): curline = curline + line linelist = list(curline) if linelist[posx] == '#': linelist[posx] = 'X' trees = trees + 1 else: linelist[posx] = 'O' posx = posx + x if posx >= len(curline): iterations = iterations + 1 posy = posy + 1 totaltrees = totaltrees * trees print('Iteration ' + str(i+1) + ' trees: ' + str(trees)) if i < 4: print('Total trees so far: ' + str(totaltrees)) print('Total trees: ' + str(totaltrees))
class PriorityQueue: def __init__(self, arr: list = [], is_min=True): self.arr = arr self.minmax = min if is_min else max self.heapify() @staticmethod def children(i): return (2 * i + 1, 2 * i + 2) @staticmethod def parent(i): return (i - 1) // 2 @staticmethod def is_root(i): return i == 0 def is_empty(self): return self.size() == 0 def size(self): return len(self.arr) def compare(self, i, j): if self.minmax(self.arr[i], self.arr[j]) == self.arr[j]: return True return False def swap(self, i, j): self.arr[i], self.arr[j] = self.arr[j], self.arr[i] def heapify(self): for i in range(self.size() // 2 - 1, -1, -1): self.move_down(i) def move_down(self, i=0): while 2 * i + 1 < self.size(): l, r = PriorityQueue.children(i) j = i if self.compare(j, l): j = l if r < self.size() and self.compare(j, r): j = r if i == j: break self.swap(i, j) i = j def move_up(self, i): while not PriorityQueue.is_root(i): p = PriorityQueue.parent(i) if not self.compare(p, i): break self.swap(p, i) i = p def push(self, num): self.arr.append(num) self.move_up(self.size() - 1) def pop(self): if self.is_empty(): return None root = self.arr[0] new_root = self.arr[-1] self.arr[0] = new_root self.arr.pop() if not self.is_empty(): self.move_down() return root if __name__ == "__main__": q = PriorityQueue([], False) for i in range(10): i = int(input()) q.push(i) print("=============") while not q.is_empty(): print(q.pop(), end=" ")
# Written by Pavel Jahoda #This class is used for evaluating and processing the results of the simulations class Evaluation: #TODO, implement evaluation class def __init__(self): pass def processResults(self,n_of_blocked_calls, n_of_dropped_calls, n_of_calls, n_of_channels_reverved): pass def evaluate(self): pass #generator class with distribution and parameters based on analyzed input data class Generator(): #TODO create def __init__(self): self.dummy_return_value = 0 def generate_speed(self): return self.dummy_return_value def generate_station(self): return self.dummy_return_value def generate_position(self): return self.dummy_return_value def generate_duration(self): return self.dummy_return_value def generate_direction(self): return self.dummy_return_value def generate_next_initiation(self): return Object() def generate_next_handover(self,obj): return Object() def generate_next_termination(self,obj): return Object() # The driving and calling object class Object(): def __init__(self, duration, speed, station, position, direction): self.duration = duration self.speed = speed self.station = station self.position = position self.direction = direction class Simualation(): def __init__(self): # system clock, which will be updated outside of events self.clock = 0 self.n_of_dropped_calls = 0 self.n_of_blocked_calls = 0 # desired number of calls in the simulation self.n_of_calls = 100 self.n_of_channels_reverved = 0 # we will update this number until we reach our # desired number of initiation calls self.n_of_calls_created = 0 self.generator = Generator() # we will have a list-like data structure that will # keep events sorted by the simulated time # [time of next event in seconds, type of event, # Object(speed, call duration etc)] # type of event -> 0: i self.eventList = [] # how many free channels each station currently has self.free_channels_by_station = [10 for i in range(20)] # parameter - number of channels reserved for handovers # when other channels are not available def Simulate(self, n_of_channels_reverved): self.n_of_channels_reverved = n_of_channels_reverved # generate first initiation self.eventList.append(self.generator.generate_next_initiation()) self.n_of_calls_created += 1 while len(self.eventList) != 0: # update the system clock time to the time of next event self.clock = self.eventList[0][0] # depending on the type of the object in the event list, # call function initiation, termination or handover if self.eventList[0][1] == 0: # if the event is new call, generate another call self.Initiation(self.eventList[0][2]) elif self.eventList[0][1] == 1: # handover self.Handover(self.eventList[0][2]) else: # termination self.Termination(self.eventList[0][2]) # after we make the call we update the event list and remove the first item self.eventList = self.eventList[1:] self.eventList.sort() return self.n_of_blocked_calls, self.n_of_dropped_calls, self.n_of_calls, self.n_of_channels_reverved def CalculateHowLongTillNextEvent(self, obj): kmTillNextEvent = obj.position % 2 # position modulo 2 kmTillNextEvent = kmTillNextEvent + 2 if kmTillNextEvent == 0 else kmTillNextEvent if obj.direction == 'RIGHT' and kmTillNextEvent != 2: kmTillNextEvent = 2 - kmTillNextEvent return kmTillNextEvent/obj.speed * 3600 # in seconds def Initiation(self, obj): blocked = False if self.free_channels_by_station[obj.station] - self.n_of_channels_reverved > 0: self.free_channels_by_station[obj.station] -= 1 else: self.n_of_blocked_calls += 1 blocked = True if not blocked: # Car leaving the highway, no other handover can occur if (obj.station == 0 and obj.direction == 'LEFT') or \ (obj.station == 19 and obj.direction == 'RIGHT'): self.eventList.append(self.generator.generate_next_termination(obj)) else: # handover self.eventList.append(self.generator.generate_next_handover(obj)) if self.n_of_calls_created != self.n_of_calls: # generate next initiation self.eventList.append(self.generator.generate_next_initiation()) self.n_of_calls_created += 1 def Termination(self, obj): self.free_channels_by_station[obj.station] += 1 def Handover(self, obj): # in the parameter station we use the new station that driver drives towards # first let's free the channel used of the previous station if obj.direction: self.free_channels_by_station[obj.station - 1] += 1 else: self.free_channels_by_station[obj.station + 1] += 1 if self.free_channels_by_station[obj.station] > 0: self.free_channels_by_station[obj.station] -= 1 # Car leaving the highway, no other handover can occur if (obj.station == 0 and obj.direction == 'LEFT') or \ (obj.station == 19 and obj.direction == 'RIGHT'): self.eventList.append(self.generator.generate_next_termination(obj)) else: # handover self.eventList.append(self.generator.generate_next_handover(obj)) else: self.n_of_dropped_calls += 1 def main(): n_of_iteratins = 1 # adjust number of iterations of the simulation evaluation = Evaluation() print('start') # We will run each simulation multiple times and evaluate the results at the end of the program run for i in range(n_of_iteratins): simulation = Simualation() evaluation.evaluate(simulation.Simulate(0)) for i in range(n_of_iteratins): simulation = Simualation() evaluation.evaluate(simulation.Simulate(1)) evaluation.evaluate() if __name__ == '__main__': main()
def fetching_episode(episode_name, stream_page): tag = "[ FETCHING ]" print(tag, episode_name, stream_page) def fetched_episode(episode_name, stream_url, success): tag = "[ SUCCESS ] " if success else "[ FAILED ] " print(tag, episode_name, stream_url, end="\n\n") def fetching_list(anime_url): print("Fetching episode list ;", anime_url, end="\n\n")
# definition class OriginalException(Exception): pass
menu = ['deathnote', 'netflix', 'teaching'] # for i in range(len(menu)): # print(i + 1,'. ',menu[i],sep='') for index, item in enumerate(menu): print(index + 1,'. ',item,sep='') # for item in menu: # print(item)
class landShift(): def __init__(self): self.shiftList = [] self.unwarpPts = [] def addPos(self, shift): self.shiftList.append(shift) if len(self.shiftList)>10: self.shiftList = self.shiftList[1:] def getVelocity(self): if len(self.shiftList): totalT = sum(self.shiftList) aveShift = totalT / len(self.shiftList) return aveShift else: return 0 def addUnwarpPts(self, pts): self.unwarpPts = pts def getUnwarpPts(self): return self.unwarpPts
""" Desafio 053 Problema: Crie um programa que leia uma frase qualquer e diga se ela é um palíndromo, desconsiderando os espaços. Ex: apos a sopa a sacada da casa a torre da derrota o lobo ama o bolo anotaram a data da maratona Resolução do problemas: """ frase = input('Digite uma frase: ').strip().replace(' ', '').lower() for idx in range(0, len(frase) // 2): # range terá o final como a metade do comprimento da frase if frase[idx] == frase[-(idx + 1)]: # frase[-(idx + 1)] percorerá a frase da última letra até a primeira if idx + 1 == len(frase) // 2: print('Essa frase informada é um palíndromo.') break else: print('Essa frase informada não é um palíndromo.') break
# Caio Beraldi Ribeiro class contiguity_list: def __init__(self, size): self.node = [0] * size self.begin = 0 self.end = -1 self.size = size def show_list(self): aux = self.begin if (aux == - 1): print("contiguity_list inexistente") else: print(self.node) def locate_node(self, value): i = 0 self.end = self.size if(value <= self.end or value >= self.begin): for i in range(self.end): if (value == self.node[i]): return print("Valor procurada", value, ",encontrado na posição", i + 1) else: print("Valor não encontrado!") def insert_node(self, location, value): if ((location > self.size - 1) or ((location < self.begin) and (location > self.end - 1))) : print ("Error: Posição não encontrada ou inválida") else: if (self.begin == - 1): self.end = 0 for i in range (self.begin, self.begin + location): self.node[i - 1] = self.node[i] self.begin = self.begin - 1 self.node[self.begin + location ] = value def remove_node(self, location): if ((location > self.size - 1) or ((location < self.begin) and (location > self.end - 1))) : print ("Posição não encontrada ou inválida") else: self.node[self.begin + location ] = None def destroy(self): self.node = None self.begin = - 1 self.end = -1 self.size = 0 contiguity_list = contiguity_list(10) contiguity_list.insert_node(9, 666) contiguity_list.insert_node(0, 9) contiguity_list.insert_node(1, 8) contiguity_list.insert_node(2, 7) contiguity_list.insert_node(3, 6) contiguity_list.insert_node(4, 5) contiguity_list.insert_node(5, 4) contiguity_list.insert_node(6, 3) contiguity_list.insert_node(7, 2) contiguity_list.insert_node(8, 1) contiguity_list.show_list() contiguity_list.locate_node(666) contiguity_list.locate_node(3) contiguity_list.remove_node(0) contiguity_list.remove_node(1) contiguity_list.remove_node(2) contiguity_list.remove_node(3) contiguity_list.remove_node(4) contiguity_list.remove_node(5) contiguity_list.remove_node(6) contiguity_list.remove_node(7) contiguity_list.remove_node(8) contiguity_list.remove_node(9) contiguity_list.show_list() contiguity_list.insert_node(4, 1) contiguity_list.insert_node(8, 3) contiguity_list.show_list() contiguity_list.locate_node(3) # backup
def swap_case(s): returnString = "" for character in s: if character.islower(): returnString += character.upper() else: returnString += character.lower() return returnString
def no_teen_sum(a, b, c): def fix_teen(n): if n ==15 or n==16: return n if 13<=n<=19: return 0 else: return n sum = fix_teen(a)+ fix_teen(b)+ fix_teen(c) return sum def round_sum(a, b, c): def round10(num): if num%10<5: return num/10 * 10 else: return (num/10+1)*10 sum = round10(a)+round10(b)+round10(c) return sum def close_far(a, b, c): def is_close(x): return abs(x-a)<=1 def is_far(x, y1, y2): return abs(x-y1)>=2 and abs(x-y2)>=2 def haha(x,y): return is_close(x) and is_far(y, x, a) return haha(b,c) or haha(c,b)
''' This code is written by bidongqinxian ''' def quick_sort(lst): if not lst: return [] base = lst[0] left = quick_sort([x for x in lst[1: ] if x < base]) right = quick_sort([x for x in lst[1: ] if x >= base]) return left + [base] + right
K, N, F = map(int, input().split()) A = list(map(int, input().split())) t = K * N - sum(A) if t < 0: print(-1) else: print(t)
_base_ = [ '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] # model settings model = dict( type='FCOS', pretrained='open-mmlab://detectron/resnet50_caffe', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=False), norm_eval=True, style='caffe'), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=1, add_extra_convs=True, extra_convs_on_inputs=False, # use P5 num_outs=5, relu_before_extra_convs=True), bbox_head=dict( type='FCOSHead', num_classes=7, in_channels=256, stacked_convs=4, feat_channels=256, strides=[8, 16, 32, 64, 128], norm_cfg=None, loss_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0), loss_bbox=dict(type='IoULoss', loss_weight=1.0), loss_centerness=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0))) # training and testing settings train_cfg = dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.4, min_pos_iou=0, ignore_iof_thr=-1), allowed_border=-1, pos_weight=-1, debug=False) test_cfg = dict( nms_pre=1000, min_bbox_size=0, score_thr=0.05, nms=dict(type='nms', iou_thr=0.5), max_per_img=100) img_norm_cfg = dict( mean=[102.9801, 115.9465, 122.7717], std=[1.0, 1.0, 1.0], to_rgb=False) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), # dict(type='Resize', img_scale=(1333, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1920, 1080), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] dataset_type = 'IKCESTDetDataset' data_root = '/root/vsislab-2/zq/data/IKCEST3rd_bbox_detection/' data = dict( samples_per_gpu=6, workers_per_gpu=2, train=dict( type=dataset_type, ann_file=data_root + 'annotations/ikcest_train_bbox_annotations.json', img_prefix=data_root + 'train/', pipeline=train_pipeline), val=dict( type=dataset_type, ann_file=data_root + 'annotations/ikcest_val_bbox_annotations.json', img_prefix=data_root + 'val/', pipeline=test_pipeline), test=dict( type=dataset_type, ann_file=data_root + 'annotations/ikcest_val_bbox_annotations.json', img_prefix=data_root + 'val/', pipeline=test_pipeline)) evaluation = dict(interval=1, metric='bbox') # optimizer optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001, paramwise_cfg=dict(bias_lr_mult=2., bias_decay_mult=0.)) optimizer_config = dict(_delete_=True, grad_clip=dict(max_norm=100, norm_type=2)) # learning policy lr_config = dict(warmup='constant') total_epochs = 12 checkpoint_config = dict(interval=1) # yapf:disable log_config = dict( interval=20, hooks=[ dict(type='TextLoggerHook'), # dict(type='TensorboardLoggerHook') ]) # yapf:enable dist_params = dict(backend='nccl') log_level = 'INFO' load_from = None resume_from = None workflow = [('train', 1)]
#! /usr/bin/env python # -*- coding: utf-8 -*- LANGUAGE_EN_NAMES_MAP = { 'de': 'German', 'en': 'English', 'es': 'Spanish', 'fr': 'French', 'id': 'Indonesian', 'it': 'Italian', 'jp': 'Japanese', 'kr': 'Korean', 'pt': 'Portuguese', 'ru': 'Russian', 'tl': 'Tagalog', 'vi': 'Vietnamese', 'zh': 'Chinese', } LANGUAGE_NAMES_MAP = { 'de': 'Deutsch', 'en': 'English', 'es': 'Español', 'fr': 'Français', 'id': 'Indonesian', 'it': 'Italiano', 'jp': '日本語', 'kr': '한국어', 'pt': 'Português', 'ru': 'русский', 'tl': 'Tagalog', 'vi': 'Tiếng Việt', 'zh': '中文', }
#!/usr/bin/python print("How you doing man???")
""" Django settings for ribbon. For more information on this file, see https://docs.djangoproject.com/en/dev/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/dev/ref/settings/ """ # Application definition INSTALLED_APPS = ('rest_framework', )
# ======================== # Information # ======================== # Direct Link: https://www.hackerrank.com/challenges/write-a-function/problem # Difficulty: Medium # Max Score: 10 # Language: Python # ======================== # Solution # ======================== def is_leap(YEAR): '''Checking whether year is a leap year''' return YEAR % 4 == 0 and (YEAR % 400 == 0 or YEAR % 100 != 0) YEAR = int(input()) print(is_leap(YEAR))
# Name: config.py # Description: defines configurations for the various components of audio extraction and processing class AudioConfig: # The format to store audio in AUDIO_FORMAT = 'mp3' # Prefix to save audio features to FEATURE_DESTINATION = '/features/' # Checkpoint frequency in number of tracks processed CHECKPOINT_FREQUENCY = 10 # Minimum required clip length for prediction MIN_CLIP_LENGTH = 29 class DisplayConfig: # What cmap to use when saving visual features # Refer to https://matplotlib.org/3.3.2/api/_as_gen/matplotlib.axes.Axes.imshow.html CMAP = "Greys" # Defines the size of the figures created by display FIGSIZE_WIDTH = 10 FIGSIZE_HEIGHT = 10 class FeatureExtractorConfig: # The Librosa features supported by the CLI SUPPORTED_FEATURES = ['chroma_stft', 'rms', 'spec_cent', 'spec_bw', 'spec_rolloff', 'zcr', 'mfcc'] NUMBER_OF_MFCC_COLS = 20 # How to aggregate the features FEATURE_AGGREGATION = ['mean', 'min', 'max', 'std'] N_FFT = 2048 HOP_LENGTH = 1024
t = '''DrawBot is a powerful, free application for MacOSX that invites you to write simple Python scripts to generate two-dimensional graphics. The builtin graphics primitives support rectangles, ovals, (bezier) paths, polygons, text objects and transparency. Education DrawBot is an ideal tool to teach the basics of programming. Students get colorful graphic treats while getting familiar with variables, conditional statements, functions and what have you. Results can be saved in a selection of different file formats, including as high resolution, scaleable PDF, svg, movie, png, jpeg, tiff... DrawBot has proven itself as part of the curriculum at selected courses at the Royal Academy in The Hague. Python DrawBot is written in Python. The binary download is fully self-contained (ie. it doesn’t need a Python install around), but the source code is available if you want to roll your own. ''' while t: newPage("A4") fontSize(40) t = textBox(t, (10, 10, 300, 300))
class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: intervals.sort(key=lambda x: x[0]) res = [] for i in range(0, len(intervals)): if not res or res[-1][1] < intervals[i][0]: res.append(intervals[i]) else: res[-1][1] = max(intervals[i][1], res[-1][1]) return res
# -*- coding: utf-8 -*- # Source: https://leetcode.com/problems/search-in-rotated-sorted-array/ def search(nums, left, right, target): if left > right: return -1 mid = int((left + right) / 2) if nums[mid] == target: return mid # left --- target --- mid --- right if nums[mid] <= nums[right]: if target < nums[mid] or target > nums[right]: return search(nums, left, mid-1, target) else: return search(nums, mid+1, right, target) # left --- mid --- target --- right if nums[left] <= nums[mid]: if target > nums[mid] or target < nums[left]: return search(nums, mid+1, right, target) else: return search(nums, left, mid-1, target) def search_rotated_array(nums, target): if len(nums) == 0: return -1 return search(nums, 0, len(nums)-1, target)
'''Use an IF statement inside a FOR loop to select only positive numbers.''' def printAllPositive(numberList): '''Print only the positive numbers in numberList.''' for num in numberList: if num > 0: print(num) printAllPositive([3, -5, 2, -1, 0, 7])
# The tests rely on a lot of absolute paths so this file # configures all of that music_folder = u'/home/rudi/music' o_path = u'/home/rudi/throwaway/ACDC_-_Back_In_Black-sample-64kbps.ogg' watch_path = u'/home/rudi/throwaway/watch/', real_path1 = u'/home/rudi/throwaway/watch/unknown/unknown/ACDC_-_Back_In_Black-sample-64kbps-64kbps.ogg' opath = u"/home/rudi/Airtime/python_apps/media-monitor2/tests/" ppath = u"/home/rudi/Airtime/python_apps/media-monitor2/media/" api_client_path = '/etc/airtime/api_client.cfg' # holdover from the time we had a special config for testing sample_config = api_client_path real_config = api_client_path
# python3 def max_ammount(W, weights): values = [[0 for _ in weights + [0]] for _ in range(W + 1)] for w in range(1, W + 1): for i, wi in enumerate(weights): values[w][i + 1] = max([ values[w][i], values[w - wi][i] + wi if w - wi >= 0 else 0 ]) return values[-1][-1] if __name__ == '__main__': capacity, _ = list(map(int, input().split())) items = list(map(int, input().split())) print(max_ammount(capacity, items))
abcd = (1 + 2 + 3 + 4 + 5 + 6) aaaa = (8188107138941 <= 90) bbbb = (123 ** 456 & 780) cccc = (123 ** 456 & 780 | 89 / 8)
# -*- coding: utf-8 -*- # auto raise exception def auto_raise(exception, silent): if not silent: raise exception class APIError(Exception): """ Common API Error """ class APINetworkError(APIError): """ Failed to load API request """ class APIJSONParesError(APIError): """ Failed to parse target """ class APISignInFailedError(APIError): """ Failed to Sign in """ class APIServerResponseError(APIError): """ Warning if server response only error""" class ModelError(Exception): """ Common Model Error """ class ModelInitError(Exception): """ Model Initialize Error """ class APIServerResponseWarning(Warning): """ Warning if server response with error""" class ModelRefreshWarning(Warning): """ Model refresh failed """ class ModelInitWarning(Warning): """ Warning with init object """
def temperature_format(value): return round(int(value) * 0.1, 1) class OkofenDefinition: def __init__(self, name=None): self.domain = name self.__datas = {} def set(self, target, value): self.__datas[target] = value def get(self, target): if target in self.__datas: return self.__datas[target] return None class OkofenDefinitionHelperMixin: def get(self, target): return super().get(target)
def findMin(a, n): su = 0 su = sum(a) dp = [[0 for i in range(su + 1)] for j in range(n + 1)] for i in range(n + 1): dp[i][0] = True for j in range(1, su + 1): dp[0][j] = False for i in range(1, n + 1): for j in range(1, su + 1): dp[i][j] = dp[i - 1][j] if a[i - 1] <= j: dp[i][j] |= dp[i - 1][j - a[i - 1]] diff = 1005 for j in range(su // 2, -1, -1): if dp[n][j] == True: diff = su - (2 * j) break return diff n = int(input()) a = list(map(int,input().split())) m = findMin(a, n) print(((sum(a)-m)//2)+m)
class AboutDialog: def __init__(self, builder): self._win = builder.get_object('dialog_about', target=self, include_children=True) def run(self): result = self._win.run() self._win.hide() return result
def extractChichipephCom(item): ''' Parser for 'chichipeph.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('the former wife', 'The Former Wife of Invisible Wealthy Man', 'translated'), ('villain father', 'Guide the Villain Father to Be Virtuous', 'translated'), ('bhwatp', 'Become Husband and Wife According To Pleasure', 'translated'), ('jiaochen', 'Jiaochen', 'translated'), ('pmfbs', 'Transmigration: Petite Mother of Four Big Shots', 'translated'), ('can you afford', 'Can You Afford To Raise?', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
# -*- coding: utf-8 -*- """ Created on Sat Feb 27 19:10:13 2021 @author: ALEX BACK lARGEST PALINDROME PRODUCT A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. Exemplos: https://www.w3schools.com/python/python_howto_reverse_string.asp """ def isPalindrome(n): # slicing return int(str(n)[::-1]) == n # definição variáveis iniciais palindromos = [] candidatos = [] # encontra todos os candidatos for n in range(999,100,-1): for m in range(999,100,-1): if n >= m: candidatos.append(n*m) # encontra os palindromos entre os candidatos for n in candidatos: if isPalindrome(n): palindromos.append(n) # apresenta os resultados print("O tamanho da lista de candidatos é", len(candidatos)) print("O maior candidato é", max(candidatos)) print("O tamanho da lista de palindromos é", len(palindromos)) print("O maior palindromo é", max(palindromos))
""" Not sure how to scientifically prove this. In order to turn all the 1 to 0, every row need to have "the same pattern". Or it is imposible. This same pattern is means they are 1. identical 2. entirely different. For example 101 and 101, 101 and 010. 110011 and 110011. 110011 and 001100. Time: O(N), N is the number of element in the grid. Space: O(N) """ class Solution(object): def removeOnes(self, grid): if not grid: return True rowStrings = set() for row in grid: rowStrings.add(''.join((str(e) for e in row))) if len(rowStrings)>2: return False if len(rowStrings)==1: return True s1 = rowStrings.pop() s2 = rowStrings.pop() for i in xrange(len(s1)): if (s1[i]=='0' and s2[i]=='1') or (s1[i]=='1' and s2[i]=='0'): continue return False return True
# # PySNMP MIB module PDN-IFEXT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PDN-IFEXT-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:30:00 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, ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "ConstraintsUnion", "ValueRangeConstraint") ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex") pdnIfExt, = mibBuilder.importSymbols("PDN-HEADER-MIB", "pdnIfExt") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") IpAddress, Gauge32, iso, ObjectIdentity, Unsigned32, Counter32, TimeTicks, Counter64, NotificationType, Bits, ModuleIdentity, Integer32, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "Gauge32", "iso", "ObjectIdentity", "Unsigned32", "Counter32", "TimeTicks", "Counter64", "NotificationType", "Bits", "ModuleIdentity", "Integer32", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn") DisplayString, RowStatus, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "RowStatus", "TextualConvention") pdnIfExtConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 12, 1)) pdnIfExtTestConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 12, 2)) pdnIfExtTable = MibTable((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 12, 1, 1), ) if mibBuilder.loadTexts: pdnIfExtTable.setStatus('mandatory') pdnIfExtEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 12, 1, 1, 1), ).setIndexNames((0, "PDN-IFEXT-MIB", "pdnIfExtIndex")) if mibBuilder.loadTexts: pdnIfExtEntry.setStatus('mandatory') pdnIfExtIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 12, 1, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pdnIfExtIndex.setStatus('mandatory') pdnIfExtInOctetRollovers = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 12, 1, 1, 1, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pdnIfExtInOctetRollovers.setStatus('mandatory') pdnIfExtOutOctetRollovers = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 12, 1, 1, 1, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pdnIfExtOutOctetRollovers.setStatus('mandatory') pdnIfExtTotalUASs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 12, 1, 1, 1, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pdnIfExtTotalUASs.setStatus('mandatory') pdnIfExtTestConfigTable = MibTable((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 12, 2, 1), ) if mibBuilder.loadTexts: pdnIfExtTestConfigTable.setStatus('mandatory') pdnIfExtTestConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 12, 2, 1, 1), ).setIndexNames((0, "PDN-IFEXT-MIB", "pdnIfExtTestConfigIfIndex")) if mibBuilder.loadTexts: pdnIfExtTestConfigEntry.setStatus('mandatory') pdnIfExtTestConfigIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 12, 2, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pdnIfExtTestConfigIfIndex.setStatus('mandatory') pdnIfExtTestConfigNearTimer = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 12, 2, 1, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pdnIfExtTestConfigNearTimer.setStatus('mandatory') pdnIfExtTestConfigFarTimer = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 12, 2, 1, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pdnIfExtTestConfigFarTimer.setStatus('mandatory') pdnIfTable = MibTable((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 12, 1, 2), ) if mibBuilder.loadTexts: pdnIfTable.setStatus('mandatory') pdnIfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 12, 1, 2, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"), (0, "PDN-IFEXT-MIB", "pdnIfAddr")) if mibBuilder.loadTexts: pdnIfEntry.setStatus('mandatory') pdnIfAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 12, 1, 2, 1, 1), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: pdnIfAddr.setStatus('mandatory') pdnIfAddrMask = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 12, 1, 2, 1, 2), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pdnIfAddrMask.setStatus('mandatory') pdnIfStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 12, 1, 2, 1, 3), RowStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: pdnIfStatus.setStatus('mandatory') mibBuilder.exportSymbols("PDN-IFEXT-MIB", pdnIfExtConfig=pdnIfExtConfig, pdnIfExtTable=pdnIfExtTable, pdnIfExtTestConfigTable=pdnIfExtTestConfigTable, pdnIfExtTestConfigEntry=pdnIfExtTestConfigEntry, pdnIfAddr=pdnIfAddr, pdnIfStatus=pdnIfStatus, pdnIfExtOutOctetRollovers=pdnIfExtOutOctetRollovers, pdnIfEntry=pdnIfEntry, pdnIfExtInOctetRollovers=pdnIfExtInOctetRollovers, pdnIfExtTotalUASs=pdnIfExtTotalUASs, pdnIfTable=pdnIfTable, pdnIfExtTestConfigNearTimer=pdnIfExtTestConfigNearTimer, pdnIfAddrMask=pdnIfAddrMask, pdnIfExtTestConfig=pdnIfExtTestConfig, pdnIfExtTestConfigIfIndex=pdnIfExtTestConfigIfIndex, pdnIfExtIndex=pdnIfExtIndex, pdnIfExtTestConfigFarTimer=pdnIfExtTestConfigFarTimer, pdnIfExtEntry=pdnIfExtEntry)
galera = list() dado = list() totmai=totmen=0 for c in range(0,3): ## pede 3 elementos dado.append(str(input('Nome : '))) ##adiciona dentro de dado dado.append(int(input('Idade: ')))## adiciona dentro de dado galera.append(dado[:]) ##coloca o conteudo de dado dentro da galera dado.clear() ##limpa dado for p in galera: if p[1] >= 21: print(f' {p[0]} é maior de idade') totmai+=1 else: print(f' {p[0]} é menor de idade') totmen+=1 print(f'Temos {totmai} maiores de idade e {totmen} menores de idade.')
class BinarySearch: def __init__(self): pass def search(self, array, item): # return self.recursively_search(array, item, 0, len(array)-1) return self.interactive_search(array, item, 0, len(array)-1) def recursively_search(self, array, item, left, right): if(left > right): return -1 mid = int((left+right)/2) if(item < array[mid]): return self.recursively_search(array, item, left, mid - 1) elif(item > array[mid]): return self.recursively_search(array, item, mid + 1, right) else: return mid def interactive_search(self, array, item, left, right): while(left <= right): mid = int((left+right)/2) if(item > array[mid]): left = mid + 1 elif(item < array[mid]): right = mid - 1 else: return mid return -1 if __name__ == '__main__': array = [ 3, 4, 5, 7, 12, 14, 18, 21, 35, 38, 44, 53, 67] bs = BinarySearch() print(bs.search(array, 44))
num = cont = soma = 0 while True: num = int(input('Digite o valor [para sair digite 999]: ')) if num == 999: break soma += num cont += 1 print('Foram digitados {} números e a soma deles é {}'.format(cont, soma))
class Solution: def makeGood(self, s: str) -> str: ans = [] for ch in s: if ans and ans[-1].lower() == ch.lower() and ans[-1] != ch: ans.pop() else: ans.append(ch) return ''.join(ans)
# 小中大 def st190301(): n = int(input()) numbers=list(map(int,input().split())) if numbers[0]>numbers[n-1]: max=numbers[0] min=numbers[n-1] else: max=numbers[n-1] min=numbers[0] print(max,end=' ') if n%2==0: zhong=(numbers[n//2-1]+numbers[n//2]) if zhong%2==0: print(zhong//2, end=' ') else: print(zhong/2, end=' ') else: print(numbers[n//2], end=' ') print(min) if __name__ == '__main__': st190301()
#----------------------------------------------------------------------------- # Runtime: 28ms # Memory Usage: # Link: #----------------------------------------------------------------------------- class Solution: def spiralOrder(self, matrix: [[int]]) -> [int]: row_length = len(matrix) if row_length <= 0: return matrix col_length = len(matrix[0]) matrix_length = col_length * row_length result = [] level = 0 while True: first_col = level first_row = level last_col = col_length - level - 1 last_row = row_length - level - 1 for i in range(first_col, last_col + 1): result.append(matrix[first_row][i]) if len(result) == matrix_length: break for i in range(first_row + 1, last_row): result.append(matrix[i][last_col]) if len(result) == matrix_length: break for i in range(last_col, first_col - 1, -1): result.append(matrix[last_row][i]) if len(result) == matrix_length: break for i in range(last_row - 1, first_row, -1): result.append(matrix[i][first_col]) if len(result) == matrix_length: break level += 1 return result
def load(h): return ({'abbr': 0, 'code': 0, 'title': 'Reserved'}, {'abbr': 'surf', 'code': 1, 'title': 'Surface', 'units': 'of the Earth, which includes sea surface'}, {'abbr': 'bcld', 'code': 2, 'title': 'Cloud base level'}, {'abbr': 'tcld', 'code': 3, 'title': 'Cloud top level'}, {'abbr': 'isot', 'code': 4, 'title': '0 deg (C) isotherm level'}, {'abbr': 5, 'code': 5, 'title': 'Adiabatic condensation level', 'units': 'parcel lifted from surface'}, {'abbr': 6, 'code': 6, 'title': 'Maximum wind speed level'}, {'abbr': 7, 'code': 7, 'title': 'Tropopause level'}, {'abbr': 'tatm', 'code': 8, 'title': 'Nominal top of atmosphere'}, {'abbr': 9, 'code': 9, 'title': 'Sea bottom'}, {'abbr': 'pl', 'code': 100, 'title': 'Isobaric level pressure in hectoPascals (hPa)', 'units': '2 octets'}, {'abbr': 101, 'code': 101, 'title': 'Layer between two isobaric levels pressure of top (kPa) pressure ' 'of bottom', 'units': 'kPa'}, {'abbr': 'msl', 'code': 102, 'title': 'Mean sea level 0 0'}, {'abbr': 'hmsl', 'code': 103, 'title': 'Fixed height level height above mean sea level (MSL) in meters'}, {'abbr': 104, 'code': 104, 'title': 'Layer between two height levels above msl height of top (hm) above ' 'mean sea level height of bottom (hm) above mean sea level'}, {'abbr': 'hl', 'code': 105, 'title': 'Fixed height above ground height in meters', 'units': '2 octets'}, {'abbr': 'lhl', 'code': 106, 'title': 'Layer between two height levels above ground height of top (hm) ' 'above ground height of bottom (hm) above ground'}, {'abbr': 107, 'code': 107, 'title': 'Sigma level sigma value in 1/10000', 'units': '2 octets'}, {'abbr': 108, 'code': 108, 'title': 'Layer between two sigma levels sigma value at top in 1/100 sigma ' 'value at bottom in 1/100'}, {'abbr': 'ml', 'code': 109, 'title': 'Hybrid level level number', 'units': '2 octets'}, {'abbr': 110, 'code': 110, 'title': 'Layer between two hybrid levels level number of top level number ' 'of bottom'}, {'abbr': 111, 'code': 111, 'title': 'Depth below land surface centimeters', 'units': '2 octets'}, {'abbr': 'ldl', 'code': 112, 'title': 'Layer between two depths below land surface depth of upper surface ' '(cm) depth of lower surface', 'units': 'cm'}, {'abbr': 'pt', 'code': 113, 'title': 'Isentropic (theta) level Potential Temp. degrees K', 'units': '2 octets'}, {'abbr': 114, 'code': 114, 'title': 'Layer between two isentropic levels 475K minus theta of top in ' 'Deg. K 475K minus theta of bottom in Deg. K'}, {'abbr': 115, 'code': 115, 'title': 'Level at specified pressure difference from ground to level hPa', 'units': '2 octets'}, {'abbr': 116, 'code': 116, 'title': 'Layer between two levels at specified pressure differences from ' 'ground to levels pressure difference from ground to top level hPa ' 'pressure difference from ground to bottom level hPa'}, {'abbr': 'pv', 'code': 117, 'title': 'Potential vorticity surface 10-9 K m2 kg-1 s-1'}, {'abbr': 121, 'code': 121, 'title': 'Layer between two isobaric surfaces (high precision) 1100 hPa ' 'minus pressure of top, in hPa 1100 hPa minus pressure of bottom, ' 'in hPa'}, {'abbr': 125, 'code': 125, 'title': 'Height level above ground (high precision) centimeters', 'units': '2 octets'}, {'abbr': 128, 'code': 128, 'title': 'Layer between two sigma levels (high precision) 1.1 minus sigma of ' 'top, in 1/1000 of sigma 1.1 minus sigma of bottom, in 1/1000 of ' 'sigma'}, {'abbr': 141, 'code': 141, 'title': 'Layer between two isobaric surfaces (mixed precision) pressure of ' 'top, in kPa 1100hPa minus pressure of bottom, in hPa'}, {'abbr': 'dp', 'code': 160, 'title': 'Depth below sea level meters', 'units': '2 octets'}, {'abbr': 'nd', 'code': 191, 'title': 'Northern Direction', 'units': 'SMHI Extension'}, {'abbr': 'ned', 'code': 192, 'title': 'Northern-Eastern Direction', 'units': 'SMHI Extension'}, {'abbr': 'ed', 'code': 193, 'title': 'Eastern Direction', 'units': 'SMHI Extension'}, {'abbr': 'sed', 'code': 194, 'title': 'Southern-Eastern Direction', 'units': 'SMHI Extension'}, {'abbr': 'sd', 'code': 195, 'title': 'Southern Direction', 'units': 'SMHI Extension'}, {'abbr': 'swd', 'code': 196, 'title': 'Southern-Western Direction', 'units': 'SMHI Extension'}, {'abbr': 'wd', 'code': 197, 'title': 'Western Direction', 'units': 'SMHI Extension'}, {'abbr': 'nwd', 'code': 198, 'title': 'Northern-Western Direction', 'units': 'SMHI Extension'}, {'abbr': 'atm', 'code': 200, 'title': 'Entire atmosphere considered as a single layer 0', 'units': '2 octets'}, {'abbr': 201, 'code': 201, 'title': 'Entire ocean considered as a single layer 0', 'units': '2 octets'})
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def __init__(self): self.preorder_i = 0 def buildTree(self, preorder, inorder) -> TreeNode: return self.rec(preorder, inorder, 0, len(preorder) - 1) def rec(self, preorder, inorder, inorder_l: int, inorder_r: int) -> TreeNode: if inorder_l > inorder_r: return None node = TreeNode(preorder[self.preorder_i]) center = self.preorder_i self.preorder_i += 1 left_l = inorder_l right_l = inorder_l while preorder[center] != inorder[right_l]: right_l += 1 node.left = self.rec(preorder, inorder, left_l, right_l - 1) node.right = self.rec(preorder, inorder, right_l + 1, inorder_r) return node x = Solution() y = x.buildTree([3, 9, 20, 15, 7], [9, 3, 15, 20, 7]) print('here')
inpt1 = int(input('enter base: ')) inpt2 = int(input('enter height: ')) inpt3 = int(input('enter hypotenus: ')) def get_area(base, height): return 0.5 * base * height def get_per(base, height, hypo): return base + height + hypo print("area of the triangle is: ") print(get_area(inpt1, inpt2)) print() print('the perimeter of the triangle is') print(get_per(inpt1, inpt2, inpt3))
def __getattr__(): pass class C1: def __str__(self): return '' def foo(self): ''' >>> class Good(): ... def __str__(self): ... return 1 ''' pass class C2: if True: def __str__(self): return '' class C3: try: if True: while True: def __str__(self): return '' break except: pass
print('=' * 12 + 'Desafio 82' + '=' * 12) lista = [] pares = [] impares = [] while True: var = int(input('Digite um valor: ')) lista.append(var) resp = input('Deseja continuar [S/N]? ').upper().strip() if resp[0] == 'N': break; for numero in lista: if numero % 2 == 0: pares.append(numero) else: impares.append(numero) print(f'A lista original digitada foi: {lista}') print(f'Os elementos pares são {pares}') print(f'Os elementos ímpares são {impares}')
class Config(object): DEBUG = False TESTING = False SECRET_KEY = 'AAABBBBAAAA' SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/test.db' class ProductionConfig(Config): DATABASE_URI = 'mysql://user@localhost/foo' class DevelopmentConfig(Config): DEBUG = True class TestingConfig(Config): TESTING = True
# # @lc app=leetcode.cn id=115 lang=python3 # # [115] 不同的子序列 # # https://leetcode-cn.com/problems/distinct-subsequences/description/ # # algorithms # Hard (49.80%) # Likes: 306 # Dislikes: 0 # Total Accepted: 23.4K # Total Submissions: 46.8K # Testcase Example: '"rabbbit"\n"rabbit"' # # 给定一个字符串 s 和一个字符串 t ,计算在 s 的子序列中 t 出现的个数。 # # 字符串的一个 子序列 是指,通过删除一些(也可以不删除)字符且不干扰剩余字符相对位置所组成的新字符串。(例如,"ACE" 是 "ABCDE" # 的一个子序列,而 "AEC" 不是) # # 题目数据保证答案符合 32 位带符号整数范围。 # # # # 示例 1: # # # 输入:s = "rabbbit", t = "rabbit" # 输出:3 # 解释: # 如下图所示, 有 3 种可以从 s 中得到 "rabbit" 的方案。 # (上箭头符号 ^ 表示选取的字母) # rabbbit # ^^^^ ^^ # rabbbit # ^^ ^^^^ # rabbbit # ^^^ ^^^ # # # 示例 2: # # # 输入:s = "babgbag", t = "bag" # 输出:5 # 解释: # 如下图所示, 有 5 种可以从 s 中得到 "bag" 的方案。 # (上箭头符号 ^ 表示选取的字母) # babgbag # ^^ ^ # babgbag # ^^ ^ # babgbag # ^ ^^ # babgbag # ⁠ ^ ^^ # babgbag # ⁠ ^^^ # # # # 提示: # # # 0 # s 和 t 由英文字母组成 # # # # @lc code=start class Solution: def numDistinct(self, s: str, t: str) -> int: if not t: return len(s) dp = [[0] * (len(t)+1) for _ in range(len(s)+1)] for i in range(len(s)+1): dp[i][0] = 1 for i in range(1,len(s)+1): for j in range(1,len(t)+1): if s[i-1] == t[j-1]: dp[i][j] = dp[i-1][j-1] + dp[i-1][j] else: dp[i][j] = dp[i-1][j] return dp[len(s)][len(t)] # @lc code=end
#!/usr/bin/python3 ''' Finds the coincidence index for the piece of text Does not format the text so make sure to pass in a formatted one ''' def findCoincidenceIndex(text: str, shift: int): shiftedText = text[:-(shift)] text = text[shift:] shiftedLen = len(shiftedText) similarCount = 0 for i in range(shiftedLen): if text[i] == shiftedText[i]: similarCount += 1 coincidenceIndex = similarCount/shiftedLen * 26 return coincidenceIndex ''' Check all coincidence indices. Returns the max of the coincidence indices, and the array of indices Does not format the input ''' def findBestCoincidenceIndex(text: str): textLen = len(text) indices = [] mx = 0 shift = -1 for i in range(1, textLen - 2): index = findCoincidenceIndex(text, i) if (index > mx): mx = index shift = i indices.append(index) return {'bestIndex': mx, 'bestShift': shift, 'indices': indices} ''' Checks if the coincidenceIndex of a piece of text is similar i.e within the error margin to given coincidence index. If yes, then the shift and the index is returned, otherwise false ''' def checkCoincidenceIndex(text: str, ci: float, errorMargin: float = 0.01): textLen = len(text) indices = [] bestIndex = 0 shift = -1 for i in range(1, textLen - 2): index = findCoincidenceIndex(text, i) diff = abs(index - ci) if (diff < errorMargin): if diff < abs(bestIndex - ci): bestIndex = index shift = i indices.append((bestIndex, i)) return {'bestIndex': bestIndex, 'bestShift': shift, 'indices': indices} if shift != -1 else False
""" Relief Visualization Toolbox – python library Contains functions for computing the visualizations. Credits: Žiga Kokalj ([email protected]) Krištof Oštir ([email protected]) Klemen Zakšek Klemen Čotar Maja Somrak Žiga Maroh Copyright: 2010-2020 Research Centre of the Slovenian Academy of Sciences and Arts 2016-2020 University of Ljubljana, Faculty of Civil and Geodetic Engineering """
# Default domainFile = "domains.txt" assets = "./assets/" targets = assets + "targets/" subdomains = assets + "subdomains/" domains = assets + "domains/" takeover = assets + "takeover/" dto = assets = "dto/" # Target Information targetFields = { "Domain" : "", "Analysis" : { "Subdomain" : "", "Ping" : "", "Dns" : "" } }
""" Recipes available to data with tags ['GSAOI', 'IMAGE'] Default is "reduce_nostack". """ recipe_tags = {'GSAOI', 'IMAGE'} def reduce_nostack(p): """ This recipe reduce GSAOI up to but NOT including alignment and stacking. It will attempt to do flat correction if a processed calibration is available. Sky subtraction is done when possible. QA metrics are measured. Parameters ---------- p : PrimitivesBASE object A primitive set matching the recipe_tags. """ p.prepare() p.addDQ() p.nonlinearityCorrect() p.ADUToElectrons() p.addVAR(read_noise=True, poisson_noise=True) p.flatCorrect() p.detectSources(detect_thresh=5., analysis_thresh=5., back_size=128) p.measureIQ(display=True) p.measureBG() p.addReferenceCatalog() p.determineAstrometricSolution() p.measureCC() p.addToList(purpose='forSky') p.getList(purpose='forSky', max_frames=9) p.separateSky() p.associateSky() p.skyCorrect() p.detectSources(detect_thresh=5., analysis_thresh=5., back_size=128) p.measureIQ(display=True) p.determineAstrometricSolution() p.measureCC() # p.scaleByExposureTime() # not really necessary in QA. p.writeOutputs() return # The nostack version is used because stacking of GSAOI is time consuming. _default = reduce_nostack
class Aluno: def __init__(self, nome, nota1, nota2): self.nome = nome self.nota1 = nota1 self.nota2 = nota2 self.media = self.media def media(self): self.media = (self.nota1 + self.nota2) / 2 return self.media def mostra(self): print('Nome: ', self.nome) print('Nota 1: ', self.nota1) print('Nota 2: ', self.nota2) print('Média: ', self.media) def resultado(self): if self.media >= 6.0: print('aprovado') else: print('reprovado') a1 = Aluno('joao', 8.5, 6.5) media = a1.media() print(a1.mostra()) print(a1.resultado()) aluno2 = Aluno('pedro', 4.5, 6.0) media2 = aluno2.media() print(aluno2.mostra()) print(aluno2.resultado())
"""Error classes for authentise_services""" class ResourceError(Exception): """arbitrary error whenever a call to a authentise resource doesnt go according to plan""" pass class ResourceStillProcessing(Exception): """most authentise resources have a status property to tell the user what state its in Whenever the resource isnt ready in some way or another, throw one of these""" pass
count = int(input()) matrix = [] for i in range(count): matrix.append(list(map(int, input().split()))) # matrix = [list(map(int, input().split())) for i in range(n)] roads = 0 for row in range(len(matrix)): for col in range(row, len(matrix)): roads += matrix[row][col] print(roads)
# BUILD FILE SYNTAX: SKYLARK SE_VERSION = '3.9.1' ASSEMBLY_VERSION = '3.9.1.0'
# # PySNMP MIB module STN-SESSION-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/STN-SESSION-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:11:40 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, ConstraintsIntersection, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ConstraintsIntersection", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Bits, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, iso, Gauge32, MibIdentifier, TimeTicks, Integer32, Counter64, IpAddress, Unsigned32, ObjectIdentity, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Counter32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "iso", "Gauge32", "MibIdentifier", "TimeTicks", "Integer32", "Counter64", "IpAddress", "Unsigned32", "ObjectIdentity", "ModuleIdentity") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") stnSystems, stnNotification = mibBuilder.importSymbols("SPRING-TIDE-NETWORKS-SMI", "stnSystems", "stnNotification") StnUserFailureType, StnConfigFailureType = mibBuilder.importSymbols("SPRING-TIDE-NETWORKS-TC", "StnUserFailureType", "StnConfigFailureType") stnEngineCpu, stnEngineIndex, stnEngineSlot = mibBuilder.importSymbols("STN-CHASSIS-MIB", "stnEngineCpu", "stnEngineIndex", "stnEngineSlot") stnRouterIndex, = mibBuilder.importSymbols("STN-ROUTER-MIB", "stnRouterIndex") stnSessions = ModuleIdentity((1, 3, 6, 1, 4, 1, 3551, 2, 5)) if mibBuilder.loadTexts: stnSessions.setLastUpdated('0002160000Z') if mibBuilder.loadTexts: stnSessions.setOrganization('Spring Tide Networks, Inc.') if mibBuilder.loadTexts: stnSessions.setContactInfo(' Spring Tide Networks, Inc. Customer Service Postal: 3 Clock Tower Place Maynard, MA 01754 Tel: 1 888-786-4357 Email: [email protected] ') if mibBuilder.loadTexts: stnSessions.setDescription('This MIB module describes Spring Tide Networks session objects.') stnSessionObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1)) stnSessionMibConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 3551, 2, 5, 2)) stnSessionTrapVars = MibIdentifier((1, 3, 6, 1, 4, 1, 3551, 2, 5, 3)) stnSession = MibIdentifier((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1)) stnGlobalSession = MibIdentifier((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 2)) stnSessionsPpp = MibIdentifier((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 2)) stnSessionsL2tp = MibIdentifier((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 3)) stnSessionsPptp = MibIdentifier((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 4)) stnSessionsIpsec = MibIdentifier((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 5)) stnSessionsIke = MibIdentifier((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 6)) stnSessionsTelnet = MibIdentifier((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 7)) stnSessionsFtp = MibIdentifier((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 8)) stnSessionsFtpAlg = MibIdentifier((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 9)) stnSessionsConsole = MibIdentifier((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 10)) stnSessionsAggregate = MibIdentifier((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 11)) stnSessionsEncaps = MibIdentifier((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 12)) stnSessionsSecureUser = MibIdentifier((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 13)) stnSessionsRemoteConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 14)) class SessionOperStatus(TextualConvention, Integer32): description = 'Operational status of a session.' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5)) namedValues = NamedValues(("unknown", 1), ("inactive", 2), ("pend-active", 3), ("active", 4), ("pend-inactive", 5)) stnSessionTable = MibTable((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 1), ) if mibBuilder.loadTexts: stnSessionTable.setStatus('current') if mibBuilder.loadTexts: stnSessionTable.setDescription('A list of session entries.') stnSessionEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 1, 1), ).setIndexNames((0, "STN-SESSION-MIB", "stnSessionIndex")) if mibBuilder.loadTexts: stnSessionEntry.setStatus('current') if mibBuilder.loadTexts: stnSessionEntry.setDescription('Entry contains information about a particular session.') stnSessionIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 1, 1, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionIndex.setStatus('current') if mibBuilder.loadTexts: stnSessionIndex.setDescription('A sequence number that identifies a session entry in the table.') stnSessionType = MibTableColumn((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13))).clone(namedValues=NamedValues(("unknown", 1), ("ppp", 2), ("l2tp-tunnel", 3), ("pptp-tunnel", 4), ("ipsec", 5), ("ike", 6), ("telnet", 7), ("ftp", 8), ("ftp-alg", 9), ("console", 10), ("encaps", 11), ("secure-user", 12), ("remote-config", 13)))).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionType.setStatus('current') if mibBuilder.loadTexts: stnSessionType.setDescription('Indicates the session type.') stnSessionContext = MibTableColumn((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 1, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 256))).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionContext.setStatus('current') if mibBuilder.loadTexts: stnSessionContext.setDescription('A unique context identifier associated with the session.') stnSessionOperStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 1, 1, 4), SessionOperStatus()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionOperStatus.setStatus('current') if mibBuilder.loadTexts: stnSessionOperStatus.setDescription('The operational status of the session.') stnSessionLastChange = MibTableColumn((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 1, 1, 5), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionLastChange.setStatus('current') if mibBuilder.loadTexts: stnSessionLastChange.setDescription('The value of sysUpTime at the time the session entered its current operational state.') stnSessionPppTotalCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 2, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionPppTotalCount.setStatus('current') if mibBuilder.loadTexts: stnSessionPppTotalCount.setDescription('The total number of PPP sessions since system start.') stnSessionPppFailedCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 2, 2), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionPppFailedCount.setStatus('current') if mibBuilder.loadTexts: stnSessionPppFailedCount.setDescription('The total number of failed sessions since system start.') stnSessionPppCurrentCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 2, 3), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionPppCurrentCount.setStatus('current') if mibBuilder.loadTexts: stnSessionPppCurrentCount.setDescription('The total number of current PPP sessions.') stnSessionPppCurrentActiveCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 2, 4), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionPppCurrentActiveCount.setStatus('current') if mibBuilder.loadTexts: stnSessionPppCurrentActiveCount.setDescription('The total number of current active PPP sessions.') stnSessionL2tpTunnelTotalCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 3, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionL2tpTunnelTotalCount.setStatus('current') if mibBuilder.loadTexts: stnSessionL2tpTunnelTotalCount.setDescription('The total number of L2TP tunnel sessions since system start.') stnSessionL2tpTunnelFailedCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 3, 2), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionL2tpTunnelFailedCount.setStatus('current') if mibBuilder.loadTexts: stnSessionL2tpTunnelFailedCount.setDescription('The total number of failed L2TP tunnel sessions since system start.') stnSessionL2tpTunnelCurrentCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 3, 3), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionL2tpTunnelCurrentCount.setStatus('current') if mibBuilder.loadTexts: stnSessionL2tpTunnelCurrentCount.setDescription('The total number of current L2TP tunnel sessions.') stnSessionL2tpTunnelCurrentActiveCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 3, 4), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionL2tpTunnelCurrentActiveCount.setStatus('current') if mibBuilder.loadTexts: stnSessionL2tpTunnelCurrentActiveCount.setDescription('The total number of current active L2TP tunnel sessions.') stnSessionPptpTunnelTotalCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 4, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionPptpTunnelTotalCount.setStatus('current') if mibBuilder.loadTexts: stnSessionPptpTunnelTotalCount.setDescription('The total number of PPTP tunnel sessions since system start.') stnSessionPptpTunnelFailedCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 4, 2), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionPptpTunnelFailedCount.setStatus('current') if mibBuilder.loadTexts: stnSessionPptpTunnelFailedCount.setDescription('The total number of failed PPTP tunnel sessions since system start.') stnSessionPptpTunnelCurrentCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 4, 3), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionPptpTunnelCurrentCount.setStatus('current') if mibBuilder.loadTexts: stnSessionPptpTunnelCurrentCount.setDescription('The total number of current PPTP tunnel sessions.') stnSessionPptpTunnelCurrentActiveCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 4, 4), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionPptpTunnelCurrentActiveCount.setStatus('current') if mibBuilder.loadTexts: stnSessionPptpTunnelCurrentActiveCount.setDescription('The total number of current active PPTP tunnel sessions.') stnSessionIpsecTotalCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 5, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionIpsecTotalCount.setStatus('current') if mibBuilder.loadTexts: stnSessionIpsecTotalCount.setDescription('The total number of IPSEC sessions since system start.') stnSessionIpsecFailedCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 5, 2), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionIpsecFailedCount.setStatus('current') if mibBuilder.loadTexts: stnSessionIpsecFailedCount.setDescription('The total number of failed IPSEC sessions since system start.') stnSessionIpsecCurrentCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 5, 3), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionIpsecCurrentCount.setStatus('current') if mibBuilder.loadTexts: stnSessionIpsecCurrentCount.setDescription('The total number of current IPSEC sessions.') stnSessionIpsecCurrentActiveCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 5, 4), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionIpsecCurrentActiveCount.setStatus('current') if mibBuilder.loadTexts: stnSessionIpsecCurrentActiveCount.setDescription('The total number of current active IPSEC sessions.') stnSessionIkeTotalCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 6, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionIkeTotalCount.setStatus('current') if mibBuilder.loadTexts: stnSessionIkeTotalCount.setDescription('The total number of IKE sessions since system start.') stnSessionIkeFailedCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 6, 2), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionIkeFailedCount.setStatus('current') if mibBuilder.loadTexts: stnSessionIkeFailedCount.setDescription('The total number of failed IKE sessions since system start.') stnSessionIkeCurrentCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 6, 3), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionIkeCurrentCount.setStatus('current') if mibBuilder.loadTexts: stnSessionIkeCurrentCount.setDescription('The total number of current IKE sessions.') stnSessionIkeCurrentActiveCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 6, 4), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionIkeCurrentActiveCount.setStatus('current') if mibBuilder.loadTexts: stnSessionIkeCurrentActiveCount.setDescription('The total number of current active IKE sessions.') stnSessionTelnetTotalCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 7, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionTelnetTotalCount.setStatus('current') if mibBuilder.loadTexts: stnSessionTelnetTotalCount.setDescription('The total number of Telnet sessions since system start.') stnSessionTelnetFailedCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 7, 2), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionTelnetFailedCount.setStatus('current') if mibBuilder.loadTexts: stnSessionTelnetFailedCount.setDescription('The total number of failed Telnet sessions since system start.') stnSessionTelnetCurrentCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 7, 3), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionTelnetCurrentCount.setStatus('current') if mibBuilder.loadTexts: stnSessionTelnetCurrentCount.setDescription('The total number of current Telnet sessions.') stnSessionTelnetCurrentActiveCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 7, 4), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionTelnetCurrentActiveCount.setStatus('current') if mibBuilder.loadTexts: stnSessionTelnetCurrentActiveCount.setDescription('The total number of current active Telnet sessions.') stnSessionFtpTotalCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 8, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionFtpTotalCount.setStatus('current') if mibBuilder.loadTexts: stnSessionFtpTotalCount.setDescription('The total number of FTP sessions since system start.') stnSessionFtpFailedCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 8, 2), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionFtpFailedCount.setStatus('current') if mibBuilder.loadTexts: stnSessionFtpFailedCount.setDescription('The total number of failed FTP sessions since system start.') stnSessionFtpCurrentCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 8, 3), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionFtpCurrentCount.setStatus('current') if mibBuilder.loadTexts: stnSessionFtpCurrentCount.setDescription('The total number of current FTP sessions.') stnSessionFtpCurrentActiveCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 8, 4), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionFtpCurrentActiveCount.setStatus('current') if mibBuilder.loadTexts: stnSessionFtpCurrentActiveCount.setDescription('The total number of current active FTP sessions.') stnSessionFtpAlgTotalCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 9, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionFtpAlgTotalCount.setStatus('current') if mibBuilder.loadTexts: stnSessionFtpAlgTotalCount.setDescription('The total number of FTP-ALG sessions since system start.') stnSessionFtpAlgFailedCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 9, 2), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionFtpAlgFailedCount.setStatus('current') if mibBuilder.loadTexts: stnSessionFtpAlgFailedCount.setDescription('The total number of failed FTP-ALG sessions since system start.') stnSessionFtpAlgCurrentCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 9, 3), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionFtpAlgCurrentCount.setStatus('current') if mibBuilder.loadTexts: stnSessionFtpAlgCurrentCount.setDescription('The total number of current FTP-ALG sessions.') stnSessionFtpAlgCurrentActiveCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 9, 4), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionFtpAlgCurrentActiveCount.setStatus('current') if mibBuilder.loadTexts: stnSessionFtpAlgCurrentActiveCount.setDescription('The total number of current active FTP-ALG sessions.') stnSessionConsoleTotalCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 10, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionConsoleTotalCount.setStatus('current') if mibBuilder.loadTexts: stnSessionConsoleTotalCount.setDescription('The total number of console sessions since system start.') stnSessionConsoleFailedCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 10, 2), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionConsoleFailedCount.setStatus('current') if mibBuilder.loadTexts: stnSessionConsoleFailedCount.setDescription('The total number of failed console sessions since system start.') stnSessionConsoleCurrentCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 10, 3), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionConsoleCurrentCount.setStatus('current') if mibBuilder.loadTexts: stnSessionConsoleCurrentCount.setDescription('The total number of current console sessions.') stnSessionConsoleCurrentActiveCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 10, 4), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionConsoleCurrentActiveCount.setStatus('current') if mibBuilder.loadTexts: stnSessionConsoleCurrentActiveCount.setDescription('The total number of current active console sessions.') stnSessionAggregateTotalCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 11, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionAggregateTotalCount.setStatus('current') if mibBuilder.loadTexts: stnSessionAggregateTotalCount.setDescription('The total number of sessions since system start.') stnSessionAggregateFailedCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 11, 2), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionAggregateFailedCount.setStatus('current') if mibBuilder.loadTexts: stnSessionAggregateFailedCount.setDescription('The total number of failed sessions since system start.') stnSessionAggregateCurrentCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 11, 3), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionAggregateCurrentCount.setStatus('current') if mibBuilder.loadTexts: stnSessionAggregateCurrentCount.setDescription('The total number of current sessions.') stnSessionAggregateCurrentActiveCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 11, 4), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionAggregateCurrentActiveCount.setStatus('current') if mibBuilder.loadTexts: stnSessionAggregateCurrentActiveCount.setDescription('The total number of current active sessions.') stnSessionEncapsTotalCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 12, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionEncapsTotalCount.setStatus('current') if mibBuilder.loadTexts: stnSessionEncapsTotalCount.setDescription('The total number of encaps sessions since system start.') stnSessionEncapsFailedCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 12, 2), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionEncapsFailedCount.setStatus('current') if mibBuilder.loadTexts: stnSessionEncapsFailedCount.setDescription('The total number of failed encaps sessions since system start.') stnSessionEncapsCurrentCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 12, 3), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionEncapsCurrentCount.setStatus('current') if mibBuilder.loadTexts: stnSessionEncapsCurrentCount.setDescription('The total number of current encaps sessions.') stnSessionEncapsCurrentActiveCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 12, 4), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionEncapsCurrentActiveCount.setStatus('current') if mibBuilder.loadTexts: stnSessionEncapsCurrentActiveCount.setDescription('The total number of current active encaps sessions.') stnSessionSecureUserTotalCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 13, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionSecureUserTotalCount.setStatus('current') if mibBuilder.loadTexts: stnSessionSecureUserTotalCount.setDescription('The total number of secure user sessions since system start.') stnSessionSecureUserFailedCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 13, 2), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionSecureUserFailedCount.setStatus('current') if mibBuilder.loadTexts: stnSessionSecureUserFailedCount.setDescription('The total number of failed secure user sessions since system start.') stnSessionSecureUserCurrentCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 13, 3), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionSecureUserCurrentCount.setStatus('current') if mibBuilder.loadTexts: stnSessionSecureUserCurrentCount.setDescription('The total number of current secure user sessions.') stnSessionSecureUserCurrentActiveCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 13, 4), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionSecureUserCurrentActiveCount.setStatus('current') if mibBuilder.loadTexts: stnSessionSecureUserCurrentActiveCount.setDescription('The total number of current active secure user sessions.') stnSessionRemoteConfigTotalCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 14, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionRemoteConfigTotalCount.setStatus('current') if mibBuilder.loadTexts: stnSessionRemoteConfigTotalCount.setDescription('The total number of remote config sessions since system start.') stnSessionRemoteConfigFailedCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 14, 2), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionRemoteConfigFailedCount.setStatus('current') if mibBuilder.loadTexts: stnSessionRemoteConfigFailedCount.setDescription('The total number of failed remote config sessions since system start.') stnSessionRemoteConfigCurrentCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 14, 3), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionRemoteConfigCurrentCount.setStatus('current') if mibBuilder.loadTexts: stnSessionRemoteConfigCurrentCount.setDescription('The total number of current remote config sessions.') stnSessionRemoteConfigCurrentActiveCount = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 1, 14, 4), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnSessionRemoteConfigCurrentActiveCount.setStatus('current') if mibBuilder.loadTexts: stnSessionRemoteConfigCurrentActiveCount.setDescription('The total number of current active remote config sessions.') stnGlobalSessionTable = MibTable((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 2, 1), ) if mibBuilder.loadTexts: stnGlobalSessionTable.setStatus('current') if mibBuilder.loadTexts: stnGlobalSessionTable.setDescription('A list of session entries with the box.') stnGlobalSessionEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 2, 1, 1), ).setIndexNames((0, "STN-SESSION-MIB", "stnGlobalSessionIndex")) if mibBuilder.loadTexts: stnGlobalSessionEntry.setStatus('current') if mibBuilder.loadTexts: stnGlobalSessionEntry.setDescription('Entry contains information about a particular session.') stnGlobalSessionIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 2, 1, 1, 1), Unsigned32()) if mibBuilder.loadTexts: stnGlobalSessionIndex.setStatus('current') if mibBuilder.loadTexts: stnGlobalSessionIndex.setDescription('A sequence number that identifies a session entry in the table.') stnGlobalSessionOperStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 3551, 2, 5, 1, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("inactive", 1), ("active", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: stnGlobalSessionOperStatus.setStatus('current') if mibBuilder.loadTexts: stnGlobalSessionOperStatus.setDescription('The operational status of the session.') stnNotificationUsername = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 3, 1), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnNotificationUsername.setStatus('current') if mibBuilder.loadTexts: stnNotificationUsername.setDescription("The user's name associated with the trap.") stnNotificationUserFailureType = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 3, 2), StnUserFailureType()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnNotificationUserFailureType.setStatus('current') if mibBuilder.loadTexts: stnNotificationUserFailureType.setDescription('The type of user failure.') stnNotificationConfigType = MibScalar((1, 3, 6, 1, 4, 1, 3551, 2, 5, 3, 3), StnConfigFailureType()).setMaxAccess("readonly") if mibBuilder.loadTexts: stnNotificationConfigType.setStatus('current') if mibBuilder.loadTexts: stnNotificationConfigType.setDescription('The type of configuration failure.') stnUserFailure = NotificationType((1, 3, 6, 1, 4, 1, 3551, 2, 100, 0, 17)).setObjects(("STN-ROUTER-MIB", "stnRouterIndex"), ("STN-SESSION-MIB", "stnNotificationUsername"), ("STN-SESSION-MIB", "stnNotificationUserFailureType"), ("STN-SESSION-MIB", "stnSessionType")) if mibBuilder.loadTexts: stnUserFailure.setStatus('current') if mibBuilder.loadTexts: stnUserFailure.setDescription('A stnUserFailure trap signifies that the agent entity has detected that a configuration failure has occurred. The generation of this trap can be controlled by the CommandLineIfaceTraps configuration object.') stnConfigFailure = NotificationType((1, 3, 6, 1, 4, 1, 3551, 2, 100, 0, 18)).setObjects(("STN-ROUTER-MIB", "stnRouterIndex"), ("STN-SESSION-MIB", "stnNotificationUsername"), ("STN-SESSION-MIB", "stnNotificationConfigType")) if mibBuilder.loadTexts: stnConfigFailure.setStatus('current') if mibBuilder.loadTexts: stnConfigFailure.setDescription('A stnConfigFailure trap signifies that the agent entity has detected that a configuration failure has occurred. The generation of this trap can be controlled by the CommandLineIfaceTraps configuration object.') stnNoFlowEntriesAvailable = NotificationType((1, 3, 6, 1, 4, 1, 3551, 2, 100, 0, 57)).setObjects(("STN-CHASSIS-MIB", "stnEngineIndex"), ("STN-CHASSIS-MIB", "stnEngineSlot"), ("STN-CHASSIS-MIB", "stnEngineCpu")) if mibBuilder.loadTexts: stnNoFlowEntriesAvailable.setStatus('current') if mibBuilder.loadTexts: stnNoFlowEntriesAvailable.setDescription('A stnNoFlowEntriesAvailable trap signifies that the agent entity has detected that the there are no more flow entries available on the indicated slot/cpu. This can occur if too many interfaces are assigned to an engine. The generation of this trap can be controlled by the SessionTraps configuration object.') stnNoLayerIfsAvailable = NotificationType((1, 3, 6, 1, 4, 1, 3551, 2, 100, 0, 58)).setObjects(("STN-CHASSIS-MIB", "stnEngineIndex"), ("STN-CHASSIS-MIB", "stnEngineSlot"), ("STN-CHASSIS-MIB", "stnEngineCpu")) if mibBuilder.loadTexts: stnNoLayerIfsAvailable.setStatus('current') if mibBuilder.loadTexts: stnNoLayerIfsAvailable.setDescription('A stnNoLayerIfsAvailable trap signifies that the agent entity has detected that the there are no more layer interfaces available on the indicated slot/cpu. This can occur if too many VCs are assigned to an engine. The generation of this trap can be controlled by the SessionTraps configuration object.') stnMaxSessionLimitExceeded = NotificationType((1, 3, 6, 1, 4, 1, 3551, 2, 100, 0, 59)).setObjects(("STN-CHASSIS-MIB", "stnEngineIndex"), ("STN-CHASSIS-MIB", "stnEngineSlot"), ("STN-CHASSIS-MIB", "stnEngineCpu")) if mibBuilder.loadTexts: stnMaxSessionLimitExceeded.setStatus('current') if mibBuilder.loadTexts: stnMaxSessionLimitExceeded.setDescription('A stnMaxSessionLimitExceeded trap signifies that the agent entity has detected that the maximum session limit has occurred on the indicated slot/cpu. The generation of this trap can be controlled by the SessionTraps configuration object.') stnTunnelEngineLimitExceeded = NotificationType((1, 3, 6, 1, 4, 1, 3551, 2, 100, 0, 60)).setObjects(("STN-CHASSIS-MIB", "stnEngineIndex"), ("STN-CHASSIS-MIB", "stnEngineSlot"), ("STN-CHASSIS-MIB", "stnEngineCpu")) if mibBuilder.loadTexts: stnTunnelEngineLimitExceeded.setStatus('current') if mibBuilder.loadTexts: stnTunnelEngineLimitExceeded.setDescription('A stnTunnelEngineLimitExceeded trap signifies that the agent entity has detected that the maximum tunnel limit has occurred on the indicated slot/cpu. The generation of this trap can be controlled by the SessionTraps configuration object.') stnCallEngineLimitExceeded = NotificationType((1, 3, 6, 1, 4, 1, 3551, 2, 100, 0, 61)).setObjects(("STN-CHASSIS-MIB", "stnEngineIndex"), ("STN-CHASSIS-MIB", "stnEngineSlot"), ("STN-CHASSIS-MIB", "stnEngineCpu")) if mibBuilder.loadTexts: stnCallEngineLimitExceeded.setStatus('current') if mibBuilder.loadTexts: stnCallEngineLimitExceeded.setDescription('A stnCallEngineLimitExceeded trap signifies that the agent entity has detected that the maximum call limit has occurred on the indicated slot/cpu. The generation of this trap can be controlled by the SessionTraps configuration object.') mibBuilder.exportSymbols("STN-SESSION-MIB", stnSessionOperStatus=stnSessionOperStatus, stnSessionPppCurrentCount=stnSessionPppCurrentCount, stnGlobalSessionEntry=stnGlobalSessionEntry, stnSessionsEncaps=stnSessionsEncaps, stnSessionIpsecCurrentActiveCount=stnSessionIpsecCurrentActiveCount, stnSessionTable=stnSessionTable, stnNotificationUserFailureType=stnNotificationUserFailureType, stnSessionAggregateFailedCount=stnSessionAggregateFailedCount, stnMaxSessionLimitExceeded=stnMaxSessionLimitExceeded, stnSessionType=stnSessionType, stnSessionLastChange=stnSessionLastChange, stnSessionTelnetTotalCount=stnSessionTelnetTotalCount, stnSessionPppTotalCount=stnSessionPppTotalCount, stnSessionIkeCurrentActiveCount=stnSessionIkeCurrentActiveCount, stnUserFailure=stnUserFailure, stnSessionsAggregate=stnSessionsAggregate, stnSessionsTelnet=stnSessionsTelnet, stnSessionRemoteConfigTotalCount=stnSessionRemoteConfigTotalCount, stnSessionTrapVars=stnSessionTrapVars, stnSessionsPpp=stnSessionsPpp, stnSessionEncapsCurrentCount=stnSessionEncapsCurrentCount, SessionOperStatus=SessionOperStatus, stnSessionIpsecTotalCount=stnSessionIpsecTotalCount, stnNoFlowEntriesAvailable=stnNoFlowEntriesAvailable, stnSessionFtpAlgFailedCount=stnSessionFtpAlgFailedCount, stnSessionFtpAlgCurrentActiveCount=stnSessionFtpAlgCurrentActiveCount, stnSessionEncapsFailedCount=stnSessionEncapsFailedCount, stnSessionTelnetFailedCount=stnSessionTelnetFailedCount, stnSessionRemoteConfigCurrentActiveCount=stnSessionRemoteConfigCurrentActiveCount, stnSessionPppCurrentActiveCount=stnSessionPppCurrentActiveCount, stnSessionFtpAlgCurrentCount=stnSessionFtpAlgCurrentCount, stnSessionSecureUserCurrentCount=stnSessionSecureUserCurrentCount, stnSessionTelnetCurrentActiveCount=stnSessionTelnetCurrentActiveCount, stnSessionIndex=stnSessionIndex, stnSessionIkeCurrentCount=stnSessionIkeCurrentCount, stnSessionL2tpTunnelTotalCount=stnSessionL2tpTunnelTotalCount, stnSessionFtpAlgTotalCount=stnSessionFtpAlgTotalCount, stnSessionsSecureUser=stnSessionsSecureUser, stnSessionContext=stnSessionContext, stnSession=stnSession, stnConfigFailure=stnConfigFailure, stnSessionL2tpTunnelFailedCount=stnSessionL2tpTunnelFailedCount, stnSessionPptpTunnelCurrentCount=stnSessionPptpTunnelCurrentCount, stnSessionSecureUserCurrentActiveCount=stnSessionSecureUserCurrentActiveCount, stnSessions=stnSessions, stnSessionIkeFailedCount=stnSessionIkeFailedCount, stnSessionIkeTotalCount=stnSessionIkeTotalCount, stnCallEngineLimitExceeded=stnCallEngineLimitExceeded, stnSessionSecureUserTotalCount=stnSessionSecureUserTotalCount, stnSessionEncapsTotalCount=stnSessionEncapsTotalCount, PYSNMP_MODULE_ID=stnSessions, stnSessionConsoleFailedCount=stnSessionConsoleFailedCount, stnSessionRemoteConfigCurrentCount=stnSessionRemoteConfigCurrentCount, stnSessionTelnetCurrentCount=stnSessionTelnetCurrentCount, stnSessionPptpTunnelCurrentActiveCount=stnSessionPptpTunnelCurrentActiveCount, stnSessionRemoteConfigFailedCount=stnSessionRemoteConfigFailedCount, stnSessionAggregateCurrentActiveCount=stnSessionAggregateCurrentActiveCount, stnSessionsPptp=stnSessionsPptp, stnSessionFtpTotalCount=stnSessionFtpTotalCount, stnSessionFtpCurrentCount=stnSessionFtpCurrentCount, stnSessionPptpTunnelFailedCount=stnSessionPptpTunnelFailedCount, stnSessionIpsecFailedCount=stnSessionIpsecFailedCount, stnSessionMibConformance=stnSessionMibConformance, stnSessionIpsecCurrentCount=stnSessionIpsecCurrentCount, stnSessionsL2tp=stnSessionsL2tp, stnSessionPptpTunnelTotalCount=stnSessionPptpTunnelTotalCount, stnSessionsIke=stnSessionsIke, stnSessionConsoleCurrentActiveCount=stnSessionConsoleCurrentActiveCount, stnNoLayerIfsAvailable=stnNoLayerIfsAvailable, stnSessionsIpsec=stnSessionsIpsec, stnSessionFtpFailedCount=stnSessionFtpFailedCount, stnSessionsFtp=stnSessionsFtp, stnSessionsConsole=stnSessionsConsole, stnGlobalSession=stnGlobalSession, stnSessionFtpCurrentActiveCount=stnSessionFtpCurrentActiveCount, stnGlobalSessionOperStatus=stnGlobalSessionOperStatus, stnTunnelEngineLimitExceeded=stnTunnelEngineLimitExceeded, stnSessionsFtpAlg=stnSessionsFtpAlg, stnSessionL2tpTunnelCurrentCount=stnSessionL2tpTunnelCurrentCount, stnSessionAggregateCurrentCount=stnSessionAggregateCurrentCount, stnNotificationConfigType=stnNotificationConfigType, stnSessionConsoleTotalCount=stnSessionConsoleTotalCount, stnNotificationUsername=stnNotificationUsername, stnSessionsRemoteConfig=stnSessionsRemoteConfig, stnSessionObjects=stnSessionObjects, stnSessionEntry=stnSessionEntry, stnSessionL2tpTunnelCurrentActiveCount=stnSessionL2tpTunnelCurrentActiveCount, stnGlobalSessionIndex=stnGlobalSessionIndex, stnSessionAggregateTotalCount=stnSessionAggregateTotalCount, stnSessionPppFailedCount=stnSessionPppFailedCount, stnSessionSecureUserFailedCount=stnSessionSecureUserFailedCount, stnSessionEncapsCurrentActiveCount=stnSessionEncapsCurrentActiveCount, stnGlobalSessionTable=stnGlobalSessionTable, stnSessionConsoleCurrentCount=stnSessionConsoleCurrentCount)
class NonNegativeInteger: def __get__(self, instance, owner): # 기본 동작 그대로 이용한다면 굳이 __get__()을 구현하지 않아도 된다. return instance.__dict__[self.name] def __set__(self, instance, value): if isinstance(value, int) and value >= 0: instance.__dict__[self.name] = value else: raise ValueError(f"value must be non-negative integer but '{value}'") def __set_name__(self, owner, name): self.name = name class IUserItem: userId = NonNegativeInteger() itemId = NonNegativeInteger() num = NonNegativeInteger() def __init__(self, userId, itemId, num): self.userId, self.itemId, self.num = userId, itemId, num def __str__(self): return f"{IUserItem.__name__} : {str(self.__dict__)}" print(IUserItem(1, 2, 3)) # IUserItem : {'userId': 1, 'itemId': 2, 'num': 3} try: print(IUserItem(1, 2, -1)) except ValueError as e: print(e) # ValueError: value must be non-negative integer but '-1'
msg = "No Smoking here" print(len(msg)) msg.count('o') msg.count('s',3,5) msg.count('n') msg.count('N') msg.count('O',7) msg.count('o',7) msg.count('o',1,7) msg.count('o',7,15)