content
stringlengths 7
1.05M
|
|---|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Author :AmosWu
# Date :2019/1/26
# Features :利用条件运算符的嵌套来完成此题:学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示。
def main():
s = int(input('Enter a number:'))
if s >= 90:
grade = 'A'
elif s >= 60:
grade = 'B'
else:
grade = 'C'
print (grade)
if __name__ == '__main__':
main()
|
# Created by MechAviv
# Map ID :: 402000630
# Desert Cavern : Below the Sinkhole
# Update Quest Record EX | Quest ID: [34931] | Data: dir=1;exp=1
sm.curNodeEventEnd(True)
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(True, False, False, False)
sm.setStandAloneMode(True)
sm.removeAdditionalEffect()
sm.zoomCamera(0, 2000, 0, -142, -250)
sm.blind(1, 255, 0, 0, 0, 0, 0)
sm.sendDelay(1200)
sm.blind(0, 0, 0, 0, 0, 1000, 0)
sm.sendDelay(1400)
sm.sendDelay(500)
sm.zoomCamera(3000, 1000, 3000, 100, 0)
sm.sendDelay(3500)
sm.setSpeakerID(3001510)
sm.setSpeakerType(3)
sm.removeEscapeButton()
sm.flipDialogue()
sm.setBoxChat()
sm.boxChatPlayerAsSpeaker()
sm.setBoxOverrideSpeaker()
sm.flipBoxChat()
sm.flipBoxChatPlayerAsSpeaker()
sm.setColor(1)
sm.sendNext("#face2#So this is what's below the sand.")
sm.setSpeakerID(3001510)
sm.setSpeakerType(3)
sm.removeEscapeButton()
sm.flipDialogue()
sm.setBoxChat()
sm.boxChatPlayerAsSpeaker()
sm.setBoxOverrideSpeaker()
sm.flipBoxChat()
sm.flipBoxChatPlayerAsSpeaker()
sm.setColor(1)
sm.sendSay("#face2#And now we've all been separated.")
sm.setSpeakerID(3001500)
sm.setSpeakerType(3)
sm.removeEscapeButton()
sm.flipDialogue()
sm.setBoxChat()
sm.boxChatPlayerAsSpeaker()
sm.setBoxOverrideSpeaker()
sm.flipBoxChat()
sm.flipBoxChatPlayerAsSpeaker()
sm.setColor(1)
sm.sendSay("#face0#Well...")
sm.blind(1, 150, 0, 0, 0, 500, 0)
sm.playSound("Sound/SoundEff.img/PinkBean/expectation", 100)
sm.OnOffLayer_On(500, "d0", 0, -80, -1, "Effect/Direction17.img/effect/ark/illust/7/1", 4, 1, -1, 0)
sm.sendDelay(1000)
sm.blind(0, 0, 0, 0, 0, 500, 0)
sm.OnOffLayer_Off(500, "d0", 0)
sm.sendDelay(500)
sm.setSpeakerID(3001500)
sm.setSpeakerType(3)
sm.removeEscapeButton()
sm.flipDialogue()
sm.setBoxChat()
sm.boxChatPlayerAsSpeaker()
sm.setBoxOverrideSpeaker()
sm.flipBoxChat()
sm.flipBoxChatPlayerAsSpeaker()
sm.setColor(1)
sm.sendNext("#face0#At least we got this.")
sm.setSpeakerID(3001510)
sm.setSpeakerType(3)
sm.removeEscapeButton()
sm.flipDialogue()
sm.setBoxChat()
sm.boxChatPlayerAsSpeaker()
sm.setBoxOverrideSpeaker()
sm.flipBoxChat()
sm.flipBoxChatPlayerAsSpeaker()
sm.setColor(1)
sm.sendSay("#face0#Wow! You managed to catch that while we were falling? Impressive!")
sm.setSpeakerID(3001510)
sm.setSpeakerType(3)
sm.removeEscapeButton()
sm.flipDialogue()
sm.setBoxChat()
sm.boxChatPlayerAsSpeaker()
sm.setBoxOverrideSpeaker()
sm.flipBoxChat()
sm.flipBoxChatPlayerAsSpeaker()
sm.setColor(1)
sm.sendSay("#face2#I'm not happy about being this far underground. What was that demolitions dummy thinking?!")
sm.setSpeakerID(3001510)
sm.setSpeakerType(3)
sm.removeEscapeButton()
sm.flipDialogue()
sm.setBoxChat()
sm.boxChatPlayerAsSpeaker()
sm.setBoxOverrideSpeaker()
sm.flipBoxChat()
sm.flipBoxChatPlayerAsSpeaker()
sm.setColor(1)
sm.sendSay("#face2#Now we're going to waste a bunch of time we don't have tracking everyone down.")
sm.showFadeTransition(0, 1000, 3000)
sm.zoomCamera(0, 1000, 2147483647, 2147483647, 2147483647)
sm.moveCamera(True, 0, 0, 0)
sm.sendDelay(300)
sm.removeOverlapScreen(1000)
sm.moveCamera(True, 0, 0, 0)
sm.setStandAloneMode(False)
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(False, True, False, False)
|
'''
StockSlayer is a multiplayer network game themed on the stock market.
This module creates all game companies and events.
Copyright (c) 2016 by Daniel Vedder and Niklas Götz.
Licensed under the terms of the MIT license.
'''
global companies
global events
companies, events = [], []
def new_company(name, industry, share_price):
'''
Create a new company and add it to the list.
'''
#XXX I think we should drop company ratings - they are probably unnecessary
global companies
company = dict(name=name, industry=industry, share=share_price, rating=0)
companies.append(company)
def new_event(name, impact, target_industry, probability=0.01,
whole_industry=False):
'''
Create a new event and add it to the list.
'''
global events
event = dict(name=name, probability=probability, impact=impact,
target_industry=target_industry,
whole_industry=whole_industry)
events.append(event)
def get_company(name):
'''
Return the desired company. Returns None if the company does not exist.
'''
global companies
for c in companies:
if c["name"] == name: return c
return None
#
# CONTENT
#
# Create some companies
new_company("Pear Computers", "Computer", 105)
new_company("Nanosoft", "Computer", 60)
new_company("Goggle", "Computer", 780)
new_company("Dutsh Bank", "Finance", 15)
new_company("JC Organ", "Finance", 30)
new_company("X Combinator", "Finance", 10)
new_company("Colditz Laboratories", "Pharmaceutics", 5)
new_company("Baier", "Pharmaceutics", 95)
new_company("Camgen", "Pharmaceutics", 155)
new_company("Mapani Copper Mines", "Mining", 10)
new_company("Australian Gold", "Mining", 5)
new_company("Chemical & Mining Co.", "Mining", 25)
new_company("Nile.com", "Logistics", 785)
new_company("Bundespost", "Logistics", 30)
new_company("Feedex", "Logistics", 165)
new_company("AMW", "Automobile", 80)
new_company("Rolls Ross", "Automobile", 135)
new_company("Generic Motors", "Automobile", 30)
# Create some events
new_event("%NAME% buys a hot new startup.", 5, "Computer")
new_event("%NAME% networks were breached in a hacker attack.", -5, "Computer")
new_event("%NAME% is accused of trying to manipulate the stock market.",
-5, "Finance")
new_event("%NAME% has just received a triple-A rating.", 5, "Finance")
new_event("%NAME%'s researchers have discovered a new cancer treatment.",
5, "Pharmaceutics")
new_event("One of %NAME%'s drugs has undisclosed side effects.",
-5, "Pharmaceutics")
new_event("%NAME%'s engineers have discovered a rich mineral deposit.",
5, "Mining")
new_event("Miners trapped underground in a %NAME% accident.", -5, "Mining")
new_event("A new procedure enables %NAME% to deliver goods even faster.",
5, "Logistics")
new_event("A strike cripples %NAME%'s transport network.", -5, "Logistics")
new_event("%NAME% introduces a new series of electric sports cars.",
5, "Automobile")
new_event("%NAME% has to lay off workers from one of their factories.",
-5, "Automobile")
|
# "directions" are all the ways you can describe going some way;
# they are code-visible names for directions for adventure authors
direction_names = ["NORTH","SOUTH","EAST","WEST","UP","DOWN","RIGHT","LEFT",
"IN","OUT","FORWARD","BACK",
"NORTHWEST","NORTHEAST","SOUTHWEST","SOUTHEAST"]
direction_list = [ NORTH, SOUTH, EAST, WEST, UP, DOWN, RIGHT, LEFT,
IN, OUT, FORWARD, BACK,
NORTHWEST, NORTHEAST, SOUTHWEST, SOUTHEAST] = \
range(len(direction_names))
NOT_DIRECTION = None
# some old names, for backwards compatibility
(NORTH_WEST, NORTH_EAST, SOUTH_WEST, SOUTH_EAST) = \
(NORTHWEST, NORTHEAST, SOUTHWEST, SOUTHEAST)
directions = dir_by_name = dict(zip(direction_names, direction_list))
def define_direction (number, name):
if name in dir_by_name:
exit("%s is already defined as %d" % (name, dir_by_name[name]))
dir_by_name[name] = number
def lookup_dir (name):
return dir_by_name.get(name, NOT_DIRECTION)
# add lower-case versions of all names in direction_names
for name in direction_names:
define_direction(dir_by_name[name], name.lower())
# add common aliases:
# maybe the alias mechanism should be a more general
# (text-based?) mechanism that works for any command?!!!
common_aliases = [
(NORTH, "n"),
(SOUTH, "s"),
(EAST, "e"),
(WEST, "w"),
(UP, "u"),
(DOWN, "d"),
(FORWARD, "fd"),
(FORWARD, "fwd"),
(FORWARD, "f"),
(BACK, "bk"),
(BACK, "b"),
(NORTHWEST,"nw"),
(NORTHEAST,"ne"),
(SOUTHWEST,"sw"),
(SOUTHEAST, "se")
]
for (k,v) in common_aliases:
define_direction(k,v)
# define the pairs of opposite directions
opposite_by_dir = {}
def define_opposite_dirs (d1, d2):
for dir in (d1, d2):
opposite = opposite_by_dir.get(dir)
if opposite is not None:
exit("opposite for %s is already defined as %s" % (dir, opposite))
opposite_by_dir[d1] = d2
opposite_by_dir[d2] = d1
opposites = [(NORTH, SOUTH),
(EAST, WEST),
(UP, DOWN),
(LEFT, RIGHT),
(IN, OUT),
(FORWARD, BACK),
(NORTHWEST, SOUTHEAST),
(NORTHEAST, SOUTHWEST)]
for (d1,d2) in opposites:
define_opposite_dirs(d1,d2)
def opposite_direction (dir):
return opposite_by_dir[dir]
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def upsideDownBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root:
return
left = self.upsideDownBinaryTree(root.left)
right = self.upsideDownBinaryTree(root.right)
if root.left:
root.left.right = root
root.left.left = root.right
root.left = root.right = None
return left if left else root
|
REQUIRED_SECTIONS = ['模块', '标题', '描述', '前提条件', '步骤', '期望结果', '优先级']
# project: 1, module: 2, plan: 3, case: 4
NUMBER_TYPE = {"1": "project", "2": "module", "3": "plan", "4": "case"}
CASE_COLOR_DIC = {"Pending": "black", "Pass": "green", "Fail": "red", "Block": "gray"}
MSG_USERNAME_OR_PASSWORD_WRONG = "用户名或密码错误"
STATUS_SUCCESS = 1
STATUS_FAILED = 0
MSG_METHOD_NOT_ALLOWED = "不允许的方法"
MSG_INVALID_KEY_DATA = "参数错误"
MSG_INVALID_DATA = "创建数据错误"
MSG_OK = "OK"
MSG_DELETE_SUCCESS = "删除成功"
MSG_DELETE_FAILED = "删除失败:{info}"
MSG_CREATE_SUCCESS = "创建成功"
MSG_MODIFY_SUCCESS = "修改成功"
MSG_MODIFY_FAIL = "修改失败"
MSG_QUERY_SUCCESS = "查询成功"
MSG_MISSING_REQUIRED_FIELDS = "{field}不能为空"
MSG_ASSOCIATE_SUCCESS = "关联成功"
MSG_ALREADY_HAVE_SAME_RECORD = "关联失败:用例'{case}'已经存在于计划{plan}中"
MSG_USER_ALREADY_HAVE_INCOMPLETE_TASK = "失败:该用户已有任务,请直接关联新用例即可"
MSG_BATCH_CREATE_SUCCESS = "批量创建成功"
MSG_BATCH_CREATE_FAILED = "批量创建失败"
MSG_CASE_EXECUTE_SUCCESS = "执行成功"
|
"""Top-level package for clinepunk."""
__author__ = """Taylor Monacelli"""
__email__ = "taylormonacelli@gmail.com"
__version__ = "0.1.14"
|
# -*- coding:utf-8 -*-
__author__ = 'zhangzhibo'
__date__ = '202018/5/18 16:56'
|
#Clases del ciclo de lavado
class lavando:
#Etapa 1. Lavado
def lavado(self):
print("Lavando...")
class enjuagando:
#Etapa 2. Enjuagado
def enjuagado(self):
print("Enjuagando...")
class centrifugando:
#Etapa 3. Centrifugado
def centrifugado(self):
print("Centrifugando...")
class finalizado:
#Etapa 4. Finalizado de ciclo
def finalizar(self):
print("Finalizado!")
class LavadoraFacade:
def __init__(self):
self.lavando = lavando()
self.enjuagando = enjuagando()
self.centrifugando = centrifugando()
self.finalizando = finalizado()
#Lista de ciclos
def ciclo_completo(self):
self.lavando.lavado()
self.enjuagando.enjuagado()
self.centrifugando.centrifugado()
self.finalizando.finalizar()
def solo_centrifugado(self):
self.centrifugando.centrifugado()
self.finalizando.finalizar()
def solo_lavado(self):
self.lavando.lavado()
self.finalizando.finalizar()
def solo_enjuagado(self):
self.enjuagando.enjuagado()
self.finalizando.finalizar()
|
'''
Date: 01/08/2019
Problem description:
===================
This problem was asked by Google.
Given an array of integers where every integer occurs three times
except for one integer, which only occurs once, find and return the
non-duplicated integer.
For example, given [6, 1, 3, 3, 3, 6, 6], return 1.
Given [13, 19, 13, 13], return 19.
Do this in O(N) time and O(1) space.
Algorithm:
==========
Input: A list of numbers
Output: An integer represeting the non-duplicate value
Psuedo code:
1. Check for valid input
2. Rerurn value from set(list-comprehension) where element
count equals to one
Note: This is why I love Python!!!
'''
def find_non_dup(A=[]):
if len(A) == 0:
return None
non_dup = list(set([x for x in A if A.count(x) == 1]))
return non_dup[-1]
def test_code():
A = [7,3,3,3,7,8,7]
assert find_non_dup(A) == 8
if __name__ == '__main__':
Array = [9,5,5,5,8,9,8,9,3,4,4,4]
non_dup = find_non_dup(Array)
print("Test1:\nGiven a list [{}]\nThe non-duplicate value is {}".format(', '.join(str(i) for i in Array), non_dup))
'''
Run-time output:
===============
(DailyCodingChallenge-wC3ocw3s) markn@raspberrypi3:~/devel/py-src/DailyCodingChallenge $ python codechallenge_025.py
Test1:
Given a list [9, 5, 5, 5, 8, 9, 8, 9, 3, 4, 4, 4]
The non-duplicate value is 3
(DailyCodingChallenge-wC3ocw3s) markn@raspberrypi3:~/devel/py-src/DailyCodingChallenge $ pytest codechallenge_025.py
================================ test session starts =================================
platform linux2 -- Python 2.7.13, pytest-3.6.3, py-1.5.4, pluggy-0.6.0
rootdir: /home/markn/devel/py-src/DailyCodingChallenge, inifile:
collected 1 item
codechallenge_025.py . [100%]
============================== 1 passed in 0.03 seconds ==============================
'''
|
"""
Faça um programa que preencha um vetor com 10 números reais, calcule e mostre a quantidade de números negativos e a
soma dos números positivos desse vetor.
"""
lista = []
for x in range(10):
n1 = float(input('Digite: '))
lista.append(n1)
soma = 0
quan = 0
for x in lista:
if x >= 0:
soma += x
else:
quan += 1
print(quan, soma)
|
# considerando o dollar 3.27$
carteira = float(input("quanto você tem na sua carteira: "))
dollar = float(3.27)
total = float(carteira / dollar)
print(f"Com total de R$ {carteira:.2f} você pode comprar US$ {total:.2f}")
|
"""
Desafio 089
Problema: Crie um programa que leia nome e duas notas de vários alunos
e guarde tudo em uma lista composta. No final, mostre um
boletim contendo a média de cada um e permita que o usuário
possa mostrar as notas de cada aluno individualmente.
Resolução do problema:
"""
historicoAlunos = []
dadosAluno = []
while True:
dadosAluno.append(input('NOME: ').strip().capitalize())
dadosAluno.append([float(input('NOTA 1: ')), float(input('NOTA 2: '))])
# Notas menores que 0 e maiores que 10 são inválidas, então solicida novamente em caso verdaidero
while (dadosAluno[1][0] < 0 or dadosAluno[1][0] > 10) or (dadosAluno[1][1] < 0 or dadosAluno[1][1] > 10):
print('-' * 25)
print('Nota inválida, informe notas de 0 a 10...')
dadosAluno[1].clear() # Limpa dados inválidos
print(f'NOME: {dadosAluno[0]}')
dadosAluno[1].append(float(input('NOTA 1: ')))
dadosAluno[1].append(float(input('NOTA 2: ')))
historicoAlunos.append(dadosAluno[:]) # Cópia completa
dadosAluno.clear() # Limpando lista de dados
print('-' * 25)
continuar = input('Continuar [S/N]: ').strip().upper()
# Caso informa uma opção inválida, entrará em loop até que informe uma valida
while continuar not in ('S', 'N'):
print('\nInforme a opção corretamente...')
continuar = input('Continuar [S/N]: ').strip().upper()
print('-' * 25)
if continuar == 'N':
print('\n')
print('+------------------------------+' + f'\n|{"MÉDIAS":^30}|\n' + '+-----+----------------+-------+')
break
for idx, nome in enumerate(historicoAlunos):
if idx == 0:
# Formatando cabeçalho da tabela
print(f'| {"ID":<4}| {"NOME":<15}| {"MÉDIA":<6}|\n' + '+-----+----------------+-------+')
media = (historicoAlunos[idx][1][0] + historicoAlunos[idx][1][1]) / 2
print(f'| {idx:<4}| {historicoAlunos[idx][0]:<15}| {media:<6.1f}|') # Dados da tabela
print('+-----+----------------+-------+')
while True:
id_aluno = int(input('\nID DO ALUNO ou (999 para sair): '))
while 0 > id_aluno or id_aluno > len(historicoAlunos) - 1 and id_aluno != 999:
print('~' * 37)
print('\nInforme um ID correto...')
id_aluno = int(input('ID DO ALUNO ou (999 para sair): '))
print('-' * 37)
if id_aluno == 999:
print('\nPrograma finalizado...')
break
print(f'Aluno(a): {historicoAlunos[id_aluno][0]}\nNotas: {historicoAlunos[id_aluno][1]}')
print('-' * 37)
|
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
class FormatPipeline(object):
"""
All crawled items are passed through this pipeline
"""
def process_item(self, item, spider):
"""
Process an item produced by the spider
"""
item["link"] = item["link"].strip()
item["category"] = [x.strip() for x in item["category"]]
item["title"] = item["title"].strip()
item["warranty"] = (item["warranty"] or "Not Specified").strip()
item["rating"] = to_float(item["rating"].replace(',', '.'))
item["features"] = [to_ascii(x) for x in item["features"]]
item["features"] = list(set(item["features"]))
item["price"]["value"] = to_float(str(item["price"]["value"]))
if "old_price" in item:
item["old_price"]["value"] = to_float(str(item["old_price"]["value"]))
item["discount_rate"] = to_int((item["discount_rate"] or "0%").strip()[:-1])
# end if
return item
# end def
# end class
def to_ascii(x):
return x.encode('ascii', 'ignore').decode('utf8').strip()
#end def
def parse(func, arg):
"""Tries to parse the value"""
try:
return func(arg)
except ValueError:
return 0
# end def
def to_float(x):
return parse(float, (x or "0"))
# end def
def to_int(x):
return parse(int, (x or "0"))
# end def
|
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
head = ListNode(0)
curr = head
currs = [h for h in lists if h is not None]
while currs:
min_i = 0
for i, p in enumerate(currs):
if p.val < currs[min_i].val:
min_i = i
curr.next = currs[min_i]
curr = curr.next
if currs[min_i].next:
currs[min_i] = currs[min_i].next
else:
currs.remove(currs[min_i])
return head.next
|
# ---------------------------------------------------------------------------------------------------------------------
# # # PARTE 1 # # #
# ---------------------------------------------------------------------------------------------------------------------
class Persona(object):
def __init__(self, **args):
self.nombre = args.get('nombre')
self.edad = args.get('edad')
self.sexo = args.get('sexo')
self.estatura = args.get('estatura')
self.peso = args.get('peso')
# ----------------------------------------------------------
def set_nombre(self, nombre):
self.nombre = nombre
def get_nombre(self):
return self.nombre
# ---------------------------------------------------------
def set_edad(self, edad):
self.edad = edad
def get_edad(self):
return self.edad
# ---------------------------------------------------------
def set_sexo(self, sexo):
self.sexo = sexo
def get_sexo(self):
return self.sexo
# ---------------------------------------------------------
def set_estatura(self, estatura):
self.estatura = estatura
def get_estatura(self):
return self.estatura
# ---------------------------------------------------------
def set_peso(self, peso):
self.peso = peso
def get_peso(self):
return self.peso
# ----------------------------------------------------------
def imc(self):
pe = self.get_peso()
es = self.get_estatura()
imc = pe / (es * es)
return "{0:.4f}".format(imc)
# ----------------------------------------------------------
def __str__(self):
return f'Nombre: {self.nombre}\nEdad: {self.edad} años\nSexo: {self.sexo}\nPeso: {self.peso} kgs.\nEstatura: {self.estatura} mts.\nIMC: {self.imc()}'
# E J E M P L O S
p1 = Persona(nombre='Luis', edad=45, sexo='Masculino', estatura=1.80, peso=108)
p2 = Persona(nombre='Carlos', edad=36, sexo='Masculino', estatura=1.75, peso=81)
p3 = Persona(nombre='Emmanuel', edad=27, sexo='Masculino', estatura=1.68, peso=63)
print(p1.__str__(), '\n')
print(p2.__str__(), '\n')
print(p3.__str__(), '\n')
# ---------------------------------------------------------------------------------------------------------------------
# # # PARTE 2 # # #
# ---------------------------------------------------------------------------------------------------------------------
class Empleado(Persona):
def __init__(self, **args):
super(Empleado, self).__init__(**args)
self._id = args.get('id')
self._puesto = args.get('puesto')
# ----------------------------------------------------------
def set_id(self, idn):
self._id = idn
def get_id(self):
return self._id
# ----------------------------------------------------------
def set_puesto(self, puesto):
self._puesto = puesto
def get_puesto(self):
return self._puesto
# ----------------------------------------------------------
def __str__(self):
return f'{super(Empleado, self).__str__()}\nID de empleado: {self._id}\nPuesto: {self._puesto}'
# E J E M P L O
slave = Empleado(id=9, puesto='Chef')
slave.set_nombre('Mario')
slave.set_edad(27)
slave.set_sexo('Masculino')
slave.set_estatura(1.8)
slave.set_peso(90)
print(slave, '\n')
# ---------------------------------------------------------------------------------------------------------------------
# # # PARTE 3 # # #
# ---------------------------------------------------------------------------------------------------------------------
class Empresa(Empleado):
def __init__(self, **args):
super(Empresa, self).__init__(**args)
self._nombre_empresa = args.get('nombre_empresa')
self._direccion = args.get('direccion')
self._rfc = args.get('rfc')
self._conj_emp = args.get('conj_emp')
def set_nombre_empresa(self, nombre_empresa):
self._nombre_empresa = nombre_empresa
def get_nombre_empresa(self):
return self._nombre_empresa
# ----------------------------------------------------------
def set_direccion(self, direccion):
self._direccion = direccion
def get_direccion(self):
return self._direccion
# ----------------------------------------------------------
def set_rfc(self, rfc):
self._rfc = rfc
def get_rfc(self):
return self._rfc
# ----------------------------------------------------------
def set_conj_emp(self, conj_emp):
self._conj_emp = conj_emp
def get_conj_emp(self):
return self._conj_emp
# ----------------------------------------------------------
def __str__(self):
return f'{super(Empresa, self).__str__()}\nNombre de la empresa: {self._nombre_empresa}\n' \
f'Dirección de la empresa: {self._direccion}\nRFC de la empresa: {self._rfc}\n'
# E J E M P L O S
slave1 = Empresa(nombre_empresa='Krusty Krab', direccion='Acámbaro, #999, Saltillo, Coah.', rfc='CC090509IDK')
slave2 = Empresa(nombre_empresa='Krusty Krab', direccion='Acámbaro, #999, Saltillo, Coah.', rfc='CC090509IDK')
slave1.set_nombre('Ricardo')
slave1.set_edad(27)
slave1.set_sexo('Masculino')
slave1.set_estatura(1.8)
slave1.set_peso(90)
slave1.set_id(1)
slave1.set_puesto('Cocinero')
slave2.set_nombre('Rodrigo')
slave2.set_edad(18)
slave2.set_sexo('Masculino')
slave2.set_estatura(1.90)
slave2.set_peso(81)
slave2.set_id(2)
slave2.set_puesto('Mesero')
print(slave1, '\n', slave2, '\n')
|
"""
link: https://leetcode-cn.com/problems/reconstruct-itinerary
problem: 给有向图和起点,求字典序最小的欧拉通路,保证解存在
solution: Hierholzer 算法。从起点开始做dfs,搜索的同时删除每次跳转的边,搜完的节点入栈,搜索遍历顺序的逆序即为结果。
"""
class Solution:
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
m = collections.defaultdict(list)
for x in tickets:
m[x[0]].append(x[1])
for x in m:
m[x].sort()
res = []
def dfs(k: str):
for i, t in enumerate(m[k]):
if m[k][i] == "x":
continue
m[k][i] = "x"
dfs(t)
res.append(k)
dfs("JFK")
res.reverse()
return res
|
START_BRAKING = 17
END_BRAKING = 25
BRAKE_SPEED = 1
""" Straight, please """
def reward_function(params):
# No rewards shaping yet, just add a brake by track position
if params['closest_waypoints'][0] >= START_BRAKING and params['closest_waypoints'][0] >= END_BRAKING and params['speed'] == BRAKE_SPEED:
# BRAKE!
reward = 1
elif params['speed'] > BRAKE_SPEED:
# Don't brake!
reward = 1
else:
# You're doing it wrong!
reward = 1e-3
return reward
|
#!/usr/bin/env python3
table = {i: chr(i + 0xFEE0) for i in range(33, 127)}
table[ord(' ')] = '\N{IDEOGRAPHIC SPACE}'
def ascii_to_fullwidth(text):
return text.translate(table)
def main():
assert ascii_to_fullwidth('h') == 'h'
if __name__ == '__main__':
main()
|
# See file COPYING distributed with xnatrest for copyright and license.
class XNATRESTError(Exception):
"""base class for xnatrest exceptions"""
class CircularReferenceError(XNATRESTError):
def __init__(self, url):
self.url = url
return
def __str__(self):
return 'circular reference to %s' % self.url
class UnidentifiedServerError(XNATRESTError):
def __str__(self):
return 'could not identify server'
# eof
|
# Start and end date
gldas_start_date = '2010-01-01'
gldas_end_date = '2014-01-01'
# Location (Latitude and Longitude)
gldas_geo_point = AutoParam([(38, -117), (38, -118)])
# Create data fetcher
gldasdf = GLDASDF([gldas_geo_point],start_date=gldas_start_date,
end_date=gldas_end_date, resample=False)
|
class IDGroup:
"""
The IDGroup Type
================
This type supports both iteration and the []
operator to get child ID properties.
You can also add new properties using the [] operator.
For example::
group['a float!'] = 0.0
group['an int!'] = 0
group['a string!'] = "hi!"
group['an array!'] = [0, 0, 1.0, 0]
group['a subgroup!] = {"float": 0.0, "an int": 1.0, "an array": [1, 2],
"another subgroup": {"a": 0.0, "str": "bleh"}}
Note that for arrays, the array type defaults to int unless a float is found
while scanning the template list; if any floats are found, then the whole
array is float. Note that double-precision floating point numbers are used for
python-created float ID properties and arrays (though the internal C api does
support single-precision floats, and the python code will read them).
You can also delete properties with the del operator. For example:
del group['property']
To get the type of a property, use the type() operator, for example::
if type(group['bleh']) == str: pass
To tell if the property is a group or array type, import the Blender.Types module and test
against IDGroupType and IDArrayType, like so::
from Blender.Types import IDGroupType, IDArrayType.
if type(group['bleghr']) == IDGroupType:
(do something)
@ivar name: The name of the property
@type name: string
"""
def pop(item):
"""
Pop an item from the group property.
@type item: string
@param item: The item name.
@rtype: can be dict, list, int, float or string.
@return: The removed property.
"""
def update(updatedict):
"""
Updates items in the dict, similar to normal python
dictionary method .update().
@type updatedict: dict
@param updatedict: A dict of simple types to derive updated/new IDProperties from.
@rtype: None
@return: None
"""
def keys():
"""
Returns a list of the keys in this property group.
@rtype: list of strings.
@return: a list of the keys in this property group.
"""
def values():
"""
Returns a list of the values in this property group.
Note that unless a value is itself a property group or an array, you
cannot change it by changing the values in this list, you must change them
in the parent property group.
For example,
group['some_property'] = new_value
. . .is correct, while,
values = group.values()
values[0] = new_value
. . .is wrong.
@rtype: list of strings.
@return: a list of the values in this property group.
"""
def iteritems():
"""
Implements the python dictionary iteritmes method.
For example::
for k, v in group.iteritems():
print "Property name: " + k
print "Property value: " + str(v)
@rtype: an iterator that spits out items of the form [key, value]
@return: an iterator.
"""
def convert_to_pyobject():
"""
Converts the entire property group to a purely python form.
@rtype: dict
@return: A python dictionary representing the property group
"""
class IDArray:
"""
The IDArray Type
================
@ivar type: returns the type of the array, can be either IDP_Int or IDP_Float
"""
def __getitem__(index):
pass
def __setitem__(index, value):
pass
def __len__():
pass
|
"""
Let's call an array A a mountain if the following properties hold:
A.length >= 3
There exists some 0 < i < A.length - 1 such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]
Given an array that is definitely a mountain, return any i such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1].
Example 1:
Input: [0,1,0]
Output: 1
Example 2:
Input: [0,2,1,0]
Output: 1
Note:
1. 3 <= A.length <= 10000
2. 0 <= A[i] <= 10^6
3. A is a mountain, as defined above.
"""
class Solution:
def peakIndexInMountainArray1(self, A):
for i in range(len(A)):
if A[i] > A[i + 1]:
return i
def peakIndexInMountainArray2(self, A):
a, b = 0, len(A) - 1
while a <= b:
c = (a + b) // 2
if A[c] < A[c + 1]:
a = c + 1
else:
b = c - 1
return a
|
c.NotebookApp.ip = '0.0.0.0'
c.NotebookApp.port = 80
c.NotebookApp.allow_root = True
c.NotebookApp.open_browser = False
c.NotebookApp.password = 'sha1:8e4f16cf0aa6:30644b99b9930e0179359266c359461493c2cec5' #填入刚刚复制的字符
|
def hola():
def bienvenido():
print("hola!")
return bienvenido
# hola()()
def mensaje():
return "Este es un mensaje"
def test(function):
print(mensaje())
test(mensaje)
|
def combination(a: int, b: int) -> int:
"""
Choose b from a. a >= b
"""
b = min(b, a - b)
numerator = 1
dominator = 1
for i in range(b):
numerator *= (a - i)
dominator *= (b - i)
return int(numerator / dominator)
if __name__ == '__main__':
t = int(input())
for _ in range(t):
n, m = map(int, input().split())
print(combination(m, n))
|
# Getting all PAL : Prime and pallindrome numbers between two given numbers
def pallindrome(n):
temp=n
rev=0
while(n>0):
dig = n % 10
rev=rev*10 +dig
n = n/10
if temp == rev:
return True
else:
return False
def isprime(n):
if n<=1:
return False
if n<=3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i*i < n:
if n % i == 0 or n % (i+2) == 0:
return False
i=i+6
return True
a=int(input("Enter the number of lower range "))
b=int(input("Enter the number of upper range "))
for i in range(a,b):
if pallindrome(i) and isprime(i):
print(i)
|
async def iter_to_aiter(iter):
"""
:type iter: synchronous iterator
:param iter: a synchronous iterator
This converts a regular iterator to an async iterator.
"""
for _ in iter:
yield _
|
# buttons
PIN_BUTTON_PROG = 17
PIN_BUTTON_ERASE = 27
# LEDs
PIN_RED = 23
PIN_GREEN = 24
PIN_BLUE = 20
PIN_BLUE2 = 25
# Jumpers
PINS_PROFILES = [5, 6, 13, 19]
# MCU
PIN_RESET_ATMEGA = 16
PIN_MASTER_POWER = 12
PIN_ESP_RESET = 8
PIN_ESP_GPIO_0 = 4
# MISC
PIN_BUZZER = 26
# Interfaces
DEFAULT_SERIAL_SPEED = 9600
DEFAULT_PRGM_COMM_SPEED = 115200
SERIAL_PORT = "/dev/serial0"
|
# -*- coding: utf-8 -*-
smtpserver = "smtp.qq.com" # will be read by smtp fixture
def test_showhelo(smtp_connection):
assert 0, smtp_connection.helo()
|
# -*- coding: utf-8 -*-
project = 'test'
master_doc = 'index'
|
s, n = map(int, input().split())
arr = [0] * n
for i in range(s):
p = int(input())
for j in range(0, len(arr), p):
arr[j] = 1
for i in arr:
print(i, end=" ")
print()
|
CHAMP_ID_TO_EMOJI = {'266': '<:champ_266:601909182748164097>', '103': '<:champ_103:601909185243774976>', '84': '<:champ_84:601909188612063233>', '12': '<:champ_12:601909190809878530>', '32': '<:champ_32:601909193456222221>', '34': '<:champ_34:601909195968610356>', '1': '<:champ_1:601909198799896690>', '22': '<:champ_22:601909201564073984>', '136': '<:champ_136:601909204034387986>', '268': '<:champ_268:601909206337191937>', '432': '<:champ_432:601909209348571136>', '53': '<:champ_53:601909212175663129>', '63': '<:champ_63:601909215262408705>', '201': '<:champ_201:601909218072592406>', '51': '<:champ_51:601909220664672275>', '164': '<:champ_164:601909222455640094>', '69': '<:champ_69:601909224213053481>', '31': '<:champ_31:601909227174494208>', '42': '<:champ_42:601909229246218250>', '122': '<:champ_122:601909231268134933>', '131': '<:champ_131:601909232954245122>', '119': '<:champ_119:601909235831406759>', '36': '<:champ_36:601909237928689714>', '245': '<:champ_245:601909241250578462>', '60': '<:champ_60:601909243112718355>', '28': '<:champ_28:601909244823863309>', '81': '<:champ_81:601909247458148353>', '9': '<:champ_9:601909250234646746>', '114': '<:champ_114:601909252642045964>', '105': '<:champ_105:601909255259291648>', '3': '<:champ_3:601909257067298865>', '41': '<:champ_41:601909258963124225>', '86': '<:champ_86:601909261915783188>', '150': '<:champ_150:601909264533028932>', '79': '<:champ_79:601909267032702989>', '104': '<:champ_104:601909269520056352>', '120': '<:champ_120:601909272825298944>', '74': '<:champ_74:601909276398714921>', '420': '<:champ_420:601909278105665588>', '39': '<:champ_39:601909281687732317>', '427': '<:champ_427:601909283675963402>', '40': '<:champ_40:601909286418907137>', '59': '<:champ_59:601909288994340933>', '24': '<:champ_24:601909292534071327>', '126': '<:champ_126:601909294975287325>', '202': '<:champ_202:601909297974083605>', '222': '<:champ_222:601909300687929355>', '145': '<:champ_145:601909302814310437>', '429': '<:champ_429:601909305662504981>', '43': '<:champ_43:601909308183150592>', '30': '<:champ_30:601909340571566080>', '38': '<:champ_38:601909342756929557>', '55': '<:champ_55:601909345663582273>', '10': '<:champ_10:601909347945283584>', '141': '<:champ_141:601909349471748112>', '85': '<:champ_85:601909351523024897>', '121': '<:champ_121:601909353540354061>', '203': '<:champ_203:601909356086296609>', '240': '<:champ_240:601909358258946048>', '96': '<:champ_96:601909360284663808>', '7': '<:champ_7:601909362222432266>', '64': '<:champ_64:601909364881883136>', '89': '<:champ_89:601909366802612236>', '127': '<:champ_127:601909370413907984>', '236': '<:champ_236:601909373194993698>', '117': '<:champ_117:601909375317311488>', '99': '<:champ_99:601909377959460885>', '54': '<:champ_54:601909383433027614>', '90': '<:champ_90:601909385614196767>', '57': '<:champ_57:601909388122390529>', '11': '<:champ_11:601909392623009793>', '21': '<:champ_21:601909395030409235>', '62': '<:champ_62:601909398578659358>', '82': '<:champ_82:601909401506414598>', '25': '<:champ_25:601909403448508437>', '267': '<:champ_267:601909406426333198>', '75': '<:champ_75:601909408628211715>', '111': '<:champ_111:601909410805055488>', '518': '<:champ_518:601909414118686752>', '76': '<:champ_76:601909416110981169>', '56': '<:champ_56:601909419189469185>', '20': '<:champ_20:601909421580484629>', '2': '<:champ_2:601909423983558668>', '61': '<:champ_61:601909426474975263>', '516': '<:champ_516:601909428958003212>', '80': '<:champ_80:601909431747346447>', '78': '<:champ_78:601909434142294086>', '555': '<:champ_555:601909436864397322>', '246': '<:champ_246:601909439876038676>', '133': '<:champ_133:601909442371387395>', '497': '<:champ_497:601909445253005335>', '33': '<:champ_33:601909447320797244>', '421': '<:champ_421:601909449850093579>', '58': '<:champ_58:601909452567871571>', '107': '<:champ_107:601909455478718491>', '92': '<:champ_92:601909458230050816>', '68': '<:champ_68:601909460482654208>', '13': '<:champ_13:601909462776676372>', '113': '<:champ_113:601909465624608777>', '35': '<:champ_35:601909468028207135>', '98': '<:champ_98:601909497539067924>', '102': '<:champ_102:601909500059975685>', '27': '<:champ_27:601909503205834764>', '14': '<:champ_14:601909506074607659>', '15': '<:champ_15:601909508129685504>', '72': '<:champ_72:601909510679953438>', '37': '<:champ_37:601909513066643456>', '16': '<:champ_16:601909515222253582>', '50': '<:champ_50:601909518082899972>', '517': '<:champ_517:601909520939089920>', '134': '<:champ_134:601909523493683213>', '223': '<:champ_223:601909526408724480>', '163': '<:champ_163:601909528652546070>', '91': '<:champ_91:601909531223654439>', '44': '<:champ_44:601909533727653918>', '17': '<:champ_17:601909535929794562>', '412': '<:champ_412:601909538701967370>', '18': '<:champ_18:601909541705089054>', '48': '<:champ_48:601909545056337960>', '23': '<:champ_23:601909548735004723>', '4': '<:champ_4:601909551637200898>', '29': '<:champ_29:601909555810795531>', '77': '<:champ_77:601909558604070961>', '6': '<:champ_6:601909560751423526>', '110': '<:champ_110:601909562953433098>', '67': '<:champ_67:601909566078451735>', '45': '<:champ_45:601909568452165653>', '161': '<:champ_161:601909571069411359>', '254': '<:champ_254:601909573863079936>', '112': '<:champ_112:601909575800717332>', '8': '<:champ_8:601909578438934677>', '106': '<:champ_106:601909581311901719>', '19': '<:champ_19:601909584277405709>', '498': '<:champ_498:601909586701582336>', '101': '<:champ_101:601909589369159691>', '5': '<:champ_5:601909591667769364>', '157': '<:champ_157:601909594758971468>', '83': '<:champ_83:601909596877094940>', '350': '<:champ_350:601909599469305875>', '154': '<:champ_154:601909605194268673>', '238': '<:champ_238:601909607824359462>', '115': '<:champ_115:601909610885939200>', '26': '<:champ_26:601909614031798447>', '142': '<:champ_142:601909616258973696>', '143': '<:champ_143:601909618808979478>'}
RUNE_ID_TO_EMOJI = {'8112': '<:rune_8112:602195444940144650>', '8124': '<:rune_8124:602195452028518410>', '8128': '<:rune_8128:602195459003514920>', '9923': '<:rune_9923:602195465299165308>', '8126': '<:rune_8126:602195466981212190>', '8139': '<:rune_8139:602195469573160970>', '8143': '<:rune_8143:602195471859056641>', '8136': '<:rune_8136:602195473264017462>', '8120': '<:rune_8120:602195475013173288>', '8138': '<:rune_8138:602195477257256963>', '8135': '<:rune_8135:602195479417192449>', '8134': '<:rune_8134:602195482487554058>', '8105': '<:rune_8105:602195484748152843>', '8106': '<:rune_8106:602195487650742283>', '8351': '<:rune_8351:602195494319423529>', '8359': '<:rune_8359:602195503048032291>', '8360': '<:rune_8360:602195510388064256>', '8306': '<:rune_8306:602195512036163585>', '8304': '<:rune_8304:602195513173082113>', '8313': '<:rune_8313:602195513546244128>', '8321': '<:rune_8321:602195517103014084>', '8316': '<:rune_8316:602195519829311562>', '8345': '<:rune_8345:602195522345893911>', '8347': '<:rune_8347:602195524338319370>', '8410': '<:rune_8410:602195527479722000>', '8352': '<:rune_8352:602195529291661489>', '8005': '<:rune_8005:602195538036785152>', '8008': '<:rune_8008:602195543464345601>', '8021': '<:rune_8021:602195550271700992>', '8010': '<:rune_8010:602195555006939137>', '9101': '<:rune_9101:602195557502681088>', '9111': '<:rune_9111:602195559880851536>', '8009': '<:rune_8009:602195562481057792>', '9104': '<:rune_9104:602195563936743455>', '9105': '<:rune_9105:602195565408813056>', '9103': '<:rune_9103:602195567241854979>', '8014': '<:rune_8014:602195568759930900>', '8017': '<:rune_8017:602195571364724774>', '8299': '<:rune_8299:602195573952479242>', '8437': '<:rune_8437:602195580919349261>', '8439': '<:rune_8439:602195586468544533>', '8465': '<:rune_8465:602195592357347358>', '8446': '<:rune_8446:602195594643243018>', '8463': '<:rune_8463:602195596736200757>', '8401': '<:rune_8401:602195601475764234>', '8429': '<:rune_8429:602195603308675078>', '8444': '<:rune_8444:602195605334392832>', '8473': '<:rune_8473:602195607670620161>', '8451': '<:rune_8451:602195610233339914>', '8453': '<:rune_8453:602195612569567250>', '8242': '<:rune_8242:602195615321030840>', '8214': '<:rune_8214:602195620601528330>', '8229': '<:rune_8229:602195626293198859>', '8230': '<:rune_8230:602195631255060541>', '8224': '<:rune_8224:602195633171857418>', '8226': '<:rune_8226:602195635868925970>', '8275': '<:rune_8275:602195639140483072>', '8210': '<:rune_8210:602195640432328792>', '8234': '<:rune_8234:602195643515011092>', '8233': '<:rune_8233:602195645956096010>', '8237': '<:rune_8237:602195647268913162>', '8232': '<:rune_8232:602195649907392525>', '8236': '<:rune_8236:602195652235231235>'}
MASTERIES_TO_EMOJI = {'1': '<:masteries_1:602201182131322886>', '2': '<:masteries_2:602201195792039967>', '3': '<:masteries_3:602201208505106453>', '4': '<:masteries_4:602201225701883924>', '5': '<:masteries_5:602201238528065557>', '6': '<:masteries_6:602201251069034496>', '7': '<:masteries_7:602201263152693325>'}
CHAMP_NONE_EMOJI = "<:champ_0:602225831095435294>"
INVISIBLE_EMOJI = "<:__:602265603893493761>"
CHAMP_NAME_TO_ID = {'Aatrox': '266', 'Ahri': '103', 'Akali': '84', 'Alistar': '12', 'Amumu': '32', 'Anivia': '34', 'Annie': '1', 'Ashe': '22', 'Aurelion Sol': '136', 'Azir': '268', 'Bard': '432', 'Blitzcrank': '53', 'Brand': '63', 'Braum': '201', 'Caitlyn': '51', 'Camille': '164', 'Cassiopeia': '69', "Cho'Gath": '31', 'Corki': '42', 'Darius': '122', 'Diana': '131', 'Draven': '119', 'Dr. Mundo': '36', 'Ekko': '245', 'Elise': '60', 'Evelynn': '28', 'Ezreal': '81', 'Fiddlesticks': '9', 'Fiora': '114', 'Fizz': '105', 'Galio': '3', 'Gangplank': '41', 'Garen': '86', 'Gnar': '150', 'Gragas': '79', 'Graves': '104', 'Hecarim': '120', 'Heimerdinger': '74', 'Illaoi': '420', 'Irelia': '39', 'Ivern': '427', 'Janna': '40', 'Jarvan IV': '59', 'Jax': '24', 'Jayce': '126', 'Jhin': '202', 'Jinx': '222', "Kai'Sa": '145', 'Kalista': '429', 'Karma': '43', 'Karthus': '30', 'Kassadin': '38', 'Katarina': '55', 'Kayle': '10', 'Kayn': '141', 'Kennen': '85', "Kha'Zix": '121', 'Kindred': '203', 'Kled': '240', "Kog'Maw": '96', 'LeBlanc': '7', 'Lee Sin': '64', 'Leona': '89', 'Lissandra': '127', 'Lucian': '236', 'Lulu': '117', 'Lux': '99', 'Malphite': '54', 'Malzahar': '90', 'Maokai': '57', 'Master Yi': '11', 'Miss Fortune': '21', 'Wukong': '62', 'Mordekaiser': '82', 'Morgana': '25', 'Nami': '267', 'Nasus': '75', 'Nautilus': '111', 'Neeko': '518', 'Nidalee': '76', 'Nocturne': '56', 'Nunu & Willump': '20', 'Olaf': '2', 'Orianna': '61', 'Ornn': '516', 'Pantheon': '80', 'Poppy': '78', 'Pyke': '555', 'Qiyana': '246', 'Quinn': '133', 'Rakan': '497', 'Rammus': '33', "Rek'Sai": '421', 'Renekton': '58', 'Rengar': '107', 'Riven': '92', 'Rumble': '68', 'Ryze': '13', 'Sejuani': '113', 'Senna': '235', 'Shaco': '35', 'Shen': '98', 'Shyvana': '102', 'Singed': '27', 'Sion': '14', 'Sivir': '15', 'Skarner': '72', 'Sona': '37', 'Soraka': '16', 'Swain': '50', 'Sylas': '517', 'Syndra': '134', 'Tahm Kench': '223', 'Taliyah': '163', 'Talon': '91', 'Taric': '44', 'Teemo': '17', 'Thresh': '412', 'Tristana': '18', 'Trundle': '48', 'Tryndamere': '23', 'Twisted Fate': '4', 'Twitch': '29', 'Udyr': '77', 'Urgot': '6', 'Varus': '110', 'Vayne': '67', 'Veigar': '45', "Vel'Koz": '161', 'Vi': '254', 'Viktor': '112', 'Vladimir': '8', 'Volibear': '106', 'Warwick': '19', 'Xayah': '498', 'Xerath': '101', 'Xin Zhao': '5', 'Yasuo': '157', 'Yorick': '83', 'Yuumi': '350', 'Zac': '154', 'Zed': '238', 'Ziggs': '115', 'Zilean': '26', 'Zoe': '142', 'Zyra': '143'}
TFT_PRICES = [INVISIBLE_EMOJI, '<:tft_g1:652142396405972992>', '<:tft_g2:652142435606069248>', '<:tft_g3:652142468007067649>', '<:tft_g4:652142511913041960>', '<:tft_g5:652142572541575181>']
|
"""Module that defines constants shared between agents."""
# pattoo-snmp constants
PATTOO_AGENT_SNMPD = 'pattoo_agent_snmpd'
PATTOO_AGENT_SNMP_IFMIBD = 'pattoo_agent_snmp_ifmibd'
|
class Preciousstone:
def __init__(self):
self.preciousStone = []
def storePreciousStone(self,name):
self.preciousStone.append(name)
if( len(self.preciousStone) > 5):
del(self.preciousStone[0])
def displayPreciousStone(self):
if( len(self.preciousStone) > 0):
print(' '.join(self.preciousStone))
preciousstone = Preciousstone()
while(1):
print('1.Store 2.Display 3.Exit')
n = int(input('Enter your choice:'))
if n == 1:
stone = input("Enter the stone name:")
preciousstone.storePreciousStone(stone)
if n == 2:
preciousstone.displayPreciousStone()
if n == 3:
break
|
class BufferList:
def __init__(self, maxlen):
self.data = []
self.maxlen = maxlen
def append(self, el):
if len(self.data) == self.maxlen:
popped = self.data.pop(0)
else:
popped = None
self.data.append(el)
return popped
def peek(self, i):
return self.data[-i-1]
def __len__(self):
return len(self.data)
|
actor_name = input("Enter the actor's name: ")
initial_points = int(input("Enter the points form academy: "))
judges_count = int(input("Enter the number of jury: "))
points_needed = 1250.5
for jury in range(judges_count):
judges_name = input("Enter the name of jury: ")
points_from_judge = float(input("Enter the points from the jury: "))
initial_points += ((len(judges_name) * points_from_judge) / 2)
if initial_points > points_needed:
print(f"Congratulations, {actor_name} got a nominee for leading role with {initial_points:.1f}!")
break
if initial_points <= points_needed:
print(f"Sorry, {actor_name} you need {points_needed - initial_points:.1f} more!")
|
print("hello world")
a = 3
b = 4
c = a * b
print(c)
|
#################################################
### THIS FILE WAS AUTOGENERATED! DO NOT EDIT! ###
#################################################
def get_resize_target(img_sz, crop_target, do_crop=False):
if crop_target is None: return None
ch,r,c = img_sz
target_r,target_c = crop_target
ratio = (min if do_crop else max)(r/target_r, c/target_c)
return ch,round(r/ratio),round(c/ratio)
|
# -*- coding: utf-8 -*-
"""
Created on August 26 20:16:44 2018
@author: ahmad
"""
"""
a program to encrypt and decrypt data in 8-bit XOR encryption using all
built-in functions. No libraries used. This program is for learning puposes
"""
def xor(x,y): #function to cypher text
g = []
for i in range(len(x)):
if x[i] == y[i]:
g.append(0)
elif x[i] != y[i]:
g.append(1)
return g
#x = [1,0,1,0,1,0,0,1] some key
#y = [1,1,1,1,1,0,1,1] values
cipher_string = []
asc_str = []
asc_list = [[]]
refined = ([[]])
cipher = []
cipher_input = input('Enter the string to cipher: ')
key_input = input('Enter 8bit key ex:10101101: ') #'01010101'
for ch in cipher_input:
cipher_string.append(ch)
num_of_char = len(cipher_string)
for i in range(num_of_char):
asc_str.append(('{0:08b}'.format(ord(cipher_string[i]))))
jr = 0
k = 0
for n in range(len(asc_str)):
refined.append([])
for object in asc_str[n]:
if(jr==8):
k += 1
jr = 0
refined[k].append(object)
jr += 1
#if(n == len(asc_str)-1):
# break
l = 0
for l in range(len(refined)):
asc_list.append([])
asc_list[l] = list(map(int, refined[l]))
key = list(map(int, key_input))
f=0
for f in range(len(asc_list)-2):
cipher.append(xor(asc_list[f], key))
cipher_text = []
cipher_str = ["".join((map(str, (cipher[i])))) for i in range(len(cipher))]
for i in range(len(cipher_str)):
cipher_text.append(chr(int(cipher_str[i],2)))
#decipher_1 = list(map(int, decipher))
cipher_text = "".join(cipher_text)
#print(cipher)
#print(cipher_str)
print('\nXOR encryption:',cipher_text)
with open('cypher.txt', 'w') as fout:
fout.write('\nXOR encryption: {0}'.format(cipher_text))
|
def func3(a):
a/0;
def func2(a, b):
func3(a);
def func1(a, b, c):
func2(a, b);
if __name__ == "__main__":
func1(12, 0, 89)
|
def setup():
global pg
pg = createGraphics(1000, 1000)
noLoop()
def draw():
pg.beginDraw()
pg.colorMode(HSB, 360, 100, 100, 100)
pg.background(0, 0, 25)
pg.stroke(60, 7, 86, 100)
pg.noFill()
for i in range(100):
pg.ellipse(random(pg.width), random(pg.height), 100, 100)
pg.endDraw()
pg.save('image.png')
exit()
|
"""
File: anagram.py
Name: Yujing Wei
----------------------------------
This program recursively finds all the anagram(s)
for the word input by user and terminates when the
input string matches the EXIT constant defined
at line 19
If you correctly implement this program, you should see the
number of anagrams for each word listed below:
* arm -> 3 anagrams
* contains -> 5 anagrams
* stop -> 6 anagrams
* tesla -> 10 anagrams
* spear -> 12 anagrams
"""
# Constants
FILE = 'dictionary.txt' # This is the filename of an English dictionary
EXIT = '-1' # Controls when to stop the loop
# Global variables
words = [] # A list to store words with target length in dictionary.txt.
d = {} # A dictionary to store target word's info -> [character: show-up time(s)].
def main():
global d, words # Call global variables.
print(f'Welcome to stanCode "Anagram Generator" (or {EXIT} to quit)') # Greeting.
while True: # While loop to find anagrams.
s = input('Find anagrams for: ').lower() # Process input word into lowercase, and assign it to 's'.
if s == EXIT: # If input == EXIT constant, break while loop.
break
print('Searching...') # Hint of searching.
read_dictionary(len(s)) # Get words with target length in FILE.
find_anagrams(s) # Function to get anagrams.
d = {} # Remove data in 'd{}' after every find_anagrams function.
words = [] # Remove data in 'words[]' after every find_anagrams function.
def read_dictionary(target_length):
with open(FILE, 'r') as f: # Open FILE and read it.
for word in f: # A line with a word in FILE.
if len(word.strip()) == target_length: # Get words with target length.
words.append(word.strip().lower()) # Append words to 'words' list.
def find_anagrams(s):
"""
:param s: str; Word, which user inputs, to get anagrams with same length and characters.
"""
for ch in s: # Record character and its times of show-up into 'd'({}).
if ch in d: # Count times of characters showing up in 's'.
d[ch] += 1
else:
d[ch] = 1
anagrams = find_anagrams_helper(s, '', []) # Get anagrams with find_anagrams_helper().
if len(anagrams) >= 1:
print(f'{len(anagrams)} anagrams: {anagrams}') # Print the result of anagrams.
else:
print(f'{s} is not in dictionary.')
def find_anagrams_helper(s, current_s, anagrams):
"""
:param s: str; user's input word.
:param current_s: str; '' empty str to place characters.
:param anagrams: list; [] empty list to place results of anagrams.
:return: list; anagrams, list with all of the results.
"""
if len(current_s) == len(s): # Base case: current_s with target length.
if current_s in words: # Check whether current_s in 'd'.
print(f'Found: {current_s}') # Print the result of anagram.
print('Searching...') # Hint of searching.
anagrams.append(current_s) # Append the result to list of 'anagrams'.
else:
for ch in d: # For characters in d, which show up in input 's'.
if d[ch] >= 1: # If the times character >= 1 (<=0 means no left),
# Choose
current_s += ch # Add ch to current_s.
d[ch] -= 1 # Times of character in 'd' -1.
# Explore
if has_prefix(current_s): # If there's prefix with current_s in 'words'.
find_anagrams_helper(s, current_s, anagrams) # Remove ch, which just added to current_s, from 's'.
# Un-choose
current_s = current_s[:len(current_s) - 1] # Remove ch from current_s.
d[ch] += 1 # Times of character in 'd' +1.
return anagrams # Return the list 'anagrams' with results of anagrams.
def has_prefix(sub_s):
"""
:param sub_s: str; test whether words in 'words' has prefix with it.
:return: True; if words in 'words' has prefix with 'sub_s'.
"""
for word in words: # Check words in 'words'.
if word.startswith(sub_s) is True: # If there's word starting with 'sub_s', return True.
return True
if __name__ == '__main__':
main()
|
n=list(map(int,input("Enter the list").split(",")))
le=max(n)
while max(n)==le:
n.remove(max(n))
print(max(n))
|
class Solution(object):
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sum([c for i, c in enumerate(sorted(nums)) if i % 2 == 0])
|
for i in range(int(input())):
text = input().replace('.', '')
countOpen = 0
countDiamonds = 0
for char in text:
if char == '<':
countOpen += 1
elif char == '>' and countOpen > 0:
countDiamonds += 1
countOpen -= 1
print(countDiamonds)
|
def read_n_values(n):
print("Please enter", n, "values.")
values = []
for i in range(n):
values.append(input("Value {}: ".format(i + 1)))
return values
def compute_average(values):
# set sum to first value of list
total_sum = values[0]
# iterate over remaining values and add them up
for value in values[1:]:
total_sum += value
return float(total_sum) / len(values)
values = read_n_values(3)
print("Average:", compute_average(values))
|
load("@rules_python//python:python.bzl", "py_binary", "py_library", "py_test")
def py3_library(*args, **kwargs):
py_library(
srcs_version = "PY3",
*args,
**kwargs
)
def py3_binary(name, main = None, *args, **kwargs):
if main == None:
main = "%s.py" % (name)
py_binary(
name = name,
main = main,
legacy_create_init = False,
python_version = "PY3",
*args,
**kwargs
)
def py3_test(*args, **kwargs):
py_test(
legacy_create_init = False,
python_version = "PY3",
srcs_version = "PY3",
*args,
**kwargs
)
|
try:
test = int(input().strip())
while test!=0:
k,d0,d1 = map(int,input().strip().split())
d2 = (d1+d0)%10
if k == 2:
if (d1+d0)%3 == 0:
print("YES")
continue
else:
print("NO")
continue
elif k == 3:
if (d1+d2+d0)%3 == 0:
print("YES")
continue
else:
print("NO")
continue
else:
a = (2*(d1+d0))%10
b = (4*(d1+d0))%10
c = (8*(d1+d0))%10
d = (6*(d1+d0))%10
su = d1+d2+d0+((a+b+c+d)*((k-3)//4))
if (k-3)%4 == 1:
su += a
elif (k-3)%4 == 2:
su += a+b
elif (k-3)%4 == 3:
su += a+b+c
if su%3 == 0:
print("YES")
continue
else:
print("NO")
continue
test -=1
except:
pass
|
##
# This software was developed and / or modified by Raytheon Company,
# pursuant to Contract DG133W-05-CQ-1067 with the US Government.
#
# U.S. EXPORT CONTROLLED TECHNICAL DATA
# This software product contains export-restricted data whose
# export/transfer/disclosure is restricted by U.S. law. Dissemination
# to non-U.S. persons whether in the United States or abroad requires
# an export license or other authorization.
#
# Contractor Name: Raytheon Company
# Contractor Address: 6825 Pine Street, Suite 340
# Mail Stop B8
# Omaha, NE 68106
# 402.291.0100
#
# See the AWIPS II Master Rights File ("Master Rights File.pdf") for
# further licensing information.
##
#
# Python wrapper for PointDataView
#
#
# SOFTWARE HISTORY
#
# Date Ticket# Engineer Description
# ------------ ---------- ----------- --------------------------
# 07/20/09 njensen Initial Creation.
#
#
#
##
# This is a base file that is not intended to be overridden.
##
class PointDataView:
def __init__(self, javaPointDataView):
self.__javaPdv = javaPointDataView
self.__keys = []
keyset = self.__javaPdv.getContainer().getParameters()
itr = keyset.iterator()
while itr.hasNext():
self.__keys.append(str(itr.next()))
def __getitem__(self, key):
result = None
strValType = self.getType(key)
if strValType == 'FLOAT':
result = self.__javaPdv.getFloat(key)
elif strValType == 'STRING':
result = self.__javaPdv.getString(key)
elif strValType == 'INT':
result = self.__javaPdv.getInt(key)
elif strValType == 'LONG':
result = self.__javaPdv.getLong(key)
return result
def getType(self, key):
val = self.__javaPdv.getType(key)
if val:
val = str(val)
return val
def has_key(self, key):
return self.__keys.__contains__(key)
def keys(self):
return self.__keys
def __contains__(self, key):
return self.has_key(key)
def getFillValue(self, key):
# TODO if we get fill value support in pointdata, hook that up
return -9999.0
def getNumberAllLevels(self, key):
strValType = self.getType(key)
jlevels = self.__javaPdv.getNumberAllLevels(key)
levels = []
for level in jlevels:
level = str(level)
if strValType == 'FLOAT':
levels.append(float(level))
elif strValType == 'STRING':
levels.append(str(level))
elif strValType == 'INT':
levels.append(int(level))
elif strValType == 'LONG':
levels.append(long(level))
return levels
|
def hypotenuse_triangle(side1, side2):
hypotenuse = side1 ** 2 + side2 ** 2
return hypotenuse
print(hypotenuse_triangle(2, 4))
|
GRADING_POST = {
'tags': ['Interview'],
'description': '면접 결과 제출',
'parameters': [
{
'name': 'access_token',
'description': '엑세스 토큰, 헤더의 Authentication',
'in': ' header',
'type': 'str',
'required': True
},
{
'name': 'exam code',
'description': '수험번호',
'in': ' path',
'type': 'int',
'required': True
},
{
'name': 'question id',
'description': '질문 번호',
'in': ' path',
'type': 'int',
'required': True
},
{
'name': 'take_interview',
'description': '면접 참가 여부',
'in': 'json',
'type': 'bool',
'required': True
},
{
'name': 'grading',
'description': '채점 결과',
'in': 'json',
'type': 'json',
'required': True
},
{
'name': 'comment',
'description': '메모',
'in': 'json',
'type': 'str',
'required': True
},
],
'responses': {
'200': {
'description': '성공'
},
'400': {
'description': '실패'
}
}
}
GRADING_GET = {
'tags': ['Interview'],
'description': '면접 결과 제출',
'parameters': [
{
'name': 'access_token',
'description': '엑세스 토큰, 헤더의 Authentication',
'in': ' header',
'type': 'str',
'required': True
},
{
'name': 'exam code',
'description': '수험번호',
'in': ' path',
'type': 'int',
'required': True
},
{
'name': 'question id',
'description': '질문 번호',
'in': ' path',
'type': 'int',
'required': True
}
],
'responses': {
'200': {
'description': '성공',
'examples': {
"form":
{
"1": "subject name"
},
"title": "question 1",
"question_id": 1,
"body": "body"
}
},
'403': {
'description': '실패'
}
}
}
|
# Tuplas sao imutaveis, nao se pode substituir um valor enquanto o programa estiver rodando
# oq foi definido no inicio permanece ate o final
lanche = ('hamburguer', 'pizza', 'suco', 'refri')
print(lanche[1])
print(lanche[-1]) #-1 mostra o ultimo elemento
print(sorted(lanche)) #para organizar a lista em ordem alfabetica porem nao vai mudar os iten
for comida in lanche:
print(f'comi bastante {comida}') # A variavel comida vai percorrer cada valor na lista lanche, vai pegar os nomes
print('estou gordo')
for cont in range(0, len(lanche)):
print(cont) # vai pegar o endereco da lista (0,1,2...) por causa das ()
print('fim')
for food in range(0, len(lanche)):
print(lanche[food], f'na posicao {food}') # vai pegar na lista lanche o endereco food 0,1,2,3...
print('end')
|
#-*-coding:utf-8-*-
ALPHABET = ['а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з',
'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р',
'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ',
'ъ', 'ы', 'ь', 'э', 'ю', 'я', ' ']
callnumber = input()
message = ''
while callnumber != 'End':
message += str(ALPHABET[int(callnumber)])
callnumber = input()
print(''.join(message))
|
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
n = len(nums)
zeroindex = -1
for i in range(n):
if nums[i] == 0 and zeroindex == -1:
zeroindex = i
elif nums[i] != 0 and zeroindex != -1:
nums[zeroindex] = nums[i]
nums[i] = 0
zeroindex += 1
return nums
if __name__ == '__main__':
solution = Solution()
print(solution.moveZeroes([3, 0, 1, 1, 2, 0, 5, 0, 2, 0, 4]));
else:
pass
|
# Time: O(m * n)
# Space: O(1)
class Solution(object):
def shiftGrid(self, grid, k):
"""
:type grid: List[List[int]]
:type k: int
:rtype: List[List[int]]
"""
def rotate(grids, k):
def reverse(grid, start, end):
while start < end:
start_r, start_c = divmod(start, len(grid[0]))
end_r, end_c = divmod(end-1, len(grid[0]))
grid[start_r][start_c], grid[end_r][end_c] = grid[end_r][end_c], grid[start_r][start_c]
start += 1
end -= 1
k %= len(grid)*len(grid[0])
reverse(grid, 0, len(grid)*len(grid[0]))
reverse(grid, 0, k)
reverse(grid, k, len(grid)*len(grid[0]))
rotate(grid, k)
return grid
|
FULL_ACCESS_GMAIL_SCOPE = "https://mail.google.com/"
LABELS_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.labels"
SEND_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.send"
READ_ONLY_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.readonly"
COMPOSE_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.compose"
INSERT_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.insert"
MODIFY_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.modify"
METADATA_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.metadata"
SETTINGS_BASIC_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.settings.basic"
SETTINGS_SHARING_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.settings.sharing"
|
def read():
x = int(input())
return x
a = read()
b = read()
c = read()
d = read()
if b == c and b + c == d and b + c + d == a:
print("S")
else:
print("N")
|
def test_home(client):
response = client.get('/')
#import pdb;pdb.set_trace()
assert response.status_code == 200
assert response.template_name == ['home.html']
|
print('{:=^40}'.format('Lojas Gui'))
n = float(input('Coloque o valor do produto: R$ '))
print('''forma de pagamento.
[1] Dinheiro/cheque.
[2] Cartão.
[3] 2x cartão.
[4] 3x ou mais.''')
n2 = int(input('Coloque a opção: '))
print('===')
if n2 == 1:
print(f'O valor a ser pago e R$ {n-(n*(10/100))}.')
elif n2 == 2:
print(f'O valor a ser pago é R$ {n-(n*(5/100))}.')
elif n2 == 3:
print(f'O valor a ser pago e R$ {n} \n2x de {n/2}.')
elif n2 == 4:
print(f'O valor a ser pago é R$ {n+(n*(20/100))} \n3x de {(n+(n*(20/100)))/3}.')
else:
print('Você fez algo errado.')
|
# MIT licensed
# Copyright (c) 2013-2020 lilydjwg <lilydjwg@gmail.com>, et al.
HACKAGE_URL = 'https://hackage.haskell.org/package/%s/preferred.json'
async def get_version(name, conf, *, cache, **kwargs):
key = conf.get('hackage', name)
data = await cache.get_json(HACKAGE_URL % key)
return data['normal-version'][0]
|
#!/usr/bin/env python3 -u
# coding: utf-8
__author__ = ["Markus Löning"]
__all__ = []
|
load(
"//scala:advanced_usage/providers.bzl",
_ScalaRulePhase = "ScalaRulePhase",
)
load(
"//scala/private:phases/phases.bzl",
_phase_bloop = "phase_bloop",
)
ext_add_phase_bloop = {
"attrs": {
# "bloopDir": attr.label(
# allow_single_file = True,
# doc = "Bloop output folder",
# ),
"_bloop": attr.label(
cfg = "host",
default = "//scala/bloop",
executable = True,
),
# "_runner": attr.label(
# allow_single_file = True,
# default = "//scala/bloop:runner",
# ),
# "_testrunner": attr.label(
# allow_single_file = True,
# default = "//scala/bloop:testrunner",
# ),
# "format": attr.bool(
# default = False,
# ),
},
"phase_providers": [
"//scala/bloop:add_phase_bloop",
],
}
def _add_phase_bloop_singleton_implementation(ctx):
return [
_ScalaRulePhase(
custom_phases = [
#TODO plan is to make it a phase at the end then replace it later. Use phases before compile.
("=", "compile", "compile", _phase_bloop),
# ("$", "", "bloop", _phase_bloop)
# ("after", "compile", "bloop", _phase_bloop)
],
),
]
add_phase_bloop_singleton = rule(
implementation = _add_phase_bloop_singleton_implementation,
)
|
soma = 0
quantidade = 0
while True:
n = int(input("Digite um número inteiro: "))
if n==0:
break;
soma = soma + n
quantidade = quantidade + 1
print(f"Quantidade de números digitados: {quantidade}")
print(f"Soma: {soma}")
print(f"A média é: {soma / quantidade:10.2f}")
|
angka = {
0: 'tepat',
1: 'satu',
2: 'dua',
3: 'tiga',
4: 'empat',
5: 'lima',
6: 'enam',
7: 'tujuh',
8: 'delapan',
9: 'sembilan',
10: 'sepuluh',
11: 'sebelas',
12: 'dua belas',
}
def eja(n):
lut1 = ['nol', 'satu', 'dua', 'tiga', 'empat',
'lima', 'enam', 'tujuh', 'delapan', 'sembilan',
'sepuluh', 'sebelas', 'dua belas', 'tiga belas',
'empat belas', 'lima belas', 'enam belas',
'tujuh belas', 'delapan belas', 'sembilan belas']
lut20 = ['x', 'x', 'dua puluh', 'tiga puluh', 'empat puluh',
'lima puluh', 'enam puluh', 'tujuh puluh', 'delapan puluh',
'sembilan puluh']
triples = ['x', 'ribu', 'juta', 'miliar',
'biliar', 'quadrillion', 'quintillion',
'sextillion', 'septillion', 'octillion',
'nonillion', 'decillion']
words = []
shift = 0
hasNumber = False
insertpos = -1
while n > 0:
ones = n % 10
shiftmod = shift % 3
shiftdiv = shift / 3
if shiftdiv > 0 and shiftmod == 0:
insertpos = len(words)
hasNumber = False
if shiftmod == 2 and ones > 0:
words.append('ratus')
words.append(lut1[ones])
hasNumber = True
if shiftmod == 1 and ones > 0:
words.append(lut20[ones])
hasNumber = True
if shiftmod == 0:
tens = n % 100
if 0 < tens < 20:
words.append(lut1[tens])
shift += 1
n = n / 10
hasNumber = True
elif ones > 0:
words.append(lut1[ones])
hasNumber = True
if hasNumber and insertpos >= 0:
words.insert(insertpos, triples[shiftdiv])
insertpos = -1
hasNumber = False
n = n / 10
shift += 1
# oldones = ones
words.reverse()
text = ' '.join(words)
result = text.split(' ')
return result
# return words if words else ['nol']
def mid(n):
"around `n` +/- 1"
return [n-1, n, n+1]
def ucapkan(h, m):
# jam = angka.get(h)
# menit = angka.get(m)
jam = eja(h)
menit = eja(m)
waktu = []
if m in mid(0) + [59]:
waktu = [jam, 'tepat']
elif m in mid(15):
waktu = [jam, 'seperempat']
elif m in mid(30):
jam = eja(h+1)
waktu = ['setengah', jam]
elif m in mid(45):
jam = eja(h+1)
waktu = [jam, 'kurang', 'seperempat']
elif m < 30:
waktu = [jam, 'lebih', menit]
else:
# waktu = [jam, menit]
jam = eja(h+1)
menit = eja(abs(60-m))
waktu = [jam, 'kurang', menit]
return flattened(waktu)
def flattened(arr):
words = []
for r in arr:
if isinstance(r, list):
words += r
else:
words.append(r)
text = ' '.join(words)
result = text.split(' ')
return result
|
"""
Expert list created from Kompetenzpool data.
List contains Microsoft Academic Graph Ids
"""
kompetenzpool_expert_list = {
"Internet of Things": [
2241467651,
673846798,
2236413454
],
"blockchain": {
1245553041,
2021103267,
},
"natural language processing": {
2794237920,
2578689274,
},
"autonomous driving": {
2490080048,
2156656717,
},
"humanoid robot": {
1047662447,
2570474579,
2772428913,
2588863116,
2910150326,
2248512682,
2565089218,
},
"evolutionary algorithm": {
2104163988,
2036573014,
},
"remote sensing": [
1983767936,
2471318715,
2636005816,
],
"cellular automaton": [
183621591,
2484531368,
],
"electronic voting": [
2038785220,
],
"kalman filter": [
154988935,
2165996130,
2228035992,
],
"software architecture": [
2145590652,
],
"robot grasping": [
1047662447,
2565089218,
],
"ubiquitous computing": [
673846798,
],
"human-computer interaction": [
673846798,
332721774,
],
"digital health": [
2021103267,
]
}
|
# Ex. 023
num = str(input("Digite um número: ")) # .zfill(4) -> preenche com 0 até completar 4 casas
while len(num) < 4:
num = "0" + num
print("Unidade: ", num[3])
print("Dezena: ", num[2])
print("Centena: ", num[1])
print("Unidade de milhar: ", num[0])
|
#!/usr/bin/env python
# coding: utf-8
# In[99]:
class TreeNode:
def __init__(self, val = None, par = None):
self.left = None
self.right = None
self.value = val
self.parent = par
def left_child(self):
return self.left
def right_child(self):
return self.right
def set_value(self, val):
self.value = val
def get_value(self):
return self.value
def set_left(self, node):
self.left = node
node.parent = self
return node
def set_right(self, node):
self.right = node
node.parent = self
return node
def get_parent(self):
return self.parent
def level(self):
result = 0
temp = self
while temp.parent is not None:
temp = temp.parent
result += 1
return result
def add(self, item):
if item < self.get_value() :
if self.left_child() is None:
self.set_left(TreeNode(item))
else:
self.left_child().add(item)
else:
if self.right_child() is None:
self.set_right(TreeNode(item))
else:
self.right_child().add(item)
def preOrder(self, resultList):
resultList.append(self.value)
if self.left_child() is not None:
self.left_child().preOrder(resultList)
if self.right_child() is not None:
self.right_child().preOrder(resultList)
def inOrder(self, resultList):
if self.left_child() is not None:
self.left_child().inOrder(resultList)
resultList.append(self.value)
if self.right_child() is not None:
self.right_child().inOrder(resultList)
def postOrder(self, resultList):
if self.left_child() is not None:
self.left_child().postOrder(resultList)
if self.right_child() is not None:
self.right_child().postOrder(resultList)
resultList.append(self.value)
def find(self, item):
if self.value == item:
return self.value
elif item < self.value:
if self.left_child() is not None:
return self.left_child().find(item)
else:
raise ValueError()
else:
if self.right_child() is not None:
return self.right_child().find(item)
else:
raise ValueError()
def preOrderStr(self):
if self.left_child() is not None:
self.left_child().preOrderStr()
if self.right_child() is not None:
self.right_child().preOrderStr()
print("".ljust(self.level()*2), str(self.value))
def __str__(self):
return str(self.value)
# In[107]:
class Pair:
''' Encapsulate letter,count pair as a single entity.
Realtional methods make this object comparable
using built-in operators.
'''
def __init__(self, letter, count = 1):
self.letter = letter
self.count = count
def __eq__(self, other):
return self.letter == other.letter
def __hash__(self):
return hash(self.letter)
def __ne__(self, other):
return self.letter != other.letter
def __lt__(self, other):
return self.letter < other.letter
def __le__(self, other):
return self.letter <= other.letter
def __gt__(self, other):
return self.letter > other.letter
def __ge__(self, other):
return self.letter >= other.letter
def __repr__(self):
return f'({self.letter}, {self.count})'
def __str__(self):
return f'({self.letter}, {self.count})'
class BinarySearchTree:
def __init__(self):
self.root = None
def is_empty(self):
return self.root is None
def size(self):
return self.__size(self.root)
def __size(self, node):
if node is None:
return 0
result = 1
result += self.__size(node.left)
result += self.__size(node.right)
return result
def add(self, item):
if self.root is None:
self.root = TreeNode(item)
else:
self.root.add(item)
return self.root
def find(self, item):
if self.root is not None:
return self.root.find(item)
raise ValueError()
def remove(self, item):
return self.__remove(self.root, item)
def __remove(self, node, item):
if node is None:
return node
if item < node.get_value():
node.set_left(self.__remove(node.left_child(), item))
elif item > node.get_value():
node.set_right(self.__remove(node.right_child(), item))
else:
if node.left_child() is None:
temp = node.right_child()
if temp is not None:
temp.parent = node.parent
node = None
return temp
elif node.right_child() is None:
temp = node.left_child()
if temp is not None:
temp.parent = node.parent
node = None
return temp
else:
minNode = self.__minValueNode(node.right_child())
node.set_value(minNode.get_value())
node.set_right(self.__remove(node.right_child(), minNode.get_value()))
return node
def __minValueNode(self, node):
current = node
while (current.left_child() is not None):
current = current.left_child()
return current
def inOrder(self):
result = []
if self.root is not None:
self.root.inOrder(result)
return result
def preOrder(self):
result = []
if self.root is not None:
self.root.preOrder(result)
return result
def postOrder(self):
result = []
if self.root is not None:
self.root.postOrder(result)
return result
def rebalance(self):
orderedList = self.inOrder()
self.root = None
self.__rebalance(orderedList, 0, len(orderedList) - 1)
def __rebalance(self, orderedList, low, high):
if (low <= high):
mid = (high - low) // 2 + low
self.add(orderedList[mid])
self.__rebalance(orderedList, low, mid - 1)
self.__rebalance(orderedList, mid + 1, high)
def height(self):
return self.__recursiveHeight(self.root, 0)
def __recursiveHeight(self, node, current):
leftValue = current
rightValue = current
if node.left_child() is not None:
leftValue = self.__recursiveHeight(node.left, current + 1)
if node.right_child() is not None:
rightValue = self.__recursiveHeight(node.right, current + 1)
return max(leftValue, rightValue)
def __strInsert(self, value, position, char):
return str(value[:position] + char + value[position + 1:])
def __str__(self):
# if self.root is not None:
# self.root.preOrderStr()
# return ""
totalLayers = self.height() + 1
totalWidth = (2 ** totalLayers) * 2
nodePosition = [None] * (totalLayers)
for i in range(totalLayers):
nodePosition[i] = [None] * (2 ** i)
for j in range(2 ** i):
nodePosition[i][j] = [0] * 3
lastLayer = nodePosition[totalLayers - 1]
gap = totalWidth // len(lastLayer)
for i in range(len(lastLayer)):
lastLayer[i][0] = i * gap
lastLayer[i][1] = lastLayer[i][0]
lastLayer[i][2] = lastLayer[i][0]
for i in reversed(range(totalLayers - 1)):
for j in range(len(nodePosition[i])):
first = nodePosition[i + 1][j * 2][0]
second = nodePosition[i + 1][j * 2 + 1][0]
nodePosition[i][j][1] = first + 1
nodePosition[i][j][2] = second - 1
nodePosition[i][j][0] = ((second - first) // 2) + first
result = [""] * (totalLayers * 2)
for i in range(1, len(result), 2):
for j in range(totalWidth):
result[i] += " "
self.__nodePrettyPrint(result, self.root, [0] * (totalLayers), nodePosition, ' ')
return "\n".join(result)
def __nodePrettyPrint(self, result, node, nodeList, nodePosition, char):
level = node.level()
startLine = nodePosition[level][nodeList[level]][1]
endLine = nodePosition[level][nodeList[level]][2]
position = nodePosition[level][nodeList[level]][0]
resultLevel = level * 2
nodeList[level] += 1
currentLen = len(result[resultLevel])
for i in range(currentLen - 1, startLine):
result[resultLevel] += " "
for i in range(startLine, position):
result[resultLevel] += "_"
result[resultLevel] += str(node.get_value())
for i in range(position + len(str(node.get_value())), endLine):
result[resultLevel] += "_"
result[resultLevel + 1] = self.__strInsert(result[resultLevel + 1], startLine, '/')
if (endLine == startLine):
endLine += len(str(node.get_value()))
result[resultLevel + 1] = self.__strInsert(result[resultLevel + 1], endLine + 1, '\\')
if (node.left_child() is not None):
self.__nodePrettyPrint(result, node.left_child(), nodeList, nodePosition, '/')
elif (level + 1) < len(nodeList):
nextLevel = level + 1
capacity = 1
while nextLevel < len(nodeList):
nodeList[nextLevel] += capacity
capacity *= 2
nextLevel += 1
if (node.right_child() is not None):
self.__nodePrettyPrint(result, node.right_child(), nodeList, nodePosition, '\\')
elif (level + 1) < len(nodeList):
nextLevel = level + 1
capacity = 1
while nextLevel < len(nodeList):
nodeList[nextLevel] += capacity
capacity *= 2
nextLevel += 1
# In[109]:
myTree = BinarySearchTree()
myTree.add(12)
myTree.add(7)
myTree.add(20)
myTree.add(99)
myTree.add(32)
myTree.add(46)
print(myTree)
myTree.rebalance()
print(myTree)
myTree.remove(46)
print()
print(myTree)
myTree.remove(20)
print()
print(myTree)
# "C:\\Users\\Tavish\\Documents\\School\\Teaching\\CS_2420\\Project5\\around-the-world-in-80-days-3.txt"
myTree = BinarySearchTree()
with open("D:\\UVU\\Code\\Fall2020\\Child-Stuff\\CS2420\\Mod5\\P5\\around-the-world-in-80-days-3.txt", "r") as f:
while True:
c = f.read(1)
if not c:
break
if c.isalnum():
try:
found = myTree.find(Pair(c))
found.count += 1
except ValueError:
myTree.add(Pair(c))
# myTree.rebalance()
# print(myTree)
# In[ ]:
# In[ ]:
|
ColorNames = \
{ u'aliceblue': (240, 248, 255),
u'antiquewhite': (250, 235, 215),
u'aqua': (0, 255, 255),
u'aquamarine': (127, 255, 212),
u'azure': (240, 255, 255),
u'beige': (245, 245, 220),
u'bisque': (255, 228, 196),
u'black': (0, 0, 0),
u'blanchedalmond': (255, 235, 205),
u'blue': (0, 0, 255),
u'blueviolet': (138, 43, 226),
u'brown': (165, 42, 42),
u'burlywood': (222, 184, 135),
u'cadetblue': (95, 158, 160),
u'chartreuse': (127, 255, 0),
u'chocolate': (210, 105, 30),
u'coral': (255, 127, 80),
u'cornflowerblue': (100, 149, 237),
u'cornsilk': (255, 248, 220),
u'crimson': (220, 20, 60),
u'cyan': (0, 255, 255),
u'darkblue': (0, 0, 139),
u'darkcyan': (0, 139, 139),
u'darkgoldenrod': (184, 134, 11),
u'darkgray': (169, 169, 169),
u'darkgreen': (0, 100, 0),
u'darkgrey': (169, 169, 169),
u'darkkhaki': (189, 183, 107),
u'darkmagenta': (139, 0, 139),
u'darkolivegreen': (85, 107, 47),
u'darkorange': (255, 140, 0),
u'darkorchid': (153, 50, 204),
u'darkred': (139, 0, 0),
u'darksalmon': (233, 150, 122),
u'darkseagreen': (143, 188, 143),
u'darkslateblue': (72, 61, 139),
u'darkslategray': (47, 79, 79),
u'darkslategrey': (47, 79, 79),
u'darkturquoise': (0, 206, 209),
u'darkviolet': (148, 0, 211),
u'deeppink': (255, 20, 147),
u'deepskyblue': (0, 191, 255),
u'dimgray': (105, 105, 105),
u'dimgrey': (105, 105, 105),
u'dodgerblue': (30, 144, 255),
u'firebrick': (178, 34, 34),
u'floralwhite': (255, 250, 240),
u'forestgreen': (34, 139, 34),
u'fuchsia': (255, 0, 255),
u'gainsboro': (220, 220, 220),
u'ghostwhite': (248, 248, 255),
u'gold': (255, 215, 0),
u'goldenrod': (218, 165, 32),
u'gray': (128, 128, 128),
u'green': (0, 128, 0),
u'greenyellow': (173, 255, 47),
u'grey': (128, 128, 128),
u'honeydew': (240, 255, 240),
u'hotpink': (255, 105, 180),
u'indianred': (205, 92, 92),
u'indigo': (75, 0, 130),
u'ivory': (255, 255, 240),
u'khaki': (240, 230, 140),
u'lavender': (230, 230, 250),
u'lavenderblush': (255, 240, 245),
u'lawngreen': (124, 252, 0),
u'lemonchiffon': (255, 250, 205),
u'lightblue': (173, 216, 230),
u'lightcoral': (240, 128, 128),
u'lightcyan': (224, 255, 255),
u'lightgoldenrodyellow': (250, 250, 210),
u'lightgray': (211, 211, 211),
u'lightgreen': (144, 238, 144),
u'lightgrey': (211, 211, 211),
u'lightpink': (255, 182, 193),
u'lightsalmon': (255, 160, 122),
u'lightseagreen': (32, 178, 170),
u'lightskyblue': (135, 206, 250),
u'lightslategray': (119, 136, 153),
u'lightslategrey': (119, 136, 153),
u'lightsteelblue': (176, 196, 222),
u'lightyellow': (255, 255, 224),
u'lime': (0, 255, 0),
u'limegreen': (50, 205, 50),
u'linen': (250, 240, 230),
u'magenta': (255, 0, 255),
u'maroon': (128, 0, 0),
u'mediumaquamarine': (102, 205, 170),
u'mediumblue': (0, 0, 205),
u'mediumorchid': (186, 85, 211),
u'mediumpurple': (147, 112, 219),
u'mediumseagreen': (60, 179, 113),
u'mediumslateblue': (123, 104, 238),
u'mediumspringgreen': (0, 250, 154),
u'mediumturquoise': (72, 209, 204),
u'mediumvioletred': (199, 21, 133),
u'midnightblue': (25, 25, 112),
u'mintcream': (245, 255, 250),
u'mistyrose': (255, 228, 225),
u'moccasin': (255, 228, 181),
u'navajowhite': (255, 222, 173),
u'navy': (0, 0, 128),
u'oldlace': (253, 245, 230),
u'olive': (128, 128, 0),
u'olivedrab': (107, 142, 35),
u'orange': (255, 165, 0),
u'orangered': (255, 69, 0),
u'orchid': (218, 112, 214),
u'palegoldenrod': (238, 232, 170),
u'palegreen': (152, 251, 152),
u'paleturquoise': (175, 238, 238),
u'palevioletred': (219, 112, 147),
u'papayawhip': (255, 239, 213),
u'peachpuff': (255, 218, 185),
u'peru': (205, 133, 63),
u'pink': (255, 192, 203),
u'plum': (221, 160, 221),
u'powderblue': (176, 224, 230),
u'purple': (128, 0, 128),
u'red': (255, 0, 0),
u'rosybrown': (188, 143, 143),
u'royalblue': (65, 105, 225),
u'saddlebrown': (139, 69, 19),
u'salmon': (250, 128, 114),
u'sandybrown': (244, 164, 96),
u'seagreen': (46, 139, 87),
u'seashell': (255, 245, 238),
u'sienna': (160, 82, 45),
u'silver': (192, 192, 192),
u'skyblue': (135, 206, 235),
u'slateblue': (106, 90, 205),
u'slategray': (112, 128, 144),
u'slategrey': (112, 128, 144),
u'snow': (255, 250, 250),
u'springgreen': (0, 255, 127),
u'steelblue': (70, 130, 180),
u'tan': (210, 180, 140),
u'teal': (0, 128, 128),
u'thistle': (216, 191, 216),
u'tomato': (255, 99, 71),
u'turquoise': (64, 224, 208),
u'violet': (238, 130, 238),
u'wheat': (245, 222, 179),
u'white': (255, 255, 255),
u'whitesmoke': (245, 245, 245),
u'yellow': (255, 255, 0),
u'yellowgreen': (154, 205, 50)}
|
# https://stackoverflow.com/questions/63626389/how-to-sort-points-along-a-hilbert-curve-without-using-hilbert-indices
N=9 # 9 points
n=2 # 2 dimension
m=3 # order of Hilbert curve
def BitTest(x,od):
result = x & (1 << od)
return int(bool(result))
def BitFlip(b,pos):
b ^= 1 << pos
return b
def partition(idx,A,st,en,od,ax,di):
i = st
j = en
while True:
while i < j and BitTest(A[i][ax],od) == di:
i = i + 1
while i < j and BitTest(A[j][ax],od) != di:
j = j - 1
if j <= i:
return i
A[i], A[j] = A[j], A[i]
idx[i], idx[j] = idx[j], idx[i]
def HSort(idx,A,st,en,od,c,e,d,di,cnt):
if en<=st:
return
p = partition(idx,A,st,en,od,(d+c)%n,BitTest(e,(d+c)%n))
if c==n-1:
if od==0:
return
d2= (d+n+n-(2 if di else cnt + 2)) % n
e=BitFlip(e,d2)
e=BitFlip(e,(d+c)%n)
HSort(idx,A,st,p-1,od-1,0,e,d2,False,0)
e=BitFlip(e,(d+c)%n)
e=BitFlip(e,d2)
d2= (d+n+n-(cnt + 2 if di else 2))%n
HSort(idx,A,p,en,od-1,0,e,d2,False,0)
else:
HSort(idx,A,st,p-1,od,c+1,e,d,False,(1 if di else cnt+1))
e=BitFlip(e,(d+c)%n)
e=BitFlip(e,(d+c+1)%n)
HSort(idx,A,p,en,od,c+1,e,d,True,(cnt+1 if di else 1))
e=BitFlip(e,(d+c+1)%n)
e=BitFlip(e,(d+c)%n)
# array = [[2,2],[2,4],[3,4],[2,5],[3,5],[1,6],[3,6],[5,6],[3,7]]
# HSort(array,st=0,en=N-1,od=m-1,c=0,e=0,d=0,di=False,cnt=0)
# print(array)
# if False:
# idx = self.recursive_sort(pca_X, n_components)
# pca_X = pca_X[idx]
# pca_X = np.array(pca_X) * 100000000
# pca_X = pca_X.astype(int)
# N=len(pca_X) # 9 points
# n=2 # 2 dimension
# m=10 # order of Hilbert curve
# idx = list(range(N))
# HSort(idx, pca_X,st=0,en=N-1,od=m-1,c=0,e=0,d=0,di=False,cnt=0)
# else:
|
"""
# ==============================================================================
# ToPy -- Topology optimization with Python.
# Copyright (C) 2012, 2015, 2016, 2017 William Hunter.
# Copyright (C) 2020, 2021 Tarcísio L. de Oliveira
# ==============================================================================
"""
__all__ = ['H8bar_K', 'H8_K', 'H8T_K', 'H18B_K', 'Q4a5B_K', 'Q4bar_K', 'Q4_K', 'Q4T_K', 'Q5B_K']
|
# Authorization data
host = '*****'
user = '*****'
passwd = '*****'
db = 'hr'
|
#
# PySNMP MIB module ENTERASYS-VLAN-AUTHORIZATION-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ENTERASYS-VLAN-AUTHORIZATION-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:04:50 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "ConstraintsUnion", "ValueRangeConstraint", "SingleValueConstraint")
dot1dBasePortEntry, = mibBuilder.importSymbols("BRIDGE-MIB", "dot1dBasePortEntry")
etsysModules, = mibBuilder.importSymbols("ENTERASYS-MIB-NAMES", "etsysModules")
EnabledStatus, = mibBuilder.importSymbols("P-BRIDGE-MIB", "EnabledStatus")
NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup")
MibIdentifier, Bits, NotificationType, IpAddress, TimeTicks, Counter64, iso, Integer32, Counter32, ObjectIdentity, Unsigned32, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "Bits", "NotificationType", "IpAddress", "TimeTicks", "Counter64", "iso", "Integer32", "Counter32", "ObjectIdentity", "Unsigned32", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
etsysVlanAuthorizationMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48))
etsysVlanAuthorizationMIB.setRevisions(('2004-06-02 19:22',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setRevisionsDescriptions(('The initial version of this MIB module',))
if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setLastUpdated('200406021922Z')
if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setOrganization('Enterasys Networks, Inc')
if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setContactInfo('Postal: Enterasys Networks, Inc. 50 Minuteman Rd. Andover, MA 01810-1008 USA Phone: +1 978 684 1000 E-mail: support@enterasys.com WWW: http://www.enterasys.com')
if mibBuilder.loadTexts: etsysVlanAuthorizationMIB.setDescription("This MIB module defines a portion of the SNMP MIB under Enterasys Networks' enterprise OID pertaining to proprietary extensions to the IETF Q-BRIDGE-MIB, as specified in RFC2674, pertaining to VLAN authorization, as specified in RFC3580. Specifically, the enabling and disabling of support for the VLAN Tunnel-Type attribute returned from a RADIUS authentication, and how that attribute is applied to the port which initiated the authentication.")
class VlanAuthEgressStatus(TextualConvention, Integer32):
description = 'The possible egress configurations which may be applied in response to a successful authentication. none(1) No egress manipulation will be made. tagged(2) The authenticating port will be added to the current egress for the VLAN-ID returned. untagged(3) The authenticating port will be added to the current untagged egress for the VLAN-ID returned. dynamic(4) The authenticating port will use information returned in the authentication response to modify the current egress lists.'
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))
namedValues = NamedValues(("none", 1), ("tagged", 2), ("untagged", 3), ("dynamic", 4))
etsysVlanAuthorizationObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1))
etsysVlanAuthorizationSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 1))
etsysVlanAuthorizationPorts = MibIdentifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2))
etsysVlanAuthorizationEnable = MibScalar((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 1, 1), EnabledStatus().clone('disabled')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: etsysVlanAuthorizationEnable.setStatus('current')
if mibBuilder.loadTexts: etsysVlanAuthorizationEnable.setDescription('The enable/disable state for the VLAN authorization feature. When disabled, no modifications to the VLAN attributes related to packet switching should be enforced.')
etsysVlanAuthorizationTable = MibTable((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1), )
if mibBuilder.loadTexts: etsysVlanAuthorizationTable.setStatus('current')
if mibBuilder.loadTexts: etsysVlanAuthorizationTable.setDescription('Extensions to the table that contains information about every port that is associated with this transparent bridge.')
etsysVlanAuthorizationEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1), )
dot1dBasePortEntry.registerAugmentions(("ENTERASYS-VLAN-AUTHORIZATION-MIB", "etsysVlanAuthorizationEntry"))
etsysVlanAuthorizationEntry.setIndexNames(*dot1dBasePortEntry.getIndexNames())
if mibBuilder.loadTexts: etsysVlanAuthorizationEntry.setStatus('current')
if mibBuilder.loadTexts: etsysVlanAuthorizationEntry.setDescription('A list of extensions that support the management of proprietary features for each port of a transparent bridge. This is indexed by dot1dBasePort.')
etsysVlanAuthorizationStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1, 1), EnabledStatus().clone('enabled')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: etsysVlanAuthorizationStatus.setStatus('current')
if mibBuilder.loadTexts: etsysVlanAuthorizationStatus.setDescription('The enabled/disabled status for the application of VLAN authorization on this port, if disabled, the information returned in the VLAN-Tunnel-Type from the authentication will not be applied to the port (although it should be represented in this table). If enabled, those results will be applied to the port.')
etsysVlanAuthorizationAdminEgress = MibTableColumn((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1, 2), VlanAuthEgressStatus().clone('untagged')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: etsysVlanAuthorizationAdminEgress.setStatus('current')
if mibBuilder.loadTexts: etsysVlanAuthorizationAdminEgress.setDescription('Controls the modification of the current vlan egress list (of the vlan returned in the VLAN-Tunnel-Type, and reported by etsysVlanAuthorizationVlanID) upon successful authentication in the following manner: none(1) No egress manipulation will be made. tagged(2) The authenticating port will be added to the current egress for the VLAN-ID returned. untagged(3) The authenticating port will be added to the current untagged egress for the VLAN-ID returned. dynamic(4) The authenticating port will use information returned in the authentication response to modify the current egress lists. This value is supported only if the device supports a mechanism through which the egress status may be returned through the RADIUS response. Should etsysVlanAuthorizationEnable become disabled, etsysVlanAuthorizationStatus become disabled for a port, or should etsysVlanAuthorizationVlanID become 0 or 4095, all effect on the port egress MUST be removed.')
etsysVlanAuthorizationOperEgress = MibTableColumn((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1, 3), VlanAuthEgressStatus().clone('none')).setMaxAccess("readonly")
if mibBuilder.loadTexts: etsysVlanAuthorizationOperEgress.setStatus('current')
if mibBuilder.loadTexts: etsysVlanAuthorizationOperEgress.setDescription('Reports the current state of modification to the current vlan egress list (of the vlan returned in the VLAN-Tunnel-Type) upon successful authentication, if etsysVlanAuthorizationStatus is enabled, in the following manner: none(1) No egress manipulation will be made. tagged(2) The authenticating port will be added to the current egress for the VLAN-ID returned. untagged(3) The authenticating port will be added to the current untagged egress for the VLAN-ID returned. The purpose of this leaf is to report, specifically when etsysVlanAuthorizationAdminEgress has been set to dynamic(4), the currently enforced egress modification. If the port is unauthenticated, or no VLAN-ID has been applied, this leaf should return none(1).')
etsysVlanAuthorizationVlanID = MibTableColumn((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 1, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(1, 4094), ValueRangeConstraint(4095, 4095), ))).setMaxAccess("readonly")
if mibBuilder.loadTexts: etsysVlanAuthorizationVlanID.setStatus('current')
if mibBuilder.loadTexts: etsysVlanAuthorizationVlanID.setDescription('The 12 bit VLAN identifier for a given port, used to override the PVID of the given port, obtained as a result of an authentication. A value of zero indicates that there is no authenticated VLAN ID for the given port. Should a port become unauthenticated this value MUST be returned to zero. A value of 4095 indicates that a the port has been authenticated, but that the VLAN returned could not be applied to the port (possibly because of resource constraints or misconfiguration). In this instance, the original PVID should still be applied. Should the feature become disabled or the session terminate, all effect on the Port VLAN ID MUST be removed.')
etsysVlanAuthorizationConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2))
etsysVlanAuthorizationGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2, 1))
etsysVlanAuthorizationCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2, 2))
etsysVlanAuthorizationGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2, 1, 1)).setObjects(("ENTERASYS-VLAN-AUTHORIZATION-MIB", "etsysVlanAuthorizationEnable"), ("ENTERASYS-VLAN-AUTHORIZATION-MIB", "etsysVlanAuthorizationStatus"), ("ENTERASYS-VLAN-AUTHORIZATION-MIB", "etsysVlanAuthorizationAdminEgress"), ("ENTERASYS-VLAN-AUTHORIZATION-MIB", "etsysVlanAuthorizationOperEgress"), ("ENTERASYS-VLAN-AUTHORIZATION-MIB", "etsysVlanAuthorizationVlanID"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
etsysVlanAuthorizationGroup = etsysVlanAuthorizationGroup.setStatus('current')
if mibBuilder.loadTexts: etsysVlanAuthorizationGroup.setDescription('A collection of objects relating to VLAN Authorization.')
etsysVlanAuthorizationCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 5624, 1, 2, 48, 2, 2, 1)).setObjects(("ENTERASYS-VLAN-AUTHORIZATION-MIB", "etsysVlanAuthorizationGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
etsysVlanAuthorizationCompliance = etsysVlanAuthorizationCompliance.setStatus('current')
if mibBuilder.loadTexts: etsysVlanAuthorizationCompliance.setDescription('The compliance statement for devices that support the Enterasys VLAN Authorization MIB.')
mibBuilder.exportSymbols("ENTERASYS-VLAN-AUTHORIZATION-MIB", etsysVlanAuthorizationVlanID=etsysVlanAuthorizationVlanID, etsysVlanAuthorizationGroup=etsysVlanAuthorizationGroup, etsysVlanAuthorizationEnable=etsysVlanAuthorizationEnable, etsysVlanAuthorizationOperEgress=etsysVlanAuthorizationOperEgress, etsysVlanAuthorizationAdminEgress=etsysVlanAuthorizationAdminEgress, etsysVlanAuthorizationConformance=etsysVlanAuthorizationConformance, VlanAuthEgressStatus=VlanAuthEgressStatus, etsysVlanAuthorizationPorts=etsysVlanAuthorizationPorts, etsysVlanAuthorizationStatus=etsysVlanAuthorizationStatus, etsysVlanAuthorizationCompliance=etsysVlanAuthorizationCompliance, etsysVlanAuthorizationMIB=etsysVlanAuthorizationMIB, etsysVlanAuthorizationGroups=etsysVlanAuthorizationGroups, etsysVlanAuthorizationObjects=etsysVlanAuthorizationObjects, etsysVlanAuthorizationTable=etsysVlanAuthorizationTable, etsysVlanAuthorizationSystem=etsysVlanAuthorizationSystem, etsysVlanAuthorizationEntry=etsysVlanAuthorizationEntry, etsysVlanAuthorizationCompliances=etsysVlanAuthorizationCompliances, PYSNMP_MODULE_ID=etsysVlanAuthorizationMIB)
|
"""Exercício 7:
Dadas duas listas, retorne uma nova lista contendo valores que aparecem nas duas da entrada"""
def repetidos_versao_1(lista1: list, lista2: list):
saida = list(set([x for x in lista1 for y in lista2 if x == y]))
return saida
def repetidos_versao_2(lista1: list, lista2: list):
auxiliar = [x for x in lista1 for y in lista2 if x == y]
saida = []
for item in auxiliar:
if item not in saida:
saida.append(item)
return saida
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
print(repetidos_versao_1(a, b))
print(repetidos_versao_2(a, b))
|
#!/usr/bin/env python
"""
_Step.Templates_
Package for containing Step Template implementations
"""
__all__ = []
|
class BookStore:
def __init__(self, book):
self.booklst = book
class Book:
def __init__(self, title, author, chapter, price):
self.title = title
self.author = author
self.chapter = list(chapter)
self.price = int(price)
book1 = Book("han kubrat", "Tangra", ['1', '3', '4', '2'], 1)
book2 = Book("han Asparuh", "Vitosha", ['12', '123', '55', '22'], 2)
book3 = Book("han Tervel", "StaraPlanina", ['155', '33', '41', '245'], 3)
lst_book = [book1, book2, book3]
bookstor = BookStore(lst_book)
|
"""submodopt - A package for maximizing submodular functions"""
__version__ = '0.1.0'
__author__ = 'Satwik Bhattamishra <satwik55@gmail.com>'
__all__ = []
|
# Contains the objects found on our user greetings page.
# Imports --------------------------------------------------------------------------------
# Page Objects ---------------------------------------------------------------------------
class PatientGreetingPageObject(object):
bio = 'This is a test bio.'
def get_current_feeling_buttons(self):
feeling1element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-0"]')
feeling2element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-1"]')
feeling3element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-2"]')
feeling4element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-3"]')
feeling5element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-4"]')
feeling6element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-5"]')
feeling7element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-6"]')
feeling8element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-7"]')
feeling9element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-8"]')
feeling10element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-9"]')
attributes = {
'feeling1 element': feeling1element,
'feeling2 element': feeling2element,
'feeling3 element': feeling3element,
'feeling4 element': feeling4element,
'feeling5 element': feeling5element,
'feeling6 element': feeling6element,
'feeling7 element': feeling7element,
'feeling8 element': feeling8element,
'feeling9 element': feeling9element,
'feeling10 element': feeling10element
}
return attributes
def click_feeling1_button(self):
self.get_current_feeling_buttons(self)['feeling1 element'].click()
def click_feeling2_button(self):
self.get_current_feeling_buttons(self)['feeling2 element'].click()
def click_feeling3_button(self):
self.get_current_feeling_buttons(self)['feeling3 element'].click()
def click_feeling4_button(self):
self.get_current_feeling_buttons(self)['feeling4 element'].click()
def click_feeling5_button(self):
self.get_current_feeling_buttons(self)['feeling5 element'].click()
def click_feeling6_button(self):
self.get_current_feeling_buttons(self)['feeling6 element'].click()
def click_feeling7_button(self):
self.get_current_feeling_buttons(self)['feeling7 element'].click()
def click_feeling8_button(self):
self.get_current_feeling_buttons(self)['feeling8 element'].click()
def click_feeling9_button(self):
self.get_current_feeling_buttons(self)['feeling9 element'].click()
def click_feeling10_button(self):
self.get_current_feeling_buttons(self)['feeling10 element'].click()
def get_feeling_comparison_buttons(self):
attributes = {
'worse element': self.client.find_element_by_xpath('//*[@id="feeling_comparison-0"]'),
'same element': self.client.find_element_by_xpath('//*[@id="feeling_comparison-1"]'),
'better element': self.client.find_element_by_xpath('//*[@id="feeling_comparison-2"]'),
}
return attributes
def click_worse_button(self):
self.get_feeling_comparison_buttons(self)['worse element'].click()
def click_same_button(self):
self.get_feeling_comparison_buttons(self)['same element'].click()
def click_better_button(self):
self.get_feeling_comparison_buttons(self)['better element'].click()
def get_behaviour_buttons(self):
attributes = {
'happy element': self.client.find_element_by_xpath('//*[@id="behaviours-0"]'),
'angry element': self.client.find_element_by_xpath('//*[@id="behaviours-1"]'),
'disappointed element': self.client.find_element_by_xpath('//*[@id="behaviours-2"]'),
'done with today element': self.client.find_element_by_xpath('//*[@id="behaviours-3"]'),
'persevering element': self.client.find_element_by_xpath('//*[@id="behaviours-4"]'),
'anxious element': self.client.find_element_by_xpath('//*[@id="behaviours-5"]'),
'confused element': self.client.find_element_by_xpath('//*[@id="behaviours-6"]'),
'worried element': self.client.find_element_by_xpath('//*[@id="behaviours-7"]'),
'ill element': self.client.find_element_by_xpath('//*[@id="behaviours-8"]'),
'exhausted element': self.client.find_element_by_xpath('//*[@id="behaviours-9"]'),
'accomplished element': self.client.find_element_by_xpath('//*[@id="behaviours-10"]'),
'star struck element': self.client.find_element_by_xpath('//*[@id="behaviours-11"]'),
'frightened element': self.client.find_element_by_xpath('//*[@id="behaviours-12"]'),
}
return attributes
def click_happy_element(self):
self.get_behaviour_buttons(self)['happy element'].click()
def click_angry_element(self):
self.get_behaviour_buttons(self)['angry element'].click()
def click_disappointed_element(self):
self.get_behaviour_buttons(self)['disappointed element'].click()
def click_done_with_today_element(self):
self.get_behaviour_buttons(self)['done with today element'].click()
def click_persevering_element(self):
self.get_behaviour_buttons(self)['persevering element'].click()
def click_anxious_element(self):
self.get_behaviour_buttons(self)['anxious element'].click()
def click_confused_element(self):
self.get_behaviour_buttons(self)['confused element'].click()
def click_worried_element(self):
self.get_behaviour_buttons(self)['worried element'].click()
def click_ill_element(self):
self.get_behaviour_buttons(self)['ill element'].click()
def click_exhausted_element(self):
self.get_behaviour_buttons(self)['exhausted element'].click()
def click_accomplished_element(self):
self.get_behaviour_buttons(self)['accomplished element'].click()
def click_star_struck_element(self):
self.get_behaviour_buttons(self)['star struck element'].click()
def click_frightened_element(self):
self.get_behaviour_buttons(self)['frightened element'].click()
def get_bio_element(self):
return self.client.find_element_by_xpath('//*[@id="patient_comment"]')
def type_in_bio_form(self, input_to_type=bio): # A function to type text into our bio form box.
# Retrieve our form attributes.
get_field_element = self.get_bio_element()
# After retrieving the field element, simulate typing into a form box.
get_field_element.send_keys(input_to_type)
print(f"Running Simulation: Currently typing '{input_to_type}' in the bio field.")
def clear_password_form(self): # A function to clear the text from within our password form box.
# Retrieve our form attributes.
get_field_element = self.get_bio_element()
get_field_element.clear() # Clears our form.
print(f"Running Simulation: Currently clearing the bio field.")
def get_submit_button(self):
return self.client.find_element_by_xpath('//*[@id="submit"]')
def click_submit_button(self):
self.get_submit_button(self).click()
def get_skip_evaluation_button(self):
return self.client.find_element_by_xpath('/html/body/p/a')
def click_skip_evaluation_button(self):
return self.get_skip_evaluation_button(self).click()
|
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
Boys = {'Tim': 18,'Charlie':12,'Robert':25}
Girls = {'Tiffany':22}
studentX=Boys.copy()
studentY=Girls.copy()
print(studentX)
print(studentY)
students = list(Dict.keys())
students.sort()
for s in students:
print(":".join((s,str(Dict[s]))))
|
"""Utilities for interacting with databases"""
def generate_connect_string(
host: str,
port: int,
db: str,
user: str,
password: str,
) -> str:
conn_string = f"postgresql://{user}:{password}@"
if not host.startswith('/'):
conn_string += f"{host}:{port}"
conn_string += f"/{db}"
if host.startswith('/'):
conn_string += f"?host={host}"
return conn_string
|
class RaiseException:
def __init__(self, exception: Exception):
self.exception = exception
|
EVENT_ALGO_LOG = "eAlgoLog"
EVENT_ALGO_SETTING = "eAlgoSetting"
EVENT_ALGO_VARIABLES = "eAlgoVariables"
EVENT_ALGO_PARAMETERS = "eAlgoParameters"
APP_NAME = "AlgoTrading"
|
class AminoAcid:
def __init__(self,name='AA'):
self.name = name
self.name3L = ''
self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic
self.charge = 0
self.polar = 0
self.corner = 0 # Would prefer to be at a corner : give positive value
self.loop = 0 # cost/benefit when on a loop
self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue
self.SpecialRes = {0:0} # Special characteristic of residue
self.ResWeight = 0 # residue weight (weight - 56) backbone weight is 56
self.ResVol = 0 # Residue volume from http://prowl.rockefeller.edu/aainfo/volume.htm
self.SideChainVol = 0 # Side Chain volume is evaluated as ResVol - 0.9 Gly.ResVol
self.Hydropathy = 0 # Hydropathy index
self.n1 = 0
self.n2 = 0
# n values
# -1 when the amino acid (AA) residue has an N donor, short residue.
# -2 when the AA residue has an O acceptor, short residue.
# -3 when the AA residue has an N donor, long residue that able to bond across two turns.
# -5 when the AA residue has an O acceptor, long residue that able to bond across two turns.
# -7 when it is a Cystine(C)
# 0 when bond is not possible.
# 1 when this N or O participating in a bond.
# A residu can only participate in one side-chain bond. So when a bond is created
# for example with n1, n1 get the bond value and n2 will be assigned 0
def __mul__ (self,other):
# Evaluating side chain interaction
Prod = self.donor * other.acceptor
return Prod
# ############ Non Polar, HydroPhobic ###########
class Ala(AminoAcid):
def __init__(self):
AminoAcid.__init__(self,'A')
# Alanine
# ###
# CH3-CH(NH2)-COOH
#
#
# Molecular weight 89.09 Da
# Non ploar
# Acidity - Natural
# Hydrophobicity 0.616 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991)
# Hydrophathy index 1.8 (J.Mol.Bio(1982) 157, 105-132)
# Isoelectric point (when protonation accure) pH 6.01
# pKa( alpha-COOH) 2.35
# pKa( alpha-NH2) 9.87
# CAS # 56-41-7
# PubChem ID 5950
#
self.name3L = 'ALA'
self.Hydrophobic = 1 # 1: Hydrophobic, 0: Hydrophilic
self.charge = 0
self.polar = 0
self.corner = 0 # Would prefer to be at a corner : give positive value
self.loop = 0 # cost/benefit when on a loop
self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue
self.SpecialRes = {0:0} # Special characteristic of residue
self.n1 = 0
self.n2 = 0
self.Hydropathy = 1.8
self.ResWeight = 33
self.ResVol = 88.6
self.SideChainVol = 88.6-54.1
class Val(AminoAcid):
def __init__(self):
AminoAcid.__init__(self,'V')
# Valine
# #########
# (CH3)2-CH-CH(NH2)-COOH
#
#
# Essential AA (cannot be synthesized by humans)
# Molecular weight 117.15 Da
# Non ploar
# Acidity - Natural
# Hydrophobicity 0.825 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991)
# Hydrophathy index 4.2 (J.Mol.Bio(1982) 157, 105-132)
# Isoelectric point 6.00
# pKa( alpha-COOH) 2.39
# pKa( alpha-NH2) 9.74
# CAS # 72-18-4
# PubChem ID 1182
#
self.name3L = 'VAL'
self.Hydrophobic = 1 # 1: Hydrophobic, 0: Hydrophilic
self.charge = 0
self.polar = 0
self.corner = 0 # Would prefer to be at a corner : give positive value
self.loop = 0 # cost/benefit when on a loop
self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue
self.SpecialRes = {0:0} # Special characteristic of residue
self.n1 = 0
self.n2 = 0
self.Hydropathy = 4.2
self.ResWeight = 61
self.ResVol = 140.0
self.SideChainVol = 140-54.1
class Leu(AminoAcid):
def __init__(self):
AminoAcid.__init__(self,'L')
# Leucine
# #############
# (CH3)2-CH-CH2-CH(NH2)-COOH
#
#
# Essential AA
# Molecular weight 131.18 Da
# Non ploar
# Acidity - Natural
# Hydrophobicity 0.943 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991)
# Hydrophathy index 3.8 (J.Mol.Bio(1982) 157, 105-132)
# Isoelectric point 6.01
# pKa( alpha-COOH) 2.33
# pKa( alpha-NH2) 9.74
# CAS # 61-90-5
# PubChem ID 6106
#
self.name3L = 'LEU'
self.Hydrophobic = 1 # 1: Hydrophobic, 0: Hydrophilic
self.charge = 0
self.polar = 0
self.corner = 0 # Would prefer to be at a corner : give positive value
self.loop = 0 # cost/benefit when on a loop
self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue
self.SpecialRes = {0:0} # Special characteristic of residue
self.n1 = 0
self.n2 = 0
self.Hydropathy = 3.8
self.ResWeight = 75
self.ResVol = 166.7
self.SideChainVol = 166.7-54.1
class Ile(AminoAcid):
def __init__(self):
AminoAcid.__init__(self,'I')
# Isoleucine
# ###############
# CH3-CH2-CH(CH3)-CH(NH2)-COOH
#
#
# Essential AA
# Molecular weight 131.18 Da
# Non ploar
# Acidity - Natural
# Hydrophobicity 0.943 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991)
# Hydrophathy index 4.5 (J.Mol.Bio(1982) 157, 105-132)
# Isoelectric point 6.05
# pKa( alpha-COOH) 2.33
# pKa( alpha-NH2) 9.74
# CAS # 61-90-5
# PubChem ID 6106
#
self.Hydropathy = 4.5
self.ResWeight = 75
self.name3L = 'ILE'
self.Hydrophobic = 1 # 1: Hydrophobic, 0: Hydrophilic
self.charge = 0
self.polar = 0
self.corner = 0 # Would prefer to be at a corner : give positive value
self.loop = 0 # cost/benefit when on a loop
self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue
self.SpecialRes = {0:0} # Special characteristic of residue
self.n1 = 0
self.n2 = 0
self.ResVol = 166.7
self.SideChainVol = 166.7-54.1
class Phe(AminoAcid):
def __init__(self):
AminoAcid.__init__(self,'F')
# Phenylalanine
# ######
# Ph-CH2-CH(NH2)-COOH
# The residue Ph-CH2 : C6H5-CH2 benzyl
#
# Essential AA
# Molecular weight 165.19 Da
# Non ploar
# Acidity - Natural
# Hydrophobicity 1 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991)
# Hydrophathy index 2.8 (J.Mol.Bio(1982) 157, 105-132)
# Isoelectric point 5.49
# pKa( alpha-COOH) 2.20
# pKa( alpha-NH2) 9.31
# CAS # 63-91-2
# PubChem ID 994
#
self.Hydropathy = 2.8
self.ResWeight = 109
self.name3L = 'PHE'
self.Hydrophobic = 1 # 1: Hydrophobic, 0: Hydrophilic
self.charge = 0
self.polar = 0
self.corner = 0 # Would prefer to be at a corner : give positive value
self.loop = 0 # cost/benefit when on a loop
self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue
self.SpecialRes = {0:0} # Special characteristic of residue
self.n1 = 0
self.n2 = 0
self.ResVol = 189.9
self.SideChainVol = 189.9-54.1
class Trp(AminoAcid):
def __init__(self):
AminoAcid.__init__(self,'W')
# Tryptophan
# ##############
# Ph-NH-CH=C-CH2-CH(NH2)-COOH
# |________|
#
# contains an indole functional group.
# aromatic heterocyclic organic compound
# It has a bicyclic structure, consisting of a six-membered benzene ring fused to
# a five-membered nitrogen-containing pyrrole ring
#
# Essential AA
# Molecular weight 204.23 Da
# Non ploar
# Acidity - Natural
# Hydrophobicity 0.878 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991)
# Hydrophathy index -0.9 (J.Mol.Bio(1982) 157, 105-132)
# Isoelectric point 5.89
# pKa( alpha-COOH) 2.46
# pKa( alpha-NH2) 9.41
# CAS # 73-22-3
# PubChem ID 6305
#
self.Hydropathy = -0.9
self.ResWeight = 148
self.name3L = 'TRP'
self.Hydrophobic = 1 # 1: Hydrophobic, 0: Hydrophilic
self.charge = 0
self.polar = 0
self.corner = 0 # Would prefer to be at a corner : give positive value
self.loop = 0 # cost/benefit when on a loop
self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue
self.SpecialRes = {0:0} # Special characteristic of residue
self.n1 = 0
self.n2 = 0
self.ResVol = 227.8
self.SideChainVol = 227.8-54.1
class Met(AminoAcid):
def __init__(self):
AminoAcid.__init__(self,'M')
# Methionine
# ############
# CH3-S-(CH2)2-CH(NH2)-COOH
# sulfur-containing residue
# methyl donor R-CH3
# methionine is incorporated into the N-terminal position of all proteins
# in eukaryotes and archaea during translation, although it is usually removed
# by post-translational modification
#
# Essential AA
# Molecular weight 149.21 Da
# Non ploar
# Acidity - Natural
# Hydrophobicity 0.738 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991)
# Hydrophathy index 1.9 (J.Mol.Bio(1982) 157, 105-132)
# Isoelectric point 5.74
# pKa( alpha-COOH) 2.13
# pKa( alpha-NH2) 9.28
# CAS # 63-68-3
# PubChem ID 876
#
self.Hydropathy = 1.9
self.ResWeight = 93
self.name3L = 'MET'
self.Hydrophobic = 1 # 1: Hydrophobic, 0: Hydrophilic
self.charge = 0
self.polar = 0
self.corner = 0 # Would prefer to be at a corner : give positive value
self.loop = 0 # cost/benefit when on a loop
self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue
self.SpecialRes = {0:0} # Special characteristic of residue
self.n1 = 0
self.n2 = 0
self.ResVol = 162.9
self.SideChainVol = 162.9-54.1
class Pro(AminoAcid):
def __init__(self):
AminoAcid.__init__(self,'P')
# Proline
# **********
# NH-(CH2)3-CH-COOH
# |_________|
# Side chain bond to C alpha
# exceptional conformational rigidity
# usually solvent-exposed.
# lacks a hydrogen on the amide group, it cannot act as a hydrogen bond donor,
# only as a hydrogen bond acceptor.
#
# Molecular weight 115.13 Da
# Non ploar
# Acidity - Natural
# Hydrophobicity 0.711 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991)
# Hydrophathy index -1.6 (J.Mol.Bio(1982) 157, 105-132)
# Isoelectric point 6.30
# pKa( alpha-COOH) 1.95
# pKa( alpha-NH2) 10.64
# CAS # 147-85-3
# PubChem ID 614
#
self.Hydropathy = -1.6
self.ResWeight = 59
self.name3L = 'PRO'
self.Hydrophobic = 1 # 1: Hydrophobic, 0: Hydrophilic
self.charge = 0
self.polar = 0
self.corner = 0 # Would prefer to be at a corner : give positive value
self.loop = 0 # cost/benefit when on a loop
self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue
self.SpecialRes = {0:0,3:-3,4:-3,5:-3,6:-2} # special value scores
self.n1 = 0
self.n2 = 0
self.ResVol = 112.7
self.SideChainVol = 112.7-54.1
# ############ Non Polar Uncharged ###########
class Gly(AminoAcid):
def __init__(self):
AminoAcid.__init__(self,'G')
#
# NH2-CH2-COOH
#
# Molecular weight 75.07 Da
# Non ploar
# Acidity - Natural
# Hydrophobicity 0.501 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991)
# Hydrophathy index -0.4 (J.Mol.Bio(1982) 157, 105-132)
# Isoelectric point 6.06
# pKa( alpha-COOH) 2.35
# pKa( alpha-NH2) 9.78
# CAS # 56-40-6
# PubChem ID 750
self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic
self.Hydropathy = -0.4
self.ResWeight = 19
self.name3L = 'GLY'
self.SpecialRes = {0:0,3:-3,5:-3} # special value scores
self.ResVol = 60.1
self.SideChainVol = 60.1-54.1
# ############ Polar Uncharged ###########
class Ser(AminoAcid):
def __init__(self):
AminoAcid.__init__(self,'S')
# Serine
# ######
# HO-CH2-CH(NH2)-COOH
#
# Molecular weight 105.09 Da
# Ploar
# Acidity - Natural
# Hydrophobicity 0.359 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991)
# Hydrophathy index -0.8 (J.Mol.Bio(1982) 157, 105-132)
# Isoelectric point 5.68
# pKa( alpha-COOH) 2.19
# pKa( alpha-NH2) 9.21
# CAS # 56-45-1
# PubChem ID 617
#
self.Hydropathy = -0.8
self.ResWeight = 49
self.name3L = 'SER'
self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic
self.charge = 0
self.polar = 1
self.corner = 0 # Would prefer to be at a corner : give positive value
self.loop = 0 # cost/benefit when on a loop
self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue
self.SpecialRes = {0:0} # Special characteristic of residue
self.n1 = 0
self.n2 = 0
self.ResVol = 89.0
self.SideChainVol = 89-54.1
class Thr(AminoAcid):
def __init__(self):
AminoAcid.__init__(self,'T')
# Threonine
# ##########
# CH3-CH(OH)-CH(NH2)-COOH
# bearing an alcohol group
#
# Essential AA
# Molecular weight 119.12 Da
# Ploar
# Acidity - Natural
# Hydrophobicity 0.450 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991)
# Hydrophathy index -0.7 (J.Mol.Bio(1982) 157, 105-132)
# Isoelectric point 5.60
# pKa( alpha-COOH) 2.09
# pKa( alpha-NH2) 9.10
# CAS # 72-19-5
# PubChem ID 6288
#
self.Hydropathy = -0.7
self.ResWeight = 63
self.name3L = 'THR'
self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic
self.charge = 0
self.polar = 1
self.corner = 0 # Would prefer to be at a corner : give positive value
self.loop = 0 # cost/benefit when on a loop
self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue
self.SpecialRes = {0:0} # Special characteristic of residue
self.n1 = 0
self.n2 = 0
self.ResVol = 116.1
self.SideChainVol = 116.1-54.1
class Cys(AminoAcid):
def __init__(self):
AminoAcid.__init__(self,'C')
# Cysteine
# ######
# HS-CH2-CH(NH2)-COOH
# thiol (R-S-H) side chain
# Has Sulfur in side chain
#
# Molecular weight 121.16 Da
# Ploar
# Acidity - Natural
# Hydrophobicity 0.680 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991)
# Hydrophathy index 2.5 (J.Mol.Bio(1982) 157, 105-132)
# Isoelectric point 5.05
# pKa( alpha-COOH) 1.92
# pKa( alpha-NH2) 10.70
# CAS # 59-90-4
# PubChem ID 5862
#
self.Hydropathy = 2.5
self.ResWeight = 65
self.name3L = 'CYS'
self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic
self.charge = 0
self.polar = 1
self.corner = 0 # Would prefer to be at a corner : give positive value
self.loop = 0 # cost/benefit when on a loop
self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue
self.n1 = -7
self.n2 = 0
self.SpecialRes = {0:0} # special value scores
self.ResVol = 108.5
self.SideChainVol = 108.5-54.1
class Tyr(AminoAcid):
def __init__(self):
AminoAcid.__init__(self,'Y')
# Tyrosine
# ###########
# HO-p-Ph-CH2-CH(NH2)-COOH
#
# Molecular weight 181.19 Da
# Non ploar
# Acidity - Natural
# Hydrophobicity 0.880 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991)
# Hydrophathy index -1.3 (J.Mol.Bio(1982) 157, 105-132)
# Isoelectric point 5.64
# pKa( alpha-COOH) 2.20
# pKa( alpha-NH2) 9.21
# CAS # 60-18-4
# PubChem ID 1153
#
self.Hydropathy = -1.3
self.ResWeight = 125
self.name3L = 'TYR'
self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic
self.charge = 0
self.polar = 1
self.corner = 0 # Would prefer to be at a corner : give positive value
self.loop = 0 # cost/benefit when on a loop
self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue
self.SpecialRes = {0:0} # Special characteristic of residue
self.n1 = 0
self.n2 = 0
self.ResVol = 193.6
self.SideChainVol = 193.6-54.1
class Asn(AminoAcid):
def __init__(self):
AminoAcid.__init__(self,'N')
# Asparagine
# ##########
# H2N-CO-CH2-CH(NH2)-COOH
# N Donor - NH2
#
# has carboxamide as the side chain's functional group(R-CO-NH2)
# side chain can form hydrogen bond interactions with the peptide backbone
# often found near the beginning and the end of alpha-helices,
# and in turn motifs in beta sheets.
#
# Molecular weight 132.12 Da
# Ploar
# Acidity - Natural
# Hydrophobicity 0.236 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991)
# Hydrophathy index -3.5 (J.Mol.Bio(1982) 157, 105-132)
# Isoelectric point 5.41
# pKa( alpha-COOH) 2.14
# pKa( alpha-NH2) 8.72
# CAS # 70-47-3
# PubChem ID 236
#
self.Hydropathy = -3.5
self.ResWeight = 76
self.name3L = 'ASN'
self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic
self.charge = 0
self.polar = 1
self.corner = 0 # Would prefer to be at a corner : give positive value
self.loop = 0 # cost/benefit when on a loop
self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue
self.SpecialRes = {0:0} # Special characteristic of residue
self.n1 = -1
self.n2 = -2
self.ResVol = 114.1
self.SideChainVol = 114.1-54.1
class Gln(AminoAcid):
def __init__(self):
AminoAcid.__init__(self,'Q')
# Glutamine
# #############
# H2N-CO-(CH2)2-CH(NH2)-COOH
# N Donor - NH2
#
# Molecular weight 146.14 Da
# Ploar
# Acidity - Natural
# Hydrophobicity 0.251 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991)
# Hydrophathy index -3.5 (J.Mol.Bio(1982) 157, 105-132)
# Isoelectric point 5.65
# pKa( alpha-COOH) 2.17
# pKa( alpha-NH2) 9.13
# CAS # 56-85-9
# PubChem ID 5950
#
self.Hydropathy = -3.5
self.ResWeight = 90
self.name3L = 'GLN'
self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic
self.charge = 0
self.polar = 1
self.corner = 0 # Would prefer to be at a corner : give positive value
self.loop = 0 # cost/benefit when on a loop
self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue
self.n1 = -1
self.n2 = -2
self.SpecialRes = {0:0} # special value scores
self.ResVol = 143.8
self.SideChainVol = 143.8-54.1
# ########## Polar Acidic ###########
class Asp(AminoAcid):
def __init__(self):
AminoAcid.__init__(self,'D')
# Aspartic acid
# ########
# HOOC-CH2-CH(NH2)-COOH
#
# Molecular weight 133.10 Da
# Ploar
# Acidity - Acidic
# Hydrophobicity 0.028 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991)
# Hydrophathy index -3.5 (J.Mol.Bio(1982) 157, 105-132)
# Isoelectric point 2.85
# pKa( alpha-COOH) 1.99
# pKa( alpha-NH2) 9.90
# CAS # 56-84-8
# PubChem ID 5960
#
self.Hydropathy = -3.5
self.ResWeight = 77
self.name3L = 'ASP'
self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic
self.charge = 1
self.polar = 1
self.corner = 0 # Would prefer to be at a corner : give positive value
self.loop = 0 # cost/benefit when on a loop self.loop = 0
self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue
self.SpecialRes = {0:0} # Special characteristic of residue
self.n1 = -2
self.n2 = 0
self.ResVol = 111.1
self.SideChainVol = 111.1-54.1
class Glu(AminoAcid):
def __init__(self):
AminoAcid.__init__(self,'E')
# ###########
# HOOC-(CH2)2-CH(NH2)-COOH
#
# Molecular weight 147.13 Da
# Ploar
# Acidity - Acidic
# Hydrophobicity 0.043 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991)
# Hydrophathy index -3.5 (J.Mol.Bio(1982) 157, 105-132)
# Isoelectric point 3.15
# pKa( alpha-COOH) 2.10
# pKa( alpha-NH2) 9.47
# CAS # 56-86-0
# PubChem ID 611
#
self.Hydropathy = -3.5
self.ResWeight = 91
self.name3L = 'GLU'
self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic
self.charge = 1
self.polar = 1
self.corner = 0 # Would prefer to be at a corner : give positive value
self.loop = 0 # cost/benefit when on a loop self.loop = 0
self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue
self.SpecialRes = {0:0} # Special characteristic of residue
self.n1 = -2
self.n2 = 0
self.ResVol = 138.4
self.SideChainVol = 138.4-54.1
# ############## Polar Basic #############
class Lys(AminoAcid):
def __init__(self):
AminoAcid.__init__(self,'K')
# Lysine
# ##########
# H2N-(CH2)4-CH(NH2)-COOH
# often participates in hydrogen bonding
# N Donor - NH2
#
# Essential AA
# Molecular weight 146.19 Da
# Ploar
# Acidity - Basic
# Hydrophobicity 0.283 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991)
# Hydrophathy index -3.9 (J.Mol.Bio(1982) 157, 105-132)
# Isoelectric point 6.90
# pKa( alpha-COOH) 2.16
# pKa( alpha-NH2) 9.06
# CAS # 56-87-1
# PubChem ID 866
#
self.Hydropathy = -3.9
self.ResWeight = 90
self.Hydropathy = -3.9
self.ResWeight = 90
self.name3L = 'LYS'
self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic
self.charge = 1
self.polar = 1
self.corner = 0 # Would prefer to be at a corner : give positive value
self.loop = 0 # cost/benefit when on a loop self.loop = 0
self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue
self.SpecialRes = {0:0} # Special characteristic of residue
self.n1 = -1
self.n2 = 0
self.ResVol = 168.6
self.SideChainVol = 168.6-54.1
class Arg(AminoAcid):
def __init__(self):
AminoAcid.__init__(self,'R')
# Arginine
# ###################
# HN=C(NH2)-NH-(CH2)3-CH(NH2)-COOH
# N Donor - NH2
#
# Molecular weight 174.20 Da
# Ploar
# Acidity - Basic (strong)
# Hydrophobicity 0.000 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991)
# Hydrophathy index -4.5 (J.Mol.Bio(1982) 157, 105-132)
# Isoelectric point (when protonation accure) pH 10.76
# pKa( alpha-COOH) 1.82
# pKa( alpha-NH2) 8.99
# CAS # 74-79-3
# PubChem ID 5950
#
self.Hydropathy = -4.5
self.ResWeight = 118
self.name3L = 'ARG'
self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic
self.charge = 1
self.polar = 1
self.corner = 0 # Would prefer to be at a corner : give positive value
self.loop = 0 # cost/benefit when on a loop self.loop = 1
self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue
self.SpecialRes = {0:0} # Special characteristic of residue
self.n1 = -1
self.n2 = -3
self.ResVol = 173.4
self.SideChainVol = 173.4-54.1
class His(AminoAcid):
def __init__(self):
AminoAcid.__init__(self,'H')
# Histidine
# ################
# NH-CH=N-CH=C-CH2-CH(NH2)-COOH
# |__________|
# N Donor - NH
# The imidazole side chain has two nitrogens with different properties
#
# Molecular weight 155.15 Da
# Ploar
# Acidity - Basic (week)
# Hydrophobicity 0.165 (Analytical Bio chemistry 193:11,72-82 Elsevier 1991)
# Hydrophathy index -3.2 (J.Mol.Bio(1982) 157, 105-132)
# Isoelectric point 7.60
# pKa( alpha-COOH) 1.80
# pKa( alpha-NH2) 9.33
# CAS # 71-00-1
# PubChem ID 773
#
self.Hydropathy = -3.2
self.ResWeight = 99
self.name3L = 'HIS'
self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic
self.charge = 0.5
self.polar = 1
self.corner = 0 # Would prefer to be at a corner : give positive value
self.loop = 0 # cost/benefit when on a loop
self.size = 0 # Residue size (0:1) 0:ignor size, 1:Large residue
self.SpecialRes = {0:0} # Special characteristic of residue
self.n1 = -1
self.n2 = 0
self.ResVol = 153.2
self.SideChainVol = 153.2-54.1
|
initialized = True
class TestFrozenUtf8_1:
"""\u00b6"""
class TestFrozenUtf8_2:
"""\u03c0"""
class TestFrozenUtf8_4:
"""\U0001f600"""
def main():
print("Hello world!")
if __name__ == '__main__':
main()
|
nome = 'Pedro Silva Mendonça'
print("O nome com todas as letras maiusculas:")
print(nome.upper())
print("O nome com todas as letras minusculas:")
print(nome.lower())
#da pra fazer assim
print('(Primeiro jeito) Quantas letras ao todo(sem considerar os espaços):')
print(len(nome.strip().replace(" ", "")))
#ou assim
print('(Segundo jeito) Quantas letras ao todo(sem considerar os espaços):')
print(len(nome) - nome.count(' '))
#da pra fazer assim
print('(Primeiro jeito) Quantas letras tem o primeiro nome:')
nomeSeparado = nome.split()
print(len(nomeSeparado[0]))
#ou assim
print('(Segundo jeito) Quantas letras tem o primeiro nome:')
print(nome.find(' '))
|
# -*- coding: utf-8 -*-
'''
username :
password :
'''
acts = ActionSet(tag=tag,desc=desc,mp=mp)
#act1
arg = { "detectRegion" : gl.R_Screen,
"imagePattern" : Pattern("6.png").similar(0.90).targetOffset(0,-69),
"loopWaitingTime": 0,
"failResponse" : "Ignore",
"loopTime": 0,
"saveImage" :True }
act = ClickAction(tag = "1",desc=u"上箭头", **arg)
acts.addAction(act)
#act2
arg = { "detectRegion" : gl.R_Screen,
"imagePattern" : Pattern("7.png").similar(0.90).targetOffset(0,70),
"loopWaitingTime": 0,
"failResponse" : "Ignore",
"loopTime": 0,
"saveImage" :True }
act = ClickAction(tag = "2",desc=u"下箭头", **arg)
acts.addAction(act)
#act3
arg = { "detectRegion" : gl.R_Screen,
"imagePattern" : Pattern("8.png").similar(0.90).targetOffset(-80,-1),
"loopWaitingTime": 0,
"failResponse" : "Ignore",
"loopTime": 0,
"saveImage" :True }
act = ClickAction(tag = "3",desc=u"左箭头", **arg)
acts.addAction(act)
#act4
arg = { "detectRegion" : gl.R_Screen,
"imagePattern" : Pattern("9.png").similar(0.90).targetOffset(74,0),
"loopWaitingTime": 0,
"failResponse" : "Ignore",
"loopTime": 0,
"saveImage" :True }
act = ClickAction(tag = "4",desc=u"右箭头", **arg)
acts.addAction(act)
|
'''
A collection of classes corresponding to fixed-income securities, to be fed into (and used with)
other classes and methods available in this repository (eg trees.py, Monte Carlo, etc)
'''
class SelfAmortizingMortgage:
def __init__(self, dates=mats6, early=False, rate=5.5 / 100, T=6, N=100):
''' Inputs:
*** early: whether you can prepay the security when it is more advantageous to do so
*** T: when the mortgage expires (maturity, years)
*** N: the face value (dollars)
*** rate: the interest rate paid yearly
*** dates: numpy nd array with the payment dates of the security '''
self.T = T
self.early = early
self.rate = rate
self.dates = dates
# coupon chosen to have value N at time 0, given the mortgage quoted rate
self.coupon = N / sum([(1 / pow(1 + self.rate, i)) for i in range(1, self.T + 1)])
if early:
self._compute_balance(N)
def get_cf(self, t, r, *args, **kwargs):
''' Inputs:
*** t: the current time
*** r: the current interest rate (at that node in the tree)
Outputs:
*** the cash-flow of the security for that (time, interest rate) '''
return self.coupon
def exercise_early(self, current_value, val_if_exercise_early, t, r):
''' Method to say whether you should exercise early or not
Inputs:
*** current_value: the value of the contract at that node, if you do not exercise early
*** t: the current time
*** r: the current interest rate
Returns: TRUE if should exercise early, FALSE otherwise '''
if not self.early:
print('WARNING: this should not be called when the security does not allow for early exercise')
return False
return current_value > val_if_exercise_early
def _compute_balance(self, N):
''' Makes a list with the amount of principal left at every possible moment,
and a list with the interests paid '''
bal_st = [N]
interest = []
princ = []
for i in range(self.T + 1): # for each payment until maturity
interest.append(bal_st[i] * self.rate)
princ.append(self.coupon - interest[i])
if i < self.T:
bal_st.append(bal_st[i] - self.coupon + interest[i])
self.balances = bal_st
self.interest = interest
self.princ = princ
def cf_early_exercise(self, t, r):
''' Gives the payoff if the security is exercised early, at time t, with rate r '''
# When a borrower prepays a mortgage, the borrower pays back the remaining principal on
# the loan, and does not make any of the remaining scheduled payments
return self.balances[t]
def get_raw_cf_mat(self, interest_rate_tree, *args, **kwargs):
''' Inputs:
*** interest_rate_tree: a 2D numpy array with corresponding interest rates in each cell
Returns:
*** the payoff matrix corresponding to the security, a matrix of the same dimension
'''
payoff_mat = np.zeros((interest_rate_tree.shape[0] + 1, interest_rate_tree.shape[0] + 1))
for time in reversed(range(1, payoff_mat.shape[0])):
for node in range(time + 1):
payoff_mat[node, time] = self.get_cf(time, interest_rate_tree[max(node - 1, 0), time - 1],
*args, **kwargs)
return payoff_mat
|
AVG = 70
FUNCTIONS = [
lambda geslacht: 0 if geslacht == 'man' else 4,
lambda rookt: -5 if rookt else 5,
lambda sport: -3 if not sport else sport,
lambda alcohol: 2 if not alcohol else -((alcohol - 7) * 0.5) if alcohol > 7 else 0,
lambda fastfood: 3 if not fastfood else 0,
]
def levensverwachting(geslacht, roker, sport, alcohol, fastfood):
return AVG + sum(func(variable) for (func, variable) in zip(FUNCTIONS, [geslacht, roker, sport, alcohol, fastfood]))
|
class CommentHandlers(object):
def __init__(self):
self.handlers = []
self.comments = {}
def handler(self):
def wrapped(func):
self.register(func)
return func
return wrapped
def register_handler(self, func):
for handler in self.handlers:
print(handler.__name__)
self.handlers.append(func)
def add(self, addr, key, value):
if (addr, key) in self.comments:
self.comments[(addr, key)].append(value)
else:
self.comments[(addr, key)] = [value]
for handler in self.handlers:
handler(addr, key, value)
|
def incrementing_time(start=2000, increment=1):
while True:
yield start
start += increment
def monotonic_time(start=2000):
return incrementing_time(start, increment=0.000001)
def static_time(value):
while True:
yield value
|
"""
Common constants and functions
Markus Konrad <markus.konrad@wzb.eu>
"""
DEFAULT_TOPIC_NAME_FMT = 'topic_{i1}'
DEFAULT_RANK_NAME_FMT = 'rank_{i1}'
|
class Solution:
def reverseBits(self, n: int) -> int:
val = 0
for i in range(32):
val <<= 1
val += n & 1
n >>= 1
return val
|
stages = iter(['alpha','beta','gamma'])
try:
next(stages)
next(stages)
next(stages)
next(stages)
except StopIteration as ex:
err_msg = 'Ran out of iterations'
|
class Payment:
def __init__(self):
pass
def setPayment(self, payment):
Payment.payment = payment
def getPayment(self):
print("Total yang harus dibayarkan Rp. ", Payment.payment)
|
#from pageParser
'''
lines = []
with open('output111.txt', 'rt') as in_file:
for line in in_file:
lines.append(line.rstrip('\n'))
counter = (len(lines))
holder = 0
for element in range(0, counter):
if(lines[holder].find('a') == -1):
print("No A is found")
lines.remove(lines[holder])
holder+=1
print('holder: ', holder)
print('counter: ', counter)
print('Line of code', lines[holder])
print(lines[holder].find('a'))
holder+=1
if(holder > counter):
break
#print(len(soup_string))
#for i in soup_string:
# if soup_string[i] == "<" and soup_string[i+1] == "a":
#print(soup.find_alloutput1
#outputFile = open('output1
##Opens fileoutput1
#with soup as websiteList:
#for line in websiteList:
#for i in range(len(line) - 1, -1, -1):
#if((line[i] == '*') and (line[i-1] == '*')):
#outputFile.write(line[5:i-1] + '\n')
#line = line[5:]
#outputFile.write(line)
#outputFile.close()
# header = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'}
# sb_get = requests.get("https://www.youtube.com", headers = header)
# sb_get.content
# scrape_url="https://www.youtube.com"
### search_url="/results?search_query="
# search_hardcode = "game+of+thrones"
# website_url = scrape_url + search_url + search_hardcode
# sb_get = requests.get(website_url, headers = header)
# sb_get.content
# soupeddata = BeautifulSoup(sb_get.content, "html.parser")
# yt_links = soupeddata.find_all("a", class_ = "yt-uix-tile-link")
#
# for x in yt_links:
# yt_href = x.get("href")
# yt_title = x.get("title")
# yt_final = scrape_url + yt_href
# print(yt_title + '\n' + yt_final + '\n')
#page = requests.get("https://play.hbogo.com/")
#soup = BeautifulSoup(page.content, 'html.parser')
#print(soup.find_all('div'))
#url = 'http://www.growingagreenerworld.com/episode125/'
#with requests.Session() as session:
#session.headers = headers
#response = session.get(url)
#soup = BeautifulSoup(response.content)
#follow the iframe url
#response = session.get('http:' + soup.iframe['src'], headers={'Referer': url})
#soup = BeautifulSoup(response.content)
# extract the video URL from the script tag
# print re.search(r'"url":"(.*?)"', soup.script.text).group(1)
#print(soup.find_all('p'))
'''
"""def findLinks():
halfParsed = []
links = []
lineNum = 1
with open("websiteSource.txt", "r") as sc:
lines = (line.rstrip() for line in sc)
lines = (line for line in lines if line)
for line in enumerate(sc):
line = sc.readline()
if(line.isspace() == True):
continue
else:
halfParsed.append(line)
for element in halfParsed:
foundLinks = re.search(r"https?", element)
if(foundLinks):
links.append(element)
for element in links:
urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', element)
print("********", type(urls))
#for x in urls
goingIn = str(urls)
htmlChecked.add(goingIn)
print(goingIn)"""
|
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
c = x^y
r = 0
while c != 0:
r += (c & 1)
c = c>>1
return r
|
#Faça um Programa que peça dois números e imprima o maior deles.
num1 = int(input("Informe o primeiro numero: "))
num2 = int(input("Informe o segundo numero: "))
if(num1>num2):
print("O maior numero eh %.0f"%num1)
elif(num2>num1):
print("O maior numero eh %.0f"%num2)
else:
print("Os dois numeros tem o mesmo valor %.0f"%num1)
|
v = "vvv"
a = [f"aaa{vvv}"
"bbb"]
print(a)
|
# worst case O(n^2)
# good case O(n)
def insertion_sort(array):
for i in range(1, len(array)):
key = array[i]
j = i -1
while (j>=0 and array[j]>key):
# scoot
array[j+1] = array[j]
j-=1
array[j+1] = key
return array
arr = [3,-9,5, 100,-2, 294,5,56]
sarr = insertion_sort(arr)
print(sarr, sorted(arr))
assert(sarr == sorted(arr))
|
x=int(input("Enter first number:\n"))
y=int(input("Enter second number:\n"))
print("Before swapping:\n",x,"\n",y,"\n")
#Inputting two numbers from user
x,y=y,x
#Swapping two variables
print("After swapping:\n",x,"\n",y,"\n")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.