content
stringlengths
7
1.05M
def generate_odd_nums(start, end): for num in range(start, end+1): if num % 2 !=0: print(num, end=" ") generate_odd_nums(start = 0, end = 15)
""" Escreva um programa que leia um número n inteiro qualquer e mostre na tela os n primeiros elementos de uma Sequência de Fibonacci. Ex.: 0 → 1 → 2 → 3 → 5 → 8 """ """ print("-"*30) print("Fibonacci Sequence") print("-"*30) n = int(input("How many Fibonacci sequence numbers do you want? ")) t1 = 0 t2 = 1 print("~"*30) print(f"{t1} → {t2}", end="") cont = 3 while cont <= n: t3 = t1 + t2 print(f' → {t3}', end="") t1 = t2 t2 = t3 cont += 1 print('\nEnd') """ Nant = 1 Fibonacci = 0 n = int(input('Digite um número:(Este vai ser o nº de elementos da sequência) ')) while n >= 0: print('{} → '.format(Fibonacci), end='') Fibonacci = Fibonacci + Nant #1 - 0 + 1 = 1 #2 - 1 + 0 = 1 #3 - 1 + 1 = 2 #4 - 2 + 1 = 3 #5 - 3 + 2 = 5 #6 - 5 + 3 = 8 #7 - 8 + 5 = 13 Nant = Fibonacci - Nant #1 - 1 - 1 = 0 #2 - 1 - 0 = 1 #3 - 2 - 1 = 1 #4 - 3 - 1 = 2 #5 - 5 - 2 = 3 #6 - 8 - 3 = 5 n -= 1 #10 -= 1 == 9 # 8 print('FIM')
__author__ = 'KKishore' PAD_WORD = '#=KISHORE=#' HEADERS = ['class', 'sms'] FEATURE_COL = 'sms' LABEL_COL = 'class' WEIGHT_COLUNM_NAME = 'weight' TARGET_LABELS = ['spam', 'ham'] TARGET_SIZE = len(TARGET_LABELS) HEADER_DEFAULTS = [['NA'], ['NA']] MAX_DOCUMENT_LENGTH = 100
class PracticeCenter: def __init__(self, practice_center_id, name, email=None, web_site=None, phone_number=None, climates=None, recommendations=None, average_note=None): self.id = practice_center_id self.name = name self.email = email self.web_site = web_site self.phone_number = phone_number self.climates = [] if climates is None else climates self.recommendations = [] if recommendations is None else recommendations self.average_note = 0 if average_note is None else average_note def __eq__(self, other): if isinstance(other, PracticeCenter): return self.id == other.id return False
class Rectangle: def __init__(self, width, height): self.width = width self.height = height def __str__(self): return "Rectangle(width=" + str(self.width) + ", height="+ str(self.height) + ")" def set_width(self, width): self.width = width def set_height(self, height): self.height = height def get_area(self): return self.width * self.height def get_perimeter(self): return 2 * (self.width + self.height) def get_diagonal(self): return (self.width ** 2 + self.height ** 2) ** 0.5 def get_picture(self): if(self.width > 50 or self.height > 50): return "Too big for picture." string = "" for i in range(self.height): for j in range(self.width): string += '*' string += '\n' return string def get_amount_inside(self, another_shape): return self.get_area() // another_shape.get_area() class Square(Rectangle): def __init__(self, length): self.length = length def __str__(self): return "Square(side=" + str(self.length) + ")" def set_side(self, length): self.length = length def set_width(self, length): self.length = length def set_height(self, length): self.length = length def get_area(self): return self.length ** 2 def get_perimeter(self): return 4 * self.length def get_diagonal(self): return (2 * self.length ** 2) ** 0.5 def get_picture(self): if(self.length > 50): return "Too big for picture." string = "" for i in range(self.length): for j in range(self.length): string += '*' string += '\n' return string
class Test: def foo(a): if a == 'foo': return 'foo' return 'bar'
#Exercício Python 3: Crie um programa que leia dois números e mostre a soma entre eles. nome = str(input("Digite seu nome: ")) print("Olá {}, tudo bem?".format(nome)) print("Espero que sim!... \nMeu nome e VanTec-9000, e hoje eu vou te ajudar com uma soma!") print("Por favor siga os passos que eu vou te pedir, é bem fácil!") n1 = int(input("Digite um número: ")) print("Muito Bem! \nAgora vamos mais uma vez!") n2 = int(input("Digite outro número: ")) print("Isso aí, não foi tão difícil né?") print("Agora estou vendo quais números você escolheu...") print("Hum... só mais um minutinho...") print("Estou vendo que você escolheu o número {} é o número {}.".format(n1,n2)) print("Vamos lá {}, agora é só somarmos os dois números que você escolheu.".format(nome)) print("Somando os números...") print("só mais um pouquinho...") print("Prontinho") print("A soma de {} + {} é igual á {}.".format(n1,n2,n1+n2)) print("Concluímos nossa missão! \nAté a proxima {}".format(nome))
#------------------------------------------------------------------- # Copyright (c) 2021, Scott D. Peckham # # Oct. 2021. Added to bypass old tf_utils.py for version, etc. # #------------------------------------------------------------------- # Notes: Update these whenever a new version is released #------------------------------------------------------------------- # # name() # version_number() # build_date() # version_string() # #------------------------------------------------------------------- def name(): return 'Stochastic Conflict Model' # name() #------------------------------------------------------------------- def version_number(): return 0.8 # version_number() #------------------------------------------------------------------- def build_date(): return '2021-10-13' # build_date() #------------------------------------------------------------------- def version_string(): num_str = str( version_number() ) date_str = ' (' + build_date() + ')' ver_string = name() + ' Version ' + num_str + date_str return ver_string # version_string() #-------------------------------------------------------------------
class Solution: def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ max_profit = temp_profit = 0 incresing = [tomorrow-today for today, tomorrow in zip(prices[:-1],prices[1:])] # print(incresing) for price in incresing: temp_profit += price if temp_profit < 0: temp_profit = 0 else: max_profit = max(max_profit, temp_profit) return max_profit
first_name = "ada" last_name = "lovelace" full_name = f"{first_name} {last_name}" #or full_name = "{} {}".format(first_name,last_name) #print(full_name) message = f"Hello, {full_name.title()}!" print(message)
''' the permission will be set in the database and only the managers will have permission to cancel an order already completed ''' class User(): def __init__(self, userid, username, permission): self.userid=userid self.username=username self.permission=permission def getUserNumber(self): return self.userid def getUserName(self): return self.username def getUserPermission(self): return self.permission def __str__(self): return self.username
class Solution: def recurse(self, A, stack) : if A == "" : self.ans.append(stack) temp_str = "" n = len(A) for i, ch in enumerate(A) : temp_str += ch if self.isPalindrome(temp_str) : self.recurse(A[i+1:], stack+[temp_str]) def isPalindrome(self, string) : if string == string[::-1] : return True return False # @param A : string # @return a list of list of strings def partition(self, A): n = len(A) if n <= 1 : return [A] self.ans = [] self.recurse(A, []) self.ans.sort() return self.ans
class DataParser: input_pub_sub_subscription = "" output_pub_sub_subscription = "" stocks: list = [] brokers: list = [] def __init__(self, html): self.html = html def parse_table_content(self, html): """ :param html: a table of stock or broker :return: """ pass def parse_stocks(self, content): """ for each stock return buys sells and net :param content: :return: """ pass def parse_brokers(self, content): """ for each broker return buys sells and net :param content: :return: """ pass def save_stocks(self, stocks): """ save all stock data to data-service main database :param stocks: :return: """ pass def save_brokers(self, brokers): """ save all brokers data to data-service main database :param brokers: :return: """ pass def get_single_stock(self, symbol): """ parse data for just one stock symbol :param stocks: :return: """ pass def send_to_pubsub_topic(self, stocks): """ get single stock from the list of stocks then send that stock through pubsub :param stocks: :return: """ pass
# name: TColors # Version: 1 # Created by: Grigory Sazanov # GitHub: https://github.com/SazanovGrigory class TerminalColors: # Description: Class that can be used to color terminal output # Example: print('GitHub: '+f"{BColors.TerminalColors.UNDERLINE}https://github.com/SazanovGrigory{BColors.TerminalColors.ENDC}") HEADER ='\033[95m' OKBLUE ='\033[94m' OKCYAN ='\033[96m' OKGREEN ='\033[92m' WARNING ='\033[93m' FAIL ='\033[91m' ENDC ='\033[0m' BOLD ='\033[1m' UNDERLINE ='\033[4m' def main(): print('Name: '+f"{TerminalColors.HEADER}TColors{TerminalColors.ENDC}") print('Version: '+f"{TerminalColors.WARNING}1{TerminalColors.ENDC}") print('Created by: '+f"{TerminalColors.BOLD}Grigory Sazanov{TerminalColors.ENDC}") print('GitHub: '+f"{TerminalColors.UNDERLINE}https://github.com/SazanovGrigory{TerminalColors.ENDC}") print(f"{TerminalColors.OKGREEN}Description: This is just a class that can be used to color terminal output{TerminalColors.ENDC}") print("Example: print(\"GitHub: \"+f\"{TColors.TerminalColors.UNDERLINE}Some text here{TColors.TerminalColors.ENDC}\")") print('Colors:') print(' '+f"{TerminalColors.HEADER}HEADER{TerminalColors.ENDC}") print(' '+f"{TerminalColors.OKBLUE}OKBLUE{TerminalColors.ENDC}") print(' '+f"{TerminalColors.OKCYAN}OKCYAN{TerminalColors.ENDC}") print(' '+f"{TerminalColors.OKGREEN}OKGREEN{TerminalColors.ENDC}") print(' '+f"{TerminalColors.WARNING}WARNING{TerminalColors.ENDC}") print(' '+f"{TerminalColors.FAIL}FAIL{TerminalColors.ENDC}") print(' '+f"{TerminalColors.BOLD}BOLD{TerminalColors.ENDC}") print(' '+f"{TerminalColors.UNDERLINE}UNDERLINE{TerminalColors.ENDC}") if __name__ == '__main__': main()
""" #David Hickox #Mar 20 17 #Typing Program #this will tell each of the 7 dwarfs if they can type fast enough or not #variables # STUDENTS = names of the dwarfs # num = WPM """ STUDENTS = ["Bashful", "Doc", "Dopey", "Happy", "Sleepy", "Sneezy", "Grumpy"] print("Welcome to the Typing program") #starts the loop for i in enumerate(STUDENTS): #asks for input num = float(input("How many words per minute can "+i[1]+" type? ")) #checks to see what wpm someone types at if num >= 150: print(i[1].upper(), "PUT DOWN THE COFFEE!!!") elif num >= 25: print(i[1], "you can type fast enough to pass Keyboarding") else: print(i[1]+", sorry you need to type faster!") input("Press Enter to exit")
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def solve(self, t1: TreeNode, t2: TreeNode) -> TreeNode: if not t1 and not t2: return None node = TreeNode(0) if t1: node.val += t1.val if t2: node.val += t2.val l = self.solve(t1.left if t1 else None, t2.left if t2 else None) r = self.solve(t1.right if t1 else None, t2.right if t2 else None) node.left = l node.right = r return node def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode: return self.solve(t1, t2)
"""Question: https://leetcode.com/problems/validate-binary-search-tree/ """ class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def isValidBST(self, root: TreeNode) -> bool: def is_valid_bst_recu(root, low, high): if root is None: return True return (low < root.val < high and is_valid_bst_recu(root.left, low, root.val) and is_valid_bst_recu(root.right, root.val, high)) return is_valid_bst_recu(root, float('-inf'), float('inf'))
# -*- coding: utf-8 -*- """ Created on Wed Jul 17 14:15:21 2019 @author: hu """
def foo(): global bar def bar(): pass
#!/usr/bin/env python """ idea: break up the address into 3 sections: 0xAABBCC. Treat each section like it is a layer in the page tables. AA is the base of one table. From that, offset BB is the base of the "PTE". Then CC is the offset into the "page" and contains a 24-bit word that we can copy. """ WORD_WIDTH = 24 DEPTH = 4 bit = 0xdeadbe bit = bit & ((1 << WORD_WIDTH) - 1) def gen(depth, prefix, max): width = DEPTH - depth indent = " "*(width) assert(max < (1<<DEPTH)) pretty_bin = "{:0{width}b}" prefix_fmt = "prefix_" + pretty_bin next_1 = (prefix << 1) | 1 prefix_1 = prefix_fmt.format(next_1, width=width+1) next_0 = (prefix << 1) | 0 prefix_0 = prefix_fmt.format(next_0, width=width+1) if depth == 0 and prefix <= max: real_label = "_BB_" + pretty_bin.format(prefix, width=width) print("{0}jmp {1}, {1}".format(indent, real_label)) elif (prefix << depth) > max: print("{}EXIT".format(indent)) else: print("{}seek PC_base + width".format(indent)) print("{}jmp {}, {}".format(indent, prefix_1, prefix_0)) print("{}prefix_{:0{width}b}:".format(indent, next_1, width=width+1)) gen(depth - 1, next_1, max) print("{}prefix_{:0{width}b}:".format(indent, next_0, width=width+1)) gen(depth - 1, next_0, max) gen(DEPTH, 0, 3)
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. INSTANCE_TAIL_LOGS_RESPONSE = """------------------------------------- /var/log/awslogs.log ------------------------------------- {'skipped_events_count': 0, 'first_event': {'timestamp': 1522962583519, 'start_position': 559799L, 'end_position': 560017L}, 'fallback_events_count': 0, 'last_event': {'timestamp': 1522962583519, 'start_position': 559799L, 'end_position': 560017L}, 'source_id': '77b026040b93055eb448bdc0b59e446f', 'num_of_events': 1, 'batch_size_in_bytes': 243} ------------------------------------- /var/log/httpd/error_log ------------------------------------- [Thu Apr 05 19:54:23.624780 2018] [mpm_prefork:warn] [pid 3470] AH00167: long lost child came home! (pid 3088) ------------------------------------- /var/log/httpd/access_log ------------------------------------- 172.31.69.153 (94.208.192.103) - - [05/Apr/2018:20:57:55 +0000] "HEAD /pma/ HTTP/1.1" 404 - "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36" ------------------------------------- /var/log/eb-activity.log ------------------------------------- + chown -R webapp:webapp /var/app/ondeck [2018-04-05T19:54:21.630Z] INFO [3555] - [Application update app-180406_044630@3/AppDeployStage0/AppDeployPreHook/02_setup_envvars.sh] : Starting activity... ------------------------------------- /tmp/sample-app.log ------------------------------------- 2018-04-05 20:52:51 Received message: \\xe2\\x96\\x88\\xe2 ------------------------------------- /var/log/eb-commandprocessor.log ------------------------------------- [2018-04-05T19:45:05.526Z] INFO [2853] : Running 2 of 2 actions: AppDeployPostHook...""" REQUEST_ENVIRONMENT_INFO_RESPONSE = { "EnvironmentInfo": [ { "InfoType": "tail", "Ec2InstanceId": "i-024a31a441247971d", "SampleTimestamp": "2018-04-06T01:05:43.875Z", "Message": "https://elasticbeanstalk-us-east-1-123123123123.s3.amazonaws.com" }, { "InfoType": "tail", "Ec2InstanceId": "i-0dce0f6c5e2d5fa48", "SampleTimestamp": "2018-04-06T01:05:43.993Z", "Message": "https://elasticbeanstalk-us-east-1-123123123123.s3.amazonaws.com" }, { "InfoType": "tail", "Ec2InstanceId": "i-090689581e5afcfc6", "SampleTimestamp": "2018-04-06T01:05:43.721Z", "Message": "https://elasticbeanstalk-us-east-1-123123123123.s3.amazonaws.com" }, { "InfoType": "tail", "Ec2InstanceId": "i-053efe7c102d0a540", "SampleTimestamp": "2018-04-06T01:05:43.900Z", "Message": "https://elasticbeanstalk-us-east-1-123123123123.s3.amazonaws.com" } ] }
class ParadoxException(Exception): pass class ParadoxConnectError(ParadoxException): def __init__(self) -> None: super().__init__('Unable to connect to panel') class ParadoxCommandError(ParadoxException): pass class ParadoxTimeout(ParadoxException): pass
#factorial(N) = N * factorial(N-1) # 예 factorial(4) = 4 * factorical(3) #... #factoral(1) = 1 def factorial(n): if n == 1: return 1 # 이 부분을 채워보세요! return n * factorial(n-1) print(factorial(5))
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: def merge(l1, l2): if not l1: return l2 if not l2: return l1 if l1[0] < l2[0]: return [l1[0]] + merge(l1[1:], l2) else: return [l2[0]] + merge(l1, l2[1:]) nums = merge(nums1,nums2) l = len(nums) if l%2: return nums[(l-1)//2] else: return (nums[l//2] +nums[l//2 -1])/2
cities = [ 'Riga', 'Daugavpils', 'Liepaja', 'Jelgava', 'Jurmala', 'Ventspils', 'Rezekne', 'Jekabpils', 'Valmiera', 'Ogre', 'Tukums', 'Cesis', 'Salaspils', 'Bolderaja', 'Kuldiga', 'Olaine', 'Saldus', 'Talsi', 'Dobele', 'Kraslava', 'Bauska', 'Ludza', 'Sigulda', 'Livani', 'Daugavgriva', 'Gulbene', 'Madona', 'Limbazi', 'Aizkraukle', 'Preili', 'Balvi', 'Karosta', 'Krustpils', 'Valka', 'Smiltene', 'Aizpute', 'Lielvarde', 'Kekava', 'Grobina', 'Iecava', 'Vilani', 'Plavinas', 'Rujiena', 'Kandava', 'Broceni', 'Salacgriva', 'Ozolnieki', 'Ikskile', 'Saulkrasti', 'Auce', 'Pinki', 'Ilukste', 'Skriveri', 'Ulbroka', 'Dagda', 'Skrunda', 'Karsava', 'Priekule', 'Priekuli', 'Vecumnieki', 'Mazsalaca', 'Kegums', 'Aluksne', 'Ergli', 'Viesite', 'Varaklani', 'Incukalns', 'Baldone', 'Jaunjelgava', 'Lubana', 'Zilupe', 'Mersrags', 'Cesvaine', 'Roja', 'Strenci', 'Vilaka', 'Ape', 'Aloja', 'Ligatne', 'Akniste', 'Nereta', 'Pavilosta', 'Jaunpils', 'Alsunga', 'Smarde', 'Vecpiebalga', 'Rucava', 'Marupe', 'Adazi', 'Aglona', 'Baltinava', 'Bergi', 'Carnikava', 'Drabesi', 'Dundaga', 'Cibla', 'Jaunpiebalga', 'Koceni', 'Koknese', 'Liegi', 'Loja', 'Malpils', 'Matisi', 'Murmuiza', 'Naukseni', 'Nica', 'Pilsrundale', 'Ragana', 'Rauna', 'Riebini', 'Ropazi', 'Garkalne', 'Rugaji', 'Sala', 'Stalbe', 'Vainode', 'Vecvarkava', 'Zelmeni' ]
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold ( s ) : n = len ( s ) ; sub_count = ( n * ( n + 1 ) ) // 2 ; arr = [ 0 ] * sub_count ; index = 0 ; for i in range ( n ) : for j in range ( 1 , n - i + 1 ) : arr [ index ] = s [ i : i + j ] ; index += 1 ; arr.sort ( ) ; res = "" ; for i in range ( sub_count ) : res += arr [ i ] ; return res ; #TOFILL if __name__ == '__main__': param = [ ('sqGOi',), ('848580',), ('01001110011001',), ('ZhWXUKmeiI',), ('0917296541285',), ('01101001111100',), ('tjP kR',), ('999907',), ('011100',), ('qJPHNSJOUj',) ] n_success = 0 for i, parameters_set in enumerate(param): if f_filled(*parameters_set) == f_gold(*parameters_set): n_success+=1 print("#Results: %i, %i" % (n_success, len(param)))
morse_translated_to_english = { ".-": "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", "...---...": "SOS", ".----": "1", "..---": "2", "...--": "3", "....-": "4", ".....": "5", "-....": "6", "--...": "7", "---..": "8", "----.": "9", "-----": "0", ".-.-.-": ".", "--..--": ",", "..--..": "?", ".----.": "'", "-.-.--": "!", "-..-.": "/", "-.--.": "(", "-.--.-": ")", ".-...": "&", "---...": ":", "-.-.-.": ";", "-...-": "=", ".-.-.": "+", "-....-": "-", "..--.-": "_", ".-..-.": '"', "...-..-": "$", ".--.-.": "@", } english_translated_to_morse = dict() for key, value in morse_translated_to_english.items(): english_translated_to_morse[value] = key def morse_code_to_english(incoming_morse_code): output = "" word = "" morse_code_list = incoming_morse_code.split(" ") i = 0 for code in morse_code_list: i += 1 if code != "" and len(morse_code_list) != i: word = word + morse_translated_to_english.get(code, code) elif len(morse_code_list) == i: word = word + morse_translated_to_english.get(code, code) output = output + " " + word else: output = f'{output} {word}' word = "" output = output.strip() output = output.replace(" ", " ") return output def english_to_morse_code(incoming_english): output = "" letter = "" english_list = list(incoming_english.upper()) i = 0 for letters in english_list: i += 1 if letters != "" and len(english_list) != i: letter = letter + " " + english_translated_to_morse.get(letters, letters) elif len(english_list) == i: letter = letter + " " + english_translated_to_morse.get(letters, letters) output = output + " " + letter else: output = f'{output} {letter}' output = output.strip() output = output.replace(" ", " ") return output
# # PySNMP MIB module Wellfleet-NAME-TABLE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-NAME-TABLE-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:41:01 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, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") IpAddress, iso, Integer32, TimeTicks, Counter32, ObjectIdentity, MibIdentifier, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, ModuleIdentity, Unsigned32, Counter64, Gauge32 = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "iso", "Integer32", "TimeTicks", "Counter32", "ObjectIdentity", "MibIdentifier", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "ModuleIdentity", "Unsigned32", "Counter64", "Gauge32") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") wfName, = mibBuilder.importSymbols("Wellfleet-COMMON-MIB", "wfName") wfNameEntry = MibIdentifier((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 18, 1)) wfNameDelete = MibScalar((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 18, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("created", 1), ("deleted", 2))).clone('created')).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfNameDelete.setStatus('mandatory') if mibBuilder.loadTexts: wfNameDelete.setDescription('Create or Delete the Object Base Record') wfNameName = MibScalar((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 18, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfNameName.setStatus('mandatory') if mibBuilder.loadTexts: wfNameName.setDescription('The BCC name of an object') mibBuilder.exportSymbols("Wellfleet-NAME-TABLE-MIB", wfNameEntry=wfNameEntry, wfNameName=wfNameName, wfNameDelete=wfNameDelete)
#!/usr/bin/env python """ Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ __all__ = ["ModuleConfigs"] class ModuleConfigs(object): """ This class maps to "/configurations" and "/configurationAttributes in command.json which includes configuration information of a service """ def __init__(self, configs, configAttributes): self.__module_configs = configs self.__module_config_attributes = configAttributes def get_raw_config_dict(self): """ Sometimes the caller needs to access to module_configs directly :return: config dict """ return self.__module_configs def get_all_attributes(self, module_name, config_type): """ Retrieve attributes from /configurationAttributes/config_type :param module_name: :param config_type: :return: """ if config_type not in self.__module_config_attributes: return {} try: return self.__module_config_attributes[config_type] except: return {} def get_all_properties(self, module_name, config_type): if config_type not in self.__module_configs: return {} try: return self.__module_configs[config_type] except: return {} def get_properties(self, module_name, config_type, property_names, default=None): properties = {} try: for property_name in property_names: properties[property_name] = self.get_property_value(module_name, config_type, property_name, default) except: return {} return properties def get_property_value(self, module_name, config_type, property_name, default=None): if config_type not in self.__module_configs or property_name not in self.__module_configs[config_type]: return default try: value = self.__module_configs[config_type][property_name] if value == None: value = default return value except: return default
''' 3) Escreva um programa que leia a quantidade de dias, horas, minutos e segundos do usuário. Calcule o total em segundos (1 min. = 60s; 1h = 60min; 1 dia = 24h). ''' dias = (int(input("Número de dias: "))) horas = (int(input("Número de horas: "))) minutos = (int(input("Número de minutos: "))) segundos = (int(input("Número de segundos: "))) total_segundos = segundos total_segundos += minutos*60 # Converter horas em segundos total_segundos += horas*60*60 # Converter minutos em segundos total_segundos += dias*24*60*60 # Converter dias em segundos print("Total em segundos: ", total_segundos)
""" Parking Cars in a List """ # create a list of cars row = ['Ford','Audi','BMW','Lexus'] # park my Mercedes at the end of the row row.append('Mercedes') print(row) print(row[4]) # swap the BMW at index 2 for a Jeep row[2] = 'Jeep' print(row) # park a Honda at the end of the row row.append('Honda') print(row) print(row[4]) # park a Kia at the front of the row row.insert(0,'Kia') print(row) print(row[4]) # find my Mercedes and leave the list print(row.index('Mercedes')) print(row.pop(5)) print(row) # find and remove the Lexus row.remove('Lexus') print(row)
#!/usr/bin/env python #### provide two configuration dictionaries: global_setting and feature_set #### ###This is basic configuration global_setting=dict( max_len = 256, # max length for the dataset ) feature_set=dict( ccmpred=dict( suffix = "ccmpred", length = 1, parser_name = "ccmpred_parser_2d", type = "2d", skip = False, ), # secondary structure ss2=dict( suffix = "ss2", length = 3, parser_name = "ss2_parser_1d", type = "1d", skip = False, ), # whether is on surface solv=dict( suffix = "solv", length = 1, parser_name = "solv_parser_1d", type = "1d", skip = False, ), # colstats colstats=dict( suffix = "colstats", length = 22, parser_name = "colstats_parser_1d", type = "1d", skip = False, ), #pairwise conatct features pairstats=dict( suffix = "pairstats", length = 3, parser_name = "pairstats_parser_2d", type = "2d", skip = False, ), # EVFold output evfold=dict( suffix = "evfold", length = 1, parser_name = "evfold_parser_2d", type = "2d", skip = False, ), # NEFF Count neff=dict( suffix = "hhmake", length = 1, parser_name = "neff_parser_1d", type = "1d", skip = False, ), # STD-DEV of CCMPRED output ccmpred_std=dict( suffix = "ccmpred", length = 1, parser_name = "ccmpred_std_parser_1d", type = "1d", skip = False, ), # STD_DEV of EVfold output evfold_std=dict( suffix = "evfold", length = 1, parser_name = "evfold_std_parser_1d", type = "1d", skip = False, ), )
class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: if not nums: return [] res = [] nums.sort() for i, num in enumerate(nums): if i > 0 and num == nums[i - 1]: continue left, right = i + 1, len(nums) - 1 while left < right: total = num + nums[left] + nums[right] if total > 0: right -= 1 elif total < 0: left += 1 else: res.append([num, nums[left], nums[right]]) left += 1 while nums[left] == nums[left - 1] and left < right: left += 1 return res obj = Solution() print(obj.threeSum([-1,0,1,2,-1,-4])) print(obj.threeSum([])) print(obj.threeSum([-2,1,1,7,1,-8])) print(obj.threeSum([0,0,0,0,0]))
#!/usr/bin/python3 with open('03_input', 'r') as f: lines = f.readlines() bits_list = [list(n.strip()) for n in lines] bit_len = len(bits_list[0]) zeros = [0 for i in range(bit_len)] ones = [0 for i in range(bit_len)] for bits in bits_list: for i, b in enumerate(bits): if b == '0': zeros[i] += 1 elif b == '1': ones[i] += 1 most = '' least = '' for i in range(bit_len): if zeros[i] > ones[i]: most += '0' least += '1' else: most += '1' least += '0' int_most = int(most, 2) int_least = int(least, 2) val = int_most * int_least print(val)
# WHICH NUMBER IS NOT LIKE THE OTHERS EDABIT SOLUTION: # creating a function to solve the problem. def unique(lst): # creating a for-loop to iterate for the elements in the list. for i in lst: # creating a nested if-statement to check for a distinct element. if lst.count(i) == 1: # returning the element if the condition is met. return i
#!/usr/bin/python3 # -*- coding: utf-8 -*- currency_symbols = {'AUD': 'A$', 'BGN': 'BGN', 'BRL': 'R$', 'CAD': 'CA$', 'CHF': 'CHF', 'CNY': 'CN¥', 'CZK': 'CZK', 'DKK': 'DKK', 'EUR': '€', 'GBP': '£', 'HKD': 'HK$', 'HRK': 'HRK', 'HUF': 'HUF', 'IDR': 'IDR', 'ILS': '₪', 'INR': '₹', 'ISK': 'ISK', 'JPY': '¥', 'KRW': '₩', 'MXN': 'MX$', 'MYR': 'MYR', 'NOK': 'NOK', 'NZD': 'NZ$', 'PHP': 'PHP', 'PLN': 'PLN', 'RON': 'RON', 'RUB': 'RUB', 'SEK': 'SEK', 'SGD': 'SGD', 'THB': 'THB', 'TRY': 'TRY', 'USD': '$', 'ZAR': 'ZAR', } currency_names = {'AUD': 'Australian Dollar', 'BGN': 'Bulgarian Lev', 'BRL': 'Brazilian Real', 'CAD': 'Canadian Dollar', 'CHF': 'Swiss Franc', 'CNY': 'Chinese Yuan', 'CZK': 'Czech Koruna', 'DKK': 'Danish Krone', 'EUR': 'Euro', 'GBP': 'British Pound', 'HKD': 'Hong Kong Dollar', 'HRK': 'Croatian Kuna', 'HUF': 'Hungarian Forint', 'IDR': 'Indonesian Rupiah', 'ILS': 'Israeli New Shekel', 'INR': 'Indian Rupee', 'ISK': 'Icelandic Króna', 'JPY': 'Japanese Yen', 'KRW': 'South Korean Won', 'MXN': 'Mexican Peso', 'MYR': 'Malaysian Ringgit', 'NOK': 'Norwegian Krone', 'NZD': 'New Zealand Dollar', 'PHP': 'Philippine Piso', 'PLN': 'Polish Zloty', 'RON': 'Romanian Leu', 'RUB': 'Russian Ruble', 'SEK': 'Swedish Krona', 'SGD': 'Singapore Dollar', 'THB': 'Thai Baht', 'TRY': 'Turkish Lira', 'USD': 'US Dollar', 'ZAR': 'South African Rand', }
# Complete the function below. # Function to check ipv4 # @Return boolean def validateIPV4(ipAddress): isIPv4 = True # ipv4 address is composed by octet for octet in ipAddress: try: # pretty straigthforward, convert to int # ensure per-octet value falls between [0,255] tmp = int(octet) if tmp<0 or tmp>255: isIPv4 = False break except: isIPv4 = False break return "IPv4" if isIPv4 else "Neither" # Function to check ipv6 # @Return boolean def validateIPV6(ipAddress): isIPv6 = True # ipv6 address is composed by hextet for hextet in ipAddress: try: # straigthforward, convert hexa to int # ensure per-hextet value falls between [0,65535] tmp = int(str(hextet),16) if (tmp<0) or tmp>65535: isIPv6 = False break except: isIPv6 = False break return "IPv6" if isIPv6 else "Neither" # Function to check IP address def checkIP(ip): # list to store final result result = [] for ipAddress in ip: # ipv4 is composed by 4 blocks of octet and separated by dot (.) if len(ipAddress.split(".")) == 4: ipCategory = validateIPV4(ipAddress.split(".")) # ipv6 is composed by 8 blocks of hextet and separated by colon (:) elif len(ipAddress.split(":")) == 8: ipCategory = validateIPV6(ipAddress.split(":")) else: ipCategory = "Neither" result.append(ipCategory) return result
""" Contains the Team object used represent NBA teams """ class Team: """ Object representing NBA teams containing: team name - three letter code - unique team id - nickname. """ def __init__(self, name, tricode, teamID, nickname): self.name = name self.tricode = tricode self.id = teamID self.nickname = nickname def get_name(self): return self.name def get_tricode(self): return self.tricode def get_id(self): return self.id def get_nickname(self): return self.nickname def __str__(self): return self.name + ", " + self.tricode
# -*- coding: utf8 -*- # ============LICENSE_START======================================================= # org.onap.vvp/validation-scripts # =================================================================== # Copyright © 2017 AT&T Intellectual Property. All rights reserved. # =================================================================== # # Unless otherwise specified, all software contained herein is licensed # under the Apache License, Version 2.0 (the “License”); # you may not use this software except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # # Unless otherwise specified, all documentation contained herein is licensed # under the Creative Commons License, Attribution 4.0 Intl. (the “License”); # you may not use this documentation except in compliance with the License. # You may obtain a copy of the License at # # https://creativecommons.org/licenses/by/4.0/ # # Unless required by applicable law or agreed to in writing, documentation # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # ============LICENSE_END============================================ # # ECOMP is a trademark and service mark of AT&T Intellectual Property. # def parse_nested_dict(d, key=""): ''' parse the nested dictionary and return values of given key of function parameter only ''' nested_elements = [] for k, v in d.items(): if isinstance(v, dict): sub_dict = parse_nested_dict(v, key) nested_elements.extend(sub_dict) else: if key: if k == key: nested_elements.append(v) else: nested_elements.append(v) return nested_elements def find_all_get_param_in_yml(yml): ''' Recursively find all referenced parameters in a parsed yaml body and return a list of parameters ''' os_pseudo_parameters = ['OS::stack_name', 'OS::stack_id', 'OS::project_id'] if not hasattr(yml, 'items'): return [] params = [] for k, v in yml.items(): if k == 'get_param' and v not in os_pseudo_parameters: for item in (v if isinstance(v, list) else [v]): if isinstance(item, dict): params.extend(find_all_get_param_in_yml(item)) elif isinstance(item, str): params.append(item) continue elif k == 'list_join': for item in (v if isinstance(v, list) else [v]): if isinstance(item, list): for d in item: params.extend(find_all_get_param_in_yml(d)) continue if isinstance(v, dict): params.extend(find_all_get_param_in_yml(v)) elif isinstance(v, list): for d in v: params.extend(find_all_get_param_in_yml(d)) return params def find_all_get_resource_in_yml(yml): ''' Recursively find all referenced resources in a parsed yaml body and return a list of resource ids ''' if not hasattr(yml, 'items'): return [] resources = [] for k, v in yml.items(): if k == 'get_resource': if isinstance(v, list): resources.append(v[0]) else: resources.append(v) continue if isinstance(v, dict): resources.extend(find_all_get_resource_in_yml(v)) elif isinstance(v, list): for d in v: resources.extend(find_all_get_resource_in_yml(d)) return resources def find_all_get_file_in_yml(yml): ''' Recursively find all get_file in a parsed yaml body and return the list of referenced files/urls ''' if not hasattr(yml, 'items'): return [] resources = [] for k, v in yml.items(): if k == 'get_file': if isinstance(v, list): resources.append(v[0]) else: resources.append(v) continue if isinstance(v, dict): resources.extend(find_all_get_file_in_yml(v)) elif isinstance(v, list): for d in v: resources.extend(find_all_get_file_in_yml(d)) return resources def find_all_get_resource_in_resource(resource): ''' Recursively find all referenced resources in a heat resource and return a list of resource ids ''' if not hasattr(resource, 'items'): return [] resources = [] for k, v in resource.items(): if k == 'get_resource': if isinstance(v, list): resources.append(v[0]) else: resources.append(v) continue if isinstance(v, dict): resources.extend( find_all_get_resource_in_resource(v)) elif isinstance(v, list): for d in v: resources.extend( find_all_get_resource_in_resource(d)) return resources def get_associated_resources_per_resource(resources): ''' Recursively find all referenced resources for each resource in a list of resource ids ''' if not hasattr(resources, 'items'): return None resources_dict = {} resources_dict["resources"] = {} ref_resources = [] for res_key, res_value in resources.items(): get_resources = [] for k, v in res_value: if k == 'get_resource' and\ isinstance(v, dict): get_resources = find_all_get_resource_in_resource(v) # if resources found, add to dict if get_resources: ref_resources.extend(get_resources) resources_dict["resources"][res_key] = { "res_value": res_value, "get_resources": get_resources, } resources_dict["ref_resources"] = set(ref_resources) return resources_dict def flatten(items): ''' flatten items from any nested iterable ''' merged_list = [] for item in items: if isinstance(item, list): sub_list = flatten(item) merged_list.extend(sub_list) else: merged_list.append(item) return merged_list
def kph(ms): return ms * 3.6 def mph(ms): return ms * 2.2369362920544 def knots(ms): return ms * 1.9438444924574 def minPkm(ms): # minutes per kilometre return ms * (100 / 6) def c(ms): # speed of light return ms / 299792458 def speedOfLight(ms): return c(ms) def mach(ms): return ms / 340 def speedOfSound(ms): return mach(ms)
# -*- encoding: utf-8 -*- # # Copyright 2015-2016 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. def test_create_user(runner, test_user): assert test_user["name"] == "foo" assert test_user["fullname"] == "Foo Bar" assert test_user["email"] == "[email protected]" def test_create_admin(runner): user = runner.invoke( [ "user-create", "--name", "foo", "--email", "[email protected]", "--password", "pass" ] )["user"] assert user["name"] == "foo" assert user["fullname"] == "foo" assert user["email"] == "[email protected]" def test_create_super_admin(runner): user = runner.invoke( [ "user-create", "--name", "foo", "--email", "[email protected]", "--password", "pass" ] )["user"] assert user["name"] == "foo" assert user["fullname"] == "foo" assert user["email"] == "[email protected]" def test_create_inactive(runner): user = runner.invoke( [ "user-create", "--name", "foo", "--password", "pass", "--email", "[email protected]", "--no-active", ] )["user"] assert user["state"] == "inactive" def test_list(runner): users_cnt = len(runner.invoke(["user-list"])["users"]) runner.invoke( [ "user-create", "--name", "bar", "--email", "[email protected]", "--password", "pass", ] ) new_users_cnt = len(runner.invoke(["user-list"])["users"]) assert new_users_cnt == users_cnt + 1 def test_update(runner, test_user): runner.invoke( [ "user-update", test_user["id"], "--etag", test_user["etag"], "--name", "bar", "--email", "[email protected]", "--fullname", "Barry White", ] ) user = runner.invoke(["user-show", test_user["id"]])["user"] assert user["name"] == "bar" assert user["fullname"] == "Barry White" assert user["email"] == "[email protected]" def test_update_active(runner, test_user, team_id): assert test_user["state"] == "active" result = runner.invoke( ["user-update", test_user["id"], "--etag", test_user["etag"], "--no-active"] ) assert result["user"]["id"] == test_user["id"] assert result["user"]["state"] == "inactive" result = runner.invoke( [ "user-update", test_user["id"], "--etag", result["user"]["etag"], "--name", "foobar", ] ) assert result["user"]["id"] == test_user["id"] assert result["user"]["state"] == "inactive" assert result["user"]["name"] == "foobar" result = runner.invoke( ["user-update", test_user["id"], "--etag", result["user"]["etag"], "--active"] ) assert result["user"]["state"] == "active" def test_delete(runner, test_user, team_id): result = runner.invoke_raw( ["user-delete", test_user["id"], "--etag", test_user["etag"]] ) assert result.status_code == 204 def test_show(runner, test_user, team_id): user = runner.invoke(["user-show", test_user["id"]])["user"] assert user["name"] == test_user["name"] def test_where_on_list(runner, test_user, team_id): runner.invoke( [ "user-create", "--name", "foo2", "--email", "[email protected]", "--password", "pass", ] ) runner.invoke( [ "user-create", "--name", "foo3", "--email", "[email protected]", "--password", "pass", ] ) users_cnt = len(runner.invoke(["user-list"])["users"]) assert runner.invoke(["user-list"])["_meta"]["count"] == users_cnt assert runner.invoke(["user-list", "--where", "name:foo"])["_meta"]["count"] == 1
# -*- coding: utf-8 -*- even = 0 for i in range(5): A = float(input()) if (A % 2) == 0: even +=1 print("%i valores pares"%even)
class user(): def __init__(self,id,passwd): self.id = id self.passwd = passwd def get_id(self): pass
def factorial(no): if no == 1: return no else: return no * factorial(no - 1) """ # Factorial using for loop Without Recursive ans = 1 for i in range(1, no+1): ans = ans * i print(ans) """ def main(): no = int(input("Enter number : ")) # ret = no+1 print(factorial(no)) if __name__ == '__main__': main()
## using hashing .. def duplicates_hash(arr, n): s = dict() for i in range(n): if arr[i] in s: s[arr[i]] = s[arr[i]]+1 else: s[arr[i]] = 1 res = [] for i in s: if s[i] > 1: res.append(i) if len(res)>0: return res else: return -1 ## using given array as hashmap because in question it is given that range of array -->[1,length of array] def duplicates_arr(arr, n): res = [] for i in range(n): arr[arr[i]%n] = arr[arr[i]%n] + n for i in range(n): if (arr[i]//n>1): res.append(i) return res ## Driver code...!!!!1 if __name__ == "__main__": n = int(input()) arr1 = list(map(int,input().split())) print('using array',duplicates_arr(arr1.copy(),n)) ## pass copy of main input array.. print('using hashmap',duplicates_hash(arr1,n)) ''' sample input 5 2 3 1 2 3 '''
lastA = 116 lastB = 299 judgeCounter = 0 for i in range(40000000): # Generation cycle aRes = (lastA * 16807) % 2147483647 bRes = (lastB * 48271) % 2147483647 # Judging time if (aRes % 65536 == bRes % 65536): print("Match found! With ", aRes, " and ", bRes, sep="") judgeCounter += 1 # Setup for next round lastA = aRes lastB = bRes print("Final judge score, part 1:", judgeCounter) ## Part 2 lastA = 116 lastB = 299 judgeCounter = 0 for i in range(5000000): # Generation cycle aRes = (lastA * 16807) % 2147483647 while (aRes % 4 != 0): aRes = (aRes * 16807) % 2147483647 bRes = (lastB * 48271) % 2147483647 while (bRes % 8 != 0): bRes = (bRes * 48271) % 2147483647 # Judging time if (aRes % 65536 == bRes % 65536): print(i, ": Match found!", sep="") judgeCounter += 1 # Setup for next round lastA = aRes lastB = bRes print("Final judge score, part 2:", judgeCounter)
"""In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number. === Example: === high_and_low("1 2 3 4 5") # return "5 1" high_and_low("1 2 -3 4 5") # return "5 -3" high_and_low("1 9 3 4 -5") # return "9 -5" === Notes: === All numbers are valid Int32, no need to validate them. There will always be at least one number in the input string. Output string must be two numbers separated by a single space, and highest number is first. """ def high_and_low(numbers: str) -> str: all_nums = tuple(int(num) for num in numbers.split()) low = min(all_nums) high = max(all_nums) return f"{high} {low}"
# # PySNMP MIB module ZYXEL-DIFFSERV-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-DIFFSERV-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:49:30 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsIntersection") dot1dBasePort, = mibBuilder.importSymbols("BRIDGE-MIB", "dot1dBasePort") EnabledStatus, = mibBuilder.importSymbols("P-BRIDGE-MIB", "EnabledStatus") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") TimeTicks, Counter64, MibIdentifier, Bits, ObjectIdentity, IpAddress, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, Unsigned32, Gauge32, Integer32, NotificationType, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "Counter64", "MibIdentifier", "Bits", "ObjectIdentity", "IpAddress", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "Unsigned32", "Gauge32", "Integer32", "NotificationType", "Counter32") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") esMgmt, = mibBuilder.importSymbols("ZYXEL-ES-SMI", "esMgmt") zyxelDiffserv = ModuleIdentity((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22)) if mibBuilder.loadTexts: zyxelDiffserv.setLastUpdated('201207010000Z') if mibBuilder.loadTexts: zyxelDiffserv.setOrganization('Enterprise Solution ZyXEL') if mibBuilder.loadTexts: zyxelDiffserv.setContactInfo('') if mibBuilder.loadTexts: zyxelDiffserv.setDescription('The subtree for Differentiated services (Diffserv)') zyxelDiffservSetup = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1)) zyDiffservState = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 1), EnabledStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: zyDiffservState.setStatus('current') if mibBuilder.loadTexts: zyDiffservState.setDescription('Enable/Disable DiffServ on the switch. DiffServ is a class of service (CoS) model that marks packets so that they receive specific per-hop treatment at DiffServ-compliant network devices along the route based on the application types and traffic flow.') zyxelDiffservMapTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 2), ) if mibBuilder.loadTexts: zyxelDiffservMapTable.setStatus('current') if mibBuilder.loadTexts: zyxelDiffservMapTable.setDescription('The table contains Diffserv map configuration. ') zyxelDiffservMapEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 2, 1), ).setIndexNames((0, "ZYXEL-DIFFSERV-MIB", "zyDiffservMapDscp")) if mibBuilder.loadTexts: zyxelDiffservMapEntry.setStatus('current') if mibBuilder.loadTexts: zyxelDiffservMapEntry.setDescription('An entry contains Diffserv map configuration.') zyDiffservMapDscp = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 2, 1, 1), Integer32()) if mibBuilder.loadTexts: zyDiffservMapDscp.setStatus('current') if mibBuilder.loadTexts: zyDiffservMapDscp.setDescription('The DSCP classification identification number.') zyDiffservMapPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 2, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: zyDiffservMapPriority.setStatus('current') if mibBuilder.loadTexts: zyDiffservMapPriority.setDescription('Set the IEEE 802.1p priority mapping.') zyxelDiffservPortTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 3), ) if mibBuilder.loadTexts: zyxelDiffservPortTable.setStatus('current') if mibBuilder.loadTexts: zyxelDiffservPortTable.setDescription('The table contains Diffserv port configuration.') zyxelDiffservPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 3, 1), ).setIndexNames((0, "BRIDGE-MIB", "dot1dBasePort")) if mibBuilder.loadTexts: zyxelDiffservPortEntry.setStatus('current') if mibBuilder.loadTexts: zyxelDiffservPortEntry.setDescription('An entry contains Diffserv port configuration.') zyDiffservPortState = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 3, 1, 1), EnabledStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: zyDiffservPortState.setStatus('current') if mibBuilder.loadTexts: zyDiffservPortState.setDescription('Enable/Disable DiffServ on the port.') mibBuilder.exportSymbols("ZYXEL-DIFFSERV-MIB", zyDiffservState=zyDiffservState, zyxelDiffservMapTable=zyxelDiffservMapTable, zyxelDiffservPortTable=zyxelDiffservPortTable, zyxelDiffservSetup=zyxelDiffservSetup, zyDiffservPortState=zyDiffservPortState, zyxelDiffservPortEntry=zyxelDiffservPortEntry, PYSNMP_MODULE_ID=zyxelDiffserv, zyxelDiffserv=zyxelDiffserv, zyDiffservMapDscp=zyDiffservMapDscp, zyxelDiffservMapEntry=zyxelDiffservMapEntry, zyDiffservMapPriority=zyDiffservMapPriority)
PLUGIN_URL_NAME_PREFIX = 'djangocms_alias' CREATE_ALIAS_URL_NAME = '{}_create'.format(PLUGIN_URL_NAME_PREFIX) DELETE_ALIAS_URL_NAME = '{}_delete'.format(PLUGIN_URL_NAME_PREFIX) DETACH_ALIAS_PLUGIN_URL_NAME = '{}_detach_plugin'.format(PLUGIN_URL_NAME_PREFIX) # noqa: E501 LIST_ALIASES_URL_NAME = '{}_list'.format(PLUGIN_URL_NAME_PREFIX) CATEGORY_LIST_URL_NAME = '{}_category_list'.format(PLUGIN_URL_NAME_PREFIX) SET_ALIAS_POSITION_URL_NAME = '{}_set_alias_position'.format(PLUGIN_URL_NAME_PREFIX) # noqa: E501 SELECT2_ALIAS_URL_NAME = '{}_select2'.format(PLUGIN_URL_NAME_PREFIX) USAGE_ALIAS_URL_NAME = '{}_alias_usage'.format(PLUGIN_URL_NAME_PREFIX)
class Party: def __init__(self): self.party_people = [] self.party_people_counter = 0 party = Party() people = input() while people != 'End': party.party_people.append(people) party.party_people_counter += 1 people = input() print(f'Going: {", ".join(party.party_people)}') print(f'Total: {party.party_people_counter}')
m = float(input('Digite o número em metros: ')) c = m * 100 mm = c * 10 print('{}m é igual à {}cm e {}mm'.format(m, c, mm))
class Solution: def __init__(self): self.count = 0 def waysToStep(self, n: int) -> int: def dfs(n): if n == 1: self.count += 1 elif n == 2: self.count += 2 elif n == 3: self.count += 4 else: dfs(n - 1) dfs(n - 2) dfs(n - 3) dfs(n) return self.count def waysToStep(self, n: int) -> int: if n < 3: return n elif n == 3: return 4 dp0, dp1, dp2 = 1, 2, 4 for _ in range(4, n + 1): dp0, dp1, dp2 = dp1, dp2, (dp0 + dp1 + dp2) % 1000000007 return dp2
# Determine whether a number is a perfect number, an Armstrong number or a palindrome. def perfect_number(n): sum1 = 0 for i in range(1, n): if(n % i == 0): sum1 = sum1 + i if (sum1 == n): return True else: return False def armstrong(n): sum = 0 temp = n while temp > 0: digit = temp % 10 sum += digit ** 3 temp //= 10 if n == sum: return True else: return False def palindrome(n): temp = n rev = 0 while(n > 0): dig = n % 10 rev = rev*10+dig n = n//10 if(temp == rev): return True else: return False k = True while k == True: n = int(input("Enter a number: ")) if perfect_number(n) == True: print(n, " is a Perfect number!") elif armstrong(n) == True: print(n, " is an Armstrong number!") elif palindrome(n) == True: print("The number is a palindrome!") else: print("The number is a Unknow!") option = input('Do you want to try again.(y/n): ').lower() if option == 'y': continue else: k = False
#!/usr/bin/env python3 '''\ Provides basic operations for Binary Search Trees using a tuple representation. In this representation, a BST is either an empty tuple or a length-3 tuple consisting of a data value, a BST called the left subtree and a BST called the right subtree ''' def is_bintree(T): if type(T) is not tuple: return False if T == (): return True if len(T) != 3: return False if is_bintree(T[1]) and is_bintree(T[2]): return True return False def bst_min(T): if T == (): return None if not T[1]: return T[0] return bst_min(T[1]) def bst_max(T): if T == (): return None if not T[2]: return T[0] return bst_max(T[2]) def is_bst(T): if not is_bintree(T): return False if T == (): return True if not is_bst(T[1]) or not is_bst(T[2]): return False if T[1] == () and T[2] == (): return True if T[2] == (): return bst_max(T[1]) < T[0] if T[1] == (): return T[0] < bst_min(T[2]) return bst_max(T[1]) < T[0] < bst_min(T[2]) def bst_search(T,x): if T == (): return T if T[0] == x: return T if x < T[0]: return bst_search(T[1],x) return bst_search(T[2],x) def bst_insert(T,x): if T == (): return (x,(),()) elif x < T[0]: return (T[0],bst_insert(T[1],x),T[2]) else: return (T[0],T[1],bst_insert(T[2],x)) def delete_min(T): if T == (): return T if not T[1]: return T[2] else: return (T[0],delete_min(T[1]),T[2]) def bst_delete(T,x): assert T, "deleting value not in tree" if x < T[0]: return (T[0],bst_delete(T[1],x),T[2]) elif x > T[0]: return (T[0],T[1],bst_delete(T[2],x)) else: # T[0] == x if not T[1]: return T[2] elif not T[2]: return T[1] else: return (bst_min(T[2]),T[1],delete_min(T[2])) def print_bintree(T,indent=0): if not T: print('*') return else: print(T[0]) print(' '*(indent + len(T[0])-1)+'---', end = '') print_bintree(T[1],indent+3) print(' '*(indent + len(T[0])-1)+'---', end = '') print_bintree(T[2],indent+3) def print_func_space(x): print(x,end=' ') def inorder(T,f): if not is_bst(T): return if not T: return inorder(T[1],f) f(T[0]) inorder(T[2],f) # Programming project: provide implementations for the functions below, # i.e., replace all the pass statements in the functions below. # Then add tests for these functions in the block # that starts "if __name__ == '__main__':" def preorder(T,f): # based on the code in inorder(), we shouldn't traverse non-BSTs if is_bst(T) and T: f(T[0]) preorder(T[1], f) preorder(T[2], f) def postorder(T,f): # based on the code in inorder(), we shouldn't traverse non-BSTs if is_bst(T) and T: postorder(T[1], f) postorder(T[2], f) f(T[0]) def tree_height(T): if is_bintree(T) and T: return 1 + max(tree_height(T[1]), tree_height(T[2])) elif T == (): return 0 def balance(T): '''Returns the height of the left subtree of T minus the height of the right subtree of T i.e., the balance of the root of T''' if is_bintree(T) and T: return tree_height(T[1]) - tree_height(T[2]) elif T == (): return 0 def minBalance(T): 'returns the minimum value of balance(S) for all subtrees S of T' if is_bintree(T) and T: return min((balance(T), minBalance(T[1]), minBalance(T[2]))) elif T == (): return 0 def maxBalance(T): 'returns the maximum value of balance(S) for all subtrees S of T' if is_bintree(T) and T: return max((balance(T), maxBalance(T[1]), maxBalance(T[2]))) elif T == (): return 0 def is_avl(T): '''Returns True if T is an AVL tree, False otherwise Hint: use minBalance(T) and maxBalance(T)''' if is_bst(T) and T: return minBalance(T) >= -1 and maxBalance(T) <= 1 elif T == (): return True return False # Add tests for the above seven functions below if __name__ == '__main__': K = () for x in ['Joe','Bob', 'Phil', 'Paul', 'Marc', 'Jean', 'Jerry', 'Alice', 'Anne']: K = bst_insert(K,x) print('\nTree elements in sorted order\n') inorder(K,print_func_space) print() print('\nPrint full tree\n') print_bintree(K) print("\nDelete Bob and print tree\n") K = bst_delete(K,'Bob') print_bintree(K) print() print("\nPrint subtree at 'Phil'\n") print_bintree(bst_search(K,'Phil')) print() # TEST CODE FOR THE FUNCTIONS YOU IMPLEMENTED GOES BELOW: # BST, AVL # 2 # 0 ────┴──── 5 # -2 ──┴── 1 3 ──┴── 7 # -5 ┴ -1 tree_a = (2, (0, (-2, (-5, (), ()), (-1, (), ())), (1, (), ())), (5, (3, (), ()), (7, (), ()))) # BST, not AVL # 2 # 0 ────┴──── 5 # -2 ──┴── 1 # -5 ┴ -1 tree_b = (2, (0, (-2, (-5, (), ()), (-1, (), ())), (1, (), ())), (5, (), ())) # BST, not AVL # 2 # 0 ─────┴───── 6 # 4 ──┴── 7 # 3 ┴ 5 tree_c = (2, (0, (), ()), (6, (4, (3, (), ()), (5, (), ())), (7, (), ()))) # BST, AVL # 2 # 0 ────┴──── 5 # -2 ──┴── 1 3 ──┴── 7 # -5 ┴ -1 ┴─ 4 tree_d = (2, (0, (-2, (-5, (), ()), (-1, (), ())), (1, (), ())), (5, (3, (), (4, (), ())), (7, (), ()))) # not BST, not AVL # 2 # 5 ────┴──── 0 # -2 ──┴── 6 -1 ──┴── 7 # -5 ┴ -1 tree_e = (2, (5, (-2, (-5, (), ()), (-1, (), ())), (6, (), ())), (0, (-1, (), ()), (7, (), ()))) # Preorder print('Test preorder... ', end='') l = [] preorder(tree_a, l.append) assert l == [2, 0, -2, -5, -1, 1, 5, 3, 7] l=[] preorder(tree_d, l.append) assert l == [2, 0, -2, -5, -1, 1, 5, 3, 4, 7] print('Passed') # Inorder print('Test inorder... ', end='') l = [] inorder(tree_b, l.append) assert l == [-5, -2, -1, 0, 1, 2, 5] l = [] inorder(tree_e, l.append) assert l == [] # based on the code in inorder(), we shouldn't traverse non-BSTs print('Passed') # Postorder print('Test postorder... ', end='') l = [] postorder(tree_c, l.append) assert l == [0, 3, 5, 4, 7, 6, 2] l = [] postorder(tree_d, l.append) assert l == [-5, -1, -2, 1, 0, 4, 3, 7, 5, 2] print('Passed') # Tree height print('Test tree_height... ', end='') assert tree_height(()) == 0 assert tree_height((1, (), ())) == 1 assert tree_height(tree_a) == 4 assert tree_height(tree_b) == 4 assert tree_height(tree_c) == 4 assert tree_height(tree_d) == 4 assert tree_height(tree_e) == 4 print('Passed') # Count (im)balance print('Test balance... ', end='') assert balance(tree_a) == 1 assert balance(tree_b) == 2 assert balance(tree_c) == -2 assert balance(tree_d) == 0 assert balance(tree_e) == 1 print('Passed') # Testing for AVLness print('Test is_avl... ', end='') assert is_avl(tree_a) assert not is_avl(tree_b) assert not is_avl(tree_c) assert is_avl(tree_d) assert not is_avl(tree_e) print('Passed')
# Created by MechAviv # [Kyrin] | [1090000] # Nautilus : Navigation Room sm.setSpeakerID(1090000) sm.sendSayOkay("Welcome aboard the Nautilus. The ship isn't headed anywhere for a while. How about going out to the deck?")
""" Nombre: Alejandro Tejada Curso: Diseño lenguajes de programacion Fecha: Abril 2021 Programa: scannerToken.py Propósito: Esta clase es para guardar los valores de token V 1.0 """ class tokenForScanner: def __init__(self): self.tipoToken = "" self.numeracion = "" self.valor = "" def getTipoToken(self): return self.tipoToken def setTipoToken(self, tipo): self.tipoToken = tipo def getNumeracion(self): return self.numeracion def setNumeracion(self, valor): self.numeracion = valor def getValor(self): return self.valor def setValor(self, valor): self.valor = valor def getAllValues(self): return [self.tipoToken, self.valor, self.numeracion]
def deduplicate_list(list_with_dups): return list(dict.fromkeys(list_with_dups)) def filter_list_by_set(original_list, filter_set): return [elem for elem in original_list if elem not in filter_set] def write_to_file(filename, text, message): # pragma: no cover with open(filename, 'w') as f: f.write(text) print(message)
# # PySNMP MIB module HM2-DNS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HM2-DNS-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:31:23 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, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection", "ValueRangeConstraint", "ValueSizeConstraint") HmActionValue, HmEnabledStatus, hm2ConfigurationMibs = mibBuilder.importSymbols("HM2-TC-MIB", "HmActionValue", "HmEnabledStatus", "hm2ConfigurationMibs") InetAddressType, InetAddress = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddressType", "InetAddress") SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Gauge32, Unsigned32, ModuleIdentity, NotificationType, TimeTicks, Counter32, Integer32, Counter64, IpAddress, MibIdentifier, iso, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "Unsigned32", "ModuleIdentity", "NotificationType", "TimeTicks", "Counter32", "Integer32", "Counter64", "IpAddress", "MibIdentifier", "iso", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits") DisplayString, TextualConvention, RowStatus = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention", "RowStatus") hm2DnsMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 248, 11, 90)) hm2DnsMib.setRevisions(('2011-06-17 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: hm2DnsMib.setRevisionsDescriptions(('Initial version.',)) if mibBuilder.loadTexts: hm2DnsMib.setLastUpdated('201106170000Z') if mibBuilder.loadTexts: hm2DnsMib.setOrganization('Hirschmann Automation and Control GmbH') if mibBuilder.loadTexts: hm2DnsMib.setContactInfo('Postal: Stuttgarter Str. 45-51 72654 Neckartenzlingen Germany Phone: +49 7127 140 E-mail: [email protected]') if mibBuilder.loadTexts: hm2DnsMib.setDescription('Hirschmann DNS MIB for DNS client, DNS client cache and DNS caching server. Copyright (C) 2011. All Rights Reserved.') hm2DnsMibNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 0)) hm2DnsMibObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1)) hm2DnsMibSNMPExtensionGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 3)) hm2DnsClientGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1)) hm2DnsCacheGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 2)) hm2DnsCachingServerGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 3)) hm2DnsClientAdminState = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 1), HmEnabledStatus().clone('disable')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hm2DnsClientAdminState.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientAdminState.setDescription('The operational status of DNS client. If disabled, no host name lookups will be done for names entered on the CLI and in the configuration of services e.g. NTP.') hm2DnsClientConfigSource = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("user", 1), ("mgmt-dhcp", 2), ("provider", 3))).clone('mgmt-dhcp')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hm2DnsClientConfigSource.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientConfigSource.setDescription('DNS client server source. If the value is set to user(1), the variables from hm2DnsClientServerCfgTable will be used. If the value is set to mgmt-dhcp(2), the DNS servers received by DHCP on the management interface will be used. If the value is set to provider(3), the DNS configuration will be taken from DHCP, PPP or PPPoE on the primary WAN link.') hm2DnsClientServerCfgTable = MibTable((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3), ) if mibBuilder.loadTexts: hm2DnsClientServerCfgTable.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerCfgTable.setDescription('The table that contains the DNS Servers entries configured by the user in the system.') hm2DnsClientServerCfgEntry = MibTableRow((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3, 1), ).setIndexNames((0, "HM2-DNS-MIB", "hm2DnsClientServerIndex")) if mibBuilder.loadTexts: hm2DnsClientServerCfgEntry.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerCfgEntry.setDescription('An entry contains the IP address of a DNS server configured in the system.') hm2DnsClientServerIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4))) if mibBuilder.loadTexts: hm2DnsClientServerIndex.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerIndex.setDescription('The unique index used for each server added in the DNS servers table.') hm2DnsClientServerAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3, 1, 2), InetAddressType().clone('ipv4')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hm2DnsClientServerAddressType.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerAddressType.setDescription('Address type for DNS server. Currently, only ipv4 is supported.') hm2DnsClientServerAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3, 1, 3), InetAddress().clone(hexValue="00000000")).setMaxAccess("readwrite") if mibBuilder.loadTexts: hm2DnsClientServerAddress.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerAddress.setDescription('The IP address of the DNS server.') hm2DnsClientServerRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3, 1, 4), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hm2DnsClientServerRowStatus.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerRowStatus.setDescription('Describes the status of a row in the table.') hm2DnsClientServerDiagTable = MibTable((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 4), ) if mibBuilder.loadTexts: hm2DnsClientServerDiagTable.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerDiagTable.setDescription('The table that contains the DNS Servers entries configured and used in the system.') hm2DnsClientServerDiagEntry = MibTableRow((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 4, 1), ).setIndexNames((0, "HM2-DNS-MIB", "hm2DnsClientServerDiagIndex")) if mibBuilder.loadTexts: hm2DnsClientServerDiagEntry.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerDiagEntry.setDescription('An entry contains the IP address of a DNS server used in the system.') hm2DnsClientServerDiagIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4))) if mibBuilder.loadTexts: hm2DnsClientServerDiagIndex.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerDiagIndex.setDescription('The unique index used for each server added in the DNS servers table.') hm2DnsClientServerDiagAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 4, 1, 2), InetAddressType()).setMaxAccess("readonly") if mibBuilder.loadTexts: hm2DnsClientServerDiagAddressType.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerDiagAddressType.setDescription('Address type for DNS server used. Currently, only ipv4 is supported.') hm2DnsClientServerDiagAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 4, 1, 3), InetAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: hm2DnsClientServerDiagAddress.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerDiagAddress.setDescription('The IP address of the DNS server used by the system. The entry can be configured by the provider, e.g. through DHCP client or PPPoE client.') hm2DnsClientGlobalGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 5)) hm2DnsClientDefaultDomainName = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 5, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readwrite") if mibBuilder.loadTexts: hm2DnsClientDefaultDomainName.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientDefaultDomainName.setDescription('The default domain name for unqualified hostnames.') hm2DnsClientRequestTimeout = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 5, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 3600)).clone(3)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hm2DnsClientRequestTimeout.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientRequestTimeout.setDescription('The timeout before retransmitting a request to the server. The timeout value is configured and displayed in seconds.') hm2DnsClientRequestRetransmits = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 5, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 100)).clone(2)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hm2DnsClientRequestRetransmits.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientRequestRetransmits.setDescription('The number of times the request is retransmitted. The request is retransmitted provided the maximum timeout value allows this many number of retransmits.') hm2DnsClientCacheAdminState = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 5, 4), HmEnabledStatus().clone('enable')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hm2DnsClientCacheAdminState.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientCacheAdminState.setDescription('Enables/Disables DNS client cache functionality of the device.') hm2DnsClientStaticHostConfigTable = MibTable((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6), ) if mibBuilder.loadTexts: hm2DnsClientStaticHostConfigTable.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientStaticHostConfigTable.setDescription('Static table of DNS hostname to IP address table') hm2DnsClientStaticHostConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1), ).setIndexNames((0, "HM2-DNS-MIB", "hm2DnsClientStaticIndex")) if mibBuilder.loadTexts: hm2DnsClientStaticHostConfigEntry.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientStaticHostConfigEntry.setDescription('An entry in the static DNS hostname IP address list. Rows may be created or deleted at any time by the DNS resolver and by SNMP SET requests.') hm2DnsClientStaticIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 64))) if mibBuilder.loadTexts: hm2DnsClientStaticIndex.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientStaticIndex.setDescription('The index of the entry.') hm2DnsClientStaticHostName = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readcreate") if mibBuilder.loadTexts: hm2DnsClientStaticHostName.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientStaticHostName.setDescription('The static hostname.') hm2DnsClientStaticHostAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1, 3), InetAddressType()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hm2DnsClientStaticHostAddressType.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientStaticHostAddressType.setDescription('Address type for static hosts used. Currently, only ipv4 is supported.') hm2DnsClientStaticHostIPAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1, 4), InetAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hm2DnsClientStaticHostIPAddress.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientStaticHostIPAddress.setDescription('The IP address of the static host.') hm2DnsClientStaticHostStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1, 5), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hm2DnsClientStaticHostStatus.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientStaticHostStatus.setDescription('Describes the status of a row in the table.') hm2DnsCachingServerGlobalGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 3, 1)) hm2DnsCachingServerAdminState = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 3, 1, 1), HmEnabledStatus().clone('enable')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hm2DnsCachingServerAdminState.setStatus('current') if mibBuilder.loadTexts: hm2DnsCachingServerAdminState.setDescription('Enables/Disables DNS caching server functionality of the device.') hm2DnsCacheAdminState = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 2, 1), HmEnabledStatus().clone('enable')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hm2DnsCacheAdminState.setStatus('deprecated') if mibBuilder.loadTexts: hm2DnsCacheAdminState.setDescription('Enables/Disables DNS cache functionality of the device. **NOTE: this object is deprecated and replaced by hm2DnsClientCacheAdminState/hm2DnsCachingServerAdminState**.') hm2DnsCacheFlushAction = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 2, 2), HmActionValue().clone('noop')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hm2DnsCacheFlushAction.setStatus('deprecated') if mibBuilder.loadTexts: hm2DnsCacheFlushAction.setDescription('Setting this value to action will flush the DNS cache. After flushing the cache, it will be set to noop automatically. **NOTE: this object is deprecated and replaced by hm2DevMgmtActionFlushDnsClientCache/hm2DevMgmtActionFlushDnsCachingServerCache**.') hm2DnsCHHostNameAlreadyExistsSESError = ObjectIdentity((1, 3, 6, 1, 4, 1, 248, 11, 90, 3, 1)) if mibBuilder.loadTexts: hm2DnsCHHostNameAlreadyExistsSESError.setStatus('current') if mibBuilder.loadTexts: hm2DnsCHHostNameAlreadyExistsSESError.setDescription('The host name entered exists and is associated with an IP. The change attempt was canceled.') hm2DnsCHBadIpNotAcceptedSESError = ObjectIdentity((1, 3, 6, 1, 4, 1, 248, 11, 90, 3, 2)) if mibBuilder.loadTexts: hm2DnsCHBadIpNotAcceptedSESError.setStatus('current') if mibBuilder.loadTexts: hm2DnsCHBadIpNotAcceptedSESError.setDescription('The Ip Adress entered is not a valid one for a host. The change attempt was canceled.') hm2DnsCHBadRowCannotBeActivatedSESError = ObjectIdentity((1, 3, 6, 1, 4, 1, 248, 11, 90, 3, 3)) if mibBuilder.loadTexts: hm2DnsCHBadRowCannotBeActivatedSESError.setStatus('current') if mibBuilder.loadTexts: hm2DnsCHBadRowCannotBeActivatedSESError.setDescription('The instance cannot be activated due to compliance issues. Please modify the entry and try again.') mibBuilder.exportSymbols("HM2-DNS-MIB", hm2DnsCachingServerGlobalGroup=hm2DnsCachingServerGlobalGroup, hm2DnsClientServerIndex=hm2DnsClientServerIndex, hm2DnsClientServerAddress=hm2DnsClientServerAddress, hm2DnsClientServerCfgTable=hm2DnsClientServerCfgTable, PYSNMP_MODULE_ID=hm2DnsMib, hm2DnsClientServerDiagAddress=hm2DnsClientServerDiagAddress, hm2DnsClientStaticHostConfigTable=hm2DnsClientStaticHostConfigTable, hm2DnsClientGlobalGroup=hm2DnsClientGlobalGroup, hm2DnsCacheGroup=hm2DnsCacheGroup, hm2DnsClientServerDiagEntry=hm2DnsClientServerDiagEntry, hm2DnsMibSNMPExtensionGroup=hm2DnsMibSNMPExtensionGroup, hm2DnsClientGroup=hm2DnsClientGroup, hm2DnsMibObjects=hm2DnsMibObjects, hm2DnsClientDefaultDomainName=hm2DnsClientDefaultDomainName, hm2DnsClientStaticHostStatus=hm2DnsClientStaticHostStatus, hm2DnsCacheAdminState=hm2DnsCacheAdminState, hm2DnsClientRequestTimeout=hm2DnsClientRequestTimeout, hm2DnsClientServerDiagAddressType=hm2DnsClientServerDiagAddressType, hm2DnsCachingServerGroup=hm2DnsCachingServerGroup, hm2DnsClientServerDiagTable=hm2DnsClientServerDiagTable, hm2DnsCHBadIpNotAcceptedSESError=hm2DnsCHBadIpNotAcceptedSESError, hm2DnsClientAdminState=hm2DnsClientAdminState, hm2DnsClientStaticHostName=hm2DnsClientStaticHostName, hm2DnsClientRequestRetransmits=hm2DnsClientRequestRetransmits, hm2DnsMibNotifications=hm2DnsMibNotifications, hm2DnsClientConfigSource=hm2DnsClientConfigSource, hm2DnsClientServerRowStatus=hm2DnsClientServerRowStatus, hm2DnsClientServerDiagIndex=hm2DnsClientServerDiagIndex, hm2DnsClientCacheAdminState=hm2DnsClientCacheAdminState, hm2DnsCHHostNameAlreadyExistsSESError=hm2DnsCHHostNameAlreadyExistsSESError, hm2DnsCacheFlushAction=hm2DnsCacheFlushAction, hm2DnsClientStaticIndex=hm2DnsClientStaticIndex, hm2DnsClientStaticHostAddressType=hm2DnsClientStaticHostAddressType, hm2DnsCachingServerAdminState=hm2DnsCachingServerAdminState, hm2DnsCHBadRowCannotBeActivatedSESError=hm2DnsCHBadRowCannotBeActivatedSESError, hm2DnsClientServerAddressType=hm2DnsClientServerAddressType, hm2DnsMib=hm2DnsMib, hm2DnsClientStaticHostIPAddress=hm2DnsClientStaticHostIPAddress, hm2DnsClientServerCfgEntry=hm2DnsClientServerCfgEntry, hm2DnsClientStaticHostConfigEntry=hm2DnsClientStaticHostConfigEntry)
class Params: def __init__(self): self.embed_size = 75 self.epochs = 2000 self.learning_rate = 0.01 self.top_k = 20 self.ent_top_k = [1, 5, 10, 50] self.lambda_3 = 0.7 self.generate_sim = 10 self.csls = 5 self.heuristic = True self.is_save = True self.mu1 = 1.0 self.mu2 = 1.0 self.nums_threads = 10 self.nums_threads_batch = 1 self.margin_rel = 0.5 self.margin_neg_triple = 1.2 self.margin_ent = 0.5 self.nums_neg = 10 self.nums_neg_neighbor = 10 self.epsilon = 0.95 self.batch_size = 10000 self.is_disc = True self.nn = 5 def print(self): print("Parameters used in this running are as follows:") items = sorted(self.__dict__.items(), key=lambda d: d[0]) for item in items: print("%s: %s" % item) print() P = Params() P.print() if __name__ == '__main__': print("w" + str(1))
""" with open("scrabble.txt", 'r') as f: count = 0 for line in f: if count > 5: break print(line) count += 1 """ #1: Compute scrabble tile score of given string input #2: Compute all "valid scrabble" words that you could make # with all char from an input string. Returns list of # valid words; if no words, returns empty list """ chars=input("input your characters in ALL CAPS: ") charsList=sorted(list(chars)) final=[] with open("scrabble.txt", 'r') as f: for line in f: line=line.strip() if sorted(list(line)) == charsList: final.append(line) print(final) """ #3: The game of ghost is played by taking turns with # a partner to add a letter to an increasingly long # word. The first person to make a valid scrabble word # of length 3 or more loses. Must continuously be valid word. #3a:Write a bot to play ghost against you. #This program is currently nonfunctional - something is not working in the block at line 48 #Will split into functions in free time but am hungry word="" with open("scrabble.txt", 'r') as g: flip = 1 while flip == 1: flip=0 char=input("input a character in ALL CAPS: ") word=word+char for line in g: temp="" line=line.strip() if line==word: print("you made the word "+line+", so you lost") break for charac in line: temp=temp+charac if temp==word: flip = 1 break print(word + " is no longer a valid word, so you lost")
class Solution: def longestPalindrome(self, s: str) -> int: m = {} for c in s: if c in m: m[c] += 1 else: m[c] = 1 ans = 0 longest_odd = 0 longest_char = None; for key in m: if m[key] % 2 == 1: if longest_odd < m[key]: longest_char = key else: ans += m[key] for key in m: if m[key] % 2 == 1: if key == longest_char: ans += m[key] else: ans += m[key] - 1 return ans
# https://www.hackerrank.com/challenges/icecream-parlor/problem t = int(input()) for _ in range(t): m = int(input()) n = int(input()) cost = list(map(int, input().split())) memo = {} for i, c in enumerate(cost): if (m - c) in memo: print('%s %s' % (memo[m - c], i + 1)) break memo[c] = i + 1
# Enum for allegiances ALLEGIANCE_MAP = { 0: "Shadow", 1: "Neutral", 2: "Hunter" } # Enum for card types CARD_COLOR_MAP = { 0: "White", 1: "Black", 2: "Green" } # Enum for text colors TEXT_COLORS = { 'server': 'rgb(200,200,200)', 'number': 'rgb(153,204,255)', 'White': 'rgb(255,255,255)', 'Black': 'rgb(75,75,75)', 'Green': 'rgb(143,194,0)', 'shadow': 'rgb(128,0,0)', 'neutral': 'rgb(255,255,153)', 'hunter': 'rgb(51,51,255)', 'Weird Woods': 'rgb(102,153,153)', 'Church': 'rgb(255,255,255)', 'Cemetery': 'rgb(75,75,75)', 'Erstwhile Altar': 'rgb(204,68,0)', 'Hermit\'s Cabin': 'rgb(143,194,0)', 'Underworld Gate': 'rgb(150,0,150)' } # Number of gameplay tests to run N_GAMEPLAY_TESTS = 250
#!/usr/bin/env python # -*- coding: utf-8 -*- """app: The package to hold shell CLI entry points. 1. cistat-cli added for demo. #. cache commands under progress. ..moduleauthor:: Max Wu < http: // maxwu.me > """
with open('binary_numbers.txt') as f: lines = f.readlines() length = len(lines) # Part One def most_common(strings): # Creates a list of amount of 1's at each index for all lines in the string. E.g. a = [1, 3, 2] will have 3 binary numbers with 1 at index 1. indices = [] bit_length = len(strings[0].strip()) for _ in range(bit_length): indices.append(0) for line in strings: line = line.strip() for index, char in enumerate(line): if char == "1": indices[index] += 1 return indices def binary_converter(list, list_length): output_str = "" for index in list: if index / list_length >= 0.5: output_str += "1" else: output_str += "0" return output_str # function to flip bits def flip_bits(binary_str): output_str = "" for char in binary_str: if char == "1": output_str += "0" else: output_str += "1" return output_str # function to convert binary to decimal def binary_to_decimal(binary_str): decimal = 0 for index, char in enumerate(binary_str): if char == "1": decimal += 2**(len(binary_str) - index - 1) return decimal gamma_binary = binary_converter(most_common(lines), length) epsilon_binary = flip_bits(binary_converter(most_common(lines), length)) gamma_decimal = binary_to_decimal(gamma_binary) epsilon_decimal = binary_to_decimal(epsilon_binary) print("Gamma binary: {} \nEpsilon binary: {}".format(gamma_binary, epsilon_binary)) print("Gamma decimal: {} \nEpsilon decimal: {}".format(gamma_decimal, epsilon_decimal)) print("Power consumption: {}".format(gamma_decimal * epsilon_decimal)) # Part Two def most_common_with_zeros(list, list_length): indices = [] for index in list: if index / list_length >= 0.5: indices.append(1) else: indices.append(0) return indices def least_common_with_zeros(list, list_length): indices = [] for index in list: if index / list_length <= 0.5: indices.append(1) else: indices.append(0) return indices def oxygen_generator_rating(most_common_list, list): line_length = len(list[0].strip()) trimmed = list for i in range(line_length): mc_index = most_common_at_index(trimmed, i) temp = trim_elements(mc_index, i, trimmed) trimmed = temp if len(trimmed) == 1: return trimmed[0] def co2_scrubber_rating(least_common_list, list): line_length = len(list[0].strip()) trimmed = list for i in range(line_length): lc_index = least_common_at_index(trimmed, i) temp = trim_elements(lc_index, i, trimmed) trimmed = temp if len(trimmed) == 1: return trimmed[0] def most_common_at_index(list, index_number): length = len(list) ind = 0 for element in list: if element[index_number] == "1": ind += 1 if ind / length >= 0.5: return 1 else: return 0 def least_common_at_index(list, index_number): length = len(list) ind = 0 for element in list: if element[index_number] == "1": ind += 1 if ind / length < 0.5: return 1 else: return 0 def trim_elements(binary_number, index, list): return_list = [] for element in list: if int(element[index]) == binary_number: return_list.append(element) return return_list def magic_binary(binary_str): # How did i never know about this? Turns binary to decimal return int(binary_str, 2) def flip_list(list): output_list = [] for item in list: if item == 1: output_list.append(0) else: output_list.append(1) return output_list mci = most_common_with_zeros(most_common(lines), length) ogr = oxygen_generator_rating(mci, lines) dec_ogr = magic_binary(ogr) lci = least_common_with_zeros(most_common(lines), length) # lci = flip_list(mci) cosr = co2_scrubber_rating(lci, lines) dec_cosr = magic_binary(cosr) print("Most common: {}".format(most_common(lines))) print("Most common with zeros: {}".format(mci)) print("Least common with zeros: {}".format(lci)) print("Oxygen Generator Rating: | binary: {} | decimal: {}".format(ogr, dec_ogr)) print("CO2 Scrubber Rate: | binary {} | decimal: {}".format(cosr, dec_cosr)) print("Life Support Rating: {}.".format(dec_ogr * dec_cosr)) #print(oxygen_generator_rating(most_common_with_zeros(lines), lines))
""" Sensor of Library to measure the 5g signal How to import: from Sensors.{sensor_package}.lib import device How to use: with device() as sensor: print(sensor.read_power()) """
class DarkKeeperError(Exception): pass class DarkKeeperCacheError(DarkKeeperError): pass class DarkKeeperCacheReadError(DarkKeeperCacheError): pass class DarkKeeperCacheWriteError(DarkKeeperCacheError): pass class DarkKeeperParseError(DarkKeeperError): pass class DarkKeeperParseContentError(DarkKeeperParseError): pass class DarkKeeperRequestError(DarkKeeperError): pass class DarkKeeperRequestResponseError(DarkKeeperRequestError): pass class DarkKeeperMongoError(DarkKeeperError): pass class DarkKeeperParseUriMongoError(DarkKeeperMongoError): pass
""" Program: bouncy.py Project 4.8 This program calculates the total distance a ball travels as it bounces given: 1. the initial height of the ball 2. its bounciness index 3. the number of times the ball is allowed to continue bouncing """ height = float(input("Enter the height from which the ball is dropped: ")) bounciness = float(input("Enter the bounciness index of the ball: ")) distance = 0 bounces = int(input("Enter the number of times the ball is allowed to continue bouncing: ")) for eachPass in range(bounces): distance += height height *= bounciness distance += height print('\nTotal distance traveled is:', distance, 'units.')
def initialize(n): for key in ['queen','row','col','rwtose','swtose']: board[key]={} for i in range(n): board['queen'][i]=-1 board['row'][i]=0 board['col'][i]=0 for i in range(-(n-1),n): board['rwtose'][i]=0 for i in range(2*n-1): board['swtose'][i]=0 def free(i,j): return( board['row'][i]==0 and board['col'][j]==0 and board['rwtose'][j-i]==0 and board['swtose'][j+i]==0 ) def addqueen(i,j): board['queen'][i]=j board['row'][i]=1 board['col'][j]=1 board['rwtose'][j-i]=1 board['swtose'][j+i]=1 def undoqueen(i,j): board['queen'][i]=-1 board['row'][i]=0 board['col'][j]=0 board['rwtose'][j-i]=0 board['swtose'][j+i]=0 def printboard(): for row in sorted(board['queen'].keys()): print((row,board['queen'][row]),end=" ") print(" ") def placequeen(i): n=len(board['queen'].keys()) for j in range(n): if free(i,j): addqueen(i,j) if i==n-1: printboard()#remove for single solution # return(True) else: extendsoln=placequeen(i+1) # if(extendsoln): # return True # else: undoqueen(i,j) # else: # return(False) board={} n=int(input("How many queen?")) initialize(n) placequeen(0) # if placequeen(0): # printboard()
class PackageManager: """ An object that contains the name used by dotstar and the true name of the PM (the one used by the OS, that dotstar calls when installing). dotstar don't uses the same name as the OS because snap has two mods of installation (sandbox and classic) so we have to differentiate them. Contains too the command shape, a string with a %s placeholder """ def __init__( self, dotstar_name: str, system_name: str, command_shape: str, multiple_apps_query_support: bool ) -> None: """ :param dotstar_name: the name of the PM that dotstar uses :param system_name: the name of the PM that the OS uses :param command_shape: the shape of the command. Must have a %s placeholder :param multiple_apps_query_support: if the PM supports query with multiple names (like "pacman -Sy atom gedit") """ self.dotstar_name = dotstar_name self.system_name = system_name self.command_shape = command_shape self.multiple_apps_query_support = multiple_apps_query_support
def raizI(x,b): if b** 2>x: return b-1 return raizI (x,b+1) raizI(11,5)
lambda x: xx def write2(): pass def write(*args, **kw): raise NotImplementedError async def foo(one, *args, **kw): """ Args: args: Test """ data = yield from read_data(db)
class Solution: def numberOfSteps (self, num: int) -> int: count = 0 while num!=0: print(num,count) if num==1: count+=1 return count if num%2==0: count+=1 else: count+=2 num = num>>1
class ErrorSeverity(object): FATAL = 'fatal' ERROR = 'error' WARNING = 'warning' ALLOWED_VALUES = (FATAL, ERROR, WARNING) @classmethod def validate(cls, value): return value in cls.ALLOWED_VALUES
#!/usr/bin/env python3 def write_csv(filename, content): with open(filename, 'w') as csvfile: for line in content: for i, item in enumerate(line): csvfile.write(str(item)) if i != len(line) - 1: csvfile.write(',') csvfile.write('\n') def read_csv(filename): with open(filename, 'r') as content: return [[v for v in line.replace('\n', '').split(',')] for line in content]
def inverte_lista(lista): a = list(lista) #Nunca esquecer do list() para NÃO alterar a lista original for i in list(range(0, int(len(a)/2))): a[i], a[len(a)-i-1] = a[len(a)-i-1], a[i] return a lista1 = [1, 2, True, 3, "opa", 4, 5] lista2 = ["um", "dois", "três", "quatro"] lista3 = "Victor" print("{} invertido fica {}" .format(lista1, inverte_lista(lista1))) print("{} invertido fica {}" .format(lista2, inverte_lista(lista2))) print("{} invertido fica {}" .format(lista3, inverte_lista(lista3)))
'''Change the database in this file Change the database in this script locally Careful here '''
class LevelUpCooldownError(Exception): pass class MaxLevelError(Exception): pass
# -*- coding: utf-8 -*- # @Time : 2021/4/23 下午8:00 """ 根据数据集构建word和index之间的映射关系 """ class Language: def __init__(self, name): """ word与index之间形成映射 Args: name (str): 语种 eg.'eng'(英文) or 'fra'(法语) """ super(Language, self).__init__() self.name = name self.word2index = {} # [单词-索引]映射字典 self.word_count = {} # [单词-数量]字典 self.index2word = {0: 'SOS', 1: 'EOS'} # [索引-单词]映射字典 self.n_words = 2 # include 'SOS' and 'EOS' # 单词数量 def add_sentence(self, sentence): for word in sentence.split(): # 句子中的单词默认以空格隔开 self.add_word(word) def add_word(self, word): if word not in self.word2index: self.word2index[word] = self.n_words self.word_count[word] = 1 self.index2word[self.n_words] = word self.n_words += 1 else: self.word_count[word] += 1 class Word2Indexs: def __init__(self, data_path): """ 根据数据集all构建word到index的映射关系 Args: data_path: 数据集(训练集+验证集) """ super(Word2Indexs, self).__init__() self.dataset_lines = open(data_path, encoding='utf-8').read().strip().split('\n') self.pairs = [[s for s in l.split('\t')] for l in self.dataset_lines] self.input_lang, self.output_lang = Language('fra'), Language('eng') # 输入法语,输出英文 for pair in self.pairs: self.input_lang.add_sentence(pair[0]) self.output_lang.add_sentence(pair[1]) print('word2index init:', self.input_lang.name, self.input_lang.n_words, ',', self.output_lang.name, self.output_lang.n_words) if __name__ == '__main__': word2index = Word2Indexs(data_path='../data/fra-eng-all.txt') print()
# # Copyright 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # RESULT_OK = 0 RESULT_ERROR = 1 PLUGIN_ERRORS = "plugin_errors" ERRORS = "errors" class Result(object): def __init__(self): self._result = {} self._result["result_code"] = RESULT_OK # no error so far.. self._result["result"] = [] def add(self, obj_list): self._result["result"].extend(obj_list) def pluginError(self, pluginName, errorMsg): self._result["result_code"] = RESULT_ERROR pluginErrors = self._result.get(PLUGIN_ERRORS, {}) # get the list of error messages for plugin or a new list # if it's the first error pluginErrorMessages = pluginErrors.get(pluginName, []) pluginErrorMessages.append(errorMsg) # put the plugin error list to the error dict # we could do that only for the first time, # but this way we can save one 'if key in dict' pluginErrors[pluginName] = pluginErrorMessages self._result[PLUGIN_ERRORS] = pluginErrors def error(self, errorMsg): self._result["result_code"] = RESULT_ERROR errors = self._result.get(ERRORS, []) errors.append(errorMsg) self._result[ERRORS] = errors def to_dict(self): return self._result class FilterResult(Result): def __init__(self): super(FilterResult, self).__init__() class WeightResult(Result): def __init__(self): super(WeightResult, self).__init__()
mys1 = {1,2,3,4} mys2 = {3,4,5,6} mys1.difference_update(mys2) print(mys1) # DU1 mys3 = {'a','b','c','d'} mys4 = {'d','w','f','g'} mys5 = {'v','w','x','z'} mys3.difference_update(mys4) print(mys3) # DU2 mys4.difference_update(mys5) print(mys4) # DU3
NUMERICAL_TYPE = "num" NUMERICAL_PREFIX = "n_" CATEGORY_TYPE = "cat" CATEGORY_PREFIX = "c_" TIME_TYPE = "time" TIME_PREFIX = "t_" MULTI_CAT_TYPE = "multi-cat" MULTI_CAT_PREFIX = "m_" MULTI_CAT_DELIMITER = "," MAIN_TABLE_NAME = "main" MAIN_TABLE_TEST_NAME = "main_test" TABLE_PREFIX = "table_" LABEL = "label" HASH_MAX = 200 AGG_FEAT_MAX = 4 RANDOM_SEED = 2019 N_RANDOM_COL = 7 SAMPLE_SIZE = 100000 HYPEROPT_TEST_SIZE = 0.5 BEST_ITER_THRESHOLD = 100 IMBALANCE_RATE = 0.001 MEMORY_LIMIT = 10000 # 10GB N_EST = 500 N_STOP = 10 KFOLD = 5
# Operations allowed : Insertion, Addition, Deletion def func(str1, str2, m, n): dp = [[0 for x in range(n+1)] for x in range(m+1)] for i in range(m+1): for j in range(n+1): if i == 0: dp[i][j] = j elif j == 0: dp[i][j] = i elif str1[i-1] == str2[j-1]: dp[i][j] = dp[i-1][j-1] else: dp[i][j] = 1 + min(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]) return dp[m][n] if __name__ == '__main__': str1 = "hacktoberfest" str2 = "hackerearth" print(func(str1, str2, len(str1), len(str2)))
# Tai Sakuma <[email protected]> ##__________________________________________________________________|| def create_file_start_length_list(file_nevents_list, max_events_per_run = -1, max_events_total = -1, max_files_per_run = 1): file_nevents_list = _apply_max_events_total(file_nevents_list, max_events_total) return _file_start_length_list(file_nevents_list, max_events_per_run, max_files_per_run) ##__________________________________________________________________|| def _apply_max_events_total(file_nevents_list, max_events_total = -1): if max_events_total < 0: return file_nevents_list ret = [ ] for file, nevents in file_nevents_list: if max_events_total == 0: break nevents = min(max_events_total, nevents) ret.append((file, nevents)) max_events_total -= nevents return ret ##__________________________________________________________________|| def _file_start_length_list(file_nevents_list, max_events_per_run, max_files_per_run): if not file_nevents_list: return [ ] total_nevents = sum([n for f, n, in file_nevents_list]) if total_nevents == 0: return [ ] if max_files_per_run == 0: return [ ] if max_events_per_run == 0: return [ ] if max_events_per_run < 0: max_events_per_run = total_nevents total_nfiles = len(set([f for f, n, in file_nevents_list])) if max_files_per_run < 0: max_files_per_run = total_nfiles files = [ ] nevents = [ ] start = [ ] length = [ ] i = 0 for file_, nev in file_nevents_list: if nev == 0: continue if i == len(files): # create a new run files.append([ ]) nevents.append(0) start.append(0) length.append(0) files[i].append(file_) nevents[i] += nev if max_events_per_run >= nevents[i]: length[i] = nevents[i] else: dlength = max_events_per_run - length[i] length[i] = max_events_per_run i += 1 files.append([file_]) nevents.append(nevents[i-1] - length[i-1]) start.append(dlength) while max_events_per_run < nevents[i]: length.append(max_events_per_run) i += 1 files.append([file_]) nevents.append(nevents[i-1] - length[i-1]) start.append(start[i-1] + length[i-1]) length.append(nevents[i]) if max_events_per_run == nevents[i]: i += 1 # to next run continue if max_files_per_run == len(files[i]): i += 1 # to next run # print files, nevents, start, length ret = list(zip(files, start, length)) return ret ##__________________________________________________________________|| def _start_length_pairs_for_split_lists(ntotal, max_per_list): # e.g., ntotal = 35, max_per_list = 10 if max_per_list < 0: return [(0, ntotal)] nlists = ntotal//max_per_list # https://stackoverflow.com/questions/1282945/python-integer-division-yields-float # nlists = 3 ret = [(i*max_per_list, max_per_list) for i in range(nlists)] # e.g., [(0, 10), (10, 10), (20, 10)] remainder = ntotal % max_per_list # e.g., 5 if remainder > 0: last = (nlists*max_per_list, remainder) # e.g, (30, 5) ret.append(last) # e.g., [(0, 10), (10, 10), (20, 10), (30, 5)] return ret ##__________________________________________________________________|| def _minimum_positive_value(vals): # returns -1 if all negative or empty vals = [v for v in vals if v >= 0] if not vals: return -1 return min(vals) ##__________________________________________________________________||
class DBModel: """Параметры для настройки подключения к БД""" def __init__(self, db_server, db_user, db_pass, db_schema, db_port): self.db_server = db_server self.db_user = db_user self.db_pass = db_pass self.db_schema = db_schema self.db_port = db_port
def metade(p=0, show=False): resp = p / 2 if show == True: return moeda(resp) else: return resp def dobro(p=0, show=False): resp = p * 2 if show == True: return moeda(resp) else: return resp def aumentar(p=0 , desc_mais=0, show=False): resp = p + (p * desc_mais / 100) if show == True: return moeda(resp) else: return resp def diminuir (p=0, desc_menos=0, show=False): resp = p - (p * desc_menos / 100) if show == True: return moeda(resp) else: return resp def moeda(p=0, moeda='R$'): return f'{moeda}{p:.2f}'.replace('.',',') def resumo(p=0, desc_mais=0, desc_menos=0): print('*' * 30) print('{:^30}'.format('RESUMO DO VALOR')) print('*' * 30) print(f'dobro do preco: \t{moeda(p)}') print(f'metade do preço: \t{metade(p, True)}') print(f'O dobro do preço: \t{dobro(p, True)}') print(f'Aumentando {desc_mais}%: \t{aumentar(p, desc_mais, True)}') print(f'Reduzindo {desc_menos}%: \t{diminuir(p, desc_menos, True)}') print('*' * 30)
def buildFireTraps(start, end, step, x, y): for i in range(start, end+1, step): if x: hero.buildXY("fire-trap", x, i) else: hero.buildXY("fire-trap", i, y) buildFireTraps(40, 112, 24, False, 114) buildFireTraps(110, 38, -18, 140, False) buildFireTraps(132, 32, -20, False, 22) buildFireTraps(28, 108, 16, 20, False) hero.moveXY(40, 94)
"""exercism protein translation module.""" def proteins(strand): """ Translate RNA sequences into proteins. :param strand string - The RNA to translate. :return list - The protein the RNA translated into. """ # Some unit tests seem to be funky because of the order ... # proteins = set() proteins = [] stop_codons = ["UAA", "UAG", "UGA"] protein_map = { "AUG": "Methionine", "UUU": "Phenylalanine", "UUC": "Phenylalanine", "UUA": "Leucine", "UUG": "Leucine", "UCU": "Serine", "UCC": "Serine", "UCA": "Serine", "UCG": "Serine", "UAU": "Tyrosine", "UAC": "Tyrosine", "UGU": "Cysteine", "UGC": "Cysteine", "UGG": "Tryptophan" } for index in range(0, len(strand), 3): codon = strand[index:index + 3] if codon in stop_codons: break # proteins.add(protein_map.get(codon)) protein = protein_map.get(codon) if proteins.count(protein) == 0: proteins.append(protein) # proteins = list(proteins) # proteins.sort() return proteins
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: [email protected] Version: 0.0.1 Created Time: 2016-01-10 Last_modify: 2016-01-10 ****************************************** ''' ''' Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases. Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front. Requirements for atoi: The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned. ''' class Solution(object): def myAtoi(self, str): """ :type str: str :rtype: int """ mini, maxi = ord('0'), ord('9') outi = 0 s = 1 start = 0 for i in range(len(str)): if i == start: if str[i] == ' ': start += 1 continue if str[i] == '+': continue if str[i] == '-': s = -1 continue num = ord(str[i]) if num >= mini and num <= maxi: num = num - mini outi = outi * 10 + num else: break if outi >= 2 ** 31: if s == 1: outi = 2 ** 31 - 1 else: outi = 2 ** 31 return s * outi
# TLV format: # TAG | LENGTH | VALUE # Header contains nested TLV triplets TRACE_TAG_HEADER = 1 TRACE_TAG_EVENTS = 2 TRACE_TAG_FILES = 3 TRACE_TAG_METADATA = 4 HEADER_TAG_VERSION = 1 HEADER_TAG_FILES = 2 HEADER_TAG_METADATA = 3
""" capo_optimizer library, allows quick determination of optimal guitar capo positioning. """ version = (0, 0, 1) __version__ = '.'.join(map(str, version))
menu = """ What would your weight would be in other celestian bodies Choose a celestial body 1-Sun 2-Mercury 3-Venus 4-Mars 5-Jupiter 6-Saturn 7-Uranus 8-Neptune 9-The Moon 10- Ganymede """ option = int(input(menu)) class celestial_body: def gravity_calculation(name,acceleration): mass = float(input("What is your mass?")) weigth = mass * acceleration print("Your weight on", celestial_body, "would be", weigth) if option == 1: sun = celestial_body sun.gravity_calculation("The Sun",274) elif option == 2: mercury = celestial_body mercury.gravity_calculation("Mercury",3.7) elif option == 3: venus = celestial_body venus.gravity_calculation("Venus",8.87) elif option == 4: mars = celestial_body mars.gravity_calculation("Mars",3.72) elif option == 5: jupiter = celestial_body jupiter.gravity_calculation("Jupiter",24.79) elif option == 6: saturn = celestial_body saturn.gravity_calculation("Saturn",10.44) elif option == 7: uranus = celestial_body uranus.gravity_calculation("Uranus",8.87) elif option == 8: neptune = celestial_body neptune.gravity_calculation("Neptune",11.15) elif option == 9: moon = celestial_body moon.gravity_calculation("The moon",1.62) elif option == 10: ganymede = celestial_body ganymede.gravity_calculation("Ganymede",1.42) else: print("That is not an option")
''' Classes to work with WebSphere Application Servers Author: Christoph Stoettner Mail: [email protected] Documentation: http://scripting101.stoeps.de Version: 5.0.1 Date: 09/19/2015 License: Apache 2.0 ''' class WasServers: def __init__(self): # Get a list of all servers in WAS cell (dmgr, nodeagents, AppServer, # webserver) self.AllServers = self.getAllServers() self.WebServers = self.getWebServers() self.AppServers = self.getAllServersWithoutWeb() # self.serverNum, self.jvm, self.cell, self.node, self.serverName = self.getAttrServers() self.serverNum, self.jvm, self.cell, self.node, self.serverName = self.getAttrServers() def getAllServers(self): # get a list of all servers self.servers = AdminTask.listServers().splitlines() return self.servers def getAppServers(self): # get a list of all application servers # includes webserver, but no dmgr and nodeagents self.servers = AdminTask.listServers( '[-serverType APPLICATION_SERVER]').splitlines() return self.servers def getWebServers(self): # get a list of all webservers self.webservers = AdminTask.listServers( '[-serverType WEB_SERVER]').splitlines() return self.webservers def getAllServersWithoutWeb(self): # inclusive dmgr and nodeagents self.AppServers = self.AllServers for webserver in self.WebServers: self.AppServers.remove(webserver) return self.AppServers def getAttrServers(self): # get jvm, node, cell from single application server srvNum = 0 jvm = [] cell = [] node = [] servername = [] for server in self.AppServers: srvNum += 1 javavm = AdminConfig.list('JavaVirtualMachine', server) jvm.append(javavm) srv = server.split('/') cell.append(srv[1]) node.append(srv[3]) servername.append(srv[5].split('|')[0]) self.jvm = jvm cell = cell node = node servername = servername # return ( serverNum, jvm, cell, node, serverName ) return (srvNum, self.jvm, cell, node, servername)
class Solution: def findReplaceString(self, S: str, indexes: List[int], sources: List[str], targets: List[str]) -> str: ans = [""] * len(S) for i in range(len(S)): ans[i] = S[i] for i in range(len(indexes)): start = indexes[i] src = sources[i] change = 1 for j in range(len(src)): if S[start + j] != src[j]: change = 0 break if change == 0: continue ans[start] = targets[i] for j in range(1,len(src)): ans[start + j] = "" return "".join(ans)
############################################################################### # Singlecell plot arrays # ############################################################################### tag = "singlecell"
class PipelineNotDeployed(Exception): def __init__(self, pipeline_id=None, message="Pipeline not deployed") -> None: self.pipeline_id = pipeline_id self.message = message super().__init__(self.message) def __str__(self): return f"{self.pipeline_id} -> {self.message}"
class TGConfigError(Exception):pass def coerce_config(configuration, prefix, converters): """Convert configuration values to expected types.""" options = dict((key[len(prefix):], configuration[key]) for key in configuration if key.startswith(prefix)) for option, converter in converters.items(): if option in options: options[option] = converter(options[option]) return options
class Solution: def search(self, nums, target): if not nums: return -1 x, y = 0, len(nums) - 1 while x <= y: m = x + (y - x) // 2 if nums[m] > nums[0]: x = m + 1 elif nums[m] < nums[0]: y = m else: x = y if nums[x] > nums[y] else y + 1 break print(x, y) if target > nums[0]: lo, hi = 0, x - 1 elif target < nums[0]: lo, hi = x, len(nums) - 1 else: return 0 print(lo, hi) while lo <= hi: m = lo + (hi - lo) // 2 if nums[m] == target: return m elif nums[m] > target: hi = m - 1 else: lo = m + 1 return -1 if __name__ == '__main__': ret1 = Solution().search(nums=[4, 5, 6, 7, 0, 1, 2], target=2) ret2 = Solution().search(nums=[1], target=1) ret3 = Solution().search(nums=[1, 3], target=1) ret4 = Solution().search(nums=[1, 3], target=3) ret5 = Solution().search(nums=[3, 1], target=1) print(ret1, ret2, ret3, ret4, ret5) ret = Solution().search(nums=[1, 3, 5], target=5) print(ret)
class Chapter: id: float title: str text: str
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getKthFromEnd(self, head: ListNode, k: int) -> ListNode: p1 = head for _ in range(k): if p1: p1 = p1.next else: return None p2 = head while p1: p1 = p1.next p2 = p2.next return p2