content
stringlengths 7
1.05M
|
|---|
# -*- coding: utf-8 -*-
"""
Пример наследования классов
"""
class Figure(object):
def __init__(self, side):
self.side = side
class Square(Figure):
def draw(self):
for i in range(self.side):
print('*' * self.side)
class Triangle(Figure):
def draw(self):
for i in range(self.side):
print('*' * i)
def main():
square = Square(10)
square.draw()
print()
triangle = Triangle(5)
triangle.draw()
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 13 21:31:02 2021
@author: eliphat
"""
class BaseConstraint:
def cause_vars(self):
raise NotImplementedError()
def effect_vars(self):
raise NotImplementedError()
def fix(self, ts):
raise NotImplementedError()
def is_resolved(self):
# is_resolved will be called after fix
raise NotImplementedError()
|
def fun():
a=89
str="adar"
return[a,str];
print(fun())
|
'''
Parâmetros: são os nomes dados aos atributos que uma função pode receber. Definem quais argumentos são aceitos por uma função, podendo ou não ter um valor padrão (default).
Argumentos: são os valores que realmente são passados para uma função.
'''
def calculadora_salario(valor, horas=220):
return horas * valor
valor_total = calculadora_salario(299.25)
print(valor_total)
'''
os parâmetros obrigatórios devem ser colocados antes de qualquer parâmetro default (da esquerda para direita), para que não ocorra uma confusão no interpretador e ocorra o erro
'''
'''
*args
É usado para passar um lista de argumentos variável sem palavras-chave em forma de tupla, pois a função que o recebe não necessariamente saberá quantos argumentos serão passados.
'''
def func_args(*args):
print(f'tipo: {type(args)} conteúdo: {args}')
for arg in args:
print(f'tipo: {type(arg)} conteúdo: {arg}')
func_args(1, 'A', {'valor': 10})
'''
**kwargs
Como a abreviação sugere, kwargs significa keyword arguments (argumentos de palavras chave). Ele permite passar um dicionário com inúmeras keys para a função.
'''
def func_kwargs(**kwargs):
print(f'tipo: {type(kwargs)} contuedo: {kwargs}')
for key, value in kwargs.items():
print(f'atributo: {key}, valor: {value}')
func_kwargs(nome='James', sobrenome='Bond', cargo='Agente 007')
# um função usando todos os parâmetros que vimos.
def func_missao_dificil(nome, *args, funcao='agente', **kwargs):
print(f'Nome do agente: {nome}')
print(f'Função: {funcao}')
print(args)
print(kwargs)
params = {
'id_agente': '007',
'proxima_missao': 'Impossível'
}
func_missao_dificil(
'James Bond',
'Missao 1',
'Missão 2',
**params
)
|
"""The version number is based on semantic versioning.
References
- https://semver.org/
- https://www.python.org/dev/peps/pep-0440/
This file is autogenerated, do not modify by hand.
"""
__version__ = "0.0.0"
COMMIT = "ed3301fdf82f5608a53a19a4aa0961c14c323421"
MAJOR = 0
MINOR = 0
PATCH = 0
|
# input
N, X, Y = map(int, input().split())
As = [*map(int, input().split())]
Bs = [*map(int, input().split())]
# compute
# output
print(sum(i not in As and i not in Bs for i in range(1, N+1)))
|
fout=open('orth_I.txt','w')
alphabet='ΕΡΤΥΘΙΟΠΑΣΔΦΓΗΞΚΛΖΧΨΩΒΝΜ'
#alphabet='ΧΥ'
#fout.write('0 0 eps eps 0\n')
for i in alphabet:
fout.write('0 0 '+i+' '+i+' 0\n')
fout.write('0')
|
names = ["duanzijie","zhaokeer","lijiaxi","zhuzi","wangwenbo","gongyijun"]
print(names)
print(names[0])
print(names[1])
print(names[2])
print(names[3])
print(names[4])
print(names[5])
hi = "hi" + " " + name[1]
print(hi)
|
"""
User defined here are allowed to use privileged bot commands
"""
regulars = [
965146, #Shree
4946380, #Mithrandir
5067311, #Andras Deak
397817, #Stephen Kennedy
6707985, #geisterfurz007
]
|
# -*- coding: utf-8 -*-
"""
Author: @heyao
Created On: 2019/6/26 上午10:07
"""
|
n = int(input())
s = input()
c=0
for i in range(n-1):
if s[i]==s[i+1]:
c +=1
print(c)
|
# Чтобы подготовиться к семинару, Гоше надо прочитать статью по эффективному менеджменту.
# Так как Гоша хочет спланировать день заранее, ему необходимо оценить сложность статьи.
# Он придумал такой метод оценки: берётся случайное предложение из текста
# и в нём ищется самое длинное слово. Его длина и будет условной сложностью статьи.
# Помогите Гоше справиться с этой задачей.
def get_longest_word(text):
words = text.split()
max_length = 0
winner = None
for word in words:
word = word.strip()
current_word_length = len(word)
if current_word_length > max_length:
max_length = current_word_length
winner = word
return winner, max_length
def read_input():
return int(input()), input()
if __name__ == "__main__":
total_length, text = read_input()
result = get_longest_word(text)
print(*result, sep="\n")
|
# practice of anna
class TestClass:
def __init__(self, name):
# __init__ is the rule first creator made so every time we have to foloow
self.name = name
if __name__ == '__main__':
obj1 = TestClass()
print(obj1)
obj2 = TestClass()
print(obj2)
|
"""
请判断一个链表是否为回文链表
**示例**
输入: 1 -> 2
输出: False
输入: 1 -> 2 -> 2 -> 1
输出: True
**test case**
# Solution
"""
class ListNode:
def __init__(self, value):
self.value = value
self.next = None
def __repr__(self):
return f"List Node Value: {self.value}"
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(2)
head.next.next.next = ListNode(1)
head1 = ListNode(1)
head1.next = ListNode(2)
def convertToList(node):
value = []
while node:
value.append(node.value)
node = node.next
return value
if __name__ == '__main__':
array = convertToList(node=head)
array2 = convertToList(node=head1)
print(array == array[::-1])
print(array2 == array2[::-1])
|
class SpiderpigError(Exception):
pass
class ValidationError(SpiderpigError):
pass
class NotInitialized(SpiderpigError):
pass
class CyclicExecution(SpiderpigError):
pass
class TooManyDependencies(SpiderpigError):
pass
|
## bisenetv2
cfg = dict(
model_type='bisenetv2',
num_aux_heads=4,
lr_start = 5e-2,
weight_decay=5e-4,
warmup_iters = 1000,
max_iter = 150000,
im_root='./datasets/coco',
train_im_anns='./datasets/coco/train.txt',
val_im_anns='./datasets/coco/val.txt',
scales=[0.5, 1.5],
cropsize=[512, 512],
ims_per_gpu=8,
use_fp16=True,
use_sync_bn=False,
respth='./res',
)
|
# Exercício 015 - Aluguel de Carros
dias = int(input('Quantos dias alugados? '))
km = float(input('Quantos Km rodados? '))
preco_dias = dias * 60
preco_km = km * 0.15
total = preco_dias + preco_km
print(f'O total a pagar é de R${total:.2f}')
|
class PorterStemmer:
def __init__(self):
self.vowels = ('a', 'e', 'i', 'o', 'u')
def is_consonant(self, s: str, i: int):
return not self.is_vowel(s, i)
def is_vowel(self, s: str, i: int):
if s[i].lower() in self.vowels:
return True
elif s[i].lower() == 'y':
if self.is_consonant(s, i-1):
return True
else:
return False
def find_m(self, s):
i = 0
m = 0
while i < len(s):
if self.is_vowel(s, i) and self.is_consonant(s, i+1):
m += 1
i += 2
else:
i += 1
return m
def contains_vowel(self, s):
for v in self.vowels:
if v in s:
return True
for i in range(len(s)):
if s[i] == 'y':
if self.is_vowel(s, i):
return True
return False
def step1a(self, s):
if s[-4:] == 'sses':
s = s[:-4] + 'ss'
elif s[-3:] == "ies":
s = s[:-3] + "i"
elif s[-2:] == "ss":
pass
elif s[-1] == "s":
s = s[:-1]
return s
def step1b(self, s):
if s[-3:] == 'eed':
m = self.find_m(s[:-3])
if m > 0:
s = s[:-1]
elif s[-2:] == 'ed':
if self.contains_vowel(s[:-2]):
s = s[:-2]
elif s[-3:] == 'ing':
if self.contains_vowel(s[:-3]):
s = s[:-3]
return s
def step2(self, s):
if s[-7:] == 'ational':
m = self.find_m(s[:-7])
if m > 0:
s = s[:-5]+"e"
elif s[-6:] == 'tional':
m = self.find_m(s[:-6])
if m > 0:
s = s[:-2]
elif s[-4:] == 'enci':
m = self.find_m(s[:-4])
if m > 0:
s = s[:-1]+"e"
elif s[-4:] == 'anci':
m = self.find_m(s[:-4])
if m > 0:
s = s[:-1]+"e"
elif s[-4:] == 'izer':
m = self.find_m(s[:-4])
if m > 0:
s = s[:-1]
elif s[-4:] == 'abli':
m = self.find_m(s[:-4])
if m > 0:
s = s[:-1]+"e"
elif s[-4:] == 'alli':
m = self.find_m(s[:-1])
if m > 0:
s = s[:-2]
elif s[-5:] == 'entli':
m = self.find_m(s[:-5])
if m > 0:
s = s[:-2]
elif s[-3:] == 'eli':
m = self.find_m(s[:-3])
if m > 0:
s = s[:-2]
elif s[-5:] == 'ousli':
m = self.find_m(s[:-5])
if m > 0:
s = s[:-2]
elif s[-7:] == 'ization':
m = self.find_m(s[:-7])
if m > 0:
s = s[:-5]+"e"
elif s[-5:] == 'ation':
m = self.find_m(s[:-5])
if m > 0:
s = s[:-3]+"e"
elif s[-4:] == 'ator':
m = self.find_m(s[:-4])
if m > 0:
s = s[:-2]+"e"
elif s[-5:] == 'alism':
m = self.find_m(s[:-5])
if m > 0:
s = s[:-3]
elif s[-7:] == 'iveness':
m = self.find_m(s[:-7])
if m > 0:
s = s[:-4]
elif s[-7:] == 'fulness':
m = self.find_m(s[:-7])
if m > 0:
s = s[:-4]
elif s[-7:] == 'ousness':
m = self.find_m(s[:-7])
if m > 0:
s = s[:-4]
elif s[-5:] == 'aliti':
m = self.find_m(s[:-5])
if m > 0:
s = s[:-3]
elif s[-5:] == 'iviti':
m = self.find_m(s[:-5])
if m > 0:
s = s[:-3]+"e"
elif s[-6:] == 'bliti':
m = self.find_m(s[:-6])
if m > 0:
s = s[:-3]+"e"
return s
def step3(self, s):
if s[-5:] == 'icate':
m = self.find_m(s[:-5])
if m > 0:
s = s[:-3]
elif s[-5:] == 'ative':
m = self.find_m(s[:-5])
if m > 0:
s = s[:-5]
elif s[-5:] == 'alize':
m = self.find_m(s[:-5])
if m > 0:
s = s[:-3]
elif s[-5:] == 'iciti':
m = self.find_m(s[:-5])
if m > 0:
s = s[:-3]
elif s[-4:] == 'ical':
m = self.find_m(s[:-4])
if m > 0:
s = s[:-2]
elif s[-3:] == 'ful':
m = self.find_m(s[:-3])
if m > 0:
s = s[:-3]
elif s[-4:] == 'ness':
m = self.find_m(s[:-4])
if m > 0:
s = s[:-4]
def step4(self, s):
if s[-2:] == 'al':
m = self.find_m(s[:-2])
if m > 1:
s = s[:-2]
elif s[-4:] == 'ance':
m = self.find_m(s[:-4])
if m > 1:
s = s[:-4]
elif s[-4:] == 'ence':
m = self.find_m(s[:-4])
if m > 1:
s = s[:-4]
elif s[-2:] == 'er':
m = self.find_m(s[:-2])
if m > 1:
s = s[:-2]
elif s[-2:] == 'ic':
m = self.find_m(s[:-2])
if m > 1:
s = s[:-2]
elif s[-4:] == 'able':
m = self.find_m(s[:-4])
if m > 1:
s = s[:-4]
elif s[-4:] == 'ible':
m = self.find_m(s[:-4])
if m > 1:
s = s[:-4]
elif s[-4:] == 'ant':
m = self.find_m(s[:-3])
if m > 1:
s = s[:-3]
elif s[-5:] == 'ement':
m = self.find_m(s[:-5])
if m > 1:
s = s[:-5]
elif s[-4:] == 'ment':
m = self.find_m(s[:-4])
if m > 1:
s = s[:-4]
elif s[-3:] == 'ent':
m = self.find_m(s[:-3])
if m > 1:
s = s[:-3]
elif s[-3:] == 'ion':
m = self.find_m(s[:-3])
if m > 1 and (s[-4]== "s" or s[-4]=="t"):
s = s[:-3]
elif s[-2:] == 'ou':
m = self.find_m(s[:-2])
if m > 1:
s = s[:-2]
elif s[-3:] == 'ism':
m = self.find_m(s[:-3])
if m > 1:
s = s[:-3]
elif s[-3:] == 'ate':
m = self.find_m(s[:-3])
if m > 1:
s = s[:-3]
elif s[-3:] == 'iti':
m = self.find_m(s[:-3])
if m > 1:
s = s[:-3]
elif s[-3:] == 'ous':
m = self.find_m(s[:-3])
if m > 1:
s = s[:-3]
elif s[-3:] == 'ive':
m = self.find_m(s[:-3])
if m > 1:
s = s[:-3]
elif s[-3:] == 'ize':
m = self.find_m(s[:-3])
if m > 1:
s = s[:-3]
def __call__(self, s: str):
s = self.step1a(s)
s = self.step1b(s)
return s
|
def bubble_sort(L):
swap = False
while not swap:
swap = True
for j in range(1, len(L)):
if L[j-1] > L[j]:
swap = False
temp = L[j]
L[j] = L[j-1]
L[j-1] = temp
|
#
# PySNMP MIB module CRESCENDO-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CRESCENDO-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:12:29 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")
ConstraintsIntersection, ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ValueSizeConstraint")
MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("RFC1212", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn")
DisplayString, = mibBuilder.importSymbols("RFC1213", "DisplayString")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
enterprises, Unsigned32, iso, MibIdentifier, Integer32, NotificationType, Counter32, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, Bits, ObjectIdentity, IpAddress, ModuleIdentity, Gauge32 = mibBuilder.importSymbols("SNMPv2-SMI", "enterprises", "Unsigned32", "iso", "MibIdentifier", "Integer32", "NotificationType", "Counter32", "Counter64", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "Bits", "ObjectIdentity", "IpAddress", "ModuleIdentity", "Gauge32")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
crescendo = MibIdentifier((1, 3, 6, 1, 4, 1, 203))
crescendoProducts = MibIdentifier((1, 3, 6, 1, 4, 1, 203, 1))
concentrator = MibIdentifier((1, 3, 6, 1, 4, 1, 203, 1, 1))
conc = MibIdentifier((1, 3, 6, 1, 4, 1, 203, 1, 1, 1))
chassis = MibIdentifier((1, 3, 6, 1, 4, 1, 203, 1, 1, 2))
module = MibIdentifier((1, 3, 6, 1, 4, 1, 203, 1, 1, 3))
port = MibIdentifier((1, 3, 6, 1, 4, 1, 203, 1, 1, 4))
concMgmtType = MibScalar((1, 3, 6, 1, 4, 1, 203, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("other", 1), ("snmp", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: concMgmtType.setStatus('mandatory')
concIpAddr = MibScalar((1, 3, 6, 1, 4, 1, 203, 1, 1, 1, 2), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: concIpAddr.setStatus('mandatory')
concNetMask = MibScalar((1, 3, 6, 1, 4, 1, 203, 1, 1, 1, 3), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: concNetMask.setStatus('mandatory')
concBroadcast = MibScalar((1, 3, 6, 1, 4, 1, 203, 1, 1, 1, 4), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: concBroadcast.setStatus('mandatory')
concTrapReceiverTable = MibTable((1, 3, 6, 1, 4, 1, 203, 1, 1, 1, 5), )
if mibBuilder.loadTexts: concTrapReceiverTable.setStatus('mandatory')
concTrapReceiverEntry = MibTableRow((1, 3, 6, 1, 4, 1, 203, 1, 1, 1, 5, 1), ).setIndexNames((0, "CRESCENDO-MIB", "concTrapReceiverAddr"))
if mibBuilder.loadTexts: concTrapReceiverEntry.setStatus('mandatory')
concTrapReceiverType = MibTableColumn((1, 3, 6, 1, 4, 1, 203, 1, 1, 1, 5, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("other", 1), ("invalid", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: concTrapReceiverType.setStatus('mandatory')
concTrapReceiverAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 203, 1, 1, 1, 5, 1, 2), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: concTrapReceiverAddr.setStatus('mandatory')
concTrapReceiverComm = MibTableColumn((1, 3, 6, 1, 4, 1, 203, 1, 1, 1, 5, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: concTrapReceiverComm.setStatus('mandatory')
concCommunityTable = MibTable((1, 3, 6, 1, 4, 1, 203, 1, 1, 1, 6), )
if mibBuilder.loadTexts: concCommunityTable.setStatus('mandatory')
concCommunityEntry = MibTableRow((1, 3, 6, 1, 4, 1, 203, 1, 1, 1, 6, 1), ).setIndexNames((0, "CRESCENDO-MIB", "concCommunityAccess"))
if mibBuilder.loadTexts: concCommunityEntry.setStatus('mandatory')
concCommunityAccess = MibTableColumn((1, 3, 6, 1, 4, 1, 203, 1, 1, 1, 6, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("other", 1), ("readOnly", 2), ("readWrite", 3), ("readWriteAll", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: concCommunityAccess.setStatus('mandatory')
concCommunityString = MibTableColumn((1, 3, 6, 1, 4, 1, 203, 1, 1, 1, 6, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: concCommunityString.setStatus('mandatory')
concAttachType = MibScalar((1, 3, 6, 1, 4, 1, 203, 1, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("other", 1), ("dualAttach", 2), ("singleAttach", 3), ("nullAttach", 4)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: concAttachType.setStatus('mandatory')
concTraffic = MibScalar((1, 3, 6, 1, 4, 1, 203, 1, 1, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setMaxAccess("readonly")
if mibBuilder.loadTexts: concTraffic.setStatus('mandatory')
concReset = MibScalar((1, 3, 6, 1, 4, 1, 203, 1, 1, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("other", 1), ("reset", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: concReset.setStatus('mandatory')
concBaudRate = MibScalar((1, 3, 6, 1, 4, 1, 203, 1, 1, 1, 10), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: concBaudRate.setStatus('mandatory')
chassisType = MibScalar((1, 3, 6, 1, 4, 1, 203, 1, 1, 2, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("other", 1), ("cxxxx", 2), ("c1000", 3), ("c1001", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: chassisType.setStatus('mandatory')
chassisBkplType = MibScalar((1, 3, 6, 1, 4, 1, 203, 1, 1, 2, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("other", 1), ("fddi", 2), ("fddiEthernet", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: chassisBkplType.setStatus('mandatory')
chassisPs1Type = MibScalar((1, 3, 6, 1, 4, 1, 203, 1, 1, 2, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("other", 1), ("none", 2), ("w50", 3), ("w200", 4), ("w600", 5)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: chassisPs1Type.setStatus('mandatory')
chassisPs1Status = MibScalar((1, 3, 6, 1, 4, 1, 203, 1, 1, 2, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("other", 1), ("ok", 2), ("minorFault", 3), ("majorFault", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: chassisPs1Status.setStatus('mandatory')
chassisPs1TestResult = MibScalar((1, 3, 6, 1, 4, 1, 203, 1, 1, 2, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: chassisPs1TestResult.setStatus('mandatory')
chassisPs2Type = MibScalar((1, 3, 6, 1, 4, 1, 203, 1, 1, 2, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("other", 1), ("none", 2), ("w50", 3), ("w200", 4), ("w600", 5)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: chassisPs2Type.setStatus('mandatory')
chassisPs2Status = MibScalar((1, 3, 6, 1, 4, 1, 203, 1, 1, 2, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("other", 1), ("ok", 2), ("minorFault", 3), ("majorFault", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: chassisPs2Status.setStatus('mandatory')
chassisPs2TestResult = MibScalar((1, 3, 6, 1, 4, 1, 203, 1, 1, 2, 8), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: chassisPs2TestResult.setStatus('mandatory')
chassisFanStatus = MibScalar((1, 3, 6, 1, 4, 1, 203, 1, 1, 2, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("other", 1), ("ok", 2), ("minorFault", 3), ("majorFault", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: chassisFanStatus.setStatus('mandatory')
chassisFanTestResult = MibScalar((1, 3, 6, 1, 4, 1, 203, 1, 1, 2, 10), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: chassisFanTestResult.setStatus('mandatory')
chassisMinorAlarm = MibScalar((1, 3, 6, 1, 4, 1, 203, 1, 1, 2, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("off", 1), ("on", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: chassisMinorAlarm.setStatus('mandatory')
chassisMajorAlarm = MibScalar((1, 3, 6, 1, 4, 1, 203, 1, 1, 2, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("off", 1), ("on", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: chassisMajorAlarm.setStatus('mandatory')
chassisTempAlarm = MibScalar((1, 3, 6, 1, 4, 1, 203, 1, 1, 2, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("off", 1), ("on", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: chassisTempAlarm.setStatus('mandatory')
chassisNumSlots = MibScalar((1, 3, 6, 1, 4, 1, 203, 1, 1, 2, 14), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: chassisNumSlots.setStatus('mandatory')
chassisSlotConfig = MibScalar((1, 3, 6, 1, 4, 1, 203, 1, 1, 2, 15), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: chassisSlotConfig.setStatus('mandatory')
moduleTable = MibTable((1, 3, 6, 1, 4, 1, 203, 1, 1, 3, 1), )
if mibBuilder.loadTexts: moduleTable.setStatus('mandatory')
moduleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 203, 1, 1, 3, 1, 1), ).setIndexNames((0, "CRESCENDO-MIB", "moduleIndex"))
if mibBuilder.loadTexts: moduleEntry.setStatus('mandatory')
moduleIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 203, 1, 1, 3, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: moduleIndex.setStatus('mandatory')
moduleType = MibTableColumn((1, 3, 6, 1, 4, 1, 203, 1, 1, 3, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("other", 1), ("empty", 2), ("c1000", 3), ("c1001", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: moduleType.setStatus('mandatory')
moduleSerialNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 203, 1, 1, 3, 1, 1, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: moduleSerialNumber.setStatus('mandatory')
moduleHwHiVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 203, 1, 1, 3, 1, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: moduleHwHiVersion.setStatus('mandatory')
moduleHwLoVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 203, 1, 1, 3, 1, 1, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: moduleHwLoVersion.setStatus('mandatory')
moduleFwHiVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 203, 1, 1, 3, 1, 1, 6), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: moduleFwHiVersion.setStatus('mandatory')
moduleFwLoVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 203, 1, 1, 3, 1, 1, 7), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: moduleFwLoVersion.setStatus('mandatory')
moduleSwHiVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 203, 1, 1, 3, 1, 1, 8), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: moduleSwHiVersion.setStatus('mandatory')
moduleSwLoVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 203, 1, 1, 3, 1, 1, 9), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: moduleSwLoVersion.setStatus('mandatory')
moduleStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 203, 1, 1, 3, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("other", 1), ("ok", 2), ("minorFault", 3), ("majorFault", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: moduleStatus.setStatus('mandatory')
moduleTestResult = MibTableColumn((1, 3, 6, 1, 4, 1, 203, 1, 1, 3, 1, 1, 11), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: moduleTestResult.setStatus('mandatory')
moduleReset = MibTableColumn((1, 3, 6, 1, 4, 1, 203, 1, 1, 3, 1, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("other", 1), ("reset", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: moduleReset.setStatus('mandatory')
moduleName = MibTableColumn((1, 3, 6, 1, 4, 1, 203, 1, 1, 3, 1, 1, 13), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: moduleName.setStatus('mandatory')
moduleNumPorts = MibTableColumn((1, 3, 6, 1, 4, 1, 203, 1, 1, 3, 1, 1, 14), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: moduleNumPorts.setStatus('mandatory')
modulePortStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 203, 1, 1, 3, 1, 1, 15), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readonly")
if mibBuilder.loadTexts: modulePortStatus.setStatus('mandatory')
portTable = MibTable((1, 3, 6, 1, 4, 1, 203, 1, 1, 4, 1), )
if mibBuilder.loadTexts: portTable.setStatus('mandatory')
portEntry = MibTableRow((1, 3, 6, 1, 4, 1, 203, 1, 1, 4, 1, 1), ).setIndexNames((0, "CRESCENDO-MIB", "portModuleIndex"), (0, "CRESCENDO-MIB", "portIndex"))
if mibBuilder.loadTexts: portEntry.setStatus('mandatory')
portModuleIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 203, 1, 1, 4, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: portModuleIndex.setStatus('mandatory')
portIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 203, 1, 1, 4, 1, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: portIndex.setStatus('mandatory')
portFddiIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 203, 1, 1, 4, 1, 1, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: portFddiIndex.setStatus('mandatory')
portName = MibTableColumn((1, 3, 6, 1, 4, 1, 203, 1, 1, 4, 1, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: portName.setStatus('mandatory')
portType = MibTableColumn((1, 3, 6, 1, 4, 1, 203, 1, 1, 4, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("other", 1), ("cddi", 2), ("fiber", 3), ("multiMedia", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: portType.setStatus('mandatory')
portStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 203, 1, 1, 4, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("other", 1), ("ok", 2), ("minorFault", 3), ("majorFault", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: portStatus.setStatus('mandatory')
mibBuilder.exportSymbols("CRESCENDO-MIB", moduleNumPorts=moduleNumPorts, chassisMinorAlarm=chassisMinorAlarm, concTrapReceiverType=concTrapReceiverType, crescendoProducts=crescendoProducts, chassisType=chassisType, chassisPs1TestResult=chassisPs1TestResult, chassisMajorAlarm=chassisMajorAlarm, chassisSlotConfig=chassisSlotConfig, modulePortStatus=modulePortStatus, chassisPs1Status=chassisPs1Status, moduleHwHiVersion=moduleHwHiVersion, concCommunityEntry=concCommunityEntry, chassisFanTestResult=chassisFanTestResult, chassisPs2TestResult=chassisPs2TestResult, chassisFanStatus=chassisFanStatus, concIpAddr=concIpAddr, chassisPs2Status=chassisPs2Status, moduleReset=moduleReset, chassisPs2Type=chassisPs2Type, concTrapReceiverComm=concTrapReceiverComm, concNetMask=concNetMask, moduleStatus=moduleStatus, chassisPs1Type=chassisPs1Type, chassisNumSlots=chassisNumSlots, concBroadcast=concBroadcast, concTrapReceiverTable=concTrapReceiverTable, concMgmtType=concMgmtType, moduleHwLoVersion=moduleHwLoVersion, moduleSwLoVersion=moduleSwLoVersion, moduleTestResult=moduleTestResult, moduleIndex=moduleIndex, moduleType=moduleType, crescendo=crescendo, module=module, concTrapReceiverEntry=concTrapReceiverEntry, concCommunityString=concCommunityString, moduleTable=moduleTable, portType=portType, concBaudRate=concBaudRate, chassisTempAlarm=chassisTempAlarm, portEntry=portEntry, moduleFwLoVersion=moduleFwLoVersion, moduleSwHiVersion=moduleSwHiVersion, moduleSerialNumber=moduleSerialNumber, concAttachType=concAttachType, portIndex=portIndex, moduleFwHiVersion=moduleFwHiVersion, moduleName=moduleName, chassis=chassis, portName=portName, port=port, concCommunityAccess=concCommunityAccess, concentrator=concentrator, portStatus=portStatus, concTrapReceiverAddr=concTrapReceiverAddr, conc=conc, concCommunityTable=concCommunityTable, concTraffic=concTraffic, moduleEntry=moduleEntry, portTable=portTable, portFddiIndex=portFddiIndex, chassisBkplType=chassisBkplType, concReset=concReset, portModuleIndex=portModuleIndex)
|
la_liga_goals = 43
champions_league_goals = 10
copa_del_rey_goals = 5
total_goals = la_liga_goals + champions_league_goals + copa_del_rey_goals
|
"""
Too Long
Print and remove all elements with length
greater than 4 in a given list of strings.
"""
the_list = ["dragon", "cab", "science", "dove", "lime", "river", "pop"]
to_remove = []
for x in the_list: # iterates through every element in the list
if len(x) > 4: # if the element length is greater than 4
print(x) # prints the element
to_remove.append(x) # appends element to remove list
for y in to_remove: # iterates through every element meant to be removed
the_list.remove(y) # removes element from list
|
class NoUserIdOrSessionKeyError(Exception):
pass
class NoProductToDelete(Exception):
pass
class NoCart(Exception):
pass
class BadConfigError(Exception):
pass
|
"""WizCoin
By Al Sweigart test@gmail.com
A basic Python project."""
__version__ = '0.1.0'
|
def main():
*t, n = map(int, input().split())
t=list(t)
for i in range(2, n):
t.append(t[i-2] + t[i-1]*t[i-1])
print(t[-1])
if __name__ == '__main__':
main()
|
'''
Created on Oct 2, 2012
@author: vadim
Todo: need to learn string algorithms.
'''
f = open('data/keylog.txt')
mx = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
while True:
line = f.readline()
if not line:
break
line = line[:-1]
mx[int(line[0])][int(line[1])] += 1
mx[int(line[1])][int(line[2])] += 1
for l in mx:
print(l)
f.close()
if __name__ == '__main__':
pass
|
""" CSCI 204, Stack lab """
""" Tongyu Yang CSCI204 Lab06 """
class MyStack:
""" Implement this Stack ADT using a Python list to hold elements.
Do NOT use the len() feature of lists.
"""
CAPACITY = 10
def __init__( self ):
""" Initialize an empty stack. """
self._capacity = MyStack.CAPACITY
self._size = 0
self._array = [None] * self._capacity
def isEmpty( self ):
""" Is the stack empty?
Returns True if the stack is empty; False otherwise. """
if self._size == 0:
return True
else:
return False
def push( self, item ):
""" Push the item onto the top of the stack. """
if self._size == 0:
self._array[0] = item
else:
if self._size == self._capacity:
new_array = [None] * (2 * self._capacity)
self._capacity *= 2
else:
new_array = [None] * self._capacity
new_array[0] = item
for index in range(self._capacity - 1):
new_array[index + 1] = self._array[index]
self._array = new_array
self._size += 1
def pop( self ):
""" Pop the top item off the stack and return it. """
if self._size == 0:
return None
else:
popped_item = self._array[0]
for index in range(self._capacity - 1):
self._array[index] = self._array[index + 1]
self._size -= 1
return popped_item
def peek( self ):
""" Return the top item on the stack (does not change the stack). """
return self._array[0]
def __repr__ (self):
return str(self._array)
# stack=MyStack()
# print(stack.isEmpty())
# stack.push(1)
# print(stack)
# stack.push(2)
# stack.push(3)
# print(stack)
# stack.pop()
# print(stack)
# stack.pop()
# print(stack)
# stack.pop()
# print(stack)
# print(stack.peek())
|
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
class MXD(object):
def __init__(self, ab, key, cut, erc, shortname):
"""
:param ab:
:param key: property name which returns a dict with numerical values
:param cut: warn/error/fatal maximum permissable deviations, exceeding error level yields non-zero RC
:param erc: integer return code if any of the values exceeds the cut
RC passed from python to C++ via system calls
are truncated beyond 0xff see: SSysTest
"""
self.ab = ab
self.key = key
self.cut = cut
self.erc = erc
self.shortname = shortname
mxd = property(lambda self:getattr(self.ab, self.key))
def _get_mx(self):
mxd = self.mxd
return max(mxd.values()) if len(mxd) > 0 else 999.
mx = property(_get_mx)
def _get_rc(self):
return self.erc if self.mx > self.cut[1] else 0
rc = property(_get_rc)
def __repr__(self):
mxd = self.mxd
pres_ = lambda d:" ".join(map(lambda kv:"%10s : %8.3g " % (kv[0], kv[1]),d.items()))
return "\n".join(["%s .rc %d .mx %7.3f .cut %7.3f/%7.3f/%7.3f %s " % ( self.shortname, self.rc, self.mx, self.cut[0], self.cut[1], self.cut[2], pres_(mxd) )])
class RC(object):
def __init__(self, ab ):
self.ab = ab
self.c2p = MXD(ab, "c2p", ab.ok.c2max, 77, "ab.rc.c2p")
self.rdv = MXD(ab, "rmxs", ab.ok.rdvmax, 88, "ab.rc.rdv")
self.pdv = MXD(ab, "pmxs", ab.ok.pdvmax, 99, "ab.rc.pdv")
def _get_rcs(self):
return map(lambda _:_.rc, [self.c2p, self.rdv, self.pdv])
rcs = property(_get_rcs)
def _get_rc(self):
return max(self.rcs+[0])
rc = property(_get_rc)
def __repr__(self):
return "\n".join([
"ab.rc .rc %3d %r " % (self.rc, self.rcs) ,
repr(self.c2p),
repr(self.rdv),
repr(self.pdv),
"."
])
|
# Swap assign variables
print("Enter 3 no.s:")
a = float(input("a: "))
b = float(input("b: "))
c = float(input("c: "))
a, b = a+b, b+c
print("Variables are: ")
print("a:", a)
print("b:", b)
print("c:", c)
|
class A:
def __setitem__(self, e, f):
print(e + f)
a = A()
a[2] = 8
|
"""
for i in range(1,101,2):
if(i%7==0):
continue
print(i)
"""
c=0
while c<=100:
if(c%2!=0 and c%7!=0):
print(c)
c=c+1
|
cpp_config = [
'query-lib/official/cpp/codeql-suites/cpp-security-and-quality.qls',
'query-lib/official/cpp/codeql-suites/cpp-security-extended.qls',
]
js_config = []
# exported
lang_configs = {
'cpp' : cpp_config,
'javascript' : js_config
}
need_compile = ['cpp', 'java']
|
# Push (temp, idx) in a stack. Pop element when a bigger elem is seen and update arr[idx] with (new_idx-idx).
# class Solution:
# def dailyTemperatures(self, T: List[int]) -> List[int]:
# S = []
# res = [0]*len(T)
# for i in range(len(T)-1, -1, -1):
# while S and T[S[-1]] <= T[i]:
# S.pop()
# if S:
# res[i] = S[-1] - i
# S.append(i)
# return res
class Solution:
# Time: O(n)
# Space: O(n)
def dailyTemperatures(self, T: List[int]) -> List[int]:
res = [0]*len(T)
stack = []
for i, t1 in enumerate(T):
while stack and t1 > stack[-1][1]:
j, t2 = stack.pop()
res[j] = i - j
stack.append((i, t1))
return res
|
class OrderBook:
"""
Implements data structure to append messages one at a time
"""
def __init__(self):
# bids, asks
self.book = (dict(), dict())
def bestBid(self):
if not self.book[0].keys():
return (float('nan'), float('nan'))
price = max(self.book[0].keys())
return (price, self.book[0][price])
def bestAsk(self):
if not self.book[1].keys():
return (float('nan'), float('nan'))
price = min(self.book[1].keys())
return (price, self.book[1][price])
def update(self, message):
buySell = 'Buy' in message.Flags
addDel = 'Add' in message.Flags
price = message.Price
amount = message.Amount
amountRest = message.AmountRest
if addDel:
if not price in self.book[1-buySell]:
self.book[1-buySell][price] = 0
self.book[1-buySell][price] += amount
else:
self.book[1-buySell][price] -= amount
if self.book[1-buySell][price] < 0:
raise RuntimeError('Negative ammount is generated in order book')
if self.book[1-buySell][price] == 0:
del self.book[1-buySell][price]
def updateBulk(self, messages):
for name, message in messages.iterrows():
self.update(message)
|
class BaseType:
def __init__(self, db_type: str, python_type: type):
self.db_type = db_type
self.python_type = python_type
Float = BaseType("REAL", float)
Int = BaseType("INTEGER", int)
String = BaseType("TEXT", str)
TypeMap = {
float: Float,
int: Int,
str: String
}
|
'''
UFCG
PROGRAMAÇÃO 1
JOSE ARTHUR NEVES DE BRITO - 119210204
PRECO DE VENDA
'''
custo = float(input())
desp_indireta = float(input())
lucro_desj = float(input())
impostos = float(input())
comissao = float(input())
desc = float(input())
encargos = float(input())
preco = ((custo + desp_indireta + lucro_desj)*100) / 100 - ((impostos - comissao - desc - encargos))
print(preco)
|
album_info = {
'Arrival - ABBA': {
'image': 'arrival.jpg',
'spotify_link_a': '1M4anG49aEs4YimBdj96Oy',
},
}
|
print('Hello, world.')
print('Hello, Python!')
print(2 + 3)
print('2' * 3)
print(f'2 + 3 = {2 + 3}')
print('1', '2', '3', sep=' + ', end=' ')
print('=', 1 + 2 + 3, end='')
print('!')
|
"""Escreva um programa que leia um número N inteiro qualquer e mostre na tela os N primeiros elementos
de uma Sequência de Fibonacci. Exemplo:
0 – 1 – 1 – 2 – 3 – 5 – 8 """
print('=*'*26)
print('*'*14, 'SEQUENCIA DE FIBONACCI', '*'*14)
print('=*'*26)
n = int(input('Quantos termos você quer mostrar? '))
t1 = 0
t2 = 1
t3 = 0
c = 3
print('{} → {}'.format(t1, t2), end='')
while c < n:
t3 = t1 + t2
print(' → {}'.format(t3), end='')
t1 = t2
t2 = t3
c += 1
|
class Settings():
'''Uma classe para armazenar todas as configurações do jogo.'''
def __init__(self):
'''Inicializa as configurações do jogo.'''
# Configurações da tela
self.screen_width = 1000
self.screen_height = 600
self.bg_color = (230, 230, 230)
# Configurações da espaçonave
self.ship_speed_factor = 1.5
|
#!/usr/bin/env python
#coding: utf-8
class Solution:
# @param A, a list of integers
# @return an integer
def firstMissingPositive(self, A):
if not A: return 1
la = len(A)
i = 0
while i < la:
if i + 1 == A[i]:
i += 1
continue
if A[i] <= 0:
i += 1
continue
j = A[i]
while j > 0 and j <= la and j != A[j-1] and j != i:
t = A[j-1]
A[j-1] = j
j = t
if j > 0 and j <= la and j != A[j-1]: A[j-1] = j
i += 1
i = 1
while i <= la:
if A[i-1] != i: return i
i += 1
return A[la-1] + 1
if __name__ == '__main__':
s = Solution()
assert 3 == s.firstMissingPositive([1,2,0])
assert 2 == s.firstMissingPositive([3,4,-1,1])
assert 2 == s.firstMissingPositive([1,1])
assert 3 == s.firstMissingPositive([1,1,2,2])
assert 2 == s.firstMissingPositive([1,1,3,3])
assert 1 == s.firstMissingPositive([])
assert 1 == s.firstMissingPositive([2])
assert 3 == s.firstMissingPositive([2,1])
|
def xor(a, b):
return (a or b) and not (a and b)
def collapse_polymer(polymer):
pos = 0
while pos + 1 < len(polymer):
first = polymer[pos]
second = polymer[pos + 1]
if first.lower() == second.lower() and xor(first.isupper(), second.isupper()):
if pos + 2 >= len(polymer):
polymer = polymer[0:pos]
else:
polymer = polymer[0:pos] + polymer[pos + 2:]
pos = max(0, pos - 1)
else :
pos += 1
return polymer
def find_shortest_poly_by_removing_one_type(polymer):
alphabet = "abcdefghijklmnopqrstuvwxyz"
ans = polymer
for letter in alphabet:
tst = polymer.replace(letter.lower(), '')
tst = tst.replace(letter.upper(), '')
tmp = collapse_polymer(tst)
if len(tmp) < len(ans):
ans = tmp
return ans
|
class Aula:
def __init__(self, id, numero, titulo):
self._id = id
self._numero = numero
self._titulo = titulo
def get_id(self):
return self._id
def get_numero(self):
return self._numero
def get_titulo(self):
return self._titulo
|
# -*- coding: utf-8 -*-
# spróbój czegos takiego jak
def index(): return dict()
def kupon():
if not session.ids:
session.ids=[]
else:
session.ids.append(2)
return request.vars.text_value
def testFunction(a):
if not request.vars.a:
request.vars.a=123
session.id=request.vars.a
return session.id
def aaa(a):
if not request.vars.a:
request.vars.a=123
session.id=request.vars.a
return session.id
def add_session():
game_id=request.vars.game_id
a=request.vars.game
home=request.vars.home
away=request.vars.away
typ=request.vars.typ
odd=request.vars.odd
custom_id=game_id+odd
kurs=request.vars.kurs
#if request.vars.cos:
# session.cos=request.vars.cos
if not session['games']:
session['games']={}
if custom_id in session.games:
del(session.games[custom_id])
elif game_id is not None:
session.games[custom_id]={}
session.games[custom_id]['home']=home
session.games[custom_id]['away']=away
session.games[custom_id]['typ']=typ
session.games[custom_id]['odd']=odd
session.games[custom_id]['kurs']=kurs
return locals()
def one():
return dict()
def echo():
return "jQuery('#target').html(%s);" % repr(request.vars.name)
def kwota():
try:
cash=int(request.vars.name) * 2.05 * 1.98 * 0.88
except:
cash=0
return cash
def podatek():
try:
tax=int(request.vars.name) * 0.12
except:
tax=0
return tax
def clear_session():
session=None
return locals
def echo():
return "jQuery('#target').html(%s);" % repr(session)
|
class Queue(object):
def __init__(self):
self.q = []
def push(self, value):
self.q.insert(0, value)
def pop(self):
return self.q.pop()
def is_empty(self):
return self.q == []
def size(self):
return len(self.q)
# Example
q = Queue()
q.push(1)
q.push(2)
q.push(3)
print(q.q) # [3, 2, 1]
q.pop()
print(q.q) # [3, 2]
|
"""
@Author: huuuuusy
@GitHub: https://github.com/huuuuusy
系统: Ubuntu 18.04
IDE: VS Code 1.37
工具: python == 3.7.3
"""
"""
思路:
动态规划
结果:
执行用时 : 36 ms, 在所有 Python3 提交中击败了98.50%的用户
内存消耗 : 13.7 MB, 在所有 Python3 提交中击败了5.14%的用户
"""
class Solution:
def uniquePaths(self, m, n):
dp = [[1]*n] + [[1]+[0] * (n-1) for _ in range(m-1)] # 注意,对于第一行 dp[0][j],或者第一列 dp[i][0],由于都是在边界,所以只能为 1
# 动态方程:dp[i][j] = dp[i-1][j] + dp[i][j-1]
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i-1][j] + dp[i][j-1]
return dp[-1][-1]
if __name__ == "__main__":
m = 3
n = 2
answer = Solution().uniquePaths(m, n)
print(answer)
|
file = open("day 04/Toon - Python/input", "r")
lines = file.readlines()
numbers = [int(x) for x in lines[0][:-1].split(',')]
boards = [[int(x) for x in line[:-1].split(' ') if x != '' ] for line in lines[2:]]
boards = [boards[i*6:i*6+5] for i in range(100)]
def contains_bingo(board):
return -5 in [sum(line) for line in board] or -5 in [sum(line) for line in [list(i) for i in zip(*board)]]
found = False
for number in numbers:
for i in range(len(boards)):
boards[i] = [[-1 if x == number else x for x in line] for line in boards[i]]
if contains_bingo(boards[i]):
result = boards[i]
result_number = number
found = True
if found:
break
def sum_board(board):
return sum([sum([0 if x == -1 else x for x in line]) for line in board])
print("part 1: %s" % (sum_board(result) * number))
boards = [[int(x) for x in line[:-1].split(' ') if x != '' ] for line in lines[2:]]
boards = [boards[i*6:i*6+5] for i in range(100)]
def find_last(boards, numbers):
good_boards = []
bad_boards = []
for i in range(len(boards)):
boards[i] = [[-1 if x == numbers[0] else x for x in line] for line in boards[i]]
if not contains_bingo(boards[i]):
good_boards += [boards[i]]
else:
bad_boards += [boards[i]]
if len(good_boards) == 0:
return sum_board(bad_boards[0]) * numbers[0]
return find_last(good_boards, numbers[1:])
print("part 2: %s" % find_last(boards, numbers))
|
# Faça um programa que leia 5 valores numéricos e guarde-os em uma lista.
# No final, mostre qual foi o maior e o menor valor digitado e as suas respectivas posições na lista.
print('—' * 60)
lista = []
for contador in range(0, 5):
lista.append(int(input(f'Digite um valor para a Posição {contador}: ')))
maior = max(lista)
menor = min(lista)
print('—' * 60)
print(f'Você digitou os valores {lista}')
print(f'O maior valor digitado foi → {maior} ← e apareceu na Posição → {lista.index(maior)} ←')
print(f'O menor valor digitado foi → {menor} ← e apareceu na Posição → {lista.index(menor)} ←')
print('—' * 60)
|
class Solution:
# s3的最后一个字符是从s1尾巴来的或者s2尾巴来的
# s3的前i个字符是s1的前个字符和s2的前k个字符交错形成的
# 降维, i = j + k, 不用开三维数组, 降到2维
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
m, n = len(s1), len(s2)
if m + n != len(s3):
return False
f = [[False] * (n + 1) for _ in range(m + 1)]
f[0][0] = True
for i in range(0, m + 1):
for j in range(0, n + 1):
if i == 0 and j == 0:
continue
if j == 0:
f[i][j] = f[i - 1][j] and s1[i - 1] == s3[i - 1]
continue
if i == 0:
f[i][j] = f[i][j - 1] and s2[j - 1] == s3[j - 1]
continue
if (s2[j - 1] == s3[i + j - 1] and f[i][j - 1]) or (s1[i - 1] == s3[i + j - 1] and f[i - 1][j]):
f[i][j] = True
return f[-1][-1]
|
listOriginPath = [
{
"header": "test.example.com",
"httpPort": 80,
"mappingUniqueId": "993419389425697",
"origin": "10.10.10.1",
"originType": "HOST_SERVER",
"path": "/example",
"status": "RUNNING"
},
{
"header": "test.example.com",
"httpPort": 80,
"mappingUniqueId": "993419389425697",
"origin": "10.10.10.1",
"originType": "HOST_SERVER",
"path": "/example1",
"status": "RUNNING"
}
]
createOriginPath = [
{
"header": "test.example.com",
"httpPort": 80,
"mappingUniqueId": "993419389425697",
"origin": "10.10.10.1",
"originType": "HOST_SERVER",
"path": "/example",
"status": "RUNNING",
"bucketName": "test-bucket",
'fileExtension': 'jpg',
"performanceConfiguration": "General web delivery"
}
]
deleteOriginPath = "Origin with path /example/videos/* has been deleted"
|
# -- coding:utf-8--
my_games = {
"pc":"GTA5",
"mac_os":"final_cut_pro",
"ipad":"皇室战争",
"iphone":"皇权",
}
print(my_games)
#中文编码不支持!
|
@jit(nopython=True)
def pressure_poisson(p, b, l2_target):
J, I = b.shape
iter_diff = l2_target + 1
n = 0
while iter_diff > l2_target and n <= 500:
pn = p.copy()
for i in range(1, I - 1):
for j in range(1, J - 1):
p[j, i] = (.25 * (pn[j, i + 1] +
pn[j, i - 1] +
pn[j + 1, i] +
pn[j - 1, i]) -
b[j, i])
for j in range(J):
p[j, 0] = p[j, 1]
p[j, -1] = p[j, -2]
for i in range(I):
p[0, i] = p[1, i]
p[-1, i] = 0
if n % 10 == 0:
iter_diff = numpy.sqrt(numpy.sum((p - pn)**2)/numpy.sum(pn**2))
n += 1
return p
|
a = [int(x) for x in input().split()]
time = None
# a[0] initial hour
# a[1] initial min
# a[2] final hour
# a[3] final min
start = 60 * a[0] + a[1]
finish = 60 * a[2] + a[3]
if finish <= start:
finish += 1440 # 24 * 60
time = finish - start
print(f"O JOGO DUROU {int(time / 60)} HORA(S) E {int(time % 60)} MINUTO(S)")
|
n = int(input('Digite um número inteiro: '))
n0 = contador = 0
n1 = 1
print('{} {}'.format(n0, n1), end=' ')
while contador < (n - 2):
n2 = n0 + n1
print(n2, end=' ')
n0 = n1
n1 = n2
contador += 1
|
def Compute_kmeans_inertia(resultsDict, FSWRITE = False, gpu_available = False):
# Measure inertia of kmeans model for a variety of values of cluster number n
km_list = list()
data = resultsDict['PCA_fit_transform']
#data = resultsDict['NP_images_STD']
N_clusters = len(resultsDict['imagesFilenameList'])
if gpu_available:
print('Running Compute_kmeans_inertia on GPU: ')
with gpu_context():
for clust in range(1,N_clusters):
km = KMeans(n_clusters=clust, init='random', random_state=42)
km = km.fit(data)
km_list.append({'clusters': clust,
'inertia': km.inertia_,
'model': km})
# It is possible to specify to make the computations on CPU
else:
print('Running Compute_kmeans_inertia on local CPU: ')
for clust in range(1,N_clusters):
km = KMeans(n_clusters=clust, init='random', random_state=42)
km = km.fit(data)
km_list.append({'clusters': clust,
'inertia': km.inertia_,
'model': km})
resultsDict['km'] = km
resultsDict['km_list'] = km_list
if FSWRITE == True:
write_results(resultsDict)
return resultsDict
|
num = 11
while num <= 10:
num += 1
if num == 3:
continue
if num == 4:
print('4')
break
else:
#不满足条件或程序报错
print('wrong')
print() # 等价于print(end = "\n") 自动换行
print(end = "\n")
|
n_students = int(input())
skills = list(input().split(" "))
skills = [int(skill) for skill in skills]
skills = sorted(skills)
n_problems = 0
ptr1 = n_students - 1
ptr2 = n_students - 2
while ptr2 >= 0:
if (skills[ptr1] == skills[ptr2]):
ptr1 -= 2
ptr2 -= 2
else:
n_problems += 1
skills[ptr2] += 1
print(n_problems)
|
"""
0011. Container With Most Water
Medium
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.
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
Example 3:
Input: height = [4,3,2,1,4]
Output: 16
Example 4:
Input: height = [1,2,1]
Output: 2
Constraints:
2 <= height.length <= 3 * 104
0 <= height[i] <= 3 * 104
"""
class Solution:
def maxArea(self, height: List[int]) -> int:
i, j, res = 0, len(height) - 1, 0
while i < j:
if height[i] < height[j]:
res = max(res, height[i] * (j - i))
i += 1
else:
res = max(res, height[j] * (j - i))
j -= 1
return res
|
teste = [0, 2, 3, 4, 5]
print(teste)
teste.insert(0, teste[3])
print(teste)
teste.pop(4)
print(teste)
|
# -*- coding: utf-8 -*-
"""Top-level package for ePages Client."""
__author__ = """Pekka Piispanen, Tero Kotti"""
__email__ = 'pekka@vilkas.fi, tero@vilkas.fi'
__version__ = '0.2.0'
|
arr = [1, 2, 3, 4, 4, 4, 5, 6, 6, 7, 8, 9]
arr.sort()
my_dict = {i:arr.count(i) for i in arr}
# sorting the dictionary based on value
my_dict = {k: v for k, v in sorted(my_dict.items(), key=lambda item: item[1])}
print(len(my_dict))
print(my_dict)
list = list(my_dict.keys())
print(list[-1])
|
# Model parameters
model_hidden_size = 768
model_embedding_size = 256
model_num_layers = 1
# Training parameters
n_steps = 2e4
learning_rate_init = 1e-3
speakers_per_batch = 16
utterances_per_speaker = 32
## Tensor-train parameters for last linear layer.
compression = 'tt'
n_cores = 2
rank = 2
# Evaluation and Test parameters
val_speakers_per_batch = 40
val_utterances_per_speaker = 32
test_speakers_per_batch = 40
test_utterances_per_speaker = 32
# seed = None
|
"""*******************************************************
This module has functions converting energies
*****************************************************
"""
#print __doc__
def convert_energy(Energy, Input_unit, Output_unit):#converts distance modulus to distance in parsec
"""Description: ocnverts energy from Input_unit to Output_unit.
Input :- Energy to be converted
- Input unit. Can be:
'erg' - ergs
'J' - Jouls
'Hz' - Frequency [1/s]
'A','Ang'- Wavelength [Ang]
'cm' - Wavelength [cm]
'nm' - Wavelength [nm]
'm' - Wavelength [m]
'eV' - Electron volts [h nu/q]
'keV' - kilo Electron volts [h nu/q]
'MeV' - Mega Electron volts [h nu/q]
'GeV' - Giga Electron volts [h nu/q]
'T' - Temperature [K]
'me' - Electron mass [E/m_e]
'mp' - Proton mass [E/m_p]
'cal' - calorie (4.184 J)
'Btu' - (1.055x10^3 J)
'kWh' - kilowatt-hour (3.6x10^6 J)
'TNT' - one ton of TNT (4.2x10^9 J)
'gr' - Energy equivalent of 1 gram of matter (9x10^13 J)
- requested output unit. One of the above.
Output :- Energy in output system
Tested : ?
By : Maayane T. Soumagnac Nov 2016
URL :
Example:
Reliable: """
Erg2Erg = 1.
Erg2J = 1e-7# 1erg=10**-7J
#Erg2Hz = 1.5092e26#?
#Erg2A = 1.9864e-8 #?
Erg2eV = 6.2415e11
#Erg2T = 7.2430e15#?
Erg2me = 1.2214e6
Erg2mp = 665.214577
Erg2cal = Erg2J/4.184
Erg2Btu = Erg2J/1.055e3
Erg2kWh = Erg2J/3.6e6
Erg2TNT = Erg2J/4.2e9
#Erg2gr = get_constant('c', 'cgs'). ^ -2
relation='inv'
if Input_unit.lower()=='erg':
ConvFactor = Erg2Erg
elif Input_unit.lower()=='j':
ConvFactor=Erg2J
#elif Input_unit.lower()=='hz':
# ConvFactor=Erg2Hz
#elif Input_unit.lower() in ('a','ang'):
# relation='inv'
# ConvFactor=Erg2A
'''
elif Input_unit.lower()=='cm':
relation='inv'
ConvFactor=Erg2A*1e-8
elif Input_unit.lower()=='nm':
relation='inv'
ConvFactor=Erg2A*1e-4
#elif Input_unit.lower()=='m':
# relation='inv'
# ConvFactor=Erg2A*1e-10
elif Input_unit.lower()=='ev':
ConvFactor = Erg2eV
elif Input_unit.lower()=='kev':
ConvFactor = Erg2eV*1e-3
elif Input_unit.lower()=='mev':
ConvFactor = Erg2eV*1e-6
elif Input_unit.lower()=='gev':
ConvFactor = Erg2eV* 1e-9
#elif Input_unit.lower()=='t':
# ConvFactor = Erg2T
elif Input_unit.lower()=='me':
ConvFactor = Erg2me
elif Input_unit.lower()=='mp':
ConvFactor = Erg2mp
elif Input_unit.lower()=='cal':
ConvFactor = Erg2cal
elif Input_unit.lower()=='btu':
ConvFactor = Erg2Btu
elif Input_unit.lower()=='kwh':
ConvFactor = Erg2kWh
elif Input_unit.lower()=='tnt':
ConvFactor = Erg2TNT
#elif Input_unit =='gr':
# ConvFactor = Erg2gr
else: print 'error: unknown InUnit option'
'''
if relation=='lin':
ErgE=Energy*ConvFactor
elif relation=='inv':
ErgE=Energy/ConvFactor
else: print('unknown relation')
relation = 'lin'
if Output_unit.lower()=='erg':
ConvFactor = Erg2Erg
elif Output_unit.lower()== 'j':
ConvFactor = Erg2J
#elif Output_unit.lower()== 'hz':
# ConvFactor = Erg2Hz
#elif Output_unit.lower()== {'a','ang'}:
# relation = 'inv'
# ConvFactor = Erg2A
#elif Output_unit.lower()== 'nm':
# relation = 'inv'
# ConvFactor = Erg2A*1e-4
#elif Output_unit.lower()== 'cm':
# relation = 'inv'
# ConvFactor = Erg2A*1e-8
#elif Output_unit.lower()== 'm':
# relation = 'inv'
# ConvFactor = Erg2A*1e-10
'''
elif Output_unit.lower()== 'ev':
ConvFactor = Erg2eV
elif Output_unit.lower()== 'kev':
ConvFactor = Erg2eV*1e-3
elif Output_unit.lower()== 'mev':
ConvFactor = Erg2eV*1e-6
elif Output_unit.lower()== 'gev':
ConvFactor = Erg2eV*1e-9
#elif Output_unit.lower()== 't':
# ConvFactor = Erg2T
elif Output_unit.lower()== 'me':
ConvFactor = Erg2me
elif Output_unit.lower()== 'mp':
ConvFactor = Erg2mp
elif Output_unit.lower()== 'cal':
ConvFactor = Erg2cal
elif Output_unit.lower()== 'btu':
ConvFactor = Erg2Btu
elif Output_unit.lower()== 'kwh':
ConvFactor = Erg2kWh
elif Output_unit.lower()== 'tnt':
ConvFactor = Erg2TNT
#elif Output_unit.lower()== 'gr':
# ConvFactor = Erg2gr
else: print 'Unknown InUnit Option'
'''
if relation == 'lin':
new_energy = ErgE * ConvFactor
elif relation == 'inv':
new_energy= ErgE/ConvFactor
else:
print('unknown relation')
return new_energy
|
BRIGHTID_NODE = 'http://node.brightid.org/brightid/v5'
VERIFICATIONS_URL = BRIGHTID_NODE + '/verifications/idchain/'
OPERATION_URL = BRIGHTID_NODE + '/operations/'
CONTEXT = 'idchain'
RPC_URL = 'wss://idchain.one/ws/'
RELAYER_ADDRESS = '0x0df7eDDd60D613362ca2b44659F56fEbafFA9bFB'
DISTRIBUTION_ADDRESS = '0x6E39d7540c2ad4C18Eb29501183AFA79156e79aa'
DISTRIBUTION_ABI = '[{"inputs": [{"internalType": "address payable", "name": "beneficiary", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}], "name": "claim", "outputs": [], "stateMutability": "nonpayable", "type": "function"}, {"anonymous": false, "inputs": [{"indexed": true, "internalType": "address", "name": "previousOwner", "type": "address"}, {"indexed": true, "internalType": "address", "name": "newOwner", "type": "address"}], "name": "OwnershipTransferred", "type": "event"}, {"inputs": [], "name": "renounceOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function"}, {"inputs": [{"internalType": "address", "name": "addr", "type": "address"}], "name": "setBrightid", "outputs": [], "stateMutability": "nonpayable", "type": "function"}, {"inputs": [{"internalType": "uint256", "name": "_claimable", "type": "uint256"}], "name": "setClaimable", "outputs": [], "stateMutability": "nonpayable", "type": "function"}, {"inputs": [{"internalType": "address", "name": "newOwner", "type": "address"}], "name": "transferOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function"}, {"stateMutability": "payable", "type": "receive"}, {"inputs": [], "name": "brightid", "outputs": [{"internalType": "contract BrightID", "name": "", "type": "address"}], "stateMutability": "view", "type": "function"}, {"inputs": [], "name": "claimable", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function"}, {"inputs": [{"internalType": "address", "name": "", "type": "address"}], "name": "claimed", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function"}, {"inputs": [], "name": "owner", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function"}]'
BRIGHTID_ADDRESS = '0x72a70314C3adD56127413F78402392744af4EF64'
BRIGHTID_ABI = '[{"anonymous": false, "inputs": [{"indexed": false, "internalType": "contract IERC20", "name": "supervisorToken", "type": "address"}, {"indexed": false, "internalType": "contract IERC20", "name": "proposerToken", "type": "address"}], "name": "MembershipTokensSet", "type": "event"}, {"anonymous": false, "inputs": [{"indexed": true, "internalType": "address", "name": "previousOwner", "type": "address"}, {"indexed": true, "internalType": "address", "name": "newOwner", "type": "address"}], "name": "OwnershipTransferred", "type": "event"}, {"inputs": [{"internalType": "bytes32", "name": "context", "type": "bytes32"}, {"internalType": "address[]", "name": "addrs", "type": "address[]"}, {"internalType": "uint8", "name": "v", "type": "uint8"}, {"internalType": "bytes32", "name": "r", "type": "bytes32"}, {"internalType": "bytes32", "name": "s", "type": "bytes32"}], "name": "propose", "outputs": [], "stateMutability": "nonpayable", "type": "function"}, {"anonymous": false, "inputs": [{"indexed": true, "internalType": "address", "name": "addr", "type": "address"}], "name": "Proposed", "type": "event"}, {"inputs": [], "name": "renounceOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function"}, {"inputs": [{"internalType": "contract IERC20", "name": "_supervisorToken", "type": "address"}, {"internalType": "contract IERC20", "name": "_proposerToken", "type": "address"}], "name": "setMembershipTokens", "outputs": [], "stateMutability": "nonpayable", "type": "function"}, {"inputs": [{"internalType": "uint256", "name": "_waiting", "type": "uint256"}, {"internalType": "uint256", "name": "_timeout", "type": "uint256"}], "name": "setTiming", "outputs": [], "stateMutability": "nonpayable", "type": "function"}, {"inputs": [], "name": "start", "outputs": [], "stateMutability": "nonpayable", "type": "function"}, {"anonymous": false, "inputs": [], "name": "Started", "type": "event"}, {"inputs": [], "name": "stop", "outputs": [], "stateMutability": "nonpayable", "type": "function"}, {"anonymous": false, "inputs": [{"indexed": false, "internalType": "address", "name": "stopper", "type": "address"}], "name": "Stopped", "type": "event"}, {"anonymous": false, "inputs": [{"indexed": false, "internalType": "uint256", "name": "waiting", "type": "uint256"}, {"indexed": false, "internalType": "uint256", "name": "timeout", "type": "uint256"}], "name": "TimingSet", "type": "event"}, {"inputs": [{"internalType": "address", "name": "newOwner", "type": "address"}], "name": "transferOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function"}, {"anonymous": false, "inputs": [{"indexed": true, "internalType": "address", "name": "addr", "type": "address"}], "name": "Verified", "type": "event"}, {"inputs": [{"internalType": "bytes32", "name": "context", "type": "bytes32"}, {"internalType": "address[]", "name": "addrs", "type": "address[]"}], "name": "verify", "outputs": [], "stateMutability": "nonpayable", "type": "function"}, {"inputs": [{"internalType": "address", "name": "", "type": "address"}], "name": "history", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function"}, {"inputs": [{"internalType": "address", "name": "", "type": "address"}], "name": "isRevoked", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "view", "type": "function"}, {"inputs": [], "name": "owner", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "stateMutability": "view", "type": "function"}, {"inputs": [{"internalType": "bytes32", "name": "", "type": "bytes32"}], "name": "proposals", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function"}, {"inputs": [], "name": "proposerToken", "outputs": [{"internalType": "contract IERC20", "name": "", "type": "address"}], "stateMutability": "view", "type": "function"}, {"inputs": [], "name": "stopped", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "stateMutability": "view", "type": "function"}, {"inputs": [], "name": "supervisorToken", "outputs": [{"internalType": "contract IERC20", "name": "", "type": "address"}], "stateMutability": "view", "type": "function"}, {"inputs": [], "name": "timeout", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function"}, {"inputs": [{"internalType": "address", "name": "", "type": "address"}], "name": "verifications", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function"}, {"inputs": [], "name": "waiting", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "stateMutability": "view", "type": "function"}]'
NOT_FOUND = 2
NOT_SPONSORED = 4
CHAINID = '0x4a'
GAS = 500000
GAS_PRICE = 10000000000
WAITING_TIME_AFTER_PROPOSING = 15
LINK_CHECK_NUM = 18
LINK_CHECK_PERIOD = 10
SPONSOR_CHECK_NUM = 6
SPONSOR_CHECK_PERIOD = 10
HOST = 'localhost'
PORT = 5000
SPONSORSHIP_PRIVATEKEY = ''
RELAYER_PRIVATE = ''
|
# Time: O(n log n); Space: O(n)
def target_indices(nums, target):
nums.sort()
ans = []
for i, n in enumerate(nums):
if n == target:
ans.append(i)
return ans
# Time: O(n + k); Space(n + k)
def target_indices2(nums, target):
count = [0] * (max(nums) + 1)
for n in nums:
count[n] += 1
sorted_nums = []
for i, n in enumerate(count):
if n != 0:
sorted_nums.extend([i] * n)
ans = []
for i, n in enumerate(sorted_nums):
if n == target:
ans.append(i)
return ans
# Time: O(n); Space: O(n)
def target_indices3(nums, target):
less, equal = 0, 0
for num in nums:
if num < target:
less += 1
if num == target:
equal += 1
return list(range(less, less + equal))
# Test cases:
print(target_indices2([1, 2, 5, 2, 3], 2))
print(target_indices2([1, 2, 5, 2, 3], 3))
print(target_indices2([1, 2, 5, 2, 3], 5))
|
class Browser(object):
def __init__(self):
form = {}
def open(self, url):
pass
def set_handle_robots(self, status):
pass
def set_cookiejar(self, cj):
pass
def forms(self):
forms = [{'session[username_or_email]':'', 'session[password]':''}]
return forms
def close(self):
pass
class submit(object):
def __init__(self):
pass
def get_data(self):
return '<code>0123456</code>'
|
class Dataset():
def __init__(self, data,feature=None):
self.len = data.shape[0]
if (feature is not None):
self.data = data[:,:feature]
self.label = data[:,feature:]
else:
feature = data.shape[1]
self.data = data[:,:feature]
self.label = None
def __getitem__(self, index):
if (self.label is None):
return self.data[index]
return self.data[index],self.label[index]
def __len__(self):
return self.len
|
date = input('Entre com uma data aa/mm/aaaa:')
if '-' in date:
date = date.replace('-', '/')
date = date.split('/')
meses = ('janeiro', 'fevereiro', 'março', 'abril', 'maio', 'junho', 'julho', 'agosto', 'setembro', 'outubro',
'novembro', 'dezembro')
if len(date[2]) <= 2:
if int(date[2]) > 50:
ano = int(date[2]) + 1900
else:
ano = int(date[2]) + 2000
else:
ano = date[2]
print(f'Sua data é {date[0]} de {meses[(int(date[1]) - 1)]} de {ano}')
date_format = f'{date[0]}/{meses[(int(date[1]) - 1)]}/{ano}'
print(date_format)
|
class UnbundledTradeIndicatorEnum:
UNBUNDLED_TRADE_NONE = 0
FIRST_SUB_TRADE_OF_UNBUNDLED_TRADE = 1
LAST_SUB_TRADE_OF_UNBUNDLED_TRADE = 2
|
# -*- coding: UTF-8 -*
def input_data2():
return None
|
def longest_possible_word_length():
return 189819
class iterlines(object):
def __init__(self, filehandle):
self._filehandle = filehandle
def __iter__(self):
self._filehandle.seek(0)
return self
def __next__(self):
line = self._filehandle.readline()
if line == '':
raise StopIteration
return line.strip('\n')
def generate_wordlist_from_file(filename, pred):
with open(filename, 'r') as f:
for word in iterlines(f):
if pred(word.replace('\n', '')):
yield word
def generate_wordlist_from_dict(pred):
for word in generate_wordlist_from_file('/usr/share/dict/words', pred):
yield word
def generate_wordlist(pred, wordlist=None, filename=None):
if wordlist is not None:
return [word for word in wordlist if pred(word)]
if filename is not None:
return [word for word in generate_wordlist_from_file(filename, pred)]
return [word for word in generate_wordlist_from_dict(pred)]
def words_by_ending(ending, wordlist=None):
def endswith(word):
return word.endswith(ending)
return generate_wordlist(endswith, wordlist)
def words_by_start(start, wordlist=None):
def startswith(word):
return word.startswith(start)
return generate_wordlist(startswith, wordlist)
def words_by_length(length, wordlist=None):
def is_correct_length(word):
return len(word) == length
def is_correct_length_tuple(word):
return len(word) >= length[0] and len(word) <= length[1]
if isinstance(length, tuple):
return generate_wordlist(is_correct_length_tuple, wordlist)
return generate_wordlist(is_correct_length, wordlist)
def words_by_maxlength(maxlength, wordlist=None):
return words_by_length((1, maxlength), wordlist)
def words_by_minlength(minlength, wordlist=None):
return words_by_length((minlength, longest_possible_word_length()), wordlist)
def len_hist(wordlist, should_print=False):
def extend_to_length(arr, newlen):
oldlen = len(arr)
if newlen > oldlen:
arr.extend([0] * (newlen - oldlen))
assert(len(arr) == newlen)
hist = []
for word in wordlist:
oldlen = len(hist)
wordlen = len(word)
if wordlen >= oldlen:
extend_to_length(hist, wordlen + 1)
assert(len(hist) == wordlen + 1)
hist[wordlen] += 1
if should_print:
print_len_hist(hist)
return hist
def print_len_hist(h):
print('Word length histogram:')
total = 0
for idx in range(len(h)):
if h[idx] > 0:
print('\t' + str(h[idx]) + ' words of length ' + str(idx))
total += h[idx]
print(str(total) + ' words total')
def remove_duplicates(wordlist):
unique_words = set()
for word in wordlist:
unique_words.add(word)
wordlist = list(unique_words)
return wordlist
def words_from_file(filename):
return generate_wordlist(lambda w: True, None, filename)
def remove_vowels(wordlist, include_y=False):
wordmap = dict()
vowels = 'aeiouy' if include_y else 'aeiou'
for word in wordlist:
trimmed = ''.join([c for c in word if c.lower() not in vowels])
wordmap[trimmed] = word
return wordmap
|
"""
Two ways for checking model architectures:
1. Use torchsummary.
2. Define your model classes as a BaseModel (instead of a nn.Module),
which specifies a __str__() function.
"""
# from __future__ import print_function
# import torch
# import torchsummary
# device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# model_test = ResNet_UNet()
# model_test.to(device)
# #torchsummary.summary(model_test, (3, 256, 256))
# print(model_test)
|
class DependencyResolutionError(RuntimeError):
"""Raised when task dependencies cannot be resolved.
This may be raised by :meth:`.Queue.submit` (if it is possible to detect at
that time), or by :meth:`.Task.result` later.
"""
class PatternMissingError(RuntimeError):
"""Raised by :meth:`.Task.result` when the :ref:`pattern <patterns>` can't
be identified."""
class DependencyFailedError(RuntimeError):
"""Raises by :meth:`.Task.result` when a dependency of the task failed."""
|
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def __repr__(self):
if type(self.data) != 'str':
return str(self.data)
return self.data
def _height(root):
if root is None:
return 0
return max(_height(root.left), _height(root.right)) + 1
def is_balanced_binary_tree(root):
'''
Binary tree where difference between the left and the right
subtree for any node is not more than one
'''
if root is None:
return True
lh = _height(root.left)
rh = _height(root.right)
if ((abs(lh - rh) <= 1) and
is_balanced_binary_tree(root.left) and
is_balanced_binary_tree(root.right)):
return True
return False
def _count_nodes(root):
if root is None:
return 0
return (1 + _count_nodes(root.left) + _count_nodes(root.right))
def is_complete_binary_tree(root, index, number_of_nodes):
'''
Binary tree in which all levels are filled except possibly the
lowest level which is filled from left to right
'''
if root is None:
return True
if index >= number_of_nodes:
return False
return (is_complete_binary_tree(root.left, 2*index+1, number_of_nodes) and
is_complete_binary_tree(root.right, 2*index+2, number_of_nodes))
def _calculate_left_depth(root):
left_depth = 0
while(root is not None):
left_depth += 1
root = root.left
return left_depth
def is_perfect_binary_tree(root, left_depth, level=0):
'''
Binary tree in which every internal node has exactly 2 child nodes and
and all leaf nodes are at the same level is a perfect binary tree
'''
if root is None:
return True
if (root.left is None and root.right is None):
return (left_depth == level + 1)
if (root.left is None or root.right is None):
return False
return (is_perfect_binary_tree(root.left, left_depth, level+1) and
is_perfect_binary_tree(root.right, left_depth, level+1))
def is_full_binary_tree(root):
'''
Binary tree with parent node and all internal nodes having either 2
children nodes or no children nodes are called full binary tree.
'''
if root is None:
return True
if root.left is None and root.right is None:
return True
if root.left is not None and root.right is not None:
return is_full_binary_tree(root.left) and is_full_binary_tree(root.right)
return False
def build_tree_one():
root = Node(1)
root.right = Node(3)
root.left = Node(2)
root.left.left = Node(4)
root.left.right = Node(5)
root.left.right.left = Node(6)
root.left.right.right = Node(7)
return root
def build_tree_two():
root = Node(1)
root.left = Node(12)
root.right = Node(9)
root.left.left = Node(5)
root.left.right = Node(6)
return root
def build_tree_three():
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(13)
root.right.right = Node(9)
return root
if __name__ == '__main__':
tree_one = build_tree_one()
if is_full_binary_tree(tree_one):
print('Tree One is full binary tree')
else:
print('Tree One is not full binary tree')
if is_perfect_binary_tree(tree_one, _calculate_left_depth(tree_one)):
print('Tree One is perfect binary tree')
else:
print('Tree One is not perfect binary tree')
if is_complete_binary_tree(tree_one, 0, _count_nodes(tree_one)):
print('Tree One is a complete binary tree')
else:
print('Tree One is not a complete binary tree')
if is_balanced_binary_tree(tree_one):
print('Tree One is balanced binary tree')
else:
print('Tree One is not a balanced binary tree')
tree_two = build_tree_two()
if is_full_binary_tree(tree_two):
print('\nTree Two is full binary tree')
else:
print('\nTree Two is not full binary tree')
if is_perfect_binary_tree(tree_two, _calculate_left_depth(tree_two)):
print('Tree Two is perfect binary tree')
else:
print('Tree Two is not perfect binary tree')
if is_complete_binary_tree(tree_two, 0, _count_nodes(tree_two)):
print('Tree Two is a complete binary tree')
else:
print('Tree Two is not a complete binary tree')
if is_balanced_binary_tree(tree_two):
print('Tree Two is balanced binary tree')
else:
print('Tree Two is not a balanced binary tree')
tree_three = build_tree_three()
if is_full_binary_tree(tree_three):
print('\nTree Three is full binary tree')
else:
print('\nTree Three is not full binary tree')
if is_perfect_binary_tree(tree_three, _calculate_left_depth(tree_three)):
print('Tree Three is perfect binary tree')
else:
print('Tree Three is not perfect binary tree')
if is_complete_binary_tree(tree_three, 0, _count_nodes(tree_three)):
print('Tree Three is a complete binary tree')
else:
print('Tree Three is not a complete binary tree')
if is_balanced_binary_tree(tree_three):
print('Tree Three is balanced binary tree')
else:
print('Tree Three is not a balanced binary tree')
|
def most_frequent(arr):
ret = None
counter = {}
max_count = -1
for n in arr:
counter.setdefault(n, 0)
counter[n] += 1
if counter[n] > max_count:
max_count = counter[n]
ret = n
return ret
|
# Created by MechAviv
# Kinesis Introduction
# Map ID :: 331003200
# Subway :: Subway Car #3
JAY = 1531001
GIRL = 1531067
sm.spawnNpc(GIRL, 699, 47)
sm.showNpcSpecialActionByTemplateId(GIRL, "summon")
sm.spawnMob(2700303, 250, 57, False)
sm.spawnMob(2700303, 250, 57, False)
sm.spawnMob(2700303, 250, 57, False)
sm.spawnMob(2700303, 250, 57, False)
sm.spawnMob(2700303, 250, 57, False)
sm.spawnMob(2700304, 300, 57, False)
sm.spawnMob(2700304, 300, 57, False)
sm.spawnMob(2700304, 300, 57, False)
sm.spawnMob(2700304, 300, 57, False)
sm.spawnMob(2700304, 300, 57, False)
sm.spawnMob(2700305, 350, 57, False)
sm.spawnMob(2700305, 350, 57, False)
sm.spawnMob(2700305, 350, 57, False)
sm.spawnMob(2700305, 350, 57, False)
sm.spawnMob(2700305, 350, 57, False)
sm.setSpineObjectEffectPlay(True, "subway_bg", "outside", True, False)
sm.setSpineObjectEffectPlay(True, "subway_main", "outside", True, False)
sm.unlockForIntro()
sm.playSound("Sound/Field.img/flowervioleta/wink")
sm.cameraSwitchNormal("go_next", 1000)
sm.addPopUpSay(JAY, 2000, "#face10#Watch out, there are more on the way!", "")
|
# https://www.hackerrank.com/challenges/30-review-loop/
T = int(input())
S = list()
for i in range(T):
S.append(str(input()))
for i in range(len(S)):
print(S[i][0] + S[i][2::2] + ' ' + S[i][1::2])
|
#
# PySNMP MIB module A3COM0420-SWITCH-EXTENSIONS (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM0420-SWITCH-EXTENSIONS
# Produced by pysmi-0.3.4 at Mon Apr 29 16:54:17 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
brasica2, = mibBuilder.importSymbols("A3COM0004-GENERIC", "brasica2")
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion, ConstraintsIntersection, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueRangeConstraint")
ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
NotificationType, Bits, MibIdentifier, TimeTicks, Integer32, ObjectIdentity, Counter64, Unsigned32, iso, Gauge32, ModuleIdentity, IpAddress, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "Bits", "MibIdentifier", "TimeTicks", "Integer32", "ObjectIdentity", "Counter64", "Unsigned32", "iso", "Gauge32", "ModuleIdentity", "IpAddress", "Counter32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn")
TextualConvention, MacAddress, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "MacAddress", "DisplayString")
stackConfigGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 10, 34, 1))
prConStackFwdingMode = MibScalar((1, 3, 6, 1, 4, 1, 43, 10, 34, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("fastForward", 1), ("fragmentFree", 2), ("storeAndForward", 3), ("intelligent", 4)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: prConStackFwdingMode.setStatus('mandatory')
prConStackPaceMode = MibScalar((1, 3, 6, 1, 4, 1, 43, 10, 34, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("notApplicable", 1), ("normalEthernet", 2), ("lowLatency", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: prConStackPaceMode.setStatus('mandatory')
prConStackVLANConfigMode = MibScalar((1, 3, 6, 1, 4, 1, 43, 10, 34, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("notApplicable", 1), ("portMode", 2), ("autoSelect", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: prConStackVLANConfigMode.setStatus('mandatory')
prConStackRAPStudyPort = MibScalar((1, 3, 6, 1, 4, 1, 43, 10, 34, 1, 4), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: prConStackRAPStudyPort.setStatus('mandatory')
prConStackRAPCopyPort = MibScalar((1, 3, 6, 1, 4, 1, 43, 10, 34, 1, 5), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: prConStackRAPCopyPort.setStatus('mandatory')
prConStackRAPEnable = MibScalar((1, 3, 6, 1, 4, 1, 43, 10, 34, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("off", 1), ("on", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: prConStackRAPEnable.setStatus('mandatory')
prConStackBridgeMode = MibScalar((1, 3, 6, 1, 4, 1, 43, 10, 34, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("single", 1), ("multiple", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: prConStackBridgeMode.setStatus('mandatory')
prConStackIpTos = MibScalar((1, 3, 6, 1, 4, 1, 43, 10, 34, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("notApplicable", 1), ("enable", 2), ("disable", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: prConStackIpTos.setStatus('mandatory')
prConStackPktRateControl = MibScalar((1, 3, 6, 1, 4, 1, 43, 10, 34, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9))).clone(namedValues=NamedValues(("notApplicable", 1), ("disable", 2), ("limitUnknownDAs", 3), ("limitMcasts", 4), ("limitMcastsAndUnknownDAs", 5), ("limitBcasts", 6), ("limitBcastsAndUnknownDAs", 7), ("limitBcastsAndMcasts", 8), ("limitBcastsMcastsAndUnknownDAs", 9)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: prConStackPktRateControl.setStatus('mandatory')
prConStackPktRateLimit = MibScalar((1, 3, 6, 1, 4, 1, 43, 10, 34, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 262143))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: prConStackPktRateLimit.setStatus('mandatory')
prConStackStpProtocolVersion = MibScalar((1, 3, 6, 1, 4, 1, 43, 10, 34, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 2))).clone(namedValues=NamedValues(("stpVersion0", 0), ("rstpVersion2", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: prConStackStpProtocolVersion.setStatus('mandatory')
prConStackStpPathCostDefault = MibScalar((1, 3, 6, 1, 4, 1, 43, 10, 34, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("stp8021d1998", 1), ("stp8021t2000", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: prConStackStpPathCostDefault.setStatus('mandatory')
prConStackLacpOperInfo = MibScalar((1, 3, 6, 1, 4, 1, 43, 10, 34, 1, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("notOperational", 1), ("operational", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: prConStackLacpOperInfo.setStatus('mandatory')
switchConfigGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 10, 34, 2))
prConfigPortTable = MibTable((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 1), )
if mibBuilder.loadTexts: prConfigPortTable.setStatus('mandatory')
prConfigPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 1, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: prConfigPortEntry.setStatus('mandatory')
prConPortVLANConfigMode = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("notApplicable", 1), ("useDefault", 2), ("portMode", 3), ("autoSelect", 4)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: prConPortVLANConfigMode.setStatus('mandatory')
prConPortIFM = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 1, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))).clone(namedValues=NamedValues(("notApplicable", 1), ("off", 2), ("maxJams6", 3), ("maxJams7", 4), ("maxJams8", 5), ("maxJams9", 6), ("maxJams10", 7), ("maxJams11", 8), ("maxJams12", 9), ("maxJams13", 10)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: prConPortIFM.setStatus('mandatory')
prConPortLacp = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 1, 1, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: prConPortLacp.setStatus('mandatory')
prConPortStpAdminPathCost = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 1, 1, 15), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 200000000))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: prConPortStpAdminPathCost.setStatus('mandatory')
prConPortCascadeMode = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 1, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: prConPortCascadeMode.setStatus('mandatory')
prConPortFdbTable = MibTable((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 2), )
if mibBuilder.loadTexts: prConPortFdbTable.setStatus('mandatory')
prConPortFdbEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 2, 1), ).setIndexNames((0, "A3COM0420-SWITCH-EXTENSIONS", "prConPortFdbPort"), (0, "A3COM0420-SWITCH-EXTENSIONS", "prConPortFdbId"), (0, "A3COM0420-SWITCH-EXTENSIONS", "prConPortFdbAddress"))
if mibBuilder.loadTexts: prConPortFdbEntry.setStatus('mandatory')
prConPortFdbPort = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535)))
if mibBuilder.loadTexts: prConPortFdbPort.setStatus('mandatory')
prConPortFdbId = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 2, 1, 2), Integer32())
if mibBuilder.loadTexts: prConPortFdbId.setStatus('mandatory')
prConPortFdbAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 2, 1, 3), MacAddress())
if mibBuilder.loadTexts: prConPortFdbAddress.setStatus('mandatory')
prConPortFdbStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("other", 1), ("invalid", 2), ("learned", 3), ("self", 4), ("mgmt", 5)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: prConPortFdbStatus.setStatus('mandatory')
prConTrunkMulticastTable = MibTable((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 3), )
if mibBuilder.loadTexts: prConTrunkMulticastTable.setStatus('mandatory')
prConTrunkMulticastEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 3, 1), ).setIndexNames((0, "A3COM0420-SWITCH-EXTENSIONS", "prConTrunkMulticastFdbId"), (0, "A3COM0420-SWITCH-EXTENSIONS", "prConTrunkMulticastAddress"))
if mibBuilder.loadTexts: prConTrunkMulticastEntry.setStatus('mandatory')
prConTrunkMulticastFdbId = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 3, 1, 1), Integer32())
if mibBuilder.loadTexts: prConTrunkMulticastFdbId.setStatus('mandatory')
prConTrunkMulticastAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 3, 1, 2), MacAddress())
if mibBuilder.loadTexts: prConTrunkMulticastAddress.setStatus('mandatory')
prConTrunkMulticastPortlist = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 3, 1, 3), OctetString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: prConTrunkMulticastPortlist.setStatus('mandatory')
prConTrunkMulticastStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 3, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("other", 1), ("invalid", 2), ("permanent", 3), ("deleteOnReset", 4), ("deleteOnTimeout", 5)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: prConTrunkMulticastStatus.setStatus('mandatory')
prConTrunkMulticastType = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 3, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("other", 1), ("invalid", 2), ("learned", 3), ("self", 4), ("mgmt", 5)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: prConTrunkMulticastType.setStatus('mandatory')
prConTrunkMulticastRobp = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 3, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("true", 1), ("false", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: prConTrunkMulticastRobp.setStatus('mandatory')
prConIfIndexTable = MibTable((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 4), )
if mibBuilder.loadTexts: prConIfIndexTable.setStatus('mandatory')
prConIfIndexEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 4, 1), ).setIndexNames((0, "A3COM0420-SWITCH-EXTENSIONS", "prConIfIndexGroupIndex"), (0, "A3COM0420-SWITCH-EXTENSIONS", "prConIfIndexPortIndex"))
if mibBuilder.loadTexts: prConIfIndexEntry.setStatus('mandatory')
prConIfIndexGroupIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1024)))
if mibBuilder.loadTexts: prConIfIndexGroupIndex.setStatus('mandatory')
prConIfIndexPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 4, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1024)))
if mibBuilder.loadTexts: prConIfIndexPortIndex.setStatus('mandatory')
prConIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 4, 1, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: prConIfIndex.setStatus('mandatory')
prConIfIndexBridgePort = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 4, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: prConIfIndexBridgePort.setStatus('mandatory')
prConfigAggTable = MibTable((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 5), )
if mibBuilder.loadTexts: prConfigAggTable.setStatus('mandatory')
prConfigAggEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 5, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: prConfigAggEntry.setStatus('mandatory')
prConfigAggStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 10, 34, 2, 5, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("unused", 1), ("autoInUse", 2), ("autoAgeing", 3), ("autoReusable", 4), ("manual", 5)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: prConfigAggStatus.setStatus('mandatory')
mibBuilder.exportSymbols("A3COM0420-SWITCH-EXTENSIONS", prConIfIndexGroupIndex=prConIfIndexGroupIndex, prConIfIndexTable=prConIfIndexTable, prConfigAggEntry=prConfigAggEntry, prConfigAggStatus=prConfigAggStatus, prConTrunkMulticastStatus=prConTrunkMulticastStatus, switchConfigGroup=switchConfigGroup, prConPortIFM=prConPortIFM, stackConfigGroup=stackConfigGroup, prConPortFdbStatus=prConPortFdbStatus, prConTrunkMulticastAddress=prConTrunkMulticastAddress, prConIfIndexEntry=prConIfIndexEntry, prConStackIpTos=prConStackIpTos, prConStackStpPathCostDefault=prConStackStpPathCostDefault, prConPortFdbId=prConPortFdbId, prConPortVLANConfigMode=prConPortVLANConfigMode, prConTrunkMulticastTable=prConTrunkMulticastTable, prConIfIndexBridgePort=prConIfIndexBridgePort, prConPortFdbPort=prConPortFdbPort, prConPortCascadeMode=prConPortCascadeMode, prConStackBridgeMode=prConStackBridgeMode, prConPortFdbTable=prConPortFdbTable, prConTrunkMulticastRobp=prConTrunkMulticastRobp, prConStackRAPEnable=prConStackRAPEnable, prConPortLacp=prConPortLacp, prConTrunkMulticastType=prConTrunkMulticastType, prConfigAggTable=prConfigAggTable, prConStackPktRateLimit=prConStackPktRateLimit, prConIfIndexPortIndex=prConIfIndexPortIndex, prConTrunkMulticastFdbId=prConTrunkMulticastFdbId, prConStackFwdingMode=prConStackFwdingMode, prConStackStpProtocolVersion=prConStackStpProtocolVersion, prConPortFdbEntry=prConPortFdbEntry, prConPortFdbAddress=prConPortFdbAddress, prConPortStpAdminPathCost=prConPortStpAdminPathCost, prConIfIndex=prConIfIndex, prConStackRAPCopyPort=prConStackRAPCopyPort, prConTrunkMulticastEntry=prConTrunkMulticastEntry, prConTrunkMulticastPortlist=prConTrunkMulticastPortlist, prConStackRAPStudyPort=prConStackRAPStudyPort, prConfigPortEntry=prConfigPortEntry, prConStackPktRateControl=prConStackPktRateControl, prConfigPortTable=prConfigPortTable, prConStackPaceMode=prConStackPaceMode, prConStackVLANConfigMode=prConStackVLANConfigMode, prConStackLacpOperInfo=prConStackLacpOperInfo)
|
L = int(input())
R = int(input())
xor = L ^ R
max_xor = 1
while xor:
xor >>= 1
max_xor <<= 1
print (max_xor-1)
|
num = int(input('Digite um número inteiro:'))
print('''Escolha uma das bases para conversão:
[1] converter para Binário
[2] converter para Octal
[3] converter para Hexadecimal''')
opção = int(input('Sua opção: '))
if opção == 1:
print('{} convertido para Binário é igual a {}'.format(num, bin(num)[2:]))
elif opção == 2:
print('{} convertido para Octal é igual a {}'.format(num, oct(num)[2:]))
elif opção == 3:
print('{} convertido para Hexadecimal é igual a {}'.format(num, hex(num)[2:]))
else:
print('Opção Inválida!.Tente novamente!')
|
# microbit-module: shared_config@0.1.0
RADIO_CHANNEL = 17
MSG_DEYLAY = 50
|
# Invert a binary tree.
# Input:
# 4
# / \
# 2 7
# / \ / \
# 1 3 6 9
#
# Output:
# 4
# / \
# 7 2
# / \ / \
# 9 6 3 1
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution:
def invertTree(self, node: TreeNode) -> TreeNode:
if not node:
return None
node.left, node.right = self.invertTree(node.right), self.invertTree(node.left)
return node
|
def roundUp(number:float)->int:
split = [int(i) for i in str(number).split(".")]
if split[1] >0:
return split[0]+1
return split[0]
## Program Start ##
n, k = [int(i) for i in input().strip().split(" ")][-2:]
scores = sorted([int(i) for i in input().strip().split(" ")])
min_days = roundUp(n/k)
output = 0
for i in range(0, min_days):
output += scores[len(scores) -1 -i]
print(output)
|
'''
Мороженое
'''
k = int(input())
if (k % 5 == 4 and k >= 9):
print('YES')
elif (k % 5 == 3):
print('YES')
elif (k % 5 == 2 and k >= 12):
print('YES')
elif (k % 5 == 1 and k >= 6):
print('YES')
elif (k % 5 == 0):
print('YES')
else:
print('NO')
|
class StackOfPlates(object):
def __init__(self):
self.stack = []
self.capacity = 10
def push(self, item):
if self.stack and self.stack[-1].length() < 10:
self.stack[-1].push(item)
else:
new_stack = Stack()
new_stack.push(item)
self.stack.append(new_stack)
def pop(self):
self.stack[-1].pop()
if self.stack[-1].length == 0:
del stack[-1]
def popAt(self, index):
self.stack[index].pop()
class Stack(object):
def __init__(self):
self.items = []
def get_items(self):
return self.items
def length(self):
return len(self.items)
def push(self, item):
self.items.append(item)
def pop(self):
self.items.pop()
stack = StackOfPlates()
stack.push(1)
stack.push(10)
stack.push(11)
stack.push(12)
stack.push(13)
stack.push(14)
stack.push(15)
stack.push(16)
stack.push(17)
stack.push(18)
stack.push(19)
stack.push(20)
stack.push(2)
stack.push(3)
stack.push(4)
stack.push(5)
print(stack.stack[0].items)
print(stack.stack[1].items)
stack.pop()
stack.popAt(0)
print(stack.stack[0].items)
print(stack.stack[1].items)
|
"""
This module will be transformed... into something far greater.
"""
a = "Hello"
msg = f"{a} World"
msg2 = f"Finally, {a} World"
print(msg)
|
'''
A+B for Input-Output Practice(VIII)
描述
Your task is to calculate the sum of some integers
输入
Input contains an integer N in the first line, and then N lines follow.
Each line starts with a integer M, and then M integers follow in the same line
输出
For each group of input integers you should output their sum in one line,
and you must note that there is a blank line between outputs.
输入样例
3
4 1 2 3 4
5 1 2 3 4 5
3 1 2 3
输出样例
10
15
6
'''
N = int(input())
for n in range(N):
input_list = list(map(int, input().split()))
# split()默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
# 使用split(" ") 报RE
M = input_list[0]
sum = 0
for m in range(M):
sum = sum + input_list[m + 1]
print(sum)
print()
|
class Person:
def __init__(self):
self.name = None
self.age = None
def input(self):
self.name = input("Введіть ім'я:")
self.age = input("Введіть вік:")
def print(self):
print(self.name, self.age)
class Friend(Person):
def __init__(self):
super(Person,self).__init__()
def input(self):
Person.input(self)
self.tel = input("Введіть номер телефону:")
def __str__(self):
return f'{self.name} {self.age} {self.tel}'
class Telefon(Person,Friend):
def __init__(self):
super().__init__()
def number(self):
a = raw_input('Введіть номер телефону')
reader = open("TelDov.txt", "w+")
name = None
for row in reader:
if a == row[2]:
name = row[0], row[1]
if name:
print(name)
else:
print ('Phone not found')
x = Person()
y = Friend()
y.input()
print(y)
|
def skipVowels(word):
novowels = ''
for ch in word:
if ch.lower() in 'aeiou':
continue
novowels += ch
novowels+=ch
return novowels
print(skipVowels('hello'))
print(skipVowels('awaited'))
|
# -*- coding: utf-8 -*-
"""
----------Phenix Labs----------
Created on Sat Jan 23 22:41:46 2021
@author: Gyan Krishna
Topic: HCF andf LCM of tow numbers
"""
a = int(input("enter first number "))
b = int(input("enter second number "))
hcf = 1
small = min(a,b)
for i in range(1,small+1):
if(a%i == 0 and b%i == 0):
hcf = i
lcm = (a * b)/hcf
print("lcm = ",lcm)
print("hcf = ",hcf)
|
class orf(object):
""" Class that represents and Open Reading Frame
Attributes:
start (int): Start codon coordinate of the ORF in the parent sequence
stop (int): Stop codon coordinate of the ORF in the parent sequence
length (int): Number of aminoacids in the ORF
translation (str): Translation of the ORF
seq (str): ORF sequence
"""
def __init__(self, start, stop, length, translation=None, sequence=None):
if(type(start) is not int):
raise Exception("ORF start is not an int")
if(type(stop) is not int):
raise Exception("ORF stop is not an int")
if(start<0 or stop<0):
raise Exception("ORF start and stop coordinates must be >=0")
if(type(length) is not int):
raise Exception("ORF length is not an int")
if(length<1):
raise Exception("ORF length is less than 1")
if(type(length) is not int):
raise Exception("ORF length is not an int")
if(translation and type(translation) is not str):
raise Exception("ORF translation is not a string")
if(sequence and type(sequence) is not str):
raise Exception("ORF sequence is not a string")
assert (stop-start) % 3 == 0
assert (stop-start) // 3 == length
self.start = start
self.stop = stop
self.length = length
self.translation = translation
self.sequence = sequence
|
"""
Test cases for 7.py found in the LeetCode folder.
Answer by @VGZELDA
"""
# function to be tested
def reverse(x):
x=int(x)
if(x>=0):
x=str(x)
x=x[::-1]
x=int(x)
if(x<-1*(2**31))or(x>=2**31):
return 0
else:
return x
else:
x=x*(-1)
x=str(x)
x=x[::-1]
x=int(x)
x=-1*x
if(x<-1*(2147483648))or(x>=2147483648):
return 0
else:
return x
# function to test reverse
def test_reverse():
assert reverse(123) == 321, "Should be 321"
assert reverse(120) == 21, "Should be 21"
test_reverse()
print("Everything passed")
|
DosTags = {
# System
33: "SYS_Input",
34: "SYS_Output",
35: "SYS_Asynch",
36: "SYS_UserShell",
37: "SYS_CustomShell",
# CreateNewProc
1001: "NP_SegList",
1002: "NP_FreeSegList",
1003: "NP_Entry",
1004: "NP_Input",
1005: "NP_Output",
1006: "NP_CloseInput",
1007: "NP_CloseOutput",
1008: "NP_Error",
1009: "NP_CloseError",
1010: "NP_CurrentDir",
1011: "NP_StackSize",
1012: "NP_Name",
1013: "NP_Priority",
1014: "NP_ConsoleTask",
1015: "NP_WindowPtr",
1016: "NP_HomeDir",
1017: "NP_CopyVars",
1018: "NP_Cli",
1019: "NP_Path",
1020: "NP_CommandName",
1021: "NP_Arguments",
1022: "NP_NotifyOnDeath",
1023: "NP_Synchronous",
1024: "NP_ExitCode",
1025: "NP_ExitData",
# AllocDosObject
2001: "ADO_FH_Mode",
2002: "ADO_DirLen",
2003: "ADR_CommNameLen",
2004: "ADR_CommFileLen",
2005: "ADR_PromptLen",
}
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findBottomLeftValue(self, root: TreeNode) -> int:
current = [root]
while True:
children = []
for node in current:
if node.left: children.append(node.left)
if node.right: children.append(node.right)
if not children:
return current[0].val
else:
current = children
|
#
# PySNMP MIB module CXMLPPP-IP-NCP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CXMLPPP-IP-NCP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:33:10 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
SingleValueConstraint, ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueSizeConstraint", "ValueRangeConstraint")
cxMLPPP, SapIndex = mibBuilder.importSymbols("CXProduct-SMI", "cxMLPPP", "SapIndex")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
Integer32, Unsigned32, MibIdentifier, Gauge32, ObjectIdentity, IpAddress, TimeTicks, Counter64, ModuleIdentity, Bits, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter32, iso = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "Unsigned32", "MibIdentifier", "Gauge32", "ObjectIdentity", "IpAddress", "TimeTicks", "Counter64", "ModuleIdentity", "Bits", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter32", "iso")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
mlpppIpNsTable = MibTable((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 49, 52), )
if mibBuilder.loadTexts: mlpppIpNsTable.setStatus('mandatory')
if mibBuilder.loadTexts: mlpppIpNsTable.setDescription('A table containing status parameters about each MLPPP module layer PPP IP Network Control Protocol.')
mlpppIpNsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 49, 52, 1), ).setIndexNames((0, "CXMLPPP-IP-NCP-MIB", "mlpppIpNsLSapNumber"), (0, "CXMLPPP-IP-NCP-MIB", "mlpppIpNsNumber"))
if mibBuilder.loadTexts: mlpppIpNsEntry.setStatus('mandatory')
if mibBuilder.loadTexts: mlpppIpNsEntry.setDescription('Status parameters for a specific PPP IP Network Control Protocol.')
mlpppIpNsLSapNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 49, 52, 1, 1), SapIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mlpppIpNsLSapNumber.setStatus('mandatory')
if mibBuilder.loadTexts: mlpppIpNsLSapNumber.setDescription('Indicates the row that contains objects for monitoring a SAP that is associated with one of the PPP links. Range of Values: 1-10 Default Value: none')
mlpppIpNsNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 49, 52, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mlpppIpNsNumber.setStatus('mandatory')
if mibBuilder.loadTexts: mlpppIpNsNumber.setDescription('Indicates the row that contains objects for monitoring a SAP that is associated with one of the PPP links. Range of Values: 1 Default Value: none')
mlpppIpNsLocalToRemoteComp = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 49, 52, 1, 40), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("none", 1), ("vj-tcp", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: mlpppIpNsLocalToRemoteComp.setStatus('mandatory')
if mibBuilder.loadTexts: mlpppIpNsLocalToRemoteComp.setDescription("Identifies whether the local end of the IP-PPP link is using TCP/IP header compression (vj-tcp) to send packets to the remote. The value of this object is determined when the PPP configuration is negotiated. The local port's preference for header compression is determined using mlpppIpNcComp of mlpppIpNcTable. Options: none (1) vj-tcp (2): header compression Default Value: None")
mlpppIpNsRemoteToLocalComp = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 49, 52, 1, 41), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("none", 1), ("vj-tcp", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: mlpppIpNsRemoteToLocalComp.setStatus('mandatory')
if mibBuilder.loadTexts: mlpppIpNsRemoteToLocalComp.setDescription("Identifies whether the remote end of the IP-PPP link is using TCP/IP header compression (vj-tcp) to send packets to the local end. The value of this object is determined when the PPP configuration is negotiated. The local port's preference for header compression is determined using mlpppIpNcComp of mlpppIpNcTable. Options: none (1) vj-tcp (2): header compression Default value: None")
mlpppIpNcTable = MibTable((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 49, 53), )
if mibBuilder.loadTexts: mlpppIpNcTable.setStatus('mandatory')
if mibBuilder.loadTexts: mlpppIpNcTable.setDescription("A table containing configuration parameters about each MLPPP module layer's PPP IP Network Control Protocol.")
mlpppIpNcEntry = MibTableRow((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 49, 53, 1), ).setIndexNames((0, "CXMLPPP-IP-NCP-MIB", "mlpppIpNcUSapNumber"), (0, "CXMLPPP-IP-NCP-MIB", "mlpppIpNcNumber"))
if mibBuilder.loadTexts: mlpppIpNcEntry.setStatus('mandatory')
if mibBuilder.loadTexts: mlpppIpNcEntry.setDescription('The configuration parameters for a specific PPP IP Network Control Protocol.')
mlpppIpNcUSapNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 49, 53, 1, 1), SapIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mlpppIpNcUSapNumber.setStatus('mandatory')
if mibBuilder.loadTexts: mlpppIpNcUSapNumber.setDescription('Indicates the row containing objects for monitoring a SAP that is associated with one of the MLPPP links . Range of Values: 1-10 Default Value: none')
mlpppIpNcNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 49, 53, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mlpppIpNcNumber.setStatus('mandatory')
if mibBuilder.loadTexts: mlpppIpNcNumber.setDescription('Indicates the row containing objects for monitoring a SAP associated with one of the MLPPP links. Range of Values: 1 Default Value: none')
mlpppIpNcComp = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 49, 53, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("none", 1), ("vj-tcp", 2))).clone('none')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: mlpppIpNcComp.setReference('Section 4.0, Van Jacobson TCP/IP Header Compression of RFC1332.')
if mibBuilder.loadTexts: mlpppIpNcComp.setStatus('mandatory')
if mibBuilder.loadTexts: mlpppIpNcComp.setDescription('Determines whether the local end of PPP link wants to use TCP/IP header compression (vj-tcp) to send packets over the link. If header compression is desired, the local will negotiate for its implementation with the remote end of the link. The result of the negotiation is displayed in mlpppIpNsLocalToRemoteComp (the local) and mlpppIpNsRemoteToLocalComp (remote). If compression is not desired, there will be no attempt to negotiate with the other end of the link. Options: none (1) vj-tcp (2): header compression Default Value: none Configuration Changed: administrative')
mibBuilder.exportSymbols("CXMLPPP-IP-NCP-MIB", mlpppIpNsRemoteToLocalComp=mlpppIpNsRemoteToLocalComp, mlpppIpNcNumber=mlpppIpNcNumber, mlpppIpNsTable=mlpppIpNsTable, mlpppIpNcEntry=mlpppIpNcEntry, mlpppIpNsNumber=mlpppIpNsNumber, mlpppIpNsLocalToRemoteComp=mlpppIpNsLocalToRemoteComp, mlpppIpNcTable=mlpppIpNcTable, mlpppIpNsLSapNumber=mlpppIpNsLSapNumber, mlpppIpNcUSapNumber=mlpppIpNcUSapNumber, mlpppIpNsEntry=mlpppIpNsEntry, mlpppIpNcComp=mlpppIpNcComp)
|
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree.
@return: Level order in a list of lists of integers
"""
def levelOrder(self, root):
# write your code here
if root is None:
return []
res, q_lvl = [], [root]
while q_lvl != []:
pre, tmp = [], []
for node in q_lvl:
pre.append(node.val)
l, r = node.left, node.right
if l:
tmp.append(l)
if r:
tmp.append(r)
res.append(pre)
q_lvl = tmp
return res
|
def B():
n = int(input())
a = [int(x) for x in input().split()]
d = {i:[] for i in range(1,n+1)}
d[0]= [0,0]
for i in range(2*n):
d[a[i]].append(i)
ans = 0
for i in range(n):
a , b = d[i] , d[i+1]
ans+= min(abs(b[0]-a[0])+abs(b[1]-a[1]) , abs(b[0]-a[1])+abs(b[1]-a[0]))
print(ans)
B()
|
# Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
# To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
# Note: Do not modify the linked list.
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# NOTE: This solution has O(n) space complexity. Jose Portilla and leetcode solutions use two pointers
# to solve this in O(1) space. In interview setting, if I give this answer, they may ask to optimize it,
# during which leetcode soln. could be useful.
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
seen = set()
cur = head
while cur:
if cur in seen:
return cur
seen.add(cur)
cur = cur.next
return None
|
line_items = [{
"invNumber": 100,
"lineNumber": 1,
"partNumber": "TU100",
"description": "TacUmbrella",
"price": 9.99
},
{
"invNumber": 100,
"lineNumber": 2,
"partNumber": "TLB9000",
"description": "TacLunchbox 9000",
"price": 19.99
},
{
"invNumber": 101,
"lineNumber": 1,
"partNumber": "TPJ5",
"description": "TacPajamas",
"price": 99.99
}]
def main(event, context):
print(f'event: {event}')
source = event['source']
return list(filter(lambda line_item: line_item['invNumber'] == source['invNumber'], line_items))
# Test
# e = {"source": {"invNumber": 100}}
# print(main(e, None))
|
class ResizeError(Exception):
pass
def codelengths_from_frequencies(freqs):
freqs = sorted(freqs.items(),
key=lambda item: (item[1], -item[0]), reverse=True)
nodes = [Node(char=key, weight=value) for (key, value) in freqs]
while len(nodes) > 1:
right, left = nodes.pop(), nodes.pop()
node = Node(weight=right.weight + left.weight)
node.add([left, right])
if not nodes:
nodes.append(node)
else:
pos = 0
while pos < len(nodes) and nodes[pos].weight > node.weight:
pos += 1
nodes.insert(pos, node)
top = nodes[0]
tree = Tree(top)
tree.reduce(15)
codes = tree.codes()
code_items = list(codes.items())
code_items.sort(key=lambda item:(len(item[1]), item[0]))
return [(car, len(value)) for car, value in code_items]
def normalized(codelengths):
car, codelength = codelengths[0]
value = 0
codes = {car: "0" * codelength}
for (newcar, nbits) in codelengths[1:]:
value += 1
bvalue = str(bin(value))[2:]
bvalue = "0" * (codelength - len(bvalue)) + bvalue
if nbits > codelength:
codelength = nbits
bvalue += "0" * (codelength - len(bvalue))
value = int(bvalue, 2)
assert len(bvalue) == nbits
codes[newcar] = bvalue
return codes
class Tree:
def __init__(self, root):
self.root = root
self.nb_levels = 0
def length(self):
self.root.level = 0
node = self.root
nb_levels = 0
def set_level(node):
nonlocal nb_levels
for child in node.children:
child.level = node.level + 1
nb_levels = max(nb_levels, child.level)
if not child.is_leaf:
set_level(child)
set_level(self.root)
return nb_levels
def reduce_tree(self):
"""Change the tree to reduce the number of levels.
Uses the algorithm described in
http://compressions.sourceforge.net/Huffman.html#3
"""
currentlen = self.length()
deepest = self.nodes_at(currentlen)
deepest_leaves = [node for node in deepest if node.is_leaf]
rightmost_leaf = deepest_leaves[-1]
sibling = rightmost_leaf.parent.children[0]
# replace rightmost_leaf's parent by rightmost_leaf
parent = rightmost_leaf.parent
grand_parent = parent.parent
rank = grand_parent.children.index(parent)
children = grand_parent.children
children[rank] = rightmost_leaf
grand_parent.add(children)
# find first upper level with leaves
up_level = rightmost_leaf.level - 2
while up_level > 0:
nodes = self.nodes_at(up_level)
leaf_nodes = [node for node in nodes if node.is_leaf]
if leaf_nodes:
leftmost_leaf = leaf_nodes[0]
# replace by node with leaves = [sibling, leftmost_leaf]
parent = leftmost_leaf.parent
rank = parent.children.index(leftmost_leaf)
new_node = Node()
new_node.level = leftmost_leaf.level
children = [sibling, leftmost_leaf]
new_node.add(children)
parent.children[rank] = new_node
new_node.parent = parent
break
else:
up_level -= 1
if up_level == 0:
raise ResizeError
def nodes_at(self, level, top=None):
"""Return list of all the nodes below top at specified level."""
res = []
if top is None:
top = self.root
if top.level == level:
res = [top]
elif not top.is_leaf:
for child in top.children:
res += self.nodes_at(level, child)
return res
def reduce(self, maxlevels):
"""Reduce number of levels to maxlevels, if possible."""
while self.length() > maxlevels:
self.reduce_tree()
def codes(self, node=None, code=''):
"""Returns a dictionary mapping leaf characters to the Huffman code
of the node, as a string of 0's and 1's."""
if node is None:
self.dic = {}
node = self.root
if node.is_leaf:
self.dic[node.char] = code
else:
for i, child in enumerate(node.children):
self.codes(child, code + str(i))
return self.dic
class Node:
def __init__(self, char=None, weight=0, level=0):
self.char = char
self.is_leaf = char is not None
self.level = level
self.weight = weight
self.height = 0
def add(self, children):
self.children = children
for child in self.children:
child.parent = self
child.level = self.level + 1
self.height = max(self.height, children[0].height + 1,
children[1].height + 1)
node = self
while hasattr(node, "parent"):
node.parent.height = max(node.parent.height, node.height + 1)
node = node.parent
def __repr__(self):
if self.is_leaf:
return f'{chr(self.char)!r}'
else:
return f'{self.children}'
class Compresser:
def __init__(self, text):
if not isinstance(text, (bytes, bytearray, memoryview)):
raise TypeError("a bytes-like object is required, not '" +
type(text).__name__ + "'")
self.text = text
freqs = {}
for car in self.text:
freqs[car] = freqs.get(car, 0) + 1
self.codelengths = codelengths_from_frequencies(freqs)
self.codes = normalized(self.codelengths)
self.max_codelength = max(len(v) for v in self.codes.values())
def compressed_bytes(self):
compressed = self.compressed_str() + self.codes[256]
out = bytearray()
pos = 0
while pos < len(compressed):
bits = compressed[pos:pos + 8]
byte = int(bits, 2)
if len(bits) < 8:
byte <<= (8 - len(bits))
out.append(byte)
pos += 8
return out
def compressed_str(self):
return ''.join(self.codes[car] for car in self.text)
class Decompresser:
def __init__(self, compressed, codelengths):
self.compressed = compressed
codes = normalized(codelengths)
self.codes = {value : key for key, value in codes.items()}
self.root = Node()
self.make_tree(self.root)
def make_tree(self, node):
if node is self.root:
node.code = ''
children = []
for bit in '01':
next_code = node.code + bit
if next_code in self.codes:
child = Node(char=self.codes[next_code])
else:
child = Node()
child.code = next_code
children.append(child)
node.add(children)
for child in children:
if not child.is_leaf:
self.make_tree(child)
def decompress(self):
source = self.compressed
if isinstance(source, (bytes, bytearray)):
return self.decompress_bytes()
pos = 0
node = self.root
res = bytearray()
while pos < len(source):
code = int(source[pos])
child = node.children[code]
if child.is_leaf:
res.append(child)
node = self.root
else:
node = child
pos += 1
return bytes(res)
def decompress_bytes(self):
source = self.compressed
pos = 0
node = self.root
res = bytearray()
while pos < len(source):
byte = source[pos]
mask = 128
while mask > 0:
code = bool(byte & mask)
child = node.children[code]
if child.is_leaf:
if child.char == 256:
break # end of block
res.append(child.char)
node = self.root
else:
node = child
mask >>= 1
pos += 1
return res
def compress(text, klass=bytes):
compr = Compresser(text)
result = {"codelengths": compr.codelengths}
if klass is bytes:
result["data"] = compr.compressed_bytes()
elif klass is str:
result["data"] = compr.compressed_str()
else:
raise TypeError("second argument of compress must be bytes or "
"str, not '{}'".format(klass))
return result
def decompress(data, codelengths):
decomp = Decompresser(data, codelengths)
return decomp.decompress()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.