content
stringlengths
7
1.05M
""" Test init module ================================== Author: Casokaks (https://github.com/Casokaks/) Created on: Aug 15th 2021 """
""" 1065. Index Pairs of a String Easy Given a text string and words (a list of strings), return all index pairs [i, j] so that the substring text[i]...text[j] is in the list of words. Example 1: Input: text = "thestoryofleetcodeandme", words = ["story","fleet","leetcode"] Output: [[3,7],[9,13],[10,17]] Example 2: Input: text = "ababa", words = ["aba","ab"] Output: [[0,1],[0,2],[2,3],[2,4]] Explanation: Notice that matches can overlap, see "aba" is found in [0,2] and [2,4]. Note: All strings contains only lowercase English letters. It's guaranteed that all strings in words are different. 1 <= text.length <= 100 1 <= words.length <= 20 1 <= words[i].length <= 50 Return the pairs [i,j] in sorted order (i.e. sort them by their first coordinate in case of ties sort them by their second coordinate). """ class Solution: def indexPairs(self, text: str, words: List[str]) -> List[List[int]]: res = [] for word in words: if word in text: a = word[0] for i in range(len(text)): new = '' if a == text[i]: new = text[int(i):int(i+len(word))] if new == word: res.append([i,i+len(word)-1]) return sorted(res)
class Point: def __init__(self, x, y): self.x = x self.y = y self.dist = math.sqrt(x ** 2 + y ** 2) class Solution: """ Quick Select algo: Time best -> O(N) Time worst -> O(N^2) """ def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: distances = [Point(x, y) for x, y in points] distances = self.quick_select(distances, k) return [[distance.x, distance.y] for distance in distances] def quick_select(self, points, k): if not points: return [] pivot_dist = random.choice(points) smaller = [point for point in points if point.dist <= pivot_dist.dist] bigger = [point for point in points if point.dist > pivot_dist.dist] M, N = len(smaller), len(bigger) if k == M: return smaller if k > M: return smaller + self.quick_select(bigger, k - M) return self.quick_select(smaller, k)
def is_odd(n): return n % 2 == 1 def not_empty(s): return s and s.strip() a = list(filter(is_odd, [1, 2, 4, 5, 6, 7, 8])) a = list(filter(lambda n : n % 2 == 1, [1, 2, 4, 5, 6, 7, 8, 9])) b = list(filter(not_empty, ['A', '' , 'B', None, 'C', ' '])) # filter 函数返回的是一个Iterator, 也就是一个惰性序列 print(a, b) def _odd_iter(): n = 1 while True: n = n + 2 yield n def _not_divisible(n): return lambda x: x % n > 0 def primes(): yield 2 it = _odd_iter() while True: n = next(it) yield n it = filter(_not_divisible(n), it) # 先过滤掉能整除3的数,从这个基础上过滤掉能整除5的数...... # 这里it = filter((...)(_not_disivible(n-2), fileter(_notdivisble(n-1), filter(_not_divisible(n), it)))) # 也就是说过滤了能整除除以[3, 5, 7, 11...](当前要求的质数之前的质数)的数 for n in primes(): if n < 30: print(n) else: break func = _not_divisible(9) # _not_divisible(9) 返回一个函数(x % 9 > 0) print(func(18)) # 18 % 9 == 0, return false f = lambda x: x * x print(f(19))
Candies = [int(x) for x in input("Enter the numbers with space: ").split()] extraCandies=int(input("Enter the number of extra candies: ")) Output=[ ] i=0 while(i<len(Candies)): if(Candies[i]+extraCandies>=max(Candies)): Output.append("True") else: Output.append("False") i+=1 print(Output)
class MotionSensor: """Get 9Dof data by using MotionSensor. See [MatrixMotionSensor](https://matrix-robotics.github.io/MatrixMotionSensor/) for more details. Parameters ---------- i2c_port : int i2c_port is corresponding with I2C1, I2C2 ... sockets on board. _dev : class MatrixControl.Device class """ def __init__(self, _dev, i2c_port): self.i2c_port = i2c_port self._dev = _dev def _complement(self, _buff): if len(str(_buff)) > 1: if _buff > 32767: _buff -= 65536 return _buff def getAccel(self, axis): """Get Accel Data. (unit: mm/s^2) Parameters ---------- axis : str options are "X", "Y" or "Z" """ _buff = "I2C{}_GETACCEL_{}".format(self.i2c_port, axis.upper()) self._dev._sendbuff(self._dev.protocol[_buff]) self._dev._readbuff() return self._complement(self._dev._rxbuff) def getGyro(self, axis): """Get Gyro Data. (unit: degree per second) Parameters ---------- axis : str options are "X", "Y" or "Z" """ _buff = "I2C{}_GETGYRO_{}".format(self.i2c_port, axis.upper()) self._dev._sendbuff(self._dev.protocol[_buff]) self._dev._readbuff() return self._complement(self._dev._rxbuff) def getRoll(self): _buff = "I2C{}_GETROLL".format(self.i2c_port) self._dev._sendbuff(self._dev.protocol[_buff]) self._dev._readbuff() return self._complement(self._dev._rxbuff) def getYaw(self): _buff = "I2C{}_GETYAW".format(self.i2c_port) self._dev._sendbuff(self._dev.protocol[_buff]) self._dev._readbuff() return self._complement(self._dev._rxbuff) def getPitch(self): _buff = "I2C{}_GETPITCH".format(self.i2c_port) self._dev._sendbuff(self._dev.protocol[_buff]) self._dev._readbuff() return self._complement(self._dev._rxbuff)
def separador(): print("-="*30) """ Considerando duas listas de inteiros ou floats (lista A e lista B) Some os valores nas listas retornando uma nova lista com os valores somados: Se uma lista for maior que a outra, a soma só vai considerar o tamanho da menor. Exemplo: lista_a = [1, 2, 3, 4, 5, 6, 7] lista_b = [1, 2, 3, 4]""" separador() #Minha solução (mais pythonica) lista_a = [1,2,3,4,5,6,7] lista_b = [1,2,3,4] temp = zip(lista_a,lista_b) for v in temp: print(sum(v)) separador() # Maneira mais lógica, comum a todas as linguagens lista_soma = [] lista_a = [1,2,3,4,5,6,7] lista_b = [1,2,3,4] for i in range(len(lista_b)): lista_soma.append(lista_a[i] + lista_b[i]) print(lista_soma) separador() #Uma outra maneira mais lógica, assim assim utilizando o enumerate, que está presente apenas no Python lista_soma = [] lista_a = [1,2,3,4,5,6,7] lista_b = [1,2,3,4] for i, _ in enumerate(lista_b): lista_soma.append(lista_a[i] + lista_b[i]) print(lista_soma) separador() #solucao do Luiz Otávio, julguei ser mais certa e correta, utilizando um modo ainda mais pythonico que o que eu desenvovi. lista_a = [1,2,3,4,5,6,7] lista_b = [1,2,3,4] lista_soma = [x + y for x,y in (zip(lista_a, lista_b))] print(lista_soma)
class MicromagneticModell: def __init__(self, name, Ms, calc): self.name = name self.Ms = Ms self.field = None self.calc = calc def __str__(self): return "AbstractMicromagneticModell(name={})".format(self.name) def relax(self): self.calc.relax(self) def set_H(self, field): print("AbstractMicromagneticModell: setting field = {}") self.field = field def hysteresis(self, fieldlist): print("AbstractMicromagneticModell: starting hysteresis") for field in fieldlist: self.set_H(field) self.relax() class OOMMFC(): def __init__(self): pass def __str__(self): return "OOMMFC()" def relax(self, mm): print("Calling OOMMF to run relax() with H={}".format(mm.field)) #a = AbstractMicromagneticModell('simulation-name', 10) #print(a) #a.hysteresis([10, 20]) ocalc = OOMMFC() o = MicromagneticModell(name='test', Ms=42, calc=ocalc) print(o) o.relax() #f = FIDIMAGC(name='fidimag-simulation', Ms=8e6) #print(o) #f.relax() #o.relax() #o.hysteresis([10, 20, 30])
# eventually we will have a proper config ANONYMIZATION_THRESHOLD = 10 WAREHOUSE_URI = 'postgres://localhost' WAGE_RECORD_URI = 'postgres://localhost'
""" Дефинирайте фуннкция `is_even`, която приема число и върща `True` ако числото е четно и `False` в противен случай. >>> is_even(4) True >>> is_even(5) False """ def is_even(number): raise Exception('Not implemented')
""" Example module """ def java_maker(*args, **kwargs): """ Make you a java """ java_library(*args, **kwargs)
N = int(input().strip()) names = [] for _ in range(N): name,email = input().strip().split(' ') name,email = [str(name),str(email)] if email.endswith("@gmail.com"): names.append(name) names.sort() for n in names: print(n)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' def upper_print(f): def wrapper(*args, **kwargs): f(*[i.upper() if hasattr(i, 'upper') else i for i in args], **kwargs) return wrapper if __name__ == '__main__': text = 'hello world!' print(text) # hello world! old_print = print print = upper_print(print) print(text) # HELLO WORLD! print = old_print print(text) # hello world!
if __name__ == '__main__': # Check correct price prediction price_input_path = 'tests/data/Price_Simple.csv' price_input = open(price_input_path, 'r').read().splitlines()[0].split(';') price_prediction = open('price_prediction.csv', 'r').read().splitlines()[0].split(';') assert price_input == price_prediction[:3] ground_truth = 1309 assert int(price_prediction[-1]) - ground_truth <= 15, "Prediction deviation > 15 deci-cents" # Check correct route prediction route_input_path = 'tests/data/Route_Bertha_Simple.csv' route_input = open(route_input_path, 'r').read().splitlines()[1].split(';') _, gas_station_id = route_input route_prediction = open('route_prediction.csv', 'r').read().splitlines()[0].split(';') gas_station_id2, price, liters = route_prediction assert gas_station_id == gas_station_id2 assert liters == '0' ground_truth = 1469 assert int(price) - ground_truth <= 15, "Prediction deviation > 15 deci-cents"
print('===== DESAFIO 041 =====') nascimento = int(input('Digite o ano q vc nasceu: ')) idade = 2021 - nascimento print(f'vc tem {idade} anos') if idade <= 9: print('vc é um nadador mirim') elif idade > 9 and idade <= 14: print('vc é um nadador infantil') elif idade > 14 and idade <= 19: print('vc é um nadador junior') elif idade > 19 and idade <= 20: print('vc é um nadador senior') elif idade > 20: print('vc é um nadador master')
#coding: utf-8 #date: 2018/7/30 19:07 #author: zhou_le # 求1000以下3和5的倍数之和 print(sum([i for i in range(1000) if i % 3 == 0 or i % 5 == 0]))
rows = [] try: while True: rows.append(int(input())) except EOFError: pass rows.sort() goal = 2020 l = 0 r = len(rows) - 1 while rows[l] + rows[r] != goal and l < r: if rows[l] + rows[r] < goal: l += 1 else: r -= 1 if rows[l] + rows[r] == goal: print(rows[l] * rows[r]) else: print('FAIL')
def mostrar(n='', g=''): if n == '': n = '<desconhecido>' if not g.isnumeric(): g = 0 return f'O jogador {n} fez {g} gol(s) no campeonato' # Main nome = input('Nome do Jogador: ').title() gols = input('Número de Gols: ') print(mostrar(nome, gols))
class Telecom: def __init__(self, contact_db_id, system, value, use, rank, period): self.contact_db_id = contact_db_id self.system = system self.value = value self.use = use self.rank = rank self.period = period def get_contact_db_id(self): return self.contact_db_id def get_system(self): return self.system def get_value(self): return self.value def get_use(self): return self.use def get_rank(self): return self.rank def get_period(self): return self.period
# kasutaja sisestab 3 numbrit number1 = int(input("Sisesta esimene arv: ")) number2 = int(input("Sisesta teine arv: ")) number3 = int(input("Sisesta kolmas arv: ")) # funktsioon, mis tagastab kolmes sisestatud arvust suurima def largest(number1, number2, number3): biggest = 0 if number1 > biggest: biggest = number1 if number2 > number1: biggest = number2 if number3 > number2 and number3 > number1: biggest = number3 return biggest print(largest(number1, number2, number3))
#Tuplas numeros = [1,2,4,5,6,7,8,9] #lista usuario = {'Nome':'Mateus' , 'senha':123456789 } #dicionario pessoa = ('Mateus' , 'Alves' , 16 , 14 , 90) #tupla print(numeros) print(usuario) print(pessoa) numeros[1] = 8 usuario['senha'] = 4545343
def lin(): print('-' * 35) # Principal program lin() print(' IAN STIGLIANO SILVA ') lin() lin() print(' CURSO EM VÍDEO ') lin() lin() print(' GUSTAVO GUANABARA ') lin()
# @Title: 重排链表 (Reorder List) # @Author: 18015528893 # @Date: 2021-02-12 16:05:36 # @Runtime: 100 ms # @Memory: 23.9 MB # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reorderList(self, head: ListNode) -> None: """ Do not return anything, modify head in-place instead. """ if head is None or head.next is None: return s = head f = head.next while f and f.next: f = f.next.next s = s.next l2 = s.next def reverse(head): pre = None cur = head while cur: tmp = cur.next cur.next = pre pre = cur cur = tmp return pre l2 = reverse(l2) s.next = None l1 = head while l2: tmp = l1.next l1.next = l2 l2 = l2.next l1 = l1.next l1.next = tmp l1 = l1.next
"""Stores constants used as numbers for readability that are used across all apps""" class AdminRoles: """ """ JCRTREASURER = 1 SENIORTREASURER = 2 BURSARY = 3 ASSISTANTBURSAR = 4 CHOICES = ( (JCRTREASURER, 'JCR Treasurer'), (SENIORTREASURER, 'Senior Treasurer'), (BURSARY, 'Bursary'), (ASSISTANTBURSAR, 'Assistant Bursar') )
def _check_inplace(trace): """Checks that all PythonOps that were not translated into JIT format are out of place. Should be run after the ONNX pass. """ graph = trace.graph() for node in graph.nodes(): if node.kind() == 'PythonOp': if node.i('inplace'): raise RuntimeError("inplace {} not supported in the JIT".format(node.pyname()))
# @Title: 旋转数组 (Rotate Array) # @Author: KivenC # @Date: 2019-03-14 16:57:56 # @Runtime: 124 ms # @Memory: 13.4 MB class Solution: def rotate(self, nums: List[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. """ ''' k = k % len(nums) while k > 0: num = nums.pop() nums.insert(0, num) k -= 1 ''' k = k % len(nums) if k > 0: nums.reverse() nums[:k] = reversed(nums[:k]) nums[k:] = reversed(nums[k:])
def test1(): arr = [["我", "你好"], ["你在干嘛", "你干啥呢"], ["吃饭呢", "打球呢", "看电视呢"]] new_arr = [] for i in arr[0]: print(i) for j in arr[1]: new_arr.append(i + j) print(new_arr) # # def test(): # while True: # test1(arr) test1()
############################################################################### # Utils functions for language models. # # NOTE: source from https://github.com/litian96/FedProx ############################################################################### ALL_LETTERS = "\n !\"&'(),-.0123456789:;>?ABCDEFGHIJKLMNOPQRSTUVWXYZ[]abcdefghijklmnopqrstuvwxyz}" NUM_LETTERS = len(ALL_LETTERS) def _one_hot(index, size): '''returns one-hot vector with given size and value 1 at given index ''' vec = [0 for _ in range(size)] vec[int(index)] = 1 return vec def letter_to_vec(letter): '''returns one-hot representation of given letter ''' index = ALL_LETTERS.find(letter) return _one_hot(index, NUM_LETTERS) def word_to_indices(word): '''returns a list of character indices Args: word: string Return: indices: int list with length len(word) ''' indices = [] for c in word: indices.append(ALL_LETTERS.find(c)) return indices
a = str(input()) b = {'0': 0, '1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, '7': 0, '8': 0, '9': 0} for i in a: b[i] = b[i] + 1 for i in range(len(b)): if b[str(i)] == 0: continue print(str(i) + ':' + str(b[str(i)]))
class ModeIndicator: LENGTH = 4 TERMINATOR_VALUE = 0x0 NUMERIC_VALUE = 0x1 ALPHANUMERIC_VALUE = 0x2 STRUCTURED_APPEND_VALUE = 0x3 BYTE_VALUE = 0x4 KANJI_VALUE = 0x8
# 11/03/21 # What does this code do? # This code introduces a new idea, Dictionaries. The codes purpose is to take an input, and convert it into the numbers you'd need to press # on an alphanumeric keypad, as shown in the picture. # How do Dictionaries work? # To use our dictionary, we first need to initialise it. We can do this as follows: # Syntax: <DICTNAME> = {'Key1':'Value1'} # Example: MyPetSounds = {"Cat":"Meow", "Dog":"Woof"} # To explain further, dictionaries work in a Key and Value paired system. To create an entry, you need to define 2 things, # The key (or how the entry will be called), and then the value (What will be referenced when the key is called.) They are seperated by a colon. # A dictionary containing the letter to digit phone keypad mappings. KEYPAD = { 'A': '2', 'B': '2', 'C': '2', 'D': '3', 'E': '3', 'F': '3', 'G': '4', 'H': '4', 'I': '4', 'J': '5', 'K': '5', 'L': '5', 'M': '6', 'N': '6', 'O': '6', 'P': '7', 'Q': '7', 'R': '7', 'S': '7', 'T': '8', 'U': '8', 'V': '8', 'W': '9', 'X': '9', 'Y': '9', 'Z': '9', } word = input("Enter word: ") for key in word: print(KEYPAD[key], end='') print() print("This code was created by $pigot.") # What is happening here? # In the first 6 lines of this code, we are simply initialising our dictionary. We are associating the numbers on the keypad, to the 3 or 4 # letters that they can enter.
# # PySNMP MIB module Juniper-V35-CONF (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-V35-CONF # Produced by pysmi-0.3.4 at Wed May 1 14:04:44 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ConstraintsUnion, SingleValueConstraint, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsIntersection") juniAgents, = mibBuilder.importSymbols("Juniper-Agents", "juniAgents") ModuleCompliance, AgentCapabilities, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "AgentCapabilities", "NotificationGroup") Bits, Integer32, MibIdentifier, Counter32, Gauge32, NotificationType, IpAddress, ModuleIdentity, iso, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, TimeTicks, Unsigned32 = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Integer32", "MibIdentifier", "Counter32", "Gauge32", "NotificationType", "IpAddress", "ModuleIdentity", "iso", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "TimeTicks", "Unsigned32") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") juniV35Agent = ModuleIdentity((1, 3, 6, 1, 4, 1, 4874, 5, 2, 54)) juniV35Agent.setRevisions(('2002-09-06 16:54', '2002-01-25 21:43',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: juniV35Agent.setRevisionsDescriptions(('Replaced Unisphere names with Juniper names.', 'The initial release of this management information module.',)) if mibBuilder.loadTexts: juniV35Agent.setLastUpdated('200209061654Z') if mibBuilder.loadTexts: juniV35Agent.setOrganization('Juniper Networks, Inc.') if mibBuilder.loadTexts: juniV35Agent.setContactInfo(' Juniper Networks, Inc. Postal: 10 Technology Park Drive Westford, MA 01886-3146 USA Tel: +1 978 589 5800 E-mail: mib@Juniper.net') if mibBuilder.loadTexts: juniV35Agent.setDescription('The agent capabilities definitions for the X.21/V.35 server component of the SNMP agent in the Juniper E-series family of products.') juniV35AgentV1 = AgentCapabilities((1, 3, 6, 1, 4, 1, 4874, 5, 2, 54, 1)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniV35AgentV1 = juniV35AgentV1.setProductRelease('Version 1 of the X.21/V.35 component of the JUNOSe SNMP agent. This\n version of the X.21/V.35 component is supported in JUNOSe 4.0 and\n subsequent system releases.') if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): juniV35AgentV1 = juniV35AgentV1.setStatus('current') if mibBuilder.loadTexts: juniV35AgentV1.setDescription('The MIB supported by the SNMP agent for the X.21/V.35 application in JUNOSe.') mibBuilder.exportSymbols("Juniper-V35-CONF", juniV35AgentV1=juniV35AgentV1, PYSNMP_MODULE_ID=juniV35Agent, juniV35Agent=juniV35Agent)
def maior_numero(lista): a = lista[0] for i in range(len(lista)): if lista[i] > a: a = lista[i] return a def remove_divisores_do_maior(lista): maiornumero=maior_numero(lista) for i in range(len(lista)-1,-1,-1): if (maiornumero%lista[i])==0: lista.pop(i) return None
# sample\core.py def run_core(): print("In pycharm run_core")
l = float(input('Digite a largura da parede em metros: ')) al = float(input('Digite a altura da parede em metros: ')) #Um litro de tinta pinta 2m², largura * altura da parede obtemos a área dela em m² e dividimos por dois para obter a quantidade de tinta necessária. lt = (l * al) / 2 print(f'Com uma parede {l}x{al}, você usará {lt:.2f}L de tinta')
raise NotImplementedError("Getting an NPE trying to parse this code") class KeyValue: def __init__(self, key, value): self.key = key self.value = value def __repr__(self): return f"{self.key}->{self.value}" class MinHeap: def __init__(self, start_size): self.heap = [None] * start_size self.next_i = 0 def add(self, key, value): self.heap[self.next_i] = KeyValue(key, value) child_i = self.next_i parent_i = child_i // 2 while child_i != parent_i: if self.heap[child_i].key < self.heap[parent_i].key: swapper = self.heap[child_i] self.heap[child_i] = self.heap[parent_i] self.heap[parent_i] = swapper child_i = parent_i parent_i //= 2 self.next_i += 1 def get(self): if self.next_i == 0: return None elif self.next_i == 1: bye_bye_root = self.heap[0] self.heap[0] = None return bye_bye_root else: bye_bye_root = self.heap[0] self.next_i -= 1 self.heap[0] = self.heap[self.next_i] self.heap[self.next_i] = None # Heapify parent_i = 0 while 2 * parent_i < len(self.heap) and self.heap[parent_i] is not None: heapify_parent = self.heap[parent_i] lchild_i = 2*parent_i + 1 rchild_i = 2*parent_i + 2 lchild = self.heap[lchild_i] rchild = self.heap[rchild_i] best = heapify_parent best_i = parent_i if lchild is not None and lchild.key < best.key: best = lchild best_i = lchild_i if rchild is not None and rchild.key < best.key: best = rchild best_i = rchild_i if heapify_parent != best: swapper = self.heap[best_i] self.heap[best_i] = heapify_parent self.heap[parent_i] = swapper parent_i = best_i else: break return bye_bye_root min_heap = MinHeap(16) min_heap.add(2, 2) min_heap.add(3, 3) min_heap.add(4, 4) min_heap.add(1, 1) print(min_heap.get().key) print(min_heap.get().key) print(min_heap.get().key) print(min_heap.get().key)
n = int(input()) c = [0]*n for i in range(n): l = int(input()) S = input() for j in range(l): if (S[j]=='0'): continue for k in range(j,l): if (S[k]=='1'): c[i] = c[i]+1 for i in range(n): print(c[i])
# # PySNMP MIB module CHECKPOINT-TRAP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CHECKPOINT-TRAP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:31:16 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint") tempertureSensorStatus, haProblemVerified, fanSpeedSensorType, multiDiskFreeAvailablePercent, raidDiskID, memActiveReal64, haBlockState, haProblemPriority, voltageSensorName, svnNetIfState, fwLSConnState, fanSpeedSensorValue, haIfName, raidVolumeID, voltageSensorType, voltageSensorValue, raidDiskFlags, multiDiskName, fwLocalLoggingStat, fanSpeedSensorStatus, haIP, fanSpeedSensorUnit, tempertureSensorName, haTrusted, haStatShort, haStatus, multiProcIndex, svnNetIfName, haState, multiProcRunQueue, voltageSensorUnit, multiProcUsage, memTotalReal64, multiProcInterrupts, multiProcSystemTime, voltageSensorStatus, tempertureSensorUnit, haProblemStatus, tempertureSensorValue, fwLSConnOverall, fwLSConnStateDesc, fanSpeedSensorName, raidVolumeState, raidDiskVolumeID, fwLSConnOverallDesc, haIdentifier, memTotalVirtual64, memActiveVirtual64, raidDiskState, haStatCode, haStatLong, haProblemName, multiProcIdleTime, haProblemDescr, fwLSConnName, multiProcUserTime, fwLocalLoggingDesc, tempertureSensorType, haShared, svnNetIfAddress, svnNetIfOperState = mibBuilder.importSymbols("CHECKPOINT-MIB", "tempertureSensorStatus", "haProblemVerified", "fanSpeedSensorType", "multiDiskFreeAvailablePercent", "raidDiskID", "memActiveReal64", "haBlockState", "haProblemPriority", "voltageSensorName", "svnNetIfState", "fwLSConnState", "fanSpeedSensorValue", "haIfName", "raidVolumeID", "voltageSensorType", "voltageSensorValue", "raidDiskFlags", "multiDiskName", "fwLocalLoggingStat", "fanSpeedSensorStatus", "haIP", "fanSpeedSensorUnit", "tempertureSensorName", "haTrusted", "haStatShort", "haStatus", "multiProcIndex", "svnNetIfName", "haState", "multiProcRunQueue", "voltageSensorUnit", "multiProcUsage", "memTotalReal64", "multiProcInterrupts", "multiProcSystemTime", "voltageSensorStatus", "tempertureSensorUnit", "haProblemStatus", "tempertureSensorValue", "fwLSConnOverall", "fwLSConnStateDesc", "fanSpeedSensorName", "raidVolumeState", "raidDiskVolumeID", "fwLSConnOverallDesc", "haIdentifier", "memTotalVirtual64", "memActiveVirtual64", "raidDiskState", "haStatCode", "haStatLong", "haProblemName", "multiProcIdleTime", "haProblemDescr", "fwLSConnName", "multiProcUserTime", "fwLocalLoggingDesc", "tempertureSensorType", "haShared", "svnNetIfAddress", "svnNetIfOperState") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Counter32, NotificationType, iso, Integer32, IpAddress, TimeTicks, ObjectIdentity, Bits, Unsigned32, MibIdentifier, ModuleIdentity, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, enterprises = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "NotificationType", "iso", "Integer32", "IpAddress", "TimeTicks", "ObjectIdentity", "Bits", "Unsigned32", "MibIdentifier", "ModuleIdentity", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "enterprises") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") chkpntTrapMibModule = ModuleIdentity((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 0, 0)) chkpntTrapMibModule.setRevisions(('2013-12-26 13:09',)) if mibBuilder.loadTexts: chkpntTrapMibModule.setLastUpdated('201312261309Z') if mibBuilder.loadTexts: chkpntTrapMibModule.setOrganization('Check Point') checkpoint = MibIdentifier((1, 3, 6, 1, 4, 1, 2620)) products = MibIdentifier((1, 3, 6, 1, 4, 1, 2620, 1)) chkpntTrap = MibIdentifier((1, 3, 6, 1, 4, 1, 2620, 1, 2000)) chkpntTrapInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 0)) chkpntTrapNet = MibIdentifier((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 1)) chkpntTrapDisk = MibIdentifier((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 2)) chkpntTrapCPU = MibIdentifier((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 3)) chkpntTrapMemory = MibIdentifier((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 4)) chkpntTrapHWSensor = MibIdentifier((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 5)) chkpntTrapHA = MibIdentifier((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 6)) chkpntTrapLSConn = MibIdentifier((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 7)) chkpntTrapOID = MibScalar((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 0, 10), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: chkpntTrapOID.setStatus('current') chkpntTrapOIDValue = MibScalar((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 0, 11), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: chkpntTrapOIDValue.setStatus('current') chkpntTrapMsgText = MibScalar((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 0, 12), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: chkpntTrapMsgText.setStatus('current') chkpntTrapSeverity = MibScalar((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 0, 13), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly") if mibBuilder.loadTexts: chkpntTrapSeverity.setStatus('current') chkpntTrapCategory = MibScalar((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 0, 14), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: chkpntTrapCategory.setStatus('current') chkpntDiskSpaceTrap = NotificationType((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 2, 1)).setObjects(("CHECKPOINT-TRAP-MIB", "chkpntTrapOID"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapOIDValue"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapMsgText"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapSeverity"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapCategory"), ("CHECKPOINT-MIB", "multiDiskName"), ("CHECKPOINT-MIB", "multiDiskFreeAvailablePercent")) if mibBuilder.loadTexts: chkpntDiskSpaceTrap.setStatus('current') chkpntRAIDVolumeTrap = NotificationType((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 2, 2)).setObjects(("CHECKPOINT-TRAP-MIB", "chkpntTrapOID"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapOIDValue"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapMsgText"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapSeverity"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapCategory"), ("CHECKPOINT-MIB", "raidVolumeID"), ("CHECKPOINT-MIB", "raidVolumeState")) if mibBuilder.loadTexts: chkpntRAIDVolumeTrap.setStatus('current') chkpntRAIDDiskTrap = NotificationType((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 2, 3)).setObjects(("CHECKPOINT-TRAP-MIB", "chkpntTrapOID"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapOIDValue"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapMsgText"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapSeverity"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapCategory"), ("CHECKPOINT-MIB", "raidDiskVolumeID"), ("CHECKPOINT-MIB", "raidDiskID"), ("CHECKPOINT-MIB", "raidDiskState")) if mibBuilder.loadTexts: chkpntRAIDDiskTrap.setStatus('current') chkpntRAIDDiskFlagsTrap = NotificationType((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 2, 4)).setObjects(("CHECKPOINT-TRAP-MIB", "chkpntTrapOID"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapOIDValue"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapMsgText"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapSeverity"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapCategory"), ("CHECKPOINT-MIB", "raidDiskVolumeID"), ("CHECKPOINT-MIB", "raidDiskID"), ("CHECKPOINT-MIB", "raidDiskState"), ("CHECKPOINT-MIB", "raidDiskFlags")) if mibBuilder.loadTexts: chkpntRAIDDiskFlagsTrap.setStatus('current') chkpntTrapNetIfState = NotificationType((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 1, 1)).setObjects(("CHECKPOINT-TRAP-MIB", "chkpntTrapOID"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapOIDValue"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapMsgText"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapSeverity"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapCategory"), ("CHECKPOINT-MIB", "svnNetIfName"), ("CHECKPOINT-MIB", "svnNetIfAddress"), ("CHECKPOINT-MIB", "svnNetIfState")) if mibBuilder.loadTexts: chkpntTrapNetIfState.setStatus('current') chkpntTrapNetIfUnplugged = NotificationType((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 1, 2)).setObjects(("CHECKPOINT-TRAP-MIB", "chkpntTrapOID"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapOIDValue"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapMsgText"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapSeverity"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapCategory"), ("CHECKPOINT-MIB", "svnNetIfName"), ("CHECKPOINT-MIB", "svnNetIfAddress")) if mibBuilder.loadTexts: chkpntTrapNetIfUnplugged.setStatus('current') chkpntTrapNewConnRate = NotificationType((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 1, 3)).setObjects(("CHECKPOINT-TRAP-MIB", "chkpntTrapOID"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapOIDValue"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapMsgText"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapSeverity"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapCategory")) if mibBuilder.loadTexts: chkpntTrapNewConnRate.setStatus('current') chkpntTrapConcurrentConnRate = NotificationType((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 1, 4)).setObjects(("CHECKPOINT-TRAP-MIB", "chkpntTrapOID"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapOIDValue"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapMsgText"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapSeverity"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapCategory")) if mibBuilder.loadTexts: chkpntTrapConcurrentConnRate.setStatus('current') chkpntTrapBytesThroughput = NotificationType((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 1, 5)).setObjects(("CHECKPOINT-TRAP-MIB", "chkpntTrapOID"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapOIDValue"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapMsgText"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapSeverity"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapCategory")) if mibBuilder.loadTexts: chkpntTrapBytesThroughput.setStatus('current') chkpntTrapAcceptedPacketRate = NotificationType((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 1, 6)).setObjects(("CHECKPOINT-TRAP-MIB", "chkpntTrapOID"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapOIDValue"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapMsgText"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapSeverity"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapCategory")) if mibBuilder.loadTexts: chkpntTrapAcceptedPacketRate.setStatus('current') chkpntTrapNetIfOperState = NotificationType((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 1, 7)).setObjects(("CHECKPOINT-TRAP-MIB", "chkpntTrapOID"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapOIDValue"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapMsgText"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapSeverity"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapCategory"), ("CHECKPOINT-MIB", "svnNetIfName"), ("CHECKPOINT-MIB", "svnNetIfAddress"), ("CHECKPOINT-MIB", "svnNetIfOperState")) if mibBuilder.loadTexts: chkpntTrapNetIfOperState.setStatus('current') chkpntCPUCoreUtilTrap = NotificationType((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 3, 1)).setObjects(("CHECKPOINT-TRAP-MIB", "chkpntTrapOID"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapOIDValue"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapMsgText"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapSeverity"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapCategory"), ("CHECKPOINT-MIB", "multiProcIndex"), ("CHECKPOINT-MIB", "multiProcUserTime"), ("CHECKPOINT-MIB", "multiProcSystemTime"), ("CHECKPOINT-MIB", "multiProcIdleTime"), ("CHECKPOINT-MIB", "multiProcUsage"), ("CHECKPOINT-MIB", "multiProcRunQueue"), ("CHECKPOINT-MIB", "multiProcInterrupts")) if mibBuilder.loadTexts: chkpntCPUCoreUtilTrap.setStatus('current') chkpntCPUCoreInterruptsTrap = NotificationType((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 3, 2)).setObjects(("CHECKPOINT-TRAP-MIB", "chkpntTrapOID"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapOIDValue"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapMsgText"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapSeverity"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapCategory"), ("CHECKPOINT-MIB", "multiProcIndex"), ("CHECKPOINT-MIB", "multiProcUserTime"), ("CHECKPOINT-MIB", "multiProcSystemTime"), ("CHECKPOINT-MIB", "multiProcIdleTime"), ("CHECKPOINT-MIB", "multiProcUsage"), ("CHECKPOINT-MIB", "multiProcRunQueue"), ("CHECKPOINT-MIB", "multiProcInterrupts")) if mibBuilder.loadTexts: chkpntCPUCoreInterruptsTrap.setStatus('current') chkpntSwapMemoryTrap = NotificationType((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 4, 1)).setObjects(("CHECKPOINT-TRAP-MIB", "chkpntTrapOID"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapOIDValue"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapMsgText"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapSeverity"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapCategory"), ("CHECKPOINT-MIB", "memTotalVirtual64"), ("CHECKPOINT-MIB", "memActiveVirtual64")) if mibBuilder.loadTexts: chkpntSwapMemoryTrap.setStatus('current') chkpntRealMemoryTrap = NotificationType((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 4, 2)).setObjects(("CHECKPOINT-TRAP-MIB", "chkpntTrapOID"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapOIDValue"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapMsgText"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapSeverity"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapCategory"), ("CHECKPOINT-MIB", "memTotalReal64"), ("CHECKPOINT-MIB", "memActiveReal64")) if mibBuilder.loadTexts: chkpntRealMemoryTrap.setStatus('current') chkpntTrapTempertureSensor = MibIdentifier((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 5, 1)) chkpntTrapFanSpeedSensor = MibIdentifier((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 5, 2)) chkpntTrapVoltageSensor = MibIdentifier((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 5, 3)) chkpntTempertureTrap = NotificationType((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 5, 1, 1)).setObjects(("CHECKPOINT-TRAP-MIB", "chkpntTrapOID"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapOIDValue"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapMsgText"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapSeverity"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapCategory"), ("CHECKPOINT-MIB", "tempertureSensorName"), ("CHECKPOINT-MIB", "tempertureSensorValue"), ("CHECKPOINT-MIB", "tempertureSensorUnit"), ("CHECKPOINT-MIB", "tempertureSensorType"), ("CHECKPOINT-MIB", "tempertureSensorStatus")) if mibBuilder.loadTexts: chkpntTempertureTrap.setStatus('current') chkpntFanSpeedTrap = NotificationType((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 5, 2, 1)).setObjects(("CHECKPOINT-TRAP-MIB", "chkpntTrapOID"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapOIDValue"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapMsgText"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapSeverity"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapCategory"), ("CHECKPOINT-MIB", "fanSpeedSensorName"), ("CHECKPOINT-MIB", "fanSpeedSensorValue"), ("CHECKPOINT-MIB", "fanSpeedSensorUnit"), ("CHECKPOINT-MIB", "fanSpeedSensorType"), ("CHECKPOINT-MIB", "fanSpeedSensorStatus")) if mibBuilder.loadTexts: chkpntFanSpeedTrap.setStatus('current') chkpntVoltageTrap = NotificationType((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 5, 3, 1)).setObjects(("CHECKPOINT-TRAP-MIB", "chkpntTrapOID"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapOIDValue"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapMsgText"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapSeverity"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapCategory"), ("CHECKPOINT-MIB", "voltageSensorName"), ("CHECKPOINT-MIB", "voltageSensorValue"), ("CHECKPOINT-MIB", "voltageSensorUnit"), ("CHECKPOINT-MIB", "voltageSensorType"), ("CHECKPOINT-MIB", "voltageSensorStatus")) if mibBuilder.loadTexts: chkpntVoltageTrap.setStatus('current') chkpntClusterMemberStateTrap = NotificationType((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 6, 1)).setObjects(("CHECKPOINT-TRAP-MIB", "chkpntTrapOID"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapOIDValue"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapMsgText"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapSeverity"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapCategory"), ("CHECKPOINT-MIB", "haIdentifier"), ("CHECKPOINT-MIB", "haState")) if mibBuilder.loadTexts: chkpntClusterMemberStateTrap.setStatus('current') chkpntClusterBlockStateTrap = NotificationType((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 6, 2)).setObjects(("CHECKPOINT-TRAP-MIB", "chkpntTrapOID"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapOIDValue"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapMsgText"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapSeverity"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapCategory"), ("CHECKPOINT-MIB", "haIdentifier"), ("CHECKPOINT-MIB", "haBlockState"), ("CHECKPOINT-MIB", "haState")) if mibBuilder.loadTexts: chkpntClusterBlockStateTrap.setStatus('current') chkpntClusterStateTrap = NotificationType((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 6, 3)).setObjects(("CHECKPOINT-TRAP-MIB", "chkpntTrapOID"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapOIDValue"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapMsgText"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapSeverity"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapCategory"), ("CHECKPOINT-MIB", "haIdentifier"), ("CHECKPOINT-MIB", "haBlockState"), ("CHECKPOINT-MIB", "haState"), ("CHECKPOINT-MIB", "haStatCode"), ("CHECKPOINT-MIB", "haStatShort"), ("CHECKPOINT-MIB", "haStatLong")) if mibBuilder.loadTexts: chkpntClusterStateTrap.setStatus('current') chkpntClusterProblemStateTrap = NotificationType((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 6, 4)).setObjects(("CHECKPOINT-TRAP-MIB", "chkpntTrapOID"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapOIDValue"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapMsgText"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapSeverity"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapCategory"), ("CHECKPOINT-MIB", "haProblemName"), ("CHECKPOINT-MIB", "haProblemStatus"), ("CHECKPOINT-MIB", "haProblemPriority"), ("CHECKPOINT-MIB", "haProblemVerified"), ("CHECKPOINT-MIB", "haProblemDescr")) if mibBuilder.loadTexts: chkpntClusterProblemStateTrap.setStatus('current') chkpntClusterInterfaceStateTrap = NotificationType((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 6, 5)).setObjects(("CHECKPOINT-TRAP-MIB", "chkpntTrapOID"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapOIDValue"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapMsgText"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapSeverity"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapCategory"), ("CHECKPOINT-MIB", "haIfName"), ("CHECKPOINT-MIB", "haIP"), ("CHECKPOINT-MIB", "haStatus"), ("CHECKPOINT-MIB", "haTrusted"), ("CHECKPOINT-MIB", "haShared")) if mibBuilder.loadTexts: chkpntClusterInterfaceStateTrap.setStatus('current') chkpntTrapLSConnState = NotificationType((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 7, 1)).setObjects(("CHECKPOINT-TRAP-MIB", "chkpntTrapOID"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapOIDValue"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapMsgText"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapSeverity"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapCategory"), ("CHECKPOINT-MIB", "fwLSConnName"), ("CHECKPOINT-MIB", "fwLSConnState"), ("CHECKPOINT-MIB", "fwLSConnStateDesc"), ("CHECKPOINT-MIB", "fwLocalLoggingDesc"), ("CHECKPOINT-MIB", "fwLocalLoggingStat")) if mibBuilder.loadTexts: chkpntTrapLSConnState.setStatus('current') chkpntTrapOverallLSConnState = NotificationType((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 7, 2)).setObjects(("CHECKPOINT-TRAP-MIB", "chkpntTrapOID"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapOIDValue"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapMsgText"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapSeverity"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapCategory"), ("CHECKPOINT-MIB", "fwLSConnOverall"), ("CHECKPOINT-MIB", "fwLSConnOverallDesc"), ("CHECKPOINT-MIB", "fwLocalLoggingDesc"), ("CHECKPOINT-MIB", "fwLocalLoggingStat")) if mibBuilder.loadTexts: chkpntTrapOverallLSConnState.setStatus('current') chkpntTrapLocalLoggingState = NotificationType((1, 3, 6, 1, 4, 1, 2620, 1, 2000, 7, 3)).setObjects(("CHECKPOINT-TRAP-MIB", "chkpntTrapOID"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapOIDValue"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapMsgText"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapSeverity"), ("CHECKPOINT-TRAP-MIB", "chkpntTrapCategory"), ("CHECKPOINT-MIB", "fwLSConnOverall"), ("CHECKPOINT-MIB", "fwLSConnOverallDesc"), ("CHECKPOINT-MIB", "fwLocalLoggingDesc"), ("CHECKPOINT-MIB", "fwLocalLoggingStat")) if mibBuilder.loadTexts: chkpntTrapLocalLoggingState.setStatus('current') mibBuilder.exportSymbols("CHECKPOINT-TRAP-MIB", chkpntTrapBytesThroughput=chkpntTrapBytesThroughput, chkpntClusterBlockStateTrap=chkpntClusterBlockStateTrap, chkpntTrap=chkpntTrap, chkpntRAIDDiskTrap=chkpntRAIDDiskTrap, chkpntCPUCoreInterruptsTrap=chkpntCPUCoreInterruptsTrap, chkpntTempertureTrap=chkpntTempertureTrap, chkpntTrapConcurrentConnRate=chkpntTrapConcurrentConnRate, chkpntTrapNewConnRate=chkpntTrapNewConnRate, chkpntFanSpeedTrap=chkpntFanSpeedTrap, chkpntSwapMemoryTrap=chkpntSwapMemoryTrap, chkpntVoltageTrap=chkpntVoltageTrap, chkpntTrapFanSpeedSensor=chkpntTrapFanSpeedSensor, chkpntCPUCoreUtilTrap=chkpntCPUCoreUtilTrap, chkpntTrapMsgText=chkpntTrapMsgText, checkpoint=checkpoint, chkpntRealMemoryTrap=chkpntRealMemoryTrap, chkpntTrapOID=chkpntTrapOID, chkpntTrapSeverity=chkpntTrapSeverity, chkpntClusterStateTrap=chkpntClusterStateTrap, chkpntTrapOverallLSConnState=chkpntTrapOverallLSConnState, chkpntTrapTempertureSensor=chkpntTrapTempertureSensor, chkpntClusterProblemStateTrap=chkpntClusterProblemStateTrap, chkpntClusterInterfaceStateTrap=chkpntClusterInterfaceStateTrap, chkpntTrapHWSensor=chkpntTrapHWSensor, chkpntTrapCategory=chkpntTrapCategory, chkpntTrapLocalLoggingState=chkpntTrapLocalLoggingState, chkpntTrapLSConnState=chkpntTrapLSConnState, chkpntTrapLSConn=chkpntTrapLSConn, chkpntTrapMibModule=chkpntTrapMibModule, chkpntTrapMemory=chkpntTrapMemory, chkpntTrapNetIfUnplugged=chkpntTrapNetIfUnplugged, chkpntTrapCPU=chkpntTrapCPU, chkpntDiskSpaceTrap=chkpntDiskSpaceTrap, products=products, chkpntTrapNet=chkpntTrapNet, chkpntTrapAcceptedPacketRate=chkpntTrapAcceptedPacketRate, chkpntTrapNetIfOperState=chkpntTrapNetIfOperState, chkpntTrapNetIfState=chkpntTrapNetIfState, chkpntTrapOIDValue=chkpntTrapOIDValue, chkpntRAIDVolumeTrap=chkpntRAIDVolumeTrap, chkpntClusterMemberStateTrap=chkpntClusterMemberStateTrap, chkpntTrapInfo=chkpntTrapInfo, chkpntRAIDDiskFlagsTrap=chkpntRAIDDiskFlagsTrap, chkpntTrapHA=chkpntTrapHA, chkpntTrapVoltageSensor=chkpntTrapVoltageSensor, chkpntTrapDisk=chkpntTrapDisk, PYSNMP_MODULE_ID=chkpntTrapMibModule)
colors_per_chi = {2: 'green', 3: 'orange', 4: 'purple', 5: 'pink', 6: 'red'} style_per_chi = {2: '-', 3: '-.', 4: 'dotted'} markers_per_reason = {'converged': 'o', 'progress': 'x', 'ressources': 'v'} linewidth = 5.31596
def get_failed_ids(txt_file): id = [] fh = open(txt_file, 'r') for row in fh: id.append(row.split('/')[1].split('.')[0]) return(id)
""" Implementation of Linked List reversal. """ # Author: Nikhil Xavier <nikhilxavier@yahoo.com> # License: BSD 3 clause class Node: """Node class for Singly Linked List.""" def __init__(self, value): self.value = value self.next_node = None def reverse_linked_list(head): """Reverse linked list. Returns reversed linked list head. """ current_node = head previous_node = None next_node = None while current_node: next_node = current_node.next_node current_node.next_node = previous_node previous_node = current_node current_node = next_node return previous_node
d=int(input("enter d")) n='' max='' for i in range(d): if i==0: n=n+str(1) else : n=n+str(0) max=max+str(9) n=int(n)+1 #smallest odd no. with d digits if d>1 or 2 if d==1 max=int(max) #largest no. with d digits def check_prime(m_odd): #returns truth value of an odd no. or of 2 being prime if m_odd==2:return True i=3 while m_odd%i!=0 and i<m_odd: i=i+2 return i==m_odd l=[] #list of prime no.s of d digits while n<=max: if check_prime(n): l.append(n) if n==2: n=n+1 continue if n>2: n=n+2 print(l) d=[] #list of tuples with consecutive difference 2 for i in range(len(l)-1): if (l[i+1]-l[i]==2): d.append((l[i],l[i+1])) f=open('myFirstFile.txt','w') for i in range(len(d)): f.write(str(d[i][0])+' '+str(d[i][1])+"\n") f.close()
class Boolable: def __bool__(self): return False class DescriptiveTrue(Boolable): def __init__(self, description): self.description = description def __bool__(self): return True def __str__(self): return f"{self.description}" def __repr__(self): return f"{self.__class__.__name__}({repr(self.description)})" class Intable: def __int__(self): return 0 def __add__(self, other): return Addition(self, other) def __repr__(self): return f"{self.__class__.__name__}()" class DescriptiveInt(Intable): def __init__(self, value, description): self.value = value self.description = description def __int__(self): return self.value def __str__(self): return f"{self.value} ({self.description})" def __repr__(self): return f"{self.__class__.__name__}({repr(self.value)}, " \ f"{repr(self.description)})" class Addition(Intable): def __init__(self, *intables): self.intables = list(intables) def __int__(self): return sum(int(i) for i in self.intables) def __repr__(self): return f"{self.__class__.__name__}(*{repr(self.intables)})" def __str__(self): return " + ".join(str(x) for x in self.intables) class Subtraction(Intable): def __init__(self, left_operand, right_operand): self.left = left_operand self.right = right_operand def __int__(self): return int(self.left) - int(self.right) def __repr__(self): return f"{self.__class__.__name__}({repr(self.left)}, " \ f"{repr(self.right)})" def __str__(self): return f"{self.left} - {self.right}"
def fuel_required(weight: int) -> int: return weight // 3 - 2 def fuel_required_accurate(weight: int) -> int: fuel = 0 while weight > 0: weight = max(0, weight // 3 - 2) fuel += weight return fuel def test_fuel_required() -> None: cases = [(12, 2), (14, 2), (1969, 654), (100756, 33583)] for x, y in cases: assert fuel_required(x) == y def test_fuel_required_accurate() -> None: cases = [(14, 2), (1969, 966), (100756, 50346)] for x, y in cases: assert fuel_required_accurate(x) == y def test_solutions() -> None: with open("input/01.txt") as f: modules = [int(line) for line in f] part_1 = sum(map(fuel_required, modules)) part_2 = sum(map(fuel_required_accurate, modules)) assert part_1 == 3375962 assert part_2 == 5061072
""" Elabore um programa que calcule o valor a ser pago por um produto, considerando o seu PREÇO NORMAL e CONDIÇÃO DE PAGAMENTO: - À vista dinheiro/cheque: 10% de desconto - À vista no cartão: 5% de desconto - Em até 2x no cartão: Preço normal - 3x ou mais no cartão: 20% de JUROS """ preco = float(input('Qual o valor do produto? ')) condicao = str(input('Como deseja pagar? Opçoes abaixo. \n' '(1) A vista dinheiro.\n' '(2) A vista cartão.\n' '(3) Em até 2x cartão.\n' '(4) 3x ou mais no cartão.\n' 'Digite a opção desejada: ')) desconto10 = (preco / 100) * 10 desconto5 = (preco / 100) * 5 juros20 = (preco / 100) * 20 if condicao == '1': print(f'O produto que era R${preco} com 10% de desconto será R${preco - desconto10}') elif condicao == '2': print(f'O produto que era R${preco} com 5% de desconto será R${preco - desconto5}') elif condicao == '3': print(f'Parcelando no cartão até 2x não terá juros o valor R${preco} em 2x de R${preco / 2} ') elif condicao == '4': print(f'Parcelando em 3x ou mais terá um acrescimo de 20% de juros, o valor de {preco} irá para {preco + juros20}') else: print('A opção escolhida não é valida, cheque o número correto! ')
class Node: def __init__(self, value, index, next, previous): self.value = value self.next_value = value self.index = index self.next = next self.previous = previous def main(): input_data = read_input() initial_row = input_data.pop(0) # Extract the initial state input_data.pop(0) # Remove the empty row rules = list(map(lambda x: x.split(" => "), input_data)) initial_row = initial_row[15:] # Build the initial state current = None for i in range(len(initial_row)): previous = None if current is not None: previous = current current = Node(initial_row[0], i, None, None) initial_row = initial_row[1:] if previous is not None: previous.next = current current.previous = previous # When growing - add 3 more to both ends, and in the end remove the non-grown nodes from both ends # Current node is always some node in the hierarchy generation_number = 0 #debug(current, True, True) for i in range(20): generation_number += 1 current = grow(current, rules) #debug(current, True, True) leftmost = get_leftmost(current) index_sum = 0 while leftmost is not None: if leftmost.value == '#': index_sum += leftmost.index leftmost = leftmost.next print(index_sum) def grow(node, rules): '''Take the current state described by one node''' # Find the leftmost node and add the 3 nodes leftmost = get_leftmost(node) for i in range(3): new_node = Node('.', leftmost.index - 1, None, None) leftmost.previous = new_node new_node.next = leftmost leftmost = new_node # Find the rightmost and add 3 nodes rightmost = get_rightmost(node) for i in range(3): new_node = Node('.', rightmost.index + 1, None, None) rightmost.next = new_node new_node.previous = rightmost rightmost = new_node # Go through the nodes and test all rules current = leftmost.next.next while current.next.next is not None: pp = current.previous.previous p = current.previous n = current.next nn = current.next.next for rule in rules: if rule[0][0] == pp.value and rule[0][1] == p.value and rule[0][2] == current.value and rule[0][3] == n.value and rule[0][4] == nn.value: current.next_value = rule[1] # Assumes that every combination is in the rules current = current.next # Remove the ungrown nodes from both ends leftmost = get_leftmost(node) while leftmost.next_value == '.': leftmost.next.previous = None leftmost = leftmost.next rightmost = get_rightmost(leftmost) while rightmost.next_value == '.': rightmost.previous.next = None rightmost = rightmost.previous # Finally update the state for all nodes current = get_leftmost(rightmost) while current is not None: current.value = current.next_value current = current.next return rightmost # Return any valid node - in this case rightmost was updated last def get_leftmost(node): leftmost = node while leftmost.previous is not None: leftmost = leftmost.previous return leftmost def get_rightmost(node): rightmost = node while rightmost.next is not None: rightmost = rightmost.next return rightmost def debug(node, p, n): if p and node.previous is not None: debug(node.previous, True, False) print(node.value, end="") if n and node.next is not None: debug(node.next, False, True) def read_input(): '''Read the file and remove trailing new line characters''' f = open('input.txt', 'r') data = list(map(lambda x: x[:-1], f.readlines())) f.close() return data if __name__ == '__main__': main()
# David Hickox # Jan 12 17 # HickoxProject2 # Displayes name and classes # prints my name and classes in columns and waits for the user to hit enter to end the program print("David Hickox") print() print("1st Band") print("2nd Programming") print("3rd Ap Pysics C") print("4th Lunch") print("5th Ap Lang") print("6th TA for R&D") print("7th Gym") print("8th AP Calc BC") print() input("Press Enter To Continue") #this works too #input("David Hickox\n\n1st Band\n2nd Programming\n3rd Ap Pysics C\n4th Lunch\n5th Ap Lang\n6th TA for R&D\n7th Gym\n8th AP Calc BC\n\nPress Enter to continue")
class Node(): def __init__(self, value): self.value = value self.adjacentlist = [] self.visited = False class Graph(): def DFS(self, node, traversal): node.visited = True traversal.append(node.value) for element in node.adjacentlist: if element.visited is False: self.DFS(element, traversal) return traversal node1 = Node("A") node2 = Node("B") node3 = Node("C") node4 = Node("D") node5 = Node("E") node6 = Node("F") node7 = Node("G") node8 = Node("H") node1.adjacentlist.append(node2) node1.adjacentlist.append(node3) node1.adjacentlist.append(node4) node2.adjacentlist.append(node5) node2.adjacentlist.append(node6) node4.adjacentlist.append(node7) node6.adjacentlist.append(node8) graph = Graph() print(graph.DFS(node1, []))
# https://www.hackerrank.com/challenges/utopian-tree def tree_height(tree, N, start): if not N: return tree if start == 'spring': for i in range(N // 2): tree = tree * 2 + 1 if N % 2: return tree * 2 else: return tree elif start == 'summer': for i in range(N // 2): tree = (tree + 1) * 2 if N % 2: return tree + 1 else: return tree else: raise ValueError('start season must be spring or summer') T = int(input().strip()) for i in range(T): print(tree_height(1, int(input().strip()), start='spring'))
### Maximum Number of Coins You Can Get - Solution class Solution: def maxCoins(self, piles: List[int]) -> int: piles.sort() max_coin, n = 0, len(piles) for i in range(n//3, n, 2): max_coin += piles[i] return max_coin
#Antonio Karlo Mijares #ICS4U-01 #November 24 2016 #1D_2D_arrays.py #Creates 1D arrays, for the variables to be placed in characteristics = [] num = [] #Creates a percentage value for the numbers to be calculated with base = 20 percentage = 100 #2d Arrays #Ugly Arrays ugly_one_D = [] ugly_one_D_two = [] ugly_two_D = [] #Nice Array nice_two_D = [] #Sets the default file name to be open filename = ('character') #Strength function that will write to a 1D Array def strength(): #Opens the file with open(str(filename)+'.txt','r') as s: #Reads the file into a list line = s.read().splitlines() #Strips a part from the selected section name = line[3].strip(': 17') number = line[3].strip('Strength: ') #Appends the info to the 1D Arrays characteristics.append(name) num.append(number) #Constitution function that will write to a 1D Array def constitution(): #Opens the file with open(str(filename)+'.txt','r') as s: #Reads the file into a list line = s.read().splitlines() #Strips a part from the selected section name = line[4].strip(': 10') number = line[4].strip('Constitution: ') #Appends the info to the 1D Arrays characteristics.append(name) num.append(number) #Dexerity function that will write to a 1D Array def dexerity(): with open(str(filename)+'.txt','r') as s: #Reads the file into a list line = s.read().splitlines() #Strips a part from the selected section name = line[5].strip(': 8') number = line[5].strip('Dexerity: ') characteristics.append(name) num.append(number) #Intelligence function that will write to def intelligence(): with open(str(filename)+'.txt','r') as s: #Reads the file into a list line = s.read().splitlines() #Strips a part from the selected section name = line[6].strip(': 19') number = line[6].strip('Intelligence: ') #Appends the info to the 1D Arrays characteristics.append(name) num.append(number) #Wisdom function that will write to def wisdom(): with open(str(filename)+'.txt','r') as s: #Reads the file into a list line = s.read().splitlines() #Strips a part from the selected section name = line[7].strip(': 2') number = line[7].strip('Wisdom: ') #Appends the info to the 1D Arrays characteristics.append(name) num.append(number) #Charisma function that will write to def charisma(): with open(str(filename)+'.txt','r') as s: #Reads the file into a list line = s.read().splitlines() #Strips a part from the selected section name = line[8].strip(': 9') number = line[8].strip('Charisma: ') #Appends the info to the 1D Arrays characteristics.append(name) num.append(number) #2d function Array that creates the 2D Array (Nice Way) def real_two_d(nice_two_D): nice_two_D = [characteristics,num] for row in nice_two_D: for element in row: print(element, end=" ") print() return nice_two_D #2d function Array that creates the 2D Array (UGLY Way) def notreal_two_d(ugly_two_D): ugly_two_D = [characteristics,num] return ugly_two_D #Percentage function calculation that determines the #percentage for each stat def percentagecalc(): #Converts the number into a interger #Then divides it by base to be multiplied by 100 strengthpercent = int(num[0]) / base * percentage constitutionpercent = int(num[1]) / base * percentage dexeritypercent = int(num[2]) / base * percentage intelligencepercent = int(num[3]) / base * percentage wisdompercent = int(num[4]) / base * percentage charismapercent = int(num[5]) / base * percentage #Displays the percentage results print('') print('Strength: '+ str(strengthpercent)+'%') print('Constitution: '+ str(constitutionpercent)+'%') print('Dexerity: '+ str(dexeritypercent)+'%') print('Intelligence: '+ str(intelligencepercent)+'%') print('Wisdom: '+ str(wisdompercent)+'%') print('Charisma: '+ str(charismapercent)+'%') menu = True #Runs the menu loop while menu: #Menu Screen print('') print('Welcome to the 2D Array Creation!') print('Press:') print('S to start') print('H for help') print('Q to quit') #Waits for player input menuinput = input('Response: ') #States if user inputs s if (menuinput == 's') or (menuinput == 'S'): #Runs the 1D array functions strength() constitution() dexerity() intelligence() wisdom() charisma() #Runs the percentage function percentagecalc() #Runs the ugly 2d function uglytwo_d= notreal_two_d(ugly_two_D) #Displays the ugly 2d function print('') print('Ugly Two D Array:') print(uglytwo_d) print('') print('Nice Two D Array: ') #Runs the nice 2d function nice_two_D2= real_two_d(nice_two_D) #Displays the nice 2d function #print('Nice Two D Array:') #print(nice_two_D2) #States if user inputs h elif (menuinput == 'h') or (menuinput == 'H'): print('') print('This program creates a 2D array') print('') helpinput = input('Press Enter to continue.') #States if user inputs q elif (menuinput == 'q') or (menuinput == 'Q'): #Quits the program print('') print('You hage quit the program') print('Have a nice day!') menu = False #States if user inputs anything else else: #Error screen print("Sorry, that's an invalid input!")
kamus = {"elephant" : "gajah", "zebra" : "zebra", "dog" : "anjing", "camel" : "unta"} kata = input("Masukan kata berbahasa inggris : ") if kata in kamus: print("Terjemahan dari " + kata + " adalah " + kamus[kata]) else: print("Kata tersebt belum ada di kamus")
# -*- coding: utf-8 -*- ''' nbpkg defspec ''' NBPKG_MAGIC_NUMBER = b'\x1f\x8b' NBPKG_HEADER_MAGIC_NUMBER = '\037\213' NBPKGINFO_MIN_NUMBER = 1000 NBPKGINFO_MAX_NUMBER = 1146 # data types definition NBPKG_DATA_TYPE_NULL = 0 NBPKG_DATA_TYPE_CHAR = 1 NBPKG_DATA_TYPE_INT8 = 2 NBPKG_DATA_TYPE_INT16 = 3 NBPKG_DATA_TYPE_INT32 = 4 NBPKG_DATA_TYPE_INT64 = 5 NBPKG_DATA_TYPE_STRING = 6 NBPKG_DATA_TYPE_BIN = 7 NBPKG_DATA_TYPE_STRING_ARRAY = 8 NBPKG_DATA_TYPE_I18NSTRING_TYPE = 9 NBPKG_DATA_TYPES = (NBPKG_DATA_TYPE_NULL, NBPKG_DATA_TYPE_CHAR, NBPKG_DATA_TYPE_INT8, NBPKG_DATA_TYPE_INT16, NBPKG_DATA_TYPE_INT32, NBPKG_DATA_TYPE_INT64, NBPKG_DATA_TYPE_STRING, NBPKG_DATA_TYPE_BIN, NBPKG_DATA_TYPE_STRING_ARRAY,) NBPKGINFO_DISTNAME = 1000 NBPKGINFO_PKGNAME = 1000 NBPKGINFO_CATEGORY = 1000 NBPKGINFO_MAINTAINER = 1000 NBPKGINFO_HOMEPAGE = 1020 NBPKGINFO_COMMENT = 1000 NBPKGINFO_LICENSE = 1000 NBPKGINFO_VERSION = 1001 NBPKGINFO_RELEASE = 1002 NBPKGINFO_DESCRIPTION = 1005 NBPKGINFO_LONG_DESCRIPTION = 1005 NBPKGINFO_OS_VERSION = 1000 NBPKGINFO_COPYRIGHT = 1014 NBPKGINFO_SIZE_PKG = 1000 NBPKGINFO_MACHINE_ARCH = 1022 NBPKGINFOS = ( NBPKGINFO_DISTNAME, NBPKGINFO_PKGNAME, NBPKGINFO_CATEGORY, NBPKGINFO_MAINTAINER, NBPKGINFO_HOMEPAGE, NBPKGINFO_COMMENT, NBPKGINFO_LICENSE, NBPKGINFO_VERSION, NBPKGINFO_RELEASE, NBPKGINFO_LONG_DESCRIPTION, NBPKGINFO_OS_VERSION, NBPKGINFO_SIZE_PKG, NBPKGINFO_MACHINE_ARCH, ) NBPKG_HEADER_BASIC_FILES = dict() NBPKG_HEADER_BASIC_FILES = { 'NBPKG_BUILD_INFO':'+BUILD_INFO', 'NBPKG_BUILD_VERSION':'+BUILD_VERSION', 'NBPKG_COMMENT':'+COMMENT', 'NBPKG_CONTENTS':'+CONTENTS', 'NBPKG_DESC':'+DESC', 'NBPKG_SIZE_ALL':'+SIZE_ALL', 'NBPKG_SIZE_PKG':'+SIZE_PKG', }
#Write a program which can compute the factorial of a given numbers. #The results should be printed in a comma-separated sequence on a single line number=int(input("Please Enter factorial Number: ")) j=1 fact = 1 for i in range(number,0,-1): fact =fact*i print(fact)
"""Defines the version number and details of ``qusetta``.""" __all__ = ( '__version__', '__author__', '__authoremail__', '__license__', '__sourceurl__', '__description__' ) __version__ = "0.0.0" __author__ = "Joseph T. Iosue" __authoremail__ = "joe.iosue@qcware.com" __license__ = "MIT License" __sourceurl__ = "https://github.com/qcware/qusetta" __description__ = "Translating quantum circuits to and from representations"
##Write a program to input from the input file a familiar greeting of any length, each word on a line. Output the greeting file you just received on a single line, the words separated by a space #Mo file voi mode='r' de doc file with open('05_ip.txt', 'r') as fileInp: #Dung ham read() doc toan bo du lieu tu file Filecomplete = fileInp.read() #Dung ham splitlines() cat du lieu theo tung dong va luu thanh danh sach listOfligne = Filecomplete.splitlines() #Dung ham join() noi cac dong du lieu lai cach nhau 1 khoang trang phrasecomplete = ' '.join(listOfligne) print(phrasecomplete) #Mo file voi mode='w' de ghi file with open('05_out.txt', 'w') as fileOut: #Ghi noi dung vao file fileOut.write(phrasecomplete)
def fuel_required_single_module(mass): fuel = int(mass / 3) - 2 return fuel if fuel > 0 else 0 def fuel_required_multiple_modules(masses): total_fuel = 0 for mass in masses: total_fuel += fuel_required_single_module(mass) return total_fuel def recursive_fuel_required_single_module(mass): total_fuel = 0 while mass := fuel_required_single_module(mass): total_fuel += mass return total_fuel def recursive_fuel_required_multiple_modules(masses): total_fuel = 0 for mass in masses: total_fuel += recursive_fuel_required_single_module(mass) return total_fuel
str_xdigits = [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", ] def convert_digit(value: int, base: int) -> str: return str_xdigits[value % base] def convert_to_val(value: int, base: int) -> str: if value == None: return "Error" current = int(value) result = "" while current != 0: result = result + convert_digit(current, base) current = current // base if len(result) == 0: return "0" return result[::-1] # reverse string def val_to_hex(value: int) -> str: return "0x" + convert_to_val(value, 16) def val_to_bin(value: int) -> str: return "0b" + convert_to_val(value, 2) def val_to_dec(value: int) -> str: return convert_to_val(value, 10) def val_from_str(value: str, base: int) -> int: value = value.lower() result = 0 for c in value: if c not in str_xdigits or int(str_xdigits.index(c)) >= base: return None result = result * base + str_xdigits.index(c) return result def val_from_hex(value: str) -> int: return val_from_str(value.removeprefix("0x"), 16) def val_from_bin(value: str) -> int: return val_from_str(value.removeprefix("0b"), 2) def val_from_dec(value: str) -> int: return val_from_str(value, 10)
class SimpleOpt(): def __init__(self): self.method = 'cpgan' self.max_epochs = 100 self.graph_type = 'ENZYMES' self.data_dir = './data/facebook.graphs' self.gpu = '2' self.lr = 0.003 self.encode_size = 16 self.decode_size = 16 self.pool_size = 10 self.epochs_log = 1 self.batch_size = 8 self.random_seed = 123 self.gen_times = 10 self.gen_gamma = 10 self.milestones = [4000, 8000, 12000] class Options(): def __init__(self): self.opt_type = 'simple' # self.opt_type = 'argparser' @staticmethod def initialize(epoch_num=180): opt = SimpleOpt() opt.max_epochs = epoch_num return opt
# What will the gender ratio be after every family stops having children after # after they have a girl and not until then. def birth_ratio(): # Everytime a child is born, there is a 0.5 chance of the baby being male # and 0.5 chance of the baby being a girl. So the ratio is 1:1. return 1
# You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are(i, 0) and (i, height[i]). # Find two lines that together with the x-axis form a container, such that the container contains the most water. # Return the maximum amount of water a container can store. # Notice that you may not slant the container. # Example 1: # Input: height = [1, 8, 6, 2, 5, 4, 8, 3, 7] # Output: 49 # Explanation: The above vertical lines are represented by array[1, 8, 6, 2, 5, 4, 8, 3, 7]. In this case, the max area of water(blue section) the container can contain is 49. # Example 2: # Input: height = [1, 1] # Output: 1 class Solution: def maxArea(self, height: List[int]) -> int: left, right = 0, len(height)-1 result = 0 while left < right: water = (right-left) * min(height[left], height[right]) if water > result: result = water if height[left] < height[right]: left += 1 else: right -= 1 return result
# 最小差值 #   给定n个数,请找出其中相差(差的绝对值)最小的两个数,输出它们的差值的绝对值。 def st171201(): n= int(input()) numbers = list(map(int, input().split())) numbers.sort() # print(numbers) before=numbers[1] temp = abs(before-numbers[0]) for i in numbers[2:]: # print(temp,before,i,abs(i-before)) if abs(i-before) < temp: temp=abs(i-before) before=i print(temp) if __name__ == '__main__': st171201()
# server backend server = 'cherrypy' # debug error messages debug = False # auto-reload reloader = False # database url db_url = 'postgresql://user:pass@localhost/dbname' # echo database engine messages db_echo = False
#decorators def decorator(myfunc): def wrapper(*args): return myfunc(*args) return wrapper @decorator def display(): print('display function') @decorator def info(name, age): print('name is {} and age is {}'.format(name,age)) info('john', 23) #hi = decorator(display) #hi() display()
def connected_tree(n, edge_list): current_edges = len(edge_list) edges_needed = (n-1) - current_edges return edges_needed def main(): with open('datasets/rosalind_tree.txt') as input_file: input_data = input_file.read().strip().split('\n') n = int(input_data.pop(0)) edge_list = list(map(int,edge.split()) for edge in input_data) edges_needed = connected_tree(n, edge_list) print(str(edges_needed)) with open('solutions/rosalind_tree.txt', 'w') as output_file: output_file.write(str(edges_needed)) if(__name__=='__main__'): main()
#============================================================================= # # JDI Unit Tests # #============================================================================= """ JDI Unit Tests ============== Run all unit tests from project's root directory. python -m unittest discover python3 -m unittest discover """ __version__ = '0.0.0'
#Задача 3. Вариант 1. #Напишите программу, которая выводит имя "Иво Ливи", и запрашивает его псевдоним. Программа должна сцеплять две эти строки и выводить полученную строку, разделяя имя и псевдоним с помощью тире. name=input('Герой нашей сегодняшней программы - Иво Ливи. \nПод каким же именем мы знаем этого человека? ') print('Ваш ответ: ', name) print('Все верно: Иво Ливи - ', name) input('Нажмите Enter') #Abdrahmanova G. I. #7.03.2016
# 魔术师 def show_magicians(magicians): for magician in magicians: print('magician\'s name is ' + magician) def make_great(magicians): i = 0 for item in magicians: magicians[i] = 'The Great ' + item i = i + 1 magicians = ['singi', 'sunjun'] make_great(magicians) show_magicians(magicians)
# # Author    : Manuel Bernal Llinares # Project   : trackhub-creator # Timestamp : 11-09-2017 11:10 # --- # © 2017 Manuel Bernal Llinares <mbdebian@gmail.com> # All rights reserved. # """ Configuration Manager for this HPC Module """ if __name__ == '__main__': print("ERROR: This script is part of a pipeline collection and it is not meant to be run in stand alone mode")
# Released under the MIT License. See LICENSE for details. # # This file was automatically generated from "rampage.ma" # pylint: disable=all points = {} # noinspection PyDictCreation boxes = {} boxes['area_of_interest_bounds'] = (0.3544110667, 5.616383286, -4.066055072) + (0.0, 0.0, 0.0) + ( 19.90053969, 10.34051135, 8.16221072) boxes['edge_box'] = (0.3544110667, 5.438284793, -4.100357672) + ( 0.0, 0.0, 0.0) + (12.57718032, 4.645176013, 3.605557343) points['ffa_spawn1'] = (0.5006944438, 5.051501304, -5.79356326) + (6.626174027, 1.0, 0.3402012662) points['ffa_spawn2'] = (0.5006944438, 5.051501304, -2.435321368) + (6.626174027, 1.0, 0.3402012662) points['flag1'] = (-5.885814199, 5.112162255, -4.251754911) points['flag2'] = (6.700855451, 5.10270501, -4.259912982) points['flag_default'] = (0.3196701116, 5.110914413, -4.292515158) boxes['map_bounds'] = (0.4528955042, 4.899663734, -3.543675157) + ( 0.0, 0.0, 0.0) + (23.54502348, 14.19991443, 12.08017448) points['powerup_spawn1'] = (-2.645358507, 6.426340583, -4.226597191) points['powerup_spawn2'] = (3.540102796, 6.549722855, -4.198476335) points['shadow_lower_bottom'] = (5.580073911, 3.136491026, 5.341226521) points['shadow_lower_top'] = (5.580073911, 4.321758709, 5.341226521) points['shadow_upper_bottom'] = (5.274539479, 8.425373402, 5.341226521) points['shadow_upper_top'] = (5.274539479, 11.93458162, 5.341226521) points['spawn1'] = (-4.745706238, 5.051501304, -4.247934288) + (0.9186962739, 1.0, 0.5153189341) points['spawn2'] = (5.838590388, 5.051501304, -4.259627405) + (0.9186962739, 1.0, 0.5153189341)
# -*- coding: utf-8 -*- # see LICENSE.rst """Basic Astronomy Functions. .. todo:: change this to C / pyx. whatever astropy's preferred C thing is. """ __author__ = "" # __copyright__ = "Copyright 2018, " # __credits__ = [""] # __license__ = "" # __version__ = "0.0.0" # __maintainer__ = "" # __email__ = "" # __status__ = "Production" # __all__ = [ # "" # ] ############################################################################## # IMPORTS # BUILT IN # THIRD PARTY # PROJECT-SPECIFIC ############################################################################## # END
"""The bias-variance tradeoff Often, researchers use the terms "bias" and "variance" or "bias- variance tradeoff" to describe the performance of a model—that is, you may stumble upon talks, books, or articles where people say that a model has a "high variance" or "high bias." So, what does that mean? In general, we might say that "high variance" is proportional to overfitting and "high bias" is proportional to underfitting. In the context of machine learning models, variance measures the consistency (or variability) of the model prediction for classifying a particular example if we retrain the model multiple times, for example, on different subsets of the training dataset. We can say that the model is sensitive to the randomness in the training data. In contrast, bias measures how far off the predictions are from the correct values in general if we rebuild the model multiple times on different training datasets; bias is the measure of the systematic error that is not due to randomness. Accurate definitions can be found in below link: https://sebastianraschka.com/pdf/lecture-notes/stat479fs18/08_eval-intro_notes.pdf """
# # PySNMP MIB module HPN-ICF-8021PAE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-8021PAE-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:24:57 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint") hpnicfRhw, = mibBuilder.importSymbols("HPN-ICF-OID-MIB", "hpnicfRhw") dot1xPaePortNumber, = mibBuilder.importSymbols("IEEE8021-PAE-MIB", "dot1xPaePortNumber") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Integer32, Bits, Counter64, Unsigned32, Counter32, ObjectIdentity, iso, NotificationType, MibIdentifier, Gauge32, IpAddress, TimeTicks, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "Bits", "Counter64", "Unsigned32", "Counter32", "ObjectIdentity", "iso", "NotificationType", "MibIdentifier", "Gauge32", "IpAddress", "TimeTicks", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn") TextualConvention, MacAddress, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "MacAddress", "DisplayString") hpnicfpaeExtMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 8, 6)) hpnicfpaeExtMib.setRevisions(('2001-06-29 00:00',)) if mibBuilder.loadTexts: hpnicfpaeExtMib.setLastUpdated('200106290000Z') if mibBuilder.loadTexts: hpnicfpaeExtMib.setOrganization('') hpnicfpaeExtMibObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 8, 6, 1)) hpnicfdot1xPaeSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 8, 6, 1, 1)) hpnicfdot1xPaeAuthenticator = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 8, 6, 1, 2)) hpnicfdot1xAuthQuietPeriod = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 8, 6, 1, 1, 1), Unsigned32().clone(60)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfdot1xAuthQuietPeriod.setStatus('current') hpnicfdot1xAuthTxPeriod = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 8, 6, 1, 1, 2), Unsigned32().clone(30)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfdot1xAuthTxPeriod.setStatus('current') hpnicfdot1xAuthSuppTimeout = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 8, 6, 1, 1, 3), Unsigned32().clone(30)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfdot1xAuthSuppTimeout.setStatus('current') hpnicfdot1xAuthServerTimeout = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 8, 6, 1, 1, 4), Unsigned32().clone(100)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfdot1xAuthServerTimeout.setStatus('current') hpnicfdot1xAuthMaxReq = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 8, 6, 1, 1, 5), Unsigned32().clone(2)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfdot1xAuthMaxReq.setStatus('current') hpnicfdot1xAuthReAuthPeriod = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 8, 6, 1, 1, 6), Unsigned32().clone(3600)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfdot1xAuthReAuthPeriod.setStatus('current') hpnicfdot1xAuthMethod = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 8, 6, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("chap", 1), ("pap", 2), ("eap", 3))).clone(1)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfdot1xAuthMethod.setStatus('current') hpnicfdot1xAuthConfigExtTable = MibTable((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 8, 6, 1, 2, 1), ) if mibBuilder.loadTexts: hpnicfdot1xAuthConfigExtTable.setStatus('current') hpnicfdot1xAuthConfigExtEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 8, 6, 1, 2, 1, 1), ).setIndexNames((0, "IEEE8021-PAE-MIB", "dot1xPaePortNumber")) if mibBuilder.loadTexts: hpnicfdot1xAuthConfigExtEntry.setStatus('current') hpnicfdot1xpaeportAuthAdminStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 8, 6, 1, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(2)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfdot1xpaeportAuthAdminStatus.setStatus('current') hpnicfdot1xpaeportControlledType = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 8, 6, 1, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("port", 1), ("mac", 2))).clone(2)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfdot1xpaeportControlledType.setStatus('current') hpnicfdot1xpaeportMaxUserNum = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 8, 6, 1, 2, 1, 1, 3), Integer32().clone(256)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfdot1xpaeportMaxUserNum.setStatus('current') hpnicfdot1xpaeportUserNumNow = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 8, 6, 1, 2, 1, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hpnicfdot1xpaeportUserNumNow.setStatus('current') hpnicfdot1xpaeportClearStatistics = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 8, 6, 1, 2, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1))).clone(namedValues=NamedValues(("clear", 1)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfdot1xpaeportClearStatistics.setStatus('current') hpnicfdot1xpaeportMcastTrigStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 8, 6, 1, 2, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(1)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfdot1xpaeportMcastTrigStatus.setStatus('current') hpnicfdot1xpaeportHandshakeStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 8, 6, 1, 2, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone(1)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfdot1xpaeportHandshakeStatus.setStatus('current') hpnicfdot1xPaeTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 8, 6, 1, 0)) hpnicfsupplicantproxycheck = NotificationType((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 8, 6, 1, 0, 1)).setObjects(("HPN-ICF-8021PAE-MIB", "hpnicfproxycheckVlanId"), ("HPN-ICF-8021PAE-MIB", "hpnicfproxycheckPortName"), ("HPN-ICF-8021PAE-MIB", "hpnicfproxycheckMacAddr"), ("HPN-ICF-8021PAE-MIB", "hpnicfproxycheckIpaddr"), ("HPN-ICF-8021PAE-MIB", "hpnicfproxycheckUsrName")) if mibBuilder.loadTexts: hpnicfsupplicantproxycheck.setStatus('current') hpnicfproxycheckVlanId = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 8, 6, 1, 0, 2), Integer32()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: hpnicfproxycheckVlanId.setStatus('current') hpnicfproxycheckPortName = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 8, 6, 1, 0, 3), OctetString()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: hpnicfproxycheckPortName.setStatus('current') hpnicfproxycheckMacAddr = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 8, 6, 1, 0, 4), MacAddress()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: hpnicfproxycheckMacAddr.setStatus('current') hpnicfproxycheckIpaddr = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 8, 6, 1, 0, 5), IpAddress()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: hpnicfproxycheckIpaddr.setStatus('current') hpnicfproxycheckUsrName = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 8, 6, 1, 0, 6), OctetString()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: hpnicfproxycheckUsrName.setStatus('current') mibBuilder.exportSymbols("HPN-ICF-8021PAE-MIB", hpnicfpaeExtMibObjects=hpnicfpaeExtMibObjects, hpnicfpaeExtMib=hpnicfpaeExtMib, hpnicfdot1xAuthServerTimeout=hpnicfdot1xAuthServerTimeout, hpnicfproxycheckUsrName=hpnicfproxycheckUsrName, hpnicfsupplicantproxycheck=hpnicfsupplicantproxycheck, hpnicfproxycheckMacAddr=hpnicfproxycheckMacAddr, PYSNMP_MODULE_ID=hpnicfpaeExtMib, hpnicfdot1xAuthMethod=hpnicfdot1xAuthMethod, hpnicfdot1xpaeportMcastTrigStatus=hpnicfdot1xpaeportMcastTrigStatus, hpnicfdot1xPaeAuthenticator=hpnicfdot1xPaeAuthenticator, hpnicfdot1xPaeSystem=hpnicfdot1xPaeSystem, hpnicfdot1xPaeTraps=hpnicfdot1xPaeTraps, hpnicfdot1xAuthReAuthPeriod=hpnicfdot1xAuthReAuthPeriod, hpnicfdot1xAuthConfigExtEntry=hpnicfdot1xAuthConfigExtEntry, hpnicfdot1xpaeportControlledType=hpnicfdot1xpaeportControlledType, hpnicfdot1xAuthSuppTimeout=hpnicfdot1xAuthSuppTimeout, hpnicfproxycheckVlanId=hpnicfproxycheckVlanId, hpnicfdot1xpaeportClearStatistics=hpnicfdot1xpaeportClearStatistics, hpnicfdot1xAuthTxPeriod=hpnicfdot1xAuthTxPeriod, hpnicfdot1xAuthMaxReq=hpnicfdot1xAuthMaxReq, hpnicfproxycheckIpaddr=hpnicfproxycheckIpaddr, hpnicfproxycheckPortName=hpnicfproxycheckPortName, hpnicfdot1xAuthConfigExtTable=hpnicfdot1xAuthConfigExtTable, hpnicfdot1xpaeportUserNumNow=hpnicfdot1xpaeportUserNumNow, hpnicfdot1xpaeportMaxUserNum=hpnicfdot1xpaeportMaxUserNum, hpnicfdot1xAuthQuietPeriod=hpnicfdot1xAuthQuietPeriod, hpnicfdot1xpaeportHandshakeStatus=hpnicfdot1xpaeportHandshakeStatus, hpnicfdot1xpaeportAuthAdminStatus=hpnicfdot1xpaeportAuthAdminStatus)
# 44. Wildcard Matching # # Implement wildcard pattern matching with support for '?' and '*'. # # '?' Matches any single character. # '*' Matches any sequence of characters (including the empty sequence). # # The matching should cover the entire input string (not partial). # # The function prototype should be: # bool isMatch(const char *s, const char *p) # # Some examples: # isMatch("aa","a") → false # isMatch("aa","aa") → true # isMatch("aaa","aa") → false # isMatch("aa", "*") → true # isMatch("aa", "a*") → true # isMatch("ab", "?*") → true # isMatch("aab", "c*a*b") → false class Solution: # @param {string} s # @param {string} p # @return {boolean} # # http://www.voidcn.com/article/p-hgfivloj-bhv.html def isMatch(self, s, p): i = 0 j = 0 sstar = 0 star = -1 while i < len(s): # compare ? or whether they are the same if j < len(p) and (s[i] == p[i] or p[j] == '?'): i += 1 j += 1 # if there is a * in p we mark current j and i elif j < len(p) and p[j] == '*': star = j j += 1 sstar = i # if current p[j] is not * we check whether prior state has * elif star != -1: j = star + 1 sstar += 1 i = sstar else: return False while j < len(p) and p[j] == '*': j += 1 # return j == len(p) if j == len(p): return True return False print(Solution().isMatch("ab", "?*"))
class SchemaError(Exception): def __init__(self, schema, code): self.schema = schema self.code = code msg = schema.errors[code].format(**schema.__dict__) super().__init__(msg) class NoCurrentApp(Exception): pass class ConfigurationError(Exception): pass
__author__ = "Wild Print" __maintainer__ = __author__ __email__ = "telegram_coin_bot@rambler.ru" __license__ = "MIT" __version__ = "0.0.1" __all__ = ( "__author__", "__email__", "__license__", "__maintainer__", "__version__", )
TT_INT = 'INT' # int TT_FLOAT = 'FLOAT' # float TT_STRING = 'STRING' # string TT_IDENTIFIER = 'IDENTIFIER' # 变量 TT_KEYWORD = 'KEYWORD' # 关键字 TT_PLUS = 'PLUS' # + TT_MINUS = 'MINUS' # - TT_MUL = 'MUL' # * TT_DIV = 'DIV' # / TT_POW = 'POW' # ^ TT_EQ = 'EQ' # = TT_LPAREN = 'LPAREN' # ( TT_RPAREN = 'RPAREN' # ) TT_LSQUARE = 'LSQUARE' TT_RSQUARE = 'RSQUARE' TT_EE = 'EE' # == TT_NE = 'NE' # != TT_LT = 'LT' # > TT_GT = 'GT' # < TT_LTE = 'LTE' # >= TT_GTE = 'GTE' # <= TT_COMMA = 'COMMA' TT_ARROW = 'ARROW' TT_NEWLINE = 'NEWLINE' TT_EOF = 'EOF' KEYWORDS = [ 'VAR', 'AND', 'OR', 'NOT', 'IF', 'ELIF', 'ELSE', 'FOR', 'TO', 'STEP', 'WHILE', 'FUN', 'THEN', 'END', 'RETURN', # 拥有净身出户的权力 'CONTINUE', 'BREAK', ] class Token: def __init__(self, type_, value=None, pos_start=None, pos_end=None): # 可选参数 value, pos_start, pos_end self.type = type_ self.value = value # 若没有传入 pos_end,比如 1,此时 pos_start == 1 且 pos_end == 1 if pos_start: self.pos_start = pos_start.copy() # 调用 copy 方法 self.pos_end = pos_start.copy() self.pos_end.advance() if pos_end: self.pos_end = pos_end.copy() # 判断 type-value 是否一致 def matches(self, type_, value): return self.type == type_ and self.value == value def __repr__(self): if self.value: return f'{self.type}:{self.value}' return f'{self.type}'
''' Created on Oct 10, 2012 @author: Brian Jimenez-Garcia @contact: brian.jimenez@bsc.es ''' class Color: def __init__(self, red=0., green=0., blue=0., alpha=1.0): self.__red = red self.__green = green self.__blue = blue self.__alpha = alpha def get_rgba(self): return self.__red, self.__green, self.__blue, self.__alpha def get_red(self): return self.__red def get_blue(self): return self.__blue def get_green(self): return self.__green def get_alpha(self): return self.__alpha # Useful predefined colors White = Color(1.0, 1.0, 1.0, 1.0) Black = Color(0.0, 0.0, 0.0, 1.0) Carbon = Color(0.17, 0.17, 0.18, 1.0) Red = Color(0.95, 0.03, 0.01, 1.0) Blue = Color(0.01, 0.03, 0.95, 1.0) Sky = Color(0.233, 0.686, 1.0, 1.0) Yellow = Color(1.0, 1.0, 0.0, 1.0) Green = Color(0.0, 0.53, 0.0, 1.0) Pink = Color(0.53, 0.12, 0.36, 1.0) DarkRed = Color(0.59, 0.13, 0.0, 1.0) Violet = Color(0.46, 0.0, 1.0, 1.0) DarkViolet = Color(0.39, 0.0, 0.73, 1.0) Cyan = Color(0.0, 1.0, 1.0, 1.0) Orange = Color(1.0, 0.59, 0.0, 1.0) Peach = Color(1.0, 0.66, 0.46, 1.0) DarkGreen = Color(0.0, 0.46, 0.0, 1.0) Gray = Color(0.59, 0.59, 0.59, 1.0) DarkOrange = Color(0.86, 0.46, 0.0, 1.0)
__COL_GOOD = '\033[32m' __COL_FAIL = '\033[31m' __COL_INFO = '\033[34m' __COL_BOLD = '\033[1m' __COL_ULIN = '\033[4m' __COL_ENDC = '\033[0m' def __TEST__(status, msg, color, args): args = ", ".join([str(key)+'='+str(args[key]) for key in args.keys()]) if args: args = "(" + args + ")" return "[{color}{status}{end}] {msg} {args}".format( color=color, status=status, end=__COL_ENDC, msg=msg, args=args ) def SUCCESS(test_name, **kwargs): msg = "Test {tname} passed.".format(tname=test_name) return __TEST__('PASS', msg, __COL_GOOD, kwargs) def FAILURE(test_name, **kwargs): msg = "Test {tname} failed.".format(tname=test_name) return __TEST__('FAIL', msg, __COL_FAIL, kwargs) def ANSI_wrapper(prefix): def inner(message): return prefix + message + __COL_ENDC return inner def truncate_repr(val, priority=None): if priority and isinstance(val, dict): val_copy = dict(val) output = '{' for k, v in priority.items(): output += "%s, %s" % (k, v) val_copy.pop(k) output += ", " + str(val_copy)[1:] else: output = str(val) if len(output) <= 64: return output output = output[:64] if isinstance(val, dict): output += "...}" elif isinstance(val, list): output += "...]" return output INFO = ANSI_wrapper(__COL_INFO) BOLD = ANSI_wrapper(__COL_BOLD) UNDERLINE = ANSI_wrapper(__COL_ULIN)
""" Funções (def) - *args **kwargs """ # def func(a1, a2, a3, a4, a5, nome=None, a6=None): # print(a1, a2, a3, a4, a5, nome, a6) def func(*args, **kwargs): print(args, kwargs) lista = [1, 2, 3, 4, 5] func(*lista, nome='João')
class Contract: """ Model class representing a Cisco ACI Contract """ def __init__(self, uid, name, dn): self.uid = uid self.name = name self.dn = dn def equals(self, con): return self.dn == con.dn
"""Routes and URIs.""" def includeme(config): """Add routes and their URIs.""" config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.add_route('about', '/about') config.add_route('details', '/journal/{id:\d+}') config.add_route('create', '/journal/new-entry') config.add_route('update', '/journal/{id:\d+}/edit-entry') config.add_route('delete', '/journal/{id:\d+}/delete')
def find_metric_transformation_by_name(metric_transformations, metric_name): for metric in metric_transformations: if metric["metricName"] == metric_name: return metric def find_metric_transformation_by_namespace(metric_transformations, metric_namespace): for metric in metric_transformations: if metric["metricNamespace"] == metric_namespace: return metric class MetricFilters: def __init__(self): self.metric_filters = [] def add_filter( self, filter_name, filter_pattern, log_group_name, metric_transformations ): self.metric_filters.append( { "filterName": filter_name, "filterPattern": filter_pattern, "logGroupName": log_group_name, "metricTransformations": metric_transformations, } ) def get_matching_filters( self, prefix=None, log_group_name=None, metric_name=None, metric_namespace=None ): result = [] for f in self.metric_filters: prefix_matches = prefix is None or f["filterName"].startswith(prefix) log_group_matches = ( log_group_name is None or f["logGroupName"] == log_group_name ) metric_name_matches = ( metric_name is None or find_metric_transformation_by_name( f["metricTransformations"], metric_name ) ) namespace_matches = ( metric_namespace is None or find_metric_transformation_by_namespace( f["metricTransformations"], metric_namespace ) ) if ( prefix_matches and log_group_matches and metric_name_matches and namespace_matches ): result.append(f) return result def delete_filter(self, filter_name=None, log_group_name=None): for f in self.metric_filters: if f["filterName"] == filter_name and f["logGroupName"] == log_group_name: self.metric_filters.remove(f) return self.metric_filters
# (C) Datadog, Inc. 2020-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) # metrics namespaced under 'scylla' SCYLLA_ALIEN = { 'scylla_alien_receive_batch_queue_length': 'alien.receive_batch_queue_length', 'scylla_alien_total_received_messages': 'alien.total_received_messages', 'scylla_alien_total_sent_messages': 'alien.total_sent_messages', } SCYLLA_BATCHLOG = { 'scylla_batchlog_manager_total_write_replay_attempts': 'batchlog_manager.total_write_replay_attempts', } SCYLLA_CACHE = { 'scylla_cache_active_reads': 'cache.active_reads', 'scylla_cache_bytes_total': 'cache.bytes_total', 'scylla_cache_bytes_used': 'cache.bytes_used', 'scylla_cache_concurrent_misses_same_key': 'cache.concurrent_misses_same_key', 'scylla_cache_mispopulations': 'cache.mispopulations', 'scylla_cache_partition_evictions': 'cache.partition_evictions', 'scylla_cache_partition_hits': 'cache.partition_hits', 'scylla_cache_partition_insertions': 'cache.partition_insertions', 'scylla_cache_partition_merges': 'cache.partition_merges', 'scylla_cache_partition_misses': 'cache.partition_misses', 'scylla_cache_partition_removals': 'cache.partition_removals', 'scylla_cache_partitions': 'cache.partitions', 'scylla_cache_pinned_dirty_memory_overload': 'cache.pinned_dirty_memory_overload', 'scylla_cache_reads': 'cache.reads', 'scylla_cache_reads_with_misses': 'cache.reads_with_misses', 'scylla_cache_row_evictions': 'cache.row_evictions', 'scylla_cache_row_hits': 'cache.row_hits', 'scylla_cache_row_insertions': 'cache.row_insertions', 'scylla_cache_row_misses': 'cache.row_misses', 'scylla_cache_row_removals': 'cache.row_removals', 'scylla_cache_rows': 'cache.rows', 'scylla_cache_rows_dropped_from_memtable': 'cache.rows_dropped_from_memtable', 'scylla_cache_rows_merged_from_memtable': 'cache.rows_merged_from_memtable', 'scylla_cache_rows_processed_from_memtable': 'cache.rows_processed_from_memtable', 'scylla_cache_sstable_partition_skips': 'cache.sstable_partition_skips', 'scylla_cache_sstable_reader_recreations': 'cache.sstable_reader_recreations', 'scylla_cache_sstable_row_skips': 'cache.sstable_row_skips', 'scylla_cache_static_row_insertions': 'cache.static_row_insertions', } SCYLLA_COMMITLOG = { 'scylla_commitlog_alloc': 'commitlog.alloc', 'scylla_commitlog_allocating_segments': 'commitlog.allocating_segments', 'scylla_commitlog_bytes_written': 'commitlog.bytes_written', 'scylla_commitlog_cycle': 'commitlog.cycle', 'scylla_commitlog_disk_total_bytes': 'commitlog.disk_total_bytes', 'scylla_commitlog_flush': 'commitlog.flush', 'scylla_commitlog_flush_limit_exceeded': 'commitlog.flush_limit_exceeded', 'scylla_commitlog_memory_buffer_bytes': 'commitlog.memory_buffer_bytes', 'scylla_commitlog_pending_allocations': 'commitlog.pending_allocations', 'scylla_commitlog_pending_flushes': 'commitlog.pending_flushes', 'scylla_commitlog_requests_blocked_memory': 'commitlog.requests_blocked_memory', 'scylla_commitlog_segments': 'commitlog.segments', 'scylla_commitlog_slack': 'commitlog.slack', 'scylla_commitlog_unused_segments': 'commitlog.unused_segments', } SCYLLA_COMPACTION = { 'scylla_compaction_manager_compactions': 'compaction_manager.compactions', } SCYLLA_CQL = { 'scylla_cql_authorized_prepared_statements_cache_evictions': 'cql.authorized_prepared_statements_cache_evictions', 'scylla_cql_authorized_prepared_statements_cache_size': 'cql.authorized_prepared_statements_cache_size', 'scylla_cql_batches': 'cql.batches', 'scylla_cql_batches_pure_logged': 'cql.batches_pure_logged', 'scylla_cql_batches_pure_unlogged': 'cql.batches_pure_unlogged', 'scylla_cql_batches_unlogged_from_logged': 'cql.batches_unlogged_from_logged', 'scylla_cql_deletes': 'cql.deletes', 'scylla_cql_filtered_read_requests': 'cql.filtered_read_requests', 'scylla_cql_filtered_rows_dropped_total': 'cql.filtered_rows_dropped_total', 'scylla_cql_filtered_rows_matched_total': 'cql.filtered_rows_matched_total', 'scylla_cql_filtered_rows_read_total': 'cql.filtered_rows_read_total', 'scylla_cql_inserts': 'cql.inserts', 'scylla_cql_prepared_cache_evictions': 'cql.prepared_cache_evictions', 'scylla_cql_prepared_cache_memory_footprint': 'cql.prepared_cache_memory_footprint', 'scylla_cql_prepared_cache_size': 'cql.prepared_cache_size', 'scylla_cql_reads': 'cql.reads', 'scylla_cql_reverse_queries': 'cql.reverse_queries', 'scylla_cql_rows_read': 'cql.rows_read', 'scylla_cql_secondary_index_creates': 'cql.secondary_index_creates', 'scylla_cql_secondary_index_drops': 'cql.secondary_index_drops', 'scylla_cql_secondary_index_reads': 'cql.secondary_index_reads', 'scylla_cql_secondary_index_rows_read': 'cql.secondary_index_rows_read', 'scylla_cql_statements_in_batches': 'cql.statements_in_batches', 'scylla_cql_unpaged_select_queries': 'cql.unpaged_select_queries', 'scylla_cql_updates': 'cql.updates', 'scylla_cql_user_prepared_auth_cache_footprint': 'cql.user_prepared_auth_cache_footprint', } SCYLLA_DATABASE = { 'scylla_database_active_reads': 'database.active_reads', 'scylla_database_active_reads_memory_consumption': 'database.active_reads_memory_consumption', 'scylla_database_clustering_filter_count': 'database.clustering_filter_count', 'scylla_database_clustering_filter_fast_path_count': 'database.clustering_filter_fast_path_count', 'scylla_database_clustering_filter_sstables_checked': 'database.clustering_filter_sstables_checked', 'scylla_database_clustering_filter_surviving_sstables': 'database.clustering_filter_surviving_sstables', 'scylla_database_counter_cell_lock_acquisition': 'database.counter_cell_lock_acquisition', 'scylla_database_counter_cell_lock_pending': 'database.counter_cell_lock_pending', 'scylla_database_dropped_view_updates': 'database.dropped_view_updates', 'scylla_database_large_partition_exceeding_threshold': 'database.large_partition_exceeding_threshold', 'scylla_database_multishard_query_failed_reader_saves': 'database.multishard_query_failed_reader_saves', 'scylla_database_multishard_query_failed_reader_stops': 'database.multishard_query_failed_reader_stops', 'scylla_database_multishard_query_unpopped_bytes': 'database.multishard_query_unpopped_bytes', 'scylla_database_multishard_query_unpopped_fragments': 'database.multishard_query_unpopped_fragments', 'scylla_database_paused_reads': 'database.paused_reads', 'scylla_database_paused_reads_permit_based_evictions': 'database.paused_reads_permit_based_evictions', 'scylla_database_querier_cache_drops': 'database.querier_cache_drops', 'scylla_database_querier_cache_lookups': 'database.querier_cache_lookups', 'scylla_database_querier_cache_memory_based_evictions': 'database.querier_cache_memory_based_evictions', 'scylla_database_querier_cache_misses': 'database.querier_cache_misses', 'scylla_database_querier_cache_population': 'database.querier_cache_population', 'scylla_database_querier_cache_resource_based_evictions': 'database.querier_cache_resource_based_evictions', 'scylla_database_querier_cache_time_based_evictions': 'database.querier_cache_time_based_evictions', 'scylla_database_queued_reads': 'database.queued_reads', 'scylla_database_requests_blocked_memory': 'database.requests_blocked_memory', 'scylla_database_requests_blocked_memory_current': 'database.requests_blocked_memory_current', 'scylla_database_short_data_queries': 'database.short_data_queries', 'scylla_database_short_mutation_queries': 'database.short_mutation_queries', 'scylla_database_sstable_read_queue_overloads': 'database.sstable_read_queue_overloads', 'scylla_database_total_reads': 'database.total_reads', 'scylla_database_total_reads_failed': 'database.total_reads_failed', 'scylla_database_total_result_bytes': 'database.total_result_bytes', 'scylla_database_total_view_updates_failed_local': 'database.total_view_updates_failed_local', 'scylla_database_total_view_updates_failed_remote': 'database.total_view_updates_failed_remote', 'scylla_database_total_view_updates_pushed_local': 'database.total_view_updates_pushed_local', 'scylla_database_total_view_updates_pushed_remote': 'database.total_view_updates_pushed_remote', 'scylla_database_total_writes': 'database.total_writes', 'scylla_database_total_writes_failed': 'database.total_writes_failed', 'scylla_database_total_writes_timedout': 'database.total_writes_timedout', 'scylla_database_view_building_paused': 'database.view_building_paused', 'scylla_database_view_update_backlog': 'database.view_update_backlog', } SCYLLA_EXECUTION = { 'scylla_execution_stages_function_calls_enqueued': 'execution_stages.function_calls_enqueued', 'scylla_execution_stages_function_calls_executed': 'execution_stages.function_calls_executed', 'scylla_execution_stages_tasks_preempted': 'execution_stages.tasks_preempted', 'scylla_execution_stages_tasks_scheduled': 'execution_stages.tasks_scheduled', } SCYLLA_GOSSIP = { 'scylla_gossip_heart_beat': 'gossip.heart_beat', } SCYLLA_HINTS = { 'scylla_hints_for_views_manager_corrupted_files': 'hints.for_views_manager_corrupted_files', 'scylla_hints_for_views_manager_discarded': 'hints.for_views_manager_discarded', 'scylla_hints_for_views_manager_dropped': 'hints.for_views_manager_dropped', 'scylla_hints_for_views_manager_errors': 'hints.for_views_manager_errors', 'scylla_hints_for_views_manager_sent': 'hints.for_views_manager_sent', 'scylla_hints_for_views_manager_size_of_hints_in_progress': 'hints.for_views_manager_size_of_hints_in_progress', 'scylla_hints_for_views_manager_written': 'hints.for_views_manager_written', 'scylla_hints_manager_corrupted_files': 'hints.manager_corrupted_files', 'scylla_hints_manager_discarded': 'hints.manager_discarded', 'scylla_hints_manager_dropped': 'hints.manager_dropped', 'scylla_hints_manager_errors': 'hints.manager_errors', 'scylla_hints_manager_sent': 'hints.manager_sent', 'scylla_hints_manager_size_of_hints_in_progress': 'hints.manager_size_of_hints_in_progress', 'scylla_hints_manager_written': 'hints.manager_written', } SCYLLA_HTTPD = { 'scylla_httpd_connections_current': 'httpd.connections_current', 'scylla_httpd_connections_total': 'httpd.connections_total', 'scylla_httpd_read_errors': 'httpd.read_errors', 'scylla_httpd_reply_errors': 'httpd.reply_errors', 'scylla_httpd_requests_served': 'httpd.requests_served', } SCYLLA_IO = { 'scylla_io_queue_delay': 'io_queue.delay', 'scylla_io_queue_queue_length': 'io_queue.queue_length', 'scylla_io_queue_shares': 'io_queue.shares', 'scylla_io_queue_total_bytes': 'io_queue.total_bytes', 'scylla_io_queue_total_operations': 'io_queue.total_operations', } SCYLLA_LSA = { 'scylla_lsa_free_space': 'lsa.free_space', 'scylla_lsa_large_objects_total_space_bytes': 'lsa.large_objects_total_space_bytes', 'scylla_lsa_memory_allocated': 'lsa.memory_allocated', 'scylla_lsa_memory_compacted': 'lsa.memory_compacted', 'scylla_lsa_non_lsa_used_space_bytes': 'lsa.non_lsa_used_space_bytes', 'scylla_lsa_occupancy': 'lsa.occupancy', 'scylla_lsa_segments_compacted': 'lsa.segments_compacted', 'scylla_lsa_segments_migrated': 'lsa.segments_migrated', 'scylla_lsa_small_objects_total_space_bytes': 'lsa.small_objects_total_space_bytes', 'scylla_lsa_small_objects_used_space_bytes': 'lsa.small_objects_used_space_bytes', 'scylla_lsa_total_space_bytes': 'lsa.total_space_bytes', 'scylla_lsa_used_space_bytes': 'lsa.used_space_bytes', } SCYLLA_MEMORY = { 'scylla_memory_allocated_memory': 'memory.allocated_memory', 'scylla_memory_cross_cpu_free_operations': 'memory.cross_cpu_free_operations', 'scylla_memory_dirty_bytes': 'memory.dirty_bytes', 'scylla_memory_free_memory': 'memory.free_memory', 'scylla_memory_free_operations': 'memory.free_operations', 'scylla_memory_malloc_live_objects': 'memory.malloc_live_objects', 'scylla_memory_malloc_operations': 'memory.malloc_operations', 'scylla_memory_reclaims_operations': 'memory.reclaims_operations', 'scylla_memory_regular_dirty_bytes': 'memory.regular_dirty_bytes', 'scylla_memory_regular_virtual_dirty_bytes': 'memory.regular_virtual_dirty_bytes', 'scylla_memory_streaming_dirty_bytes': 'memory.streaming_dirty_bytes', 'scylla_memory_streaming_virtual_dirty_bytes': 'memory.streaming_virtual_dirty_bytes', 'scylla_memory_system_dirty_bytes': 'memory.system_dirty_bytes', 'scylla_memory_system_virtual_dirty_bytes': 'memory.system_virtual_dirty_bytes', 'scylla_memory_total_memory': 'memory.total_memory', 'scylla_memory_virtual_dirty_bytes': 'memory.virtual_dirty_bytes', } SCYLLA_MEMTABLES = { 'scylla_memtables_pending_flushes': 'memtables.pending_flushes', 'scylla_memtables_pending_flushes_bytes': 'memtables.pending_flushes_bytes', } SCYLLA_NODE = { 'scylla_node_operation_mode': 'node.operation_mode', } SCYLLA_QUERY = { 'scylla_query_processor_queries': 'query_processor.queries', 'scylla_query_processor_statements_prepared': 'query_processor.statements_prepared', } SCYLLA_REACTOR = { 'scylla_reactor_aio_bytes_read': 'reactor.aio_bytes_read', 'scylla_reactor_aio_bytes_write': 'reactor.aio_bytes_write', 'scylla_reactor_aio_errors': 'reactor.aio_errors', 'scylla_reactor_aio_reads': 'reactor.aio_reads', 'scylla_reactor_aio_writes': 'reactor.aio_writes', 'scylla_reactor_cpp_exceptions': 'reactor.cpp_exceptions', 'scylla_reactor_cpu_busy_ms': 'reactor.cpu_busy_ms', 'scylla_reactor_cpu_steal_time_ms': 'reactor.cpu_steal_time_ms', 'scylla_reactor_fstream_read_bytes': 'reactor.fstream_read_bytes', 'scylla_reactor_fstream_read_bytes_blocked': 'reactor.fstream_read_bytes_blocked', 'scylla_reactor_fstream_reads': 'reactor.fstream_reads', 'scylla_reactor_fstream_reads_ahead_bytes_discarded': 'reactor.fstream_reads_ahead_bytes_discarded', 'scylla_reactor_fstream_reads_aheads_discarded': 'reactor.fstream_reads_aheads_discarded', 'scylla_reactor_fstream_reads_blocked': 'reactor.fstream_reads_blocked', 'scylla_reactor_fsyncs': 'reactor.fsyncs', 'scylla_reactor_io_queue_requests': 'reactor.io_queue_requests', 'scylla_reactor_io_threaded_fallbacks': 'reactor.io_threaded_fallbacks', 'scylla_reactor_logging_failures': 'reactor.logging_failures', 'scylla_reactor_polls': 'reactor.polls', 'scylla_reactor_tasks_pending': 'reactor.tasks_pending', 'scylla_reactor_tasks_processed': 'reactor.tasks_processed', 'scylla_reactor_timers_pending': 'reactor.timers_pending', 'scylla_reactor_utilization': 'reactor.utilization', } SCYLLA_SCHEDULER = { 'scylla_scheduler_queue_length': 'scheduler.queue_length', 'scylla_scheduler_runtime_ms': 'scheduler.runtime_ms', 'scylla_scheduler_shares': 'scheduler.shares', 'scylla_scheduler_tasks_processed': 'scheduler.tasks_processed', 'scylla_scheduler_time_spent_on_task_quota_violations_ms': 'scheduler.time_spent_on_task_quota_violations_ms', } SCYLLA_SSTABLES = { 'scylla_sstables_capped_local_deletion_time': 'sstables.capped_local_deletion_time', 'scylla_sstables_capped_tombstone_deletion_time': 'sstables.capped_tombstone_deletion_time', 'scylla_sstables_cell_tombstone_writes': 'sstables.cell_tombstone_writes', 'scylla_sstables_cell_writes': 'sstables.cell_writes', 'scylla_sstables_index_page_blocks': 'sstables.index_page_blocks', 'scylla_sstables_index_page_hits': 'sstables.index_page_hits', 'scylla_sstables_index_page_misses': 'sstables.index_page_misses', 'scylla_sstables_partition_reads': 'sstables.partition_reads', 'scylla_sstables_partition_seeks': 'sstables.partition_seeks', 'scylla_sstables_partition_writes': 'sstables.partition_writes', 'scylla_sstables_range_partition_reads': 'sstables.range_partition_reads', 'scylla_sstables_range_tombstone_writes': 'sstables.range_tombstone_writes', 'scylla_sstables_row_reads': 'sstables.row_reads', 'scylla_sstables_row_writes': 'sstables.row_writes', 'scylla_sstables_single_partition_reads': 'sstables.single_partition_reads', 'scylla_sstables_sstable_partition_reads': 'sstables.sstable_partition_reads', 'scylla_sstables_static_row_writes': 'sstables.static_row_writes', 'scylla_sstables_tombstone_writes': 'sstables.tombstone_writes', } SCYLLA_STORAGE = { # Scylla 3.1 'scylla_storage_proxy_coordinator_background_read_repairs': 'storage.proxy.coordinator_background_read_repairs', 'scylla_storage_proxy_coordinator_background_reads': 'storage.proxy.coordinator_background_reads', 'scylla_storage_proxy_coordinator_background_replica_writes_failed_local_node': 'storage.proxy.coordinator_background_replica_writes_failed_local_node', # noqa E501 'scylla_storage_proxy_coordinator_background_write_bytes': 'storage.proxy.coordinator_background_write_bytes', 'scylla_storage_proxy_coordinator_background_writes': 'storage.proxy.coordinator_background_writes', 'scylla_storage_proxy_coordinator_background_writes_failed': 'storage.proxy.coordinator_background_writes_failed', 'scylla_storage_proxy_coordinator_canceled_read_repairs': 'storage.proxy.coordinator_canceled_read_repairs', 'scylla_storage_proxy_coordinator_completed_reads_local_node': 'storage.proxy.coordinator_completed_reads_local_node', # noqa E501 'scylla_storage_proxy_coordinator_current_throttled_base_writes': 'storage.proxy.coordinator_current_throttled_base_writes', # noqa E501 'scylla_storage_proxy_coordinator_current_throttled_writes': 'storage.proxy.coordinator_current_throttled_writes', 'scylla_storage_proxy_coordinator_foreground_read_repair': 'storage.proxy.coordinator_foreground_read_repair', 'scylla_storage_proxy_coordinator_foreground_reads': 'storage.proxy.coordinator_foreground_reads', 'scylla_storage_proxy_coordinator_foreground_writes': 'storage.proxy.coordinator_foreground_writes', 'scylla_storage_proxy_coordinator_last_mv_flow_control_delay': 'storage.proxy.coordinator_last_mv_flow_control_delay', # noqa E501 'scylla_storage_proxy_coordinator_queued_write_bytes': 'storage.proxy.coordinator_queued_write_bytes', 'scylla_storage_proxy_coordinator_range_timeouts': 'storage.proxy.coordinator_range_timeouts', 'scylla_storage_proxy_coordinator_range_unavailable': 'storage.proxy.coordinator_range_unavailable', 'scylla_storage_proxy_coordinator_read_errors_local_node': 'storage.proxy.coordinator_read_errors_local_node', 'scylla_storage_proxy_coordinator_read_latency': 'storage.proxy.coordinator_read_latency', 'scylla_storage_proxy_coordinator_read_repair_write_attempts_local_node': 'storage.proxy.coordinator_read_repair_write_attempts_local_node', # noqa E501 'scylla_storage_proxy_coordinator_read_retries': 'storage.proxy.coordinator_read_retries', 'scylla_storage_proxy_coordinator_read_timeouts': 'storage.proxy.coordinator_read_timeouts', 'scylla_storage_proxy_coordinator_read_unavailable': 'storage.proxy.coordinator_read_unavailable', 'scylla_storage_proxy_coordinator_reads_local_node': 'storage.proxy.coordinator_reads_local_node', 'scylla_storage_proxy_coordinator_speculative_data_reads': 'storage.proxy.coordinator_speculative_data_reads', 'scylla_storage_proxy_coordinator_speculative_digest_reads': 'storage.proxy.coordinator_speculative_digest_reads', 'scylla_storage_proxy_coordinator_throttled_writes': 'storage.proxy.coordinator_throttled_writes', 'scylla_storage_proxy_coordinator_total_write_attempts_local_node': 'storage.proxy.coordinator_total_write_attempts_local_node', # noqa E501 'scylla_storage_proxy_coordinator_write_errors_local_node': 'storage.proxy.coordinator_write_errors_local_node', 'scylla_storage_proxy_coordinator_write_latency': 'storage.proxy.coordinator_write_latency', 'scylla_storage_proxy_coordinator_write_timeouts': 'storage.proxy.coordinator_write_timeouts', 'scylla_storage_proxy_coordinator_write_unavailable': 'storage.proxy.coordinator_write_unavailable', 'scylla_storage_proxy_replica_cross_shard_ops': 'storage.proxy.replica_cross_shard_ops', 'scylla_storage_proxy_replica_forwarded_mutations': 'storage.proxy.replica_forwarded_mutations', 'scylla_storage_proxy_replica_forwarding_errors': 'storage.proxy.replica_forwarding_errors', 'scylla_storage_proxy_replica_reads': 'storage.proxy.replica_reads', 'scylla_storage_proxy_replica_received_counter_updates': 'storage.proxy.replica_received_counter_updates', 'scylla_storage_proxy_replica_received_mutations': 'storage.proxy.replica_received_mutations', # Scylla 3.2 - renamed 'scylla_storage_proxy_coordinator_foreground_read_repairs': 'storage.proxy.coordinator_foreground_read_repair', } SCYLLA_STREAMING = { 'scylla_streaming_total_incoming_bytes': 'streaming.total_incoming_bytes', 'scylla_streaming_total_outgoing_bytes': 'streaming.total_outgoing_bytes', } SCYLLA_THRIFT = { 'scylla_thrift_current_connections': 'thrift.current_connections', 'scylla_thrift_served': 'thrift.served', 'scylla_thrift_thrift_connections': 'thrift.thrift_connections', } SCYLLA_TRACING = { 'scylla_tracing_active_sessions': 'tracing.active_sessions', 'scylla_tracing_cached_records': 'tracing.cached_records', 'scylla_tracing_dropped_records': 'tracing.dropped_records', 'scylla_tracing_dropped_sessions': 'tracing.dropped_sessions', 'scylla_tracing_flushing_records': 'tracing.flushing_records', 'scylla_tracing_keyspace_helper_bad_column_family_errors': 'tracing.keyspace_helper_bad_column_family_errors', 'scylla_tracing_keyspace_helper_tracing_errors': 'tracing.keyspace_helper_tracing_errors', 'scylla_tracing_pending_for_write_records': 'tracing.pending_for_write_records', 'scylla_tracing_trace_errors': 'tracing.trace_errors', 'scylla_tracing_trace_records_count': 'tracing.trace_records_count', } SCYLLA_TRANSPORT = { 'scylla_transport_cql_connections': 'transport.cql_connections', 'scylla_transport_current_connections': 'transport.current_connections', 'scylla_transport_requests_blocked_memory': 'transport.requests_blocked_memory', 'scylla_transport_requests_blocked_memory_current': 'transport.requests_blocked_memory_current', 'scylla_transport_requests_served': 'transport.requests_served', 'scylla_transport_requests_serving': 'transport.requests_serving', } INSTANCE_DEFAULT_METRICS = [ SCYLLA_CACHE, SCYLLA_COMPACTION, SCYLLA_GOSSIP, SCYLLA_NODE, SCYLLA_REACTOR, SCYLLA_STORAGE, SCYLLA_STREAMING, SCYLLA_TRANSPORT, ] ADDITIONAL_METRICS_MAP = { 'scylla.alien': SCYLLA_ALIEN, 'scylla.batchlog': SCYLLA_BATCHLOG, 'scylla.commitlog': SCYLLA_COMMITLOG, 'scylla.cql': SCYLLA_CQL, 'scylla.database': SCYLLA_DATABASE, 'scylla.execution': SCYLLA_EXECUTION, 'scylla.hints': SCYLLA_HINTS, 'scylla.httpd': SCYLLA_HTTPD, 'scylla.io': SCYLLA_IO, 'scylla.lsa': SCYLLA_LSA, 'scylla.memory': SCYLLA_MEMORY, 'scylla.memtables': SCYLLA_MEMTABLES, 'scylla.query': SCYLLA_QUERY, 'scylla.scheduler': SCYLLA_SCHEDULER, 'scylla.sstables': SCYLLA_SSTABLES, 'scylla.thrift': SCYLLA_THRIFT, 'scylla.tracing': SCYLLA_TRACING, }
#Среднее гармоническое #!/usr/bin/env python3 # -*- coding: utf-8 -*- def harmid(*args): if args and 0 not in args: a = 0 for item in args: a += 1 / item return len(args) / a else: return None if __name__ == "__main__": print(harmid()) print(harmid(1, 3, 5, 7, 9)) print(harmid(2, 4, 6, 8, 10, 12))
# List of tables that should be routed to this app. # Note that this is not intended to be a complete list of the available tables. TABLE_NAMES = ( 'lemma', 'inflection', 'aspect_pair', )
[ { 'date': '2014-01-01', 'description': 'Yılbaşı', 'locale': 'tr-TR', 'notes': '', 'region': '', 'type': 'NF' }, { 'date': '2014-04-23', 'description': 'Ulusal Egemenlik ve Çocuk Bayramı', 'locale': 'tr-TR', 'notes': '', 'region': '', 'type': 'NF' }, { 'date': '2014-05-01', 'description': 'Emek ve Dayanışma Günü', 'locale': 'tr-TR', 'notes': '', 'region': '', 'type': 'NF' }, { 'date': '2014-05-19', 'description': "Atatürk'ü Anma, Gençlik ve Spor Bayramı", 'locale': 'tr-TR', 'notes': '', 'region': '', 'type': 'NF' }, { 'date': '2014-07-28', 'description': 'Ramazan Bayramı (1. Gün)', 'locale': 'tr-TR', 'notes': '', 'region': '', 'type': 'NRV' }, { 'date': '2014-07-29', 'description': 'Ramazan Bayramı (2. Gün)', 'locale': 'tr-TR', 'notes': '', 'region': '', 'type': 'NRV' }, { 'date': '2014-07-30', 'description': 'Ramazan Bayramı (3. Gün)', 'locale': 'tr-TR', 'notes': '', 'region': '', 'type': 'NRV' }, { 'date': '2014-08-30', 'description': 'Zafer Bayramı', 'locale': 'tr-TR', 'notes': '', 'region': '', 'type': 'NF' }, { 'date': '2014-10-04', 'description': 'Kurban Bayramı (1. Gün)', 'locale': 'tr-TR', 'notes': '', 'region': '', 'type': 'NRV' }, { 'date': '2014-10-05', 'description': 'Kurban Bayramı (2. Gün)', 'locale': 'tr-TR', 'notes': '', 'region': '', 'type': 'NRV' }, { 'date': '2014-10-06', 'description': 'Kurban Bayramı (3. Gün)', 'locale': 'tr-TR', 'notes': '', 'region': '', 'type': 'NRV' }, { 'date': '2014-10-07', 'description': 'Kurban Bayramı (4. Gün)', 'locale': 'tr-TR', 'notes': '', 'region': '', 'type': 'NRV' }, { 'date': '2014-10-29', 'description': 'Cumhuriyet Bayramı', 'locale': 'tr-TR', 'notes': '', 'region': '', 'type': 'NF' } ]
nome = [] temp = [] pesoMaior = pesoMenor = 0 count = 1 while True: temp.append(str(input('Nome: '))) temp.append(float(input('Peso: '))) if count == 1: pesoMaior = pesoMenor = temp[1] else: if temp[1] >= pesoMaior: pesoMaior = temp[1] elif temp[1] <= pesoMenor: pesoMenor = temp[1] nome.append(temp[:]) temp.clear() usuario = 'O' while usuario != 'S' or usuario != 'N': usuario = str(input('Deseja Continuar ? S/N: ')).upper().strip()[0] if usuario == 'S': break elif usuario == 'N': break if usuario == 'N': break count += 1 print(f'Foram cadastradas {len(nome)} pessoas') print(f'O menor peso foi {pesoMenor}.', end=' ') for c in nome: if c[1] == pesoMenor: print(c[0], end=' ') print() print(f'O maior peso foi {pesoMaior}.') for c in nome: if c[1] == pesoMaior: print(c[0])
# Necro(ネクロ) # sidmishra94540@gmail.com def binaryGenerator(n): pad = [0]*n res = [] for _ in range(2**n): num = list(map(int, bin(_)[2:])) num = pad[:n-len(num)]+num res.append(num) return res if __name__ == '__main__': print(binaryGenerator(int(input())))
""" Реализовать класс Road (дорога), в котором определить атрибуты: length (длина), width (ширина). Значения данных атрибутов должны передаваться при создании экземпляра класса. Атрибуты сделать защищенными. Определить метод расчета массы асфальта, необходимого для покрытия всего дорожного полотна. Использовать формулу: длина*ширина*масса асфальта для покрытия одного кв метра дороги асфальтом, толщиной в 1 см*число см толщины полотна. Проверить работу метода. Например: 20м*5000м*25кг*5см = 12500 т """ class Road: asphalt_per_sqmeter = 25 def __init__(self, road_length, road_width, thickness=5): self._road_length = road_length self._road_width = road_width self._thickness = thickness def calc(self): return self._road_length*self._road_width*self._thickness*self.asphalt_per_sqmeter a = Road(5000, 20) print(f'Масса асфальта {a.calc()} кг.')
tcase = int(input()) while(tcase): str= input() [::-1] print(int(str)) tcase -= 1
class FixtureException(Exception): pass class FixtureUploadError(FixtureException): pass class DuplicateFixtureTagException(FixtureUploadError): pass class ExcelMalformatException(FixtureUploadError): pass class FixtureAPIException(Exception): pass class FixtureTypeCheckError(Exception): pass class FixtureVersionError(Exception): pass
#!/usr/bin/env python3 # tuples is a type of list. # tuples is immutable. # the structure of a tuple: (1, "nice work", 2.3, [1,2,"hey"]) my_tuple = ("hey", 1, 2, "hey ho!", "hey", "hey") print("My tuple:", my_tuple) # to get a tuple value use it's index print("Second item in my_tuple:", my_tuple[1]) # to count how many times a values appears in a tuple: tuple.count(value) # returns 0 if no values exists. print("How many 'hey' in my_tuple:", my_tuple.count("hey")) # go get the index value of a tuple item. tuple.index(value) # if value does not exist you will get an error like "ValueError: tuple.index(x): x not in tuple" print("Index position of 'hey ho!' in my_tuple:", my_tuple.index("hey ho!")) # tuples are immutable so you cannot reassign a value like # my_tuple[2] = "wop wop" # TypeError: 'tuple' object does not support item assignment
def possibleHeights(parent): edges = [[] for i in range(len(parent))] height = [0 for i in range(len(parent))] isPossibleHeight = [False for i in range(len(parent))] def initGraph(parent): for i in range(1, len(parent)): edges[parent[i]].append(i) def calcHeight(v): for u in edges[v]: calcHeight(u) height[v] = max(height[v], height[u]+1) countHeights = [[] for i in range(len(edges))] for i in range(len(edges[v])): u = edges[v][i] countHeights[height[u]].append(u) edges[v] = [] for i in range(len(edges) - 1, -1, -1): for j in range(len(countHeights[i])): edges[v].append(countHeights[i][j]) def findNewHeights(v, tailHeight): isPossibleHeight[max(height[v], tailHeight)] = True firstMaxHeight = tailHeight + 1 secondMaxHeight = tailHeight + 1 if len(edges[v]) > 0: firstMaxHeight = max(firstMaxHeight, height[edges[v][0]] + 2) if len(edges[v]) > 1: secondMaxHeight = max(secondMaxHeight, height[edges[v][1]] + 2) if len(edges[v]) > 0: findNewHeights(edges[v][0], secondMaxHeight) for i in range(1, len(edges[v])): findNewHeights(edges[v][i], firstMaxHeight) initGraph(parent) calcHeight(0) findNewHeights(0, 0) heights = [] for i in range(len(parent)): if isPossibleHeight[i]: heights.append(i) return heights
expected_output = { 'instance': { 'isp': { 'address_family': { 'IPv4 Unicast': { 'spf_log': { 1: { 'type': 'FSPF', 'time_ms': 1, 'level': 1, 'total_nodes': 1, 'trigger_count': 1, 'first_trigger_lsp': '12a5.00-00', 'triggers': 'NEWLSP0', 'start_timestamp': 'Mon Aug 16 2004 19:25:35.140', 'delay': { 'since_first_trigger_ms': 51, }, 'spt_calculation': { 'cpu_time_ms': 0, 'real_time_ms': 0, }, 'prefix_update': { 'cpu_time_ms': 1, 'real_time_ms': 1, }, 'new_lsp_arrivals': 0, 'next_wait_interval_ms': 200, 'results': { 'nodes': { 'reach': 1, 'unreach': 0, 'total': 1, }, 'prefixes': { 'items': { 'critical_priority': { 'reach': 0, 'unreach': 0, 'total': 0, }, 'high_priority': { 'reach': 0, 'unreach': 0, 'total': 0, }, 'medium_priority': { 'reach': 0, 'unreach': 0, 'total': 0, }, 'low_priority': { 'reach': 0, 'unreach': 0, 'total': 0, }, 'all_priority': { 'reach': 0, 'unreach': 0, 'total': 0, }, }, 'routes': { 'critical_priority': { 'reach': 0, 'total': 0, }, 'high_priority': { 'reach': 0, 'total': 0, }, 'medium_priority': { 'reach': 0, 'total': 0, }, 'low_priority': { 'reach': 0, 'total': 0, }, 'all_priority': { 'reach': 0, 'total': 0, }, }, }, }, }, }, }, }, }, }, }
b = "r n b q k b n r p p p p p p p p".split(" ") + ['.']*32 + "p p p p p p p p r n b q k b n r".upper().split(" ") def newBoard(): b = "r n b q k b n r p p p p p p p p".split(" ") + ['.']*32 + "p p p p p p p p r n b q k b n r".upper().split(" ") def display(): #white side view c , k= 1 ,0 ap = range(1,9)[::-1] row,col=[],[] for i in b: row.append(i) if c==8 : c=0 col.append(row) row=[] c+=1 for j in col[::-1]: print(ap[k] , " |" ,end=" ") for i in j: print(i,end=' ') print() k+=1 print(" ",end="") print("-"*18," A B C D E F G H",sep="\n") def move(fr,to): fnum = (conv(fr))-1 tnum = (conv(to))-1 b[fnum], b[tnum] = '.',b[fnum] display() def conv(s): num = int(s[1]) alp = s[0] a = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8} alpn = a[alp] return ((num-1)*8)+alpn def rookValid(fr,to): fnum = (conv(fr))-1 tnum = (conv(to))-1 con1,con2,con3=False,False,False if abs(fnum-tnum)%8==0: con1=True rows=[range(0,8),range(8,16),range(16,24),range(24,32),range(32,40),range(40,48),range(48,56),range(56,64)] for k in rows: if fnum in k and tnum in k: con2=True if con2: #verifies if path is clear if fr and to are in same row for l in range(fnum+1,tnum): if b[l] != '.': con2=False mi =min(fnum,tnum) ma = max(fnum,tnum) if con1: while mi < ma: mi+=8 if b[mi] !='.': con1=False if (b[fnum].isupper() and not b[tnum].isupper()) or (b[fnum].islower() and not b[tnum].islower()) : con3 = True return (con1 or con2) and con3 def kingValid(fr,to): fnum = (conv(fr))-1 tnum = (conv(to))-1 if not addressValid(fnum,tnum): return False con1,con2=False,False if fnum%8!=0 and fnum%9!=0: val = [fnum+1 , fnum-1,fnum+8,fnum-8] elif fnum%8==0: val =[fnum+8 , fnum-8,fnum-1] else: val =[fnum+8 , fnum-8,fnum+1] if fnum in val : con=True if (b[fnum].isupper() and not b[tnum].isupper()) or (b[fnum].islower() and not b[tnum].islower()) : con2 = True return con1 and con2 def pawnValid(fr,to): fnum = (conv(fr))-1 tnum = (conv(to))-1 if not addressValid(fnum,tnum): return False if fr.isupper() : c='b' if fr.islower() : c='w' if c=='w': if fr in range(8,16): vm = [fnum+8,fnum+16] else : vm= [fnum+8] if b[fnum+7].isupper(): vm.append(fnum+7) if b[fnum+9].isupper(): vm.append(fnum+9) if tnum in vm and not b[tnum].islower(): return True else: return False if c=='b': if fr in range(48,56): vm = [fnum-8,fnum-16] else : vm= [fnum-8] if b[fnum-7].islower(): vm.append(fnum+7) if b[fnum-9].islower(): vm.append(fnum+9) if tnum in vm and not b[tnum].isupper(): return True else: return False def bishopValid(fr,to): fnum = (conv(fr))-1 tnum = (conv(to))-1 if not addressValid(fnum,tnum): return False con1=False if abs(fnum-tnum)%9==0 or abs(fnum-tnum)%7==0: con1 = True if (fnum-tnum)%9==0: while fnum!=tnum: tnum+=9 if b[tnum]!='.' : return False if (fnum-tnum)%7==0: while fnum!=tnum: tnum+=7 if b[tnum]!='.' : return False if (tnum-fnum)%9==0: while tnum!=fnum: fnum+=9 if b[fnum]!='.' : return False if (tnum-fnum)%7==0: while tnum!=fnum: fnum+=7 if b[fnum]!='.' : return False if (b[fnum].isupper() and not b[tnum].isupper()) or (b[fnum].islower() and not b[tnum].islower()) : con2 = True return con1 and con2 def queenValid(fr,to): fnum = (conv(fr))-1 tnum = (conv(to))-1 if not addressValid(fnum,tnum): return False return bishopValid(fr,to) or rookValid(fr,to) def knightValid(fr,to): fnum = (conv(fr))-1 tnum = (conv(to))-1 if not addressValid(fnum,tnum): return False if tnum in [fnum+17,fnum-17,fnum+15,fnum-15,fnum+10,fnum-6,fnum+6,fnum-10]: con1=True if (b[fnum].isupper() and not b[tnum].isupper()) or (b[fnum].islower() and not b[tnum].islower()) : con2=True return con1 and con2 def addressValid(fnum,tnum): return 0<=fnum<64 and 0<=tnum<64 def rookMoves(pos): num=(conv(pos))-1 #num is index if b[num].isupper() : c='b' elif b[num].islower() : c='w' else: return "Block is empty" vm=[] col=(num+1)%8 if col==0: col=8 row=int(pos[1]) if c=='w': block=num+8 while row<=8: if b[block] == '.' : vm.append(block) if b[block].isupper() : vm.append(block) break if b[block].islower(): break block+=8 row+=1 row=int(pos[1]) block=num-8 while row>0: if b[block] == '.' : vm.append(block) if b[block].isupper() : vm.append(block) break if b[block].islower(): break block-=8 row-=1 tcol=col+1 #col is from 1 to 8 , row is from 1 to 8 block =num+1 while tcol<=8: if b[block] == '.' : vm.append(block) if b[block].isupper() : vm.append(block) break if b[block].islower(): break block+=1 tcol+=1 block =num-1 tcol=col while tcol>1: if b[block] == '.' : vm.append(block) if b[block].isupper() : vm.append(block) break if b[block].islower(): break block-=1 tcol-=1 tcol=col row=int(pos[1]) if c=='b': block=num+8 while row<=8: if b[block] == '.' : vm.append(block) if b[block].islower() : vm.append(block) break if b[block].isupper(): break block+=8 row+=1 row=int(pos[1]) block=num-8 while row>1: if b[block] == '.' : vm.append(block) if b[block].islower() : vm.append(block) break if b[block].isupper(): break block-=8 row-=1 tcol=col+1 #col is from 1 to 8 , row is from 1 to 8 block =num+1 while tcol<=8: if b[block] == '.' : vm.append(block) if b[block].islower() : vm.append(block) break if b[block].isupper(): break block+=1 tcol+=1 block =num-1 tcol=col while tcol>1: if b[block] == '.' : vm.append(block) if b[block].islower() : vm.append(block) break if b[block].isupper(): break block-=1 tcol-=1 move=[] for l in vm: move.append(numToAlg(l)) return move def bishopMoves(pos): num=(conv(pos))-1 if b[num].isupper() : c='b' elif b[num].islower() : c='w' else: return "Block is empty" vm=[] col=(num+1)%8 if col==0: col=8 row=int(pos[1])+1 if c=='w': tcol=col+1 row=int(pos[1])+1 block=num+9 while row<=8 and col<=8 : #goes top right if b[block] == '.' : vm.append(block) if b[block].isupper() : vm.append(block) break if b[block].islower(): break block+=9 row+=1 tcol+=1 row=int(pos[1])-1 tcol=col-1 block=num-9 while row>0 and tcol>1: #goes below left if b[block] == '.' : vm.append(block) if b[block].isupper() : vm.append(block) break if b[block].islower(): break block-=9 row-=1 tcol-=1 row=int(pos[1])-1 tcol=col+1 block =num-7 while tcol<=8 and row>1: #goes below right if b[block] == '.' : vm.append(block) if b[block].isupper() : vm.append(block) break if b[block].islower(): break block-=7 tcol+=1 row-=1 block =num+7 tcol=col-1 row=int(pos[1])+1 while tcol>0 and row<=8: #goes top left if b[block] == '.' : vm.append(block) if b[block].isupper() : vm.append(block) break if b[block].islower(): break block+=7 tcol-=1 row+=1 if c=='b': tcol=col+1 row=int(pos[1])+1 block=num+9 while row<=8 and col<=8 : #goes top right if b[block] == '.' : vm.append(block) if b[block].islower() : vm.append(block) break if b[block].isupper(): break block+=9 row+=1 tcol+=1 row=int(pos[1])-1 tcol=col-1 block=num-9 while row>0 and tcol>1: #goes below left if b[block] == '.' : vm.append(block) if b[block].islower() : vm.append(block) break if b[block].isupper(): break block-=9 row-=1 tcol-=1 row=int(pos[1])-1 tcol=col+1 block =num-7 while tcol<=8 and row>1: #goes below right if b[block] == '.' : vm.append(block) if b[block].islower() : vm.append(block) break if b[block].isupper(): break block-=7 tcol+=1 row-=1 block =num+7 tcol=col-1 row=int(pos[1])+1 while tcol>0 and row<=8: #goes top left if b[block] == '.' : vm.append(block) if b[block].islower() : vm.append(block) break if b[block].upper(): break block+=7 tcol-=1 row+=1 move=[] for l in vm: move.append(numToAlg(l)) return move def queenMoves(pos): return rookMoves(pos) + bishopMoves(pos) def knightMoves(pos): num = conv(pos)-1 #num is index vm = [num-17,num-15,num-10,num-6,num+6,num+10,num+15,num+17] if vm[3]%8 in [0,1]: vm.pop(3) vm.pop(5) if vm[4]%8 in [6,7]: vm.pop(4) vm.pop(2) tvm=[] for i in vm: if (i>=0 and i<=63) and not ((b[num].isupper and b[i].isupper()) or (b[num].islower and b[i].islower())) : tvm.append(i) move=[] for l in tvm: move.append(numToAlg(l)) return move def kingMoves(pos): num = conv(pos)-1 #num is index vm = [num+8,num-8,num+9,num-9,num+7,num-7,num+1,num-1] if vm[2]%8==0: vm.pop(2) vm.pop(6) vm.pop(5) if vm[3]%8 ==7: vm.pop(3) vm.pop(-1) vm.pop(4) tvm=[] for i in vm: if (i>=0 and i<=63) and not ((b[num].isupper and b[i].isupper()) or (b[num].islower and b[i].islower())) : tvm.append(i) move=[] for l in tvm: move.append(numToAlg(l)) return move def pawnMoves(pos): num = conv(pos)-1 vm=[] if b[num].islower() : if b[num+8] =='.':vm.append(num+8) if b[num+9].isupper() : vm.append(num+9) if b[num+7].isupper() : vm.append(num+7) if b[num+16] =='.' and 7<num<16 : vm.append(num+16) if b[num].isupper() : if b[num-8] =='.':vm.append(num-8) if b[num-9].islower() : vm.append(num-9) if b[num-7].islower() : vm.append(num-7) if b[num-16] =='.' and 7<num<16 : vm.append(num-16) list =[] for i in vm: list.append(numToAlg(i)) return list def moves(pos): num = conv(pos)-1 if b[num].lower() =='k': return(kingMoves(pos)) elif b[num].lower() == 'q': return(queenMoves(pos)) elif b[num].lower() == 'p': return(pawnMoves(pos)) elif b[num].lower() == 'r': return(rookMoves(pos)) elif b[num].lower() == 'b': return(bishopMoves(pos)) elif b[num].lower() == 'n': return(knightMoves(pos)) def isCheck(pos): num = conv(pos)-1 r = rookMoves(pos) b = bishopMoves(pos) n = knightMoves(pos) check = False for rcase in r: if b[conv(rcase)-1].lower() in ['r','q'] and ( (b[num].islower() and b[conv(rcase)-1].isupper()) or (b[num].isupper() and b[conv(rcase)-1].islower()) ) : check=True for bcase in r: if b[conv(bcase)-1].lower() in ['b','q'] and ( (b[num].islower() and b[conv(rcase)-1].isupper()) or (b[num].isupper() and b[conv(rcase)-1].islower()) ): check=True for kcas in r: if b[conv(bcase)-1].lower()=='n' and ( (b[num].islower() and b[conv(rcase)-1].isupper()) or (b[num].isupper() and b[conv(rcase)-1].islower()) ): check=True return check def numToAlg(ind): alp=(ind+1)%8 n=((ind+1)//8) + 1 if alp==0: n-=1 a = {0:'h',1 : 'a' , 2:'b',3:'c',4:'d',5:'e',6:'f',7:'g',8:'h'} return str(a[alp]) + str(n)
#!/usr/bin/env python3 print("""\ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """)
tree_count, tree_hinput, tree_chosen = int(input()), input().split(), 0 tree_height = [int(x) for x in tree_hinput] for each_tree in range(tree_count): if each_tree==0 and tree_height[0]>tree_height[1]:tree_chosen+=1 elif each_tree==tree_count-1 and tree_height[each_tree]>tree_height[each_tree-1]:tree_chosen+=1 elif tree_height[each_tree-1]<tree_height[each_tree]>tree_height[each_tree+1]:tree_chosen+=1 print(tree_chosen) # Passed
# Create the DMatrix: housing_dmatrix housing_dmatrix = xgb.DMatrix(data=X, label=y) # Create the parameter dictionary: params params = {'objective':'reg:linear', 'max_depth':4} # Train the model: xg_reg xg_reg = xgb.train(dtrain=housing_dmatrix, params=params, num_boost_round=10) # Plot the feature importances xgb.plot_importance(xg_reg) plt.show()
# -*- encoding:utf-8 -*- impar = lambda n : 2 * n - 1 header = """ Demostrar que es cierto: 1 + 3 + 5 + ... + (2*n)-1 = n ^ 2 Luego con este programa se busca probar dicha afirmacion. """ def suma_impares(n): suma = 0 for i in range(1, n+1): suma += impar(i) return suma def main(): print(header) num = int(input('Numero: ')) suma = suma_impares(num) cuadrado = num ** 2 print('Suma de los ', num, ' primeros impares = ', suma) print('Cuadrado del numero: ', cuadrado) if suma == cuadrado: print('Son iguales, luego se cumple la afirmacion') else: print('No son iguales, luego no se cumple la afirmacion') if __name__ == '__main__': main()