content stringlengths 7 1.05M |
|---|
def show_sequence(n):
if n == 0:
return '0=0'
elif n < 0:
return '{}<0'.format(n)
return '{} = {}'.format(
'+'.join(str(a) for a in xrange(n + 1)), n * (n + 1) // 2
)
|
class Pool:
__slots__ = ('_value', 'max_value', )
def __init__(self, value, max_value=None):
self._value = 0
value = int(value)
max_value = max_value and int(max_value)
self.max_value = max_value or value
self.value = value
@property
def value(self):
return self._value
@value.setter
def value(self, value):
self._value = max(0, min(value, self.max_value))
def __iadd__(self, value):
self._value += int(value)
return self
def __isub__(self, value):
self._value -= int(value)
return self
def __int__(self):
return self.value
class Attribute:
__slots__ = ('base', 'modifier')
def __init__(self, base, modifier=None):
self.base = base
self.modifier = modifier or 0
@property
def total(self):
return self.base + self.modifier
def __int__(self):
return self.total
|
class ArticleTypeNotAllowed(Exception):
def __init__(self):
super().__init__("403 The article type is not allowed")
|
"""
You are going to be given an array of integers. Your job is to take that array and find an index N
where the sum of the integers to the left of N is equal to the sum of the integers to the right of N.
If there is no index that would make this happen, return -1.
For example:
Let's say you are given the array {1,2,3,4,3,2,1}:
Your function will return the index 3, because at the 3rd position of the array, the sum of left side
of the index ({1,2,3}) and the sum of the right side of the index ({3,2,1}) both equal 6.
Let's look at another one.
You are given the array {1,100,50,-51,1,1}:
Your function will return the index 1, because at the 1st position of the array, the sum of
left side of the index ({1}) and the sum of the right side of the index ({50,-51,1,1}) both equal 1.
Last one:
You are given the array {20,10,-80,10,10,15,35}
At index 0 the left side is {}
The right side is {10,-80,10,10,15,35}
They both are equal to 0 when added. (Empty arrays are equal to 0 in this problem)
Index 0 is the place where the left side and right side are equal.
Note: Please remember that in most programming/scripting languages the index of an array starts at 0.
Input:
An integer array of length 0 < arr < 1000. The numbers in the array can be any integer positive or negative.
Output:
The lowest index N where the side to the left of N is equal to the side to the right of N.
If you do not find an index that fits these rules, then you will return -1.
Note:
If you are given an array with multiple answers, return the lowest correct index.
"""
def find_even_index(arr):
for i in range(len(arr)):
if sum(arr[:i]) == sum(arr[i + 1 :]):
return i
else:
continue
return -1
|
f=open("/home/pirl/darknet/train.txt",'a')
for i in range(1,801):
#data = 'data/green_light/green_light%d.jpg\n' % i
#data = 'data/red_light/ red_light%d.jpg\n' % i
#data = 'data/yellow_light/yellow_light%d.jpg\n' % i
#data = 'data/60_speed/60_speed%d.jpg\n' % i
#data = 'data/30_speed/30_speed%d.jpg\n' % i
#data = 'data/Nright_sign/Nright_sign%d.jpg\n' % i
#data = 'data/right_sign/right_sign%d.jpg\n' % i
f.write(data)
f.close()
|
def aumentar(preço, taxa, formato=False):
res = preço + (preço * taxa/100)
return res if formato is False else moeda(res)
def diminuir(preço, taxa, formato=False):
res = preço - (preço * taxa/100)
return res if formato is False else moeda(res)
def dobro(preço, formato=False):
res = preço * 2
return res if not formato else moeda(res)
def metade(preço, formato=False):
res = preço / 2
return res if not formato else moeda(res)
def moeda(valor, moeda='R$'):
return f'{moeda}{valor:>8.2f}'.replace('.', ',')
|
# -*- coding: utf-8 -*-
class Processador(object):
def __init__(self):
self.processo_em_execucao = None
|
USER_LOCK = []
PROCESS_LOCK = []
def user_lock(userid):
if userid in USER_LOCK: return False
else:
USER_LOCK.append(userid)
return True
def user_unlock(userid):
if userid in USER_LOCK: USER_LOCK.remove(userid)
def user_check(userid):
return userid in USER_LOCK
def process_lock(pid):
if pid in PROCESS_LOCK: return False
else:
PROCESS_LOCK.append(pid)
return True
def process_unlock(pid):
if pid in PROCESS_LOCK: PROCESS_LOCK.remove(pid)
def process_check(pid):
return pid in PROCESS_LOCK
|
#!/usr/bin/env python
# Use local host when running locally
# port = 'localhost:50051'
# Use simple_server_app when running inside docker
port = 'simple_server_app:50051'
streaming_rate = 0.1 |
#!/usr/bin/env python
def reverse(iterable):
"""Reverses the iterable.
Iterate through the collection with two pointers, one increasing from the
beginning of the collection and the other decreasing from the end of the
collection, and swap the items at the respective pointers. Iterations through
the collection are repeated until the pointer that is increasing is no longer
less than the pointer that is decreasing.
* O(n) time complexity
* O(1) space complexity
Args:
iterable: A collection that is iterable.
Raises:
TypeError: If iterable is not iterable.
"""
try:
_ = iter(iterable)
except TypeError:
raise TypeError('\'{}\' object is not iterable'.format(
type(iterable).__name__))
low = 0
high = len(iterable) - 1
while low < high:
iterable[low], iterable[high] = iterable[high], iterable[low]
low += 1
high -= 1
|
# the hardcoded key used in every mozi sample.
MOZI_XOR_KEY = b"\x4e\x66\x5a\x8f\x80\xc8\xac\x23\x8d\xac\x47\x06\xd5\x4f\x6f\x7e"
# the first 4 bytes of the XOR-ed config. It always begins with [ss].
MOZI_CONFIG_HEADER = b"\x15\x15\x29\xd2" # b"[ss]" ^ XOR_KEY[:4]
# the size of the Mozi config string
MOZI_CONFIG_TOTAL_SIZE = 524
# the size of the actual Mozi config
MOZI_CONFIG_SIZE = 428
# the first ECDSA384 signature, xored
MOZI_SIGNATURE_A = \
b"\x4C\xB3\x8F\x68\xC1\x26\x70\xEB\
\x9D\xC1\x68\x4E\xD8\x4B\x7D\x5F\
\x69\x5F\x9D\xCA\x8D\xE2\x7D\x63\
\xFF\xAD\x96\x8D\x18\x8B\x79\x1B\
\x38\x31\x9B\x12\x69\x73\xA9\x2E\
\xB6\x63\x29\x76\xAC\x2F\x9E\x94\xA1"
# the second ECDSA384 signature, xored
MOZI_SIGNATURE_B = \
b"\x4C\xA6\xFB\xCC\xF8\x9B\x12\x1F\
\x49\x64\x4D\x2F\x3C\x17\xD0\xB8\
\xE9\x7D\x24\x24\xF2\xDD\xB1\x47\
\xE9\x34\xD2\xC2\xBF\x07\xAC\x53\
\x22\x5F\xD8\x92\xFE\xED\x5F\xA3\
\xC9\x5B\x6A\x16\xBE\x84\x40\x77\x88"
# the magic UPX number that marks UPX data within the executable.
UPX_MAGIC = b"UPX!"
# name and size in bytes of the upx checksum
UPX_CHECKSUM = ("l_checksum", 4)
# name and size in bytes of the upx magic number
UPX_MAGIC_SIZE = ("l_magic", 4)
# name and size in bytes of the l_lsize field
UPX_LSIZE = ("l_lsize", 2)
# name and size in bytes of the l_version field
UPX_LVERSION = ("l_version", 1)
# name and size in bytes of the l_format field
UPX_LFORMAT = ("l_format", 1)
# name and size in bytes of the p_progid field
UPX_PPROGID = ("p_progid", 4)
# name and size in bytes of the p_filesize field
UPX_PFILESIZE = ("p_filesize", 4)
# name and size in bytes of the p_blocksize field
UPX_PBLOCKSIZE = ("p_blocksize", 4)
# the offset from the UPX trailer magic number to read the data from
# 6 doublewords (4 bytes) away from the start of the magic number
UPX_TRAILER_OFFSET = 6 * 4
# (name, has_suffix) e.g. [ss], [/ss]
# taken from https://blog.netlab.360.com/mozi-another-botnet-using-dht/
CONFIG_FIELDS = {
# declaration
"ss" : "bot role",
"cpu" : "cpu arch",
"nd" : "new DHT node",
"count" : "url to report to",
# control
"atk" : "ddos attack type",
"ver" : "verify",
"sv" : "update config",
"hp" : "DHT id prefix",
"dip" : "address to get new sample",
# subtasks
"dr" : "download and exec payload",
"ud" : "update bot",
"rn" : "execute command",
"idp" : "report bot info", # bot id, ip, port, file name, gateway, cpu arch
}
DHT_BOOTSTRAP_NODES = [
"dht.transmissionbt.com:6881",
"router.bittorrent.com:6881",
"router.utorrent.com:6881",
"bttracker.debian.org:6881",
"212.129.33.59:6881",
"82.221.103.244:6881",
"130.239.18.159:6881",
"87.98.162.88:6881",
] |
#!/usr/bin/python3
# maximizing_xor.py
# Author : Rajat Mhetre
# follow and drop me a line at @rajat_mhetre
def max_xor(l,r):
return max(x^y for x in range(l,r+1) for y in range(l,r+1))
if __name__ == '__main__':
l = int(input())
r = int(input())
print(max_xor(l,r))
|
def main():
combined_rect = set()
overlapped_rect = set()
f = open("input")
lines = f.readlines()
for line in lines:
id_, x, y, size_x, size_y = parse(line)
for coord in generate_coord(x, y, size_x, size_y):
if coord in combined_rect:
overlapped_rect.add(coord)
combined_rect.add(coord)
for line in lines:
id_, x, y, size_x, size_y = parse(line)
temp = set()
for coord in generate_coord(x, y, size_x, size_y):
temp.add(coord)
t = temp.intersection(overlapped_rect)
if not t:
print(id_)
def parse(line):
id_, _, start_point, size = line.split()
x, y = start_point.split(",")
y = y[:-1]
size_x, size_y = size.split("x")
return id_, int(x), int(y), int(size_x), int(size_y)
def generate_coord(x, y, size_x, size_y):
for x_ in range(x, x + size_x):
for y_ in range(y, y + size_y):
yield (x_, y_)
if __name__ == "__main__":
main()
|
class B(object):
b:int =1
a:int =1
d:int =1
class C(object):
c:int =1
class A(B):
a:int = 1 #attr redefined in B
b:int = 1 #attr redefined in B
# this declaration will be ignore
class A(C):
a:int = 1 #ok,check attr in C
c:int = 1 #attr redefined
class D(A):
a:int = 1 #attr redefined
b:int = 1 #attr redefined
c:int = 1 #no problem
d:int = 1 #attr redefined in B |
"""
ARGENTINA:
Estos datos son públicos generados, guardados y publicados por organismos de gobierno de la República Argentina.
Referencia: http://datos.salud.gob.ar/dataset
"""
URLS = {
'ar': {
'llamadas_107': 'https://cdn.buenosaires.gob.ar/datosabiertos/datasets/salud/llamados-107-covid/llamados_107_covid.csv',
'dosis': {
'acumulado': {
'primera': 'https://sisa.msal.gov.ar/datos/descargas/covid-19/files/covid_1raDosis_acumulado.csv',
'segunda': 'https://sisa.msal.gov.ar/datos/descargas/covid-19/files/covid_2daDosis_acumulado.csv',
'total': 'https://sisa.msal.gov.ar/datos/descargas/covid-19/files/covid_total_acumulado.csv'
},
'diario': {
'primera': 'https://sisa.msal.gov.ar/datos/descargas/covid-19/files/covid_1raDosis_diario.csv',
'segunda': 'https://sisa.msal.gov.ar/datos/descargas/covid-19/files/covid_2daDosis_diario.csv',
'total': 'https://sisa.msal.gov.ar/datos/descargas/covid-19/files/covid_total_diario.csv'
}
},
'confirmados': 'https://raw.githubusercontent.com/manucabral/Codavi/main/reportes/confirmados.csv',
'fallecidos': 'https://raw.githubusercontent.com/manucabral/Codavi/main/reportes/fallecidos.csv',
'vacunas' : 'https://sisa.msal.gov.ar/datos/descargas/covid-19/files/Covid19VacunasAgrupadas.csv.zip',
},
'chl': {
'vacunas_aplicadas': 'https://raw.githubusercontent.com/MinCiencia/Datos-COVID19/master/output/producto76/vacunacion_t.csv'
}
}
FILTROS = {
'sexo': {
'm': 2,
'f': 3,
'todos': 1
},
'dosis': {
'unica': 'dosis_unica_cantidad',
'primera': 'primera_dosis_cantidad',
'segunda': 'segunda_dosis_cantidad',
'adicional': 'dosis_adicional_cantidad',
'refuerzo': 'dosis_refuerzo_cantidad'
}
}
MES = {
1: 'JAN',
2: 'FEB',
3: 'MAR',
4: 'APR',
5: 'MAY',
6: 'JUN',
7: 'JUL',
8: 'AUG',
9: 'SEP',
10: 'OCT',
11: 'NOV',
12: 'DEC'
}
|
class Solution:
# O(n) time | O(n) space
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
if n <= 1: return 0
diff = [prices[i+1] - prices[i] for i in range(n-1)]
dp, dp_max = [0]*(n + 1), [0]*(n + 1)
for i in range(n-1):
dp[i] = diff[i] + max(dp_max[i-3], dp[i-1])
dp_max[i] = max(dp_max[i-1], dp[i])
return dp_max[-3] |
# 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 findTarget(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: bool
"""
s = set([])
return self.dfs(root, s, k)
def dfs (self, root, set, target):
if not root:
return False
if target-root.val in set:
return True
set.add(root.val)
return self.dfs(root.left, set, target) or self.dfs(root.right,set, target)
|
# Importação de bibliotecas
# Título do programa
print('\033[1;34;40mSOMA ÍMPARES MÚLTIPLOS DE TRÊS\033[m')
# Objetos
s = 0
# Lógica
for c in range(1, 500, 2):
if c % 3 == 0:
s = s + c
print('A somatória de todos os números ímpares múltiplos de 3 entre 1 e 500 é \033[4;34m{}\033[m'.format(s)) |
#coding=utf-8
# email
smtp_server = "smtp.exmail.qq.com"
from_addr = "test@qq.com"
mail_username = "test2@qq.com"
mail_password = "admin"
mail_port = 465
# sms
SmsUrl = ""
SmsPath = ""
AppCode = ""
SignName = "" |
#
# PySNMP MIB module ChrComPmSonetSNT-P-Day-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ChrComPmSonetSNT-P-Day-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:20:38 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, ConstraintsIntersection, SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint")
chrComIfifIndex, = mibBuilder.importSymbols("ChrComIfifTable-MIB", "chrComIfifIndex")
TruthValue, = mibBuilder.importSymbols("ChrTyp-MIB", "TruthValue")
chrComPmSonet, = mibBuilder.importSymbols("Chromatis-MIB", "chrComPmSonet")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, Integer32, iso, TimeTicks, Bits, IpAddress, ObjectIdentity, Unsigned32, ModuleIdentity, MibIdentifier, Gauge32, Counter64, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Integer32", "iso", "TimeTicks", "Bits", "IpAddress", "ObjectIdentity", "Unsigned32", "ModuleIdentity", "MibIdentifier", "Gauge32", "Counter64", "Counter32")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
chrComPmSonetSNT_P_DayTable = MibTable((1, 3, 6, 1, 4, 1, 3695, 1, 10, 2, 12), ).setLabel("chrComPmSonetSNT-P-DayTable")
if mibBuilder.loadTexts: chrComPmSonetSNT_P_DayTable.setStatus('current')
chrComPmSonetSNT_P_DayEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3695, 1, 10, 2, 12, 1), ).setLabel("chrComPmSonetSNT-P-DayEntry").setIndexNames((0, "ChrComIfifTable-MIB", "chrComIfifIndex"), (0, "ChrComPmSonetSNT-P-Day-MIB", "chrComPmSonetDayNumber"))
if mibBuilder.loadTexts: chrComPmSonetSNT_P_DayEntry.setStatus('current')
chrComPmSonetDayNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 3695, 1, 10, 2, 12, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 2))).setMaxAccess("readonly")
if mibBuilder.loadTexts: chrComPmSonetDayNumber.setStatus('current')
chrComPmSonetSuspectedInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 3695, 1, 10, 2, 12, 1, 2), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: chrComPmSonetSuspectedInterval.setStatus('current')
chrComPmSonetElapsedTime = MibTableColumn((1, 3, 6, 1, 4, 1, 3695, 1, 10, 2, 12, 1, 3), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setMaxAccess("readonly")
if mibBuilder.loadTexts: chrComPmSonetElapsedTime.setStatus('current')
chrComPmSonetSuppressedIntrvls = MibTableColumn((1, 3, 6, 1, 4, 1, 3695, 1, 10, 2, 12, 1, 4), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setMaxAccess("readonly")
if mibBuilder.loadTexts: chrComPmSonetSuppressedIntrvls.setStatus('current')
chrComPmSonetES = MibTableColumn((1, 3, 6, 1, 4, 1, 3695, 1, 10, 2, 12, 1, 5), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setMaxAccess("readonly")
if mibBuilder.loadTexts: chrComPmSonetES.setStatus('current')
chrComPmSonetSES = MibTableColumn((1, 3, 6, 1, 4, 1, 3695, 1, 10, 2, 12, 1, 6), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setMaxAccess("readonly")
if mibBuilder.loadTexts: chrComPmSonetSES.setStatus('current')
chrComPmSonetCV = MibTableColumn((1, 3, 6, 1, 4, 1, 3695, 1, 10, 2, 12, 1, 7), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setMaxAccess("readonly")
if mibBuilder.loadTexts: chrComPmSonetCV.setStatus('current')
chrComPmSonetUAS = MibTableColumn((1, 3, 6, 1, 4, 1, 3695, 1, 10, 2, 12, 1, 8), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setMaxAccess("readonly")
if mibBuilder.loadTexts: chrComPmSonetUAS.setStatus('current')
chrComPmSonetPS = MibTableColumn((1, 3, 6, 1, 4, 1, 3695, 1, 10, 2, 12, 1, 9), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setMaxAccess("readonly")
if mibBuilder.loadTexts: chrComPmSonetPS.setStatus('current')
chrComPmSonetThresholdProfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3695, 1, 10, 2, 12, 1, 10), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setMaxAccess("readonly")
if mibBuilder.loadTexts: chrComPmSonetThresholdProfIndex.setStatus('current')
chrComPmSonetResetPmCountersAction = MibTableColumn((1, 3, 6, 1, 4, 1, 3695, 1, 10, 2, 12, 1, 11), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: chrComPmSonetResetPmCountersAction.setStatus('current')
mibBuilder.exportSymbols("ChrComPmSonetSNT-P-Day-MIB", chrComPmSonetSNT_P_DayTable=chrComPmSonetSNT_P_DayTable, chrComPmSonetResetPmCountersAction=chrComPmSonetResetPmCountersAction, chrComPmSonetThresholdProfIndex=chrComPmSonetThresholdProfIndex, chrComPmSonetES=chrComPmSonetES, chrComPmSonetPS=chrComPmSonetPS, chrComPmSonetSNT_P_DayEntry=chrComPmSonetSNT_P_DayEntry, chrComPmSonetSuppressedIntrvls=chrComPmSonetSuppressedIntrvls, chrComPmSonetElapsedTime=chrComPmSonetElapsedTime, chrComPmSonetDayNumber=chrComPmSonetDayNumber, chrComPmSonetSuspectedInterval=chrComPmSonetSuspectedInterval, chrComPmSonetCV=chrComPmSonetCV, chrComPmSonetSES=chrComPmSonetSES, chrComPmSonetUAS=chrComPmSonetUAS)
|
#Class Inheritance
#Feline class
class Feline:
def __init__(self,name):
self.name = name
print('Creating a feline')
def meow(self):
print(f'{self.name}: meow')
def setName(self, name):
print(f'{self} setting name: {name}')
self.name = name
#Lion class
class Lion(Feline):
def roar(self):
print(f'{self.name} roar')
#Tiger class
class Tiger(Feline):
#override the contructor is a BAD idea
def __init__(self):
#Super alows is to access the parent
#if we forget this we will have a bad time later
super().__init__('No Name')
print('Creating a tiger')
def stalk(self):
#have to make sure name is set in the parent
#this is considered -LBYL (look before you leap)
#here we are dynamically adding the attribute
#If we did not init the super we will have to be careful
#if not hasattr(self,'name'): super().setName('No Name')
print(f'{self.name}: stalking')
def rename(self,name):
super().setName(name)
c = Feline('kitty')
print(c)
c.meow()
l = Lion('Leo')
print(l)
l.meow()
l.roar()
t = Tiger() #is a Feline, but with a different constructor
print(t)
t.stalk()
t.rename('Tony')
t.meow()
t.stalk() |
#snapshot parameters
snapshot_num = 77
galaxy_num = 0
galaxy_num_str = str(galaxy_num)
snapnum_str = '{:03d}'.format(snapshot_num)
hydro_dir = '/orange/narayanan/desika.narayanan/gizmo_runs/simba/m12_n256_active_boxes/output_m12n256_7/'
snapshot_name = 'snapshot_'+snapnum_str+'.hdf5'
#where the files should go
PD_output_dir = '/home/desika.narayanan/pd_git/tests/SKIRT/m12_extinction/'
Auto_TF_file = 'snap'+snapnum_str+'.logical'
Auto_dustdens_file = 'snap'+snapnum_str+'.dustdens'
#===============================================
#FILE I/O
#===============================================
inputfile = PD_output_dir+'/pd_skirt_comparison.'+snapnum_str+'.rtin'
outputfile = PD_output_dir+'/pd_skirt_comparison.'+snapnum_str+'.rtout'
#===============================================
#GRID POSITIONS
#===============================================
#x_cent=7791.04289063
#y_cent=11030.12925781
#z_cent=4567.8734375
x_cent = 5527.42349609
y_cent = 4680.46623047
z_cent = 10704.73
#x_cent = 5.00925088e+03
#y_cent = 1.22012878e+04
#z_cent = 8.88592731e+00
#x_cent = 10898.06515625
#y_cent = 10868.67308594
#z_cent = 4419.96082031
#===============================================
#CMB
#===============================================
TCMB = 2.73
|
'''
Projeto: Primeiro e último nome de uma pessoa
'''
name = input('Digite seu nome completo: ').strip().split()
print('Muito prezer em te conhecer!')
print('Seu primeiro nome é {}'.format(name[0]))
print('Seu último nome é {}'.format(name[-1])) |
class Solution:
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
ret = []
candidates.sort()
def traverse(pos, tmp, left):
nonlocal candidates, ret
if left < 0:
return
if left == 0:
ret.append(tmp)
for i in range(len(candidates)):
if i < pos:
continue
traverse(i, tmp + [candidates[i]], left - candidates[i])
traverse(0, [], target)
return ret
|
#!/usr/bin/env python3
################################################################
# From an imported list, this will sort and return a string
# pg 202
################################################################
def alphalist( orginal_list=[] ):
# Create working copy of list passed in
sorted_list = orginal_list.copy()
sorted_list.sort()
final_list = ''
for name in sorted_list:
final_list += name + ', '
# strip the ending comma and space
final_list = final_list[:-2]
# To return a list instead of a string, uncomment these lines and comment out the original return statement
# new_list = []
# splitOrig = final_list.split(', ')
# for item in splitOrig:
# new_list.append(item)
# return new_list
return final_list
# Call function
list = [ 'a', 'q', 'b']
new_list = alphalist(list)
print(new_list)
print('new list type = ')
print(type(new_list))
# preferred, single line
print('new list type = ',end='')
print(type(new_list))
|
# -*- coding: utf-8 -*-
class Numbers:
def __init__(self, dct):
self.date = dct["date"]
self.numbers = dct["balls"]
self.stars = dct["stars"]
self.draw = dct["draw"]
def factory(dct):
return Numbers(dct)
def __repr__(self):
return f"date: {self.date}, draw: {self.draw}, numbers: {self.numbers}, stars: {self.stars}"
|
# class Meta(type):
# def __new__(mcs, name, bases, namespace):
# if name == 'A':
# return type.__new__(mcs, name, bases, namespace)
#
# if 'b_fala' not in namespace:
# print(f'Oi, você precisa criar o metodo b_fala em {name}')
# else:
# if not callable(namespace['b_fala']):
# print(f'b_fala precisa ser um metodo, não atributo em {name}.')
# return type.__new__(mcs, name, bases, namespace)
# class A(metaclass=Meta):
# def fala(self):
# self.b_fala()
#
#
# class B(A):
# def b_fala(self):
# print('oi')
#
#
# b = B()
# Outro codigo com esse codigo apaga o codigo que ia rescrever o codigo
# class Meta(type):
# def __new__(mcs, name, bases, namespace):
# if name == 'A':
# return type.__new__(mcs, name, bases, namespace)
# if 'attr_classe' in namespace:
# print(f'{name} tentou sobrescrever o atributo.')
# del namespace['attr_classe']
# return type.__new__(mcs, name, bases, namespace)
#
#
# class A(metaclass=Meta):
# attr_classe = 'Valor A'
#
#
# class B(A):
# attr_classe = 'Valor B'
#
#
# class C(B):
# attr_classe = 'Valor C'
#
#
# b = B()
# print(b.attr_classe)
# Jeito mais abreviado de fazer
class Pai:
nome = 'teste'
A = type('A', (Pai, ), {'attr': 'Olá Mundo!'})
a = A()
print(a.attr)
print(type(a.nome)) |
# MIT License
# Copyright (c) 2021 David Rice
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
Media Player and Announcement Board
Classes related to announcements
https://github.com/davidsmakerworks/media-display
TODO: Move announcement parsing to Announcement class
TODO: Better format to store announcements(?)
"""
class AnnouncementLine:
"""
Class representing one line of an announcement after it has
been parsed from JSON file
Properties:
text -- text of the line, or None if it is a blank line
size -- size of text or height of the blank line
color -- text color as a PyGame color object
center -- determines if line should be centered on the screen
"""
def __init__(self, text=None, size=0, color=None, center=False):
self.text = text
self.size = size
self.color = color
self.center = center
class Announcement:
"""
Class representing an announcement after it has been parsed from the
JSON file.
Properties:
start_date -- earliest date to show announcement
end_date -- latest date to show announcement
lines -- list of AnnouncementLine objects representing the individual
lines of the announcement
"""
def __init__(self, start_date, end_date, lines=None):
self.start_date = start_date
self.end_date = end_date
if lines:
self.lines = lines
else:
self.lines = []
if __name__ == '__main__':
print('This file should not be run directly. Run main.py instead.') |
#!/usr/bin/env python3
"""
This code is under Apache License 2.0
Written by B_Gameiro (Bernardo Bernardino Gameiro)
More in
SoloLearn: https://www.sololearn.com/Profile/8198571
GitHub: https://github.com/BGameiro76
Repl.it: https://repl.it/@B_Gameiro
Program display help menu
GUI in Python 3
Using Tkinter
"""
#======================
# Strings to use with the messages
#======================
Title = "Media Organizer GUI Help"
Message = "This app has the purpose of allowing the user to quickly access any app to display the different kinds of media in the computer." |
# Copyright 2017 mgIT GmbH All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Defines a rule for automatically updating deb_packages repository rules."""
_script_content = """
BASE=$(pwd)
WORKSPACE=$(dirname $(readlink WORKSPACE))
cd "$WORKSPACE"
$BASE/{update_deb_packages} {args} $@
"""
def _update_deb_packages_script_impl(ctx):
args = ctx.attr.args + ["--pgp-key=\"" + f.path + "\"" for f in ctx.files.pgp_keys] + ctx.attr.bzl_files
script_content = _script_content.format(update_deb_packages = ctx.file.update_deb_packages_exec.short_path, args = " ".join(args))
script_file = ctx.actions.declare_file(ctx.label.name + ".bash")
ctx.actions.write(script_file, script_content, True)
return [DefaultInfo(
files = depset([script_file]),
runfiles = ctx.runfiles([ctx.file.update_deb_packages_exec]),
executable = script_file,
)]
_update_deb_packages_script = rule(
_update_deb_packages_script_impl,
attrs = {
"args": attr.string_list(),
"bzl_files": attr.string_list(),
"pgp_keys": attr.label_list(),
"update_deb_packages_exec": attr.label(
allow_single_file = True,
executable = True,
cfg = "host",
),
},
)
def update_deb_packages(name, pgp_keys, **kwargs):
script_name = name + "_script"
_update_deb_packages_script(
name = script_name,
tags = ["manual"],
pgp_keys = pgp_keys,
update_deb_packages_exec = select({
"@bazel_tools//src/conditions:linux_aarch64": Label("@update_deb_packages_linux_arm64//file"),
"@bazel_tools//src/conditions:linux_x86_64": Label("@update_deb_packages_linux_amd64//file"),
"@bazel_tools//src/conditions:windows": Label("@update_deb_packages_windows_amd64//file"),
"@bazel_tools//src/conditions:darwin_x86_64": Label("@update_deb_packages_darwin_amd64//file"),
}),
**kwargs
)
native.sh_binary(
name = name,
srcs = [script_name],
data = ["//:WORKSPACE"] + pgp_keys,
tags = ["manual"],
)
|
#!/usr/bin/env python3
# creates a function add_one() from the lambda x: x + 1
add_one = lambda x: x + 1
print(add_one(2))
|
__all__ = ["is_private", "Mirror"]
def is_private(attribute):
"""Return whether an attribute is private."""
return attribute.startswith("_")
class Mirror:
"""Class to access attributes via reflection.
:param hide_private: do not include private (according to
:any:`is_private`) attributes when reflecting attributes. Default is
`True`.
:param top_down: if `True`, reflect classes from top (most base, usually
:any:`object`) to bottom (most derived, i.e., the type of the
instance); otherwise from bottom to top. Default is `True` (top to
bottom).
"""
def __init__(self, hide_private=True, top_down=True):
self.hide_private = hide_private
self.top_down = top_down
def reflect_classes(self, instance):
"""Return all classes in the method resolution order (MRO) for the
given instance's type.
:param instance: the object whose classes should be reflected
"""
classes_bottom_up = type(instance).__mro__
if not self.top_down:
return classes_bottom_up
return reversed(classes_bottom_up)
def reflect_attributes(self, instance):
"""Return all visible attributes of the given instance.
:param instance: the object whose attributes should be reflected
"""
attributes = []
for klass in self.reflect_classes(instance):
slots = klass.__dict__.get("__slots__", None)
if slots is not None:
attributes.extend(
attribute
for attribute in self._filter_private_attributes(slots)
if hasattr(instance, attribute)
)
if hasattr(instance, "__dict__"):
attributes.extend(self._filter_private_attributes(instance.__dict__.keys()))
return attributes
def _filter_private_attributes(self, candidate_attributes):
if not self.hide_private:
return candidate_attributes
return (
attribute for attribute in candidate_attributes if not is_private(attribute)
)
def __repr__(self):
# No easy way to get EasyRepr in here. "I guide others to a treasure I
# cannot possess."
return f"Mirror(skip_private={self.hide_private}, top_down={self.top_down})"
|
#!/usr/bin/python
# SPDX-License-Identifier: MIT
with open("input", "r") as file:
depths = list(map(int, file))
differences = [j - i for i, j in zip(depths[:-1], depths[1:])]
increases = len([i for i in differences if i > 0])
print(f"number of depth increases: {increases}")
|
s = input()
while len(s) > 10:
print(s[0:10], end='\n')
s = s[10:]
if len(s) != 0:
print(s)
# Reference: https://cleancode-ws.tistory.com/60
"""
s = input()
for i in range(0, len(s), 10):
print(s[i: i+10])
""" |
"""Escreva um programa que leia a velocidade de um carro. Se ele ultrapassar 80Km/h, mostre uma mensagem dizendo
que ele foi multado. A multa vai custar R$7,00 por cada Km acima do limite."""
velocidade = float(input('Qual foi a velocidade do carro em Km/h? '))
if velocidade > 80:
print('\033[31mVocê ultrapassou o limite de velocidade e foi MULTADO\033[m. \033[33mO valor da multa é de R${:.2f}\033[m'.format((velocidade-80)*7))
else:
print('Você não ultrapassou o limite. Continue assim!')
|
cavemap_raw = """4323999434356678989012399854245901359876432101298901239876569892012345896567996545678912345689998921
6319898921234589878923987653129892349989949212347892398765498765423456789469884326789923468998997890
5498767892945678967899876543256789998999898943456789987654329878534567994398765434567894579997876789
7598756789896789656799988654347897897898787899969894198969210989675679865789987645678965989986845678
9987642356789995345789999767658966956987676987898943019898921299789789989898998759789996899895434567
8765421234597893234567899878979654645696545545787892198797993459895995797967439867899989998756523456
9873210123456789145978967989989743234985432123456953987676889567994379976543123978969878987643212677
8654321234599891059899656196899820189876541034567999876545678978989457898991034989454569899876543467
8765432346789932129789543245698721278987632175679789985434899299879768909989549994323798789997654578
9876543459999943398656959366797632368999543286789679876545789349768979219978998943212345695498765679
8987654567899854987847898997987543456987655399896598987656999998657894398769876543101456789329876789
7998766678998769876236987789998787567898867899989467898789679876546796987654989654212567893210989894
6879878789439898765134896578999898678999978999876347999892498765435689996543498765323989964348994943
5667989894323949873256789459899969989799989298765276789901999976523499989432369878554899979767893212
4456998976210239954367892365797654395689990198754345890199898765434678978943458987675789989989989103
3347897654321298765458921234998753234567891259869656789989729879656789567954667898789895698794567924
2256998985434349999567890147899432145678942345998969999877610998789893457895978989899924997643457895
0197899876579569878998921356987553269789653496987898998765431239898921238989989876968999876432346796
1989921989698998767889432387898769998997654989976767999865432378997632345678998765656789997321245989
9879899998997897658978943499949898787898769878765657892976543456796543458989987654245894395460349878
8768778987986986546569765678934987656789898765454345991097694567987654567999998742134589987651298766
7656567996765987432458979899929876545689997654343234789198989798998785688958999821023678987542987654
8543457895454599543567898987898965432398789543210123678999978989109898799767898762124589998963499763
7432568976323987654678987896587898751987678954621234567899868878998969899878987654355678999654598754
6563678996454598785789876543456789899896567976542545689988759767897653978989698776456789498775679876
7674569987887679899899998954587893998765456897678766789977648956789792368994569897568992349896789987
8789678998998799987978989899998941987654347998989877899866537845678989457893556998989641239987896599
9996989469239899976567976798889432398743257789995989999654326534989878968942445989899932398998965456
9765794345999998655456985697778943469854345679954197898765410129798956899321239876787899497899999999
7654654239878899543257894986567954567965466789893246799987654397657645965490399865676798976789987878
6543210198768789954145993214456895699876587898789345678998766498543237896989988754545987545698986767
7659323498756567893239872102345696989987679987678956989999987987632126789879876543234985434767895456
8798944987643476789398765213456989878998793236567897899897899876543245998765987656129876323456789346
9997955698652345679459854323469878767899892105478898998766976987654346789654598761034987654979893234
9986896789821239896567967469598765457894999212345789999845275698766457896543469878236798899897992123
8875989899843345798999897578999854346795698923458897898732154569899598987674878989345899988756789634
7654678998764466989987789989899965234896987894567976987621013456987699698765999999456999879645899546
8463567899876577978996578898659894365689876789678965496434154789998789549896899898767898766434578957
4322456799988789467986459789548789456790245678989654398645865699899899932987998789998999654323467898
3210345989999891239874345678937578968921576789998763219856776789799999891098997656569998765634678959
4421299876789999498763234589425467899432347999899865498987887895679998789129986543467949976545689646
5542989665678998987654345678912348997543598998799986597898998954598987679298765432599234987898795431
6743976564567796598765466789323556789954689898678999986569899323987896567999877653789345698939894310
7769865433475689439876578895434667899899797654589998777476789012396543457899998789898959899323965621
9898764321234678912987889976545978998798976543478997654365692126597632349789109898967898989459875432
6969875430345799323498998797667899457657897652367898743234589987698721234589299987654987678998998745
5456989561256789534679967698799954312445679721458999892123678999899830145678989976543498899897897656
3237898762347897645789854549899543101239998932369898989294569767998764234889679885432459998786789767
6545679654456798789999753234997653212398887893456797679989678955349854345796598754101345987675679878
7656799765767899899899875123989964329987676799569986568678989844239965566897399543212659976564568999
8767949879878999956798765234567895498766565688998765454567897632198987677979987674353598989323656789
9878933989999997345987654347978987987657474567899864323456789543987798789657898765674987643212347898
2989212399899976499899765456789598999843323456798543412345897689976579896546989978786799532101234567
1099923456789897988769896567893459988732012347987632101276889798865456965435678989897899744312345678
2989894569898789876553987878932349876543123457898543242345678997655329876323468996998998765423456899
9878789678987678965432398989321956987654234567998765953456889896543212965414567895469999876536567893
8767679789876569896543459999939897899776876678929878767967996795432109876525678994356987987897678954
7654568998965456789654597899898789999897898789213989879979645689643234987987989789249876598998989865
6543457976434345678969986789787678989969959892102398998796534679865359898998995678998765459789999986
7532369865421237789998995897678459876553345943234567895679845989877899789999434567897654345678998987
8643456976510175893987654589541234985432237899765678954598759992989987678985326789999543256899987799
9754567984323234992199867678920349894321018989887899943698767921399976569876434697698954387929876545
9965678999654345689023978789321298765732147678998999892349878992349989678998556789567895998934984334
9896789698765456795434989897632349876654234567899998789759989789498798789987667898488976789949893213
8789996539876568976765699976543456987769645778998987698998795678997629899998979987569987899898789323
8678789623987878989876789987656567898998756789987654597899654578987510949879989097698998987678678934
6577678910198989099987899999878978999459867897898769986898943139995421234569992198987989766534567965
5464569923239099198798978987989989989234978976789898765567892098986532345678943469876878954323588976
6323467894549198999659767896590195678949899965878987653467894987987645456799654979765767893212789987
7467878995698987888943656987321234789998799894569876542345695986799656777898769898954456794325678999
9878989789987656567892346895499995894987676789678984321237989875678967888959998767893345689634789343
9989795678976545456789498976987889963298545798789995452345678964569898999543989656921239796545895212
8799654345987432367898569299876978954987656789896976563456789543456789212959876967892398987656954101
5698743239874321298987694398765767896799767899965698754689897632345898909899765898993987898787893212
8789842198765453456998789987654656789899879999854569869793998943458967898798654789989796789898965337
9898651019976764567899899876553234899999998999763579878892349894967898987698765678979655679929598656
8999532124987989678921999765454123689998987688932389989921498789898999876549876799768443458913459767
7987693535698998799210198754321014599997698567893499995210988679789498765434987897654312367904599898
6298989545679129898921239895932135679876542348954569874329876565699349954323698998766423778912989989
5129878996989098987892398989893234598765430567895678965498765434598998766464569239976534567899878879
4298767789998997645789997868689395987654321789989789876989954323457979887575698999988785678998767656
9987656679987673234669876546578989998865439896578999989879765545568967998786987989999876799987654343
8764346567895432123456987432446678969976546965456789998769877696678957899899876878913987891098765212
9843213457897641012349996551234569655987697892347999879656989987889345679999985467899999942139876909
9874326567999973253598987767897678934598788901256789765345699898998956798798754376788987659245989898
8765534567899654345696598988969789012479999432346789654236987649567897897649654234567898798967998767
9876645678958987656985459199459892123467987656759896543129876533456789986539867545678989987899879756
1989856789767898769874321012389943234568998767867987321013976512356899876621998656789679876789769845
0198967899878959998765453125678974345899459898978998534123497301245798765433498767896567965398654976
1987698901999239879876875234569865456789345949989987643294989212398999879754699878965459876797743988
9876569892999398767987864345678976567899276932994398784989978934567891989876789999894323987896532399
8765456789878999856998875457899987679998999899875999899876867897678910199997890123789412398965321246
9984345898768897645879987568999998793467989799989899988965456998989329988998943235694325499984210123
9765457987656789734567898979998879912399865689998789877652347899395498977899876545789434989875331234
9876569876545678923456789989987762101987754679987698768341236789219987656789998756789649878989445678
8997699997656789212345898795496543212976763567896549854210145678997697545899989867899998767898986789
7698989698767892101256987656398654323965432356789430969321234567976543234878978998999894854567997891
3569876569898976412345896546239876579876321245695321298763367898965432123458965459998763213458998942
2345965412969994324456789634123998689988432357976763497654456999976543234567898567987654101556789543
0156976323456789534567994321014569795499543568987954698767767894397654545798987678996543232345678954"""
cavemap_raw_example = """2199943210
3987894921
9856789892
8767896789
9899965678"""
cavemap = list(map(lambda line: list(map(int, list(line))), cavemap_raw.splitlines()))
height = len(cavemap)
width = len(cavemap[0])
total_risk_level = 0
basin_sizes = []
def get_basin(y, x, known_basin):
search_space = [(y, x)]
while len(search_space) > 0:
(y,x) = search_space.pop()
if y < 0 or y == height or x < 0 or x == width:
continue
# Add everything to search space that isn't already in the basin and is higher than this point.
for (candidate_y, candidate_x) in [(y-1, x), (y+1, x), (y, x-1), (y, x+1)]:
if candidate_y >= 0 and candidate_y < height and candidate_x >= 0 and candidate_x < width:
if cavemap[candidate_y][candidate_x] != 9 and cavemap[y][x] < cavemap[candidate_y][candidate_x]:
if (candidate_y, candidate_x) not in known_basin:
search_space.append((candidate_y, candidate_x))
known_basin.add((y,x))
return known_basin
for y in range(0, height):
for x in range (0, width):
if ((y == 0 or cavemap[y-1][x] > cavemap[y][x])
and (y == height - 1 or cavemap[y+1][x] > cavemap[y][x])
and (x == 0 or cavemap[y][x-1] > cavemap[y][x])
and (x == width - 1 or cavemap[y][x+1] > cavemap[y][x])):
# This is a low point
basin_sizes.append(len(get_basin(y, x, {(y,x)})))
total_risk_level += 1 + cavemap[y][x]
print(total_risk_level)
print(sorted(basin_sizes))
# I plugged the last three into a calculator lol |
"""Clean Code in Python - Chapter 3: General Traits of Good Code
> Packing / unpacking
"""
USERS = [(i, f"first_name_{i}", f"last_name_{i}") for i in range(1_000)]
class User:
"""
>>> jsmith = User(1, "John", "Smith")
>>> repr(jsmith)
"User(1, 'John', 'Smith')"
"""
def __init__(self, user_id, first_name, last_name):
self.user_id = user_id
self.first_name = first_name
self.last_name = last_name
def __repr__(self):
return (
f"{self.__class__.__name__}({self.user_id!r}, "
f"{self.first_name!r}, "
f"{self.last_name!r})"
)
def bad_users_from_rows(dbrows) -> list:
"""A bad case (non-pythonic) of creating ``User``s from DB rows."""
return [User(row[0], row[1], row[2]) for row in dbrows]
def users_from_rows(dbrows) -> list:
"""Create ``User``s from DB rows."""
return [
User(user_id, first_name, last_name)
for (user_id, first_name, last_name) in dbrows
]
|
load("@debian_package_list//:packages_db.bzl", "PACKAGES_DB")
load("@rules_deb//deb/internal:virtual_filesystem.bzl", "write_path_to_label_mapping")
load("@rules_deb//deb/internal:packages_parser.bzl", "sanitize_package_name")
load("@rules_deb//deb/internal:ldconfig.bzl", "create_shlibs_symlinks")
def _remove_extension(path, extension):
""" Removes the extension from a path. """
return path[:-len(extension)] if path.endswith(extension) else path
def lib_info(static_libs, shared_libs):
""" Returns a list of library information for the current package.
Libraries usually ship with two versions a static library and a shared both
of which are located in the same directory with different extensions. This
function returns a list of libraries with both of the shared and static
versions of the library, or either if only one link mode is available.
Args:
static_libs: A list of static library paths.
shared_libs: A list of shared library paths.
Returns:
A list of dicts in the format
[{'static': static_path, 'shared': shared_path},...].
"""
lib_info = {_remove_extension(lib, ".a"): {"static": lib, "shared": None} for lib in static_libs}
for shared_lib in shared_libs:
if _remove_extension(shared_lib, ".so") in lib_info:
lib_info[_remove_extension(shared_lib, ".so")]["shared"] = shared_lib
else:
lib_info[_remove_extension(shared_lib, ".so")] = {"static": None, "shared": shared_lib}
return lib_info.values()
def _build_cc_deps_info(repository_ctx, packages_db, break_deps):
""" Builds the C/C++ dependencies info. """
# Starlark doesn't support sets, so we can instead use a dict to
# deduplicate.
return {
"@{dep}//:cc_{dep}".format(dep = dep.name): None
for dep in packages_db[repository_ctx.name].depends
if dep.name not in [
sanitize_package_name(dep)
for dep in break_deps
]
}.keys()
def _build_package_info(repository_ctx, break_deps):
return {
"name": repository_ctx.name,
"cc_deps": _build_cc_deps_info(repository_ctx, PACKAGES_DB, break_deps),
}
def _file_exists(repository_ctx, path):
return repository_ctx.execute(["test", "-f", path]).return_code == 0
def _deb_archive_base_impl(repository_ctx):
""" Builds the base Debian archive. """
break_deps = [
sanitize_package_name(dep)
for dep in repository_ctx.attr.break_deps
]
repository_ctx.download(
url = repository_ctx.attr.url,
sha256 = repository_ctx.attr.sha256,
output = "package.deb",
)
repository_ctx.report_progress("Extracting package.")
result = repository_ctx.execute(["ar", "x", "package.deb"])
repository_ctx.execute(["rm", "package.deb"])
for archive in ["data.tar.xz", "control.tar.gz"]:
# Only extract if the archive exists.
if _file_exists(repository_ctx, archive):
repository_ctx.extract(archive)
repository_ctx.execute(["rm", archive])
if repository_ctx.attr.build_file_content and \
repository_ctx.attr.build_file:
fail("Specify either build_file_content or build_file, not both.")
if repository_ctx.attr.build_file_content:
repository_ctx.file(
"BUILD.bazel",
repository_ctx.attr.build_file_content,
)
else:
repository_ctx.symlink(repository_ctx.attr.build_file, "BUILD.bazel")
repository_ctx.report_progress("Creating package info.")
repository_ctx.file(
"package_info.bzl",
"INFO = " + str(_build_package_info(
repository_ctx,
break_deps,
)),
)
create_shlibs_symlinks(repository_ctx)
write_path_to_label_mapping(
repository_ctx,
PACKAGES_DB[repository_ctx.name].depends,
break_deps,
)
deb_archive = repository_rule(
implementation = _deb_archive_base_impl,
attrs = {
"url": attr.string(
mandatory = True,
doc = "The URL of the package to download.",
),
"sha256": attr.string(
doc = "The SHA256 of the package to download.",
),
"build_file": attr.label(
doc = "The BUILD file to use for this package.",
),
"build_file_content": attr.string(
doc = "The content of the BUILD file to use, if 'build_file' is not specified.",
),
"break_deps": attr.string_list(
doc = "A list of dependencies to break. e.g. libc is provided by the toolchain, but is often depended on by other packages.",
),
},
)
|
test_str="Codility we test coders"
k=14
for i in range(len(test_str)):
if len(test_str)==14:
print(test_str)
elif len(test_str)<14:
print(test_str.strip())
else:
test_str1=test_str.split()
print(test_str1)
lenth=len(test_str1)
print(lenth)
new_array=[]
for element in test_str:
if len(element)==14:
print(test_str)
break
elif len(element)<14:
new_array.append(element)
print(new_array)
else:
print('')
|
"""
Write a Python program to print the following floating numbers upto 2 decimal places.
"""
x = 3.141593
y = 12.99999
print("Original Number: {}".format(x))
print("Formatted Number: {:.2f}".format(x))
print("Original Number: {}".format(y))
print("Formatted Number: {:.2f}".format(y)) |
#
# PySNMP MIB module PDN-DNS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PDN-DNS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:38:29 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ValueRangeConstraint, ConstraintsUnion, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueRangeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ValueSizeConstraint")
pdn_dns, = mibBuilder.importSymbols("PDN-HEADER-MIB", "pdn-dns")
DomainName, DNSServerType = mibBuilder.importSymbols("PDN-TC", "DomainName", "DNSServerType")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Counter64, iso, Bits, ModuleIdentity, Gauge32, Unsigned32, Integer32, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter32, ObjectIdentity, TimeTicks, IpAddress, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "Counter64", "iso", "Bits", "ModuleIdentity", "Gauge32", "Unsigned32", "Integer32", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter32", "ObjectIdentity", "TimeTicks", "IpAddress", "NotificationType")
RowStatus, DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "DisplayString", "TextualConvention")
pdnDNSMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 17, 1))
pdnDNSMIBTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 17, 2))
devDNSDefaultDomainName = MibScalar((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 17, 1, 1), DomainName()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: devDNSDefaultDomainName.setStatus('mandatory')
if mibBuilder.loadTexts: devDNSDefaultDomainName.setDescription('the object allows the NMS to configure the default domain name for the device')
devDNSRetryTimeout = MibScalar((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 17, 1, 2), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: devDNSRetryTimeout.setStatus('mandatory')
if mibBuilder.loadTexts: devDNSRetryTimeout.setDescription('the object allows the NMS to configure in seconds the time to wait for a response from a DNS server. The default value for this object is 5')
devDNSMaxRetries = MibScalar((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 17, 1, 3), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: devDNSMaxRetries.setStatus('mandatory')
if mibBuilder.loadTexts: devDNSMaxRetries.setDescription('the object allows the NMS to configure the number of maximum number of retires by the device before giving up or trying one of the secondary DNS servers if they have been configured. The default value for this object is 2')
devDNSServerTable = MibTable((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 17, 1, 4), )
if mibBuilder.loadTexts: devDNSServerTable.setStatus('mandatory')
if mibBuilder.loadTexts: devDNSServerTable.setDescription('A Table that contains information about the DNS server IP addresses')
devDNSServerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 17, 1, 4, 1), ).setIndexNames((0, "PDN-DNS-MIB", "devDNSServerIP"))
if mibBuilder.loadTexts: devDNSServerEntry.setStatus('mandatory')
if mibBuilder.loadTexts: devDNSServerEntry.setDescription('A Table that contains information about the DNS server IP addresses')
devDNSServerIP = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 17, 1, 4, 1, 1), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: devDNSServerIP.setStatus('mandatory')
if mibBuilder.loadTexts: devDNSServerIP.setDescription('This Objects allows an NMS to configure a DNS server IP address Default value is 1')
devDNSServerType = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 17, 1, 4, 1, 2), DNSServerType()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: devDNSServerType.setStatus('mandatory')
if mibBuilder.loadTexts: devDNSServerType.setDescription('This Objects allows an NMS to specify whether the Server IP address is the primary DNS server or the secondary DNS server. Only One Primary DNS server is allowed to be configured.')
devDNSRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 17, 1, 4, 1, 3), RowStatus()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: devDNSRowStatus.setStatus('mandatory')
if mibBuilder.loadTexts: devDNSRowStatus.setDescription('Use CreateAndGo to Create a new object. use Destroy to remove an entry from this table')
devHostMappingTable = MibTable((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 17, 1, 5), )
if mibBuilder.loadTexts: devHostMappingTable.setStatus('mandatory')
if mibBuilder.loadTexts: devHostMappingTable.setDescription('A Table that contains information about host names for devices')
devHostMappingEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 17, 1, 5, 1), ).setIndexNames((0, "PDN-DNS-MIB", "devHostMappingIpAddress"))
if mibBuilder.loadTexts: devHostMappingEntry.setStatus('mandatory')
if mibBuilder.loadTexts: devHostMappingEntry.setDescription('An entry that contains information about a device host name')
devHostMappingIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 17, 1, 5, 1, 1), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: devHostMappingIpAddress.setStatus('mandatory')
if mibBuilder.loadTexts: devHostMappingIpAddress.setDescription('This object contains the IP Address of the host')
devHostMappingHostName = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 17, 1, 5, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: devHostMappingHostName.setStatus('mandatory')
if mibBuilder.loadTexts: devHostMappingHostName.setDescription('This object contains the name of the host')
devHostMappingRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 17, 1, 5, 1, 3), RowStatus()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: devHostMappingRowStatus.setStatus('mandatory')
if mibBuilder.loadTexts: devHostMappingRowStatus.setDescription('This object is used to create or delete a row from the table')
mibBuilder.exportSymbols("PDN-DNS-MIB", devDNSServerEntry=devDNSServerEntry, devDNSRowStatus=devDNSRowStatus, devDNSServerType=devDNSServerType, pdnDNSMIBObjects=pdnDNSMIBObjects, devHostMappingIpAddress=devHostMappingIpAddress, devHostMappingHostName=devHostMappingHostName, pdnDNSMIBTraps=pdnDNSMIBTraps, devDNSMaxRetries=devDNSMaxRetries, devDNSServerIP=devDNSServerIP, devHostMappingTable=devHostMappingTable, devDNSRetryTimeout=devDNSRetryTimeout, devHostMappingEntry=devHostMappingEntry, devHostMappingRowStatus=devHostMappingRowStatus, devDNSServerTable=devDNSServerTable, devDNSDefaultDomainName=devDNSDefaultDomainName)
|
hexnum = input()
number = int(hexnum,16)
if(number % 2 == 0):
print(0)
else:
print(1)
|
# Desenvolva uam lógica que leia o peso e a altura de uma pessoa
#calcule seu imc e mostre seu status,de acordo com a tabela abaixo:
# - abaixo de 18.5: abaixo do peso
# - entre 18.5 e 25: Peso ideal
# - 25 até 30: sobrepeso
# - 30 até 40: obesidade
# - acima de 40: obesidade mórbida
peso = float(input('Digite aqui o seu peso em Kg: '))
altura = float(input('Digite aqui a sua altura em M: '))
imc = peso/(altura ** altura)
if imc < 18.5:
print('Você está abaixo do peso.')
elif 18.5 <= imc < 25:
print('Você está no peso ideal.')
elif 25 >= imc < 30:
print('Você está acima do seu peso')
elif 30 < imc < 40:
print('Você está na obesidade.')
elif imc >= 40:
print('Você está com obesidade mórbida.')
|
class Solution:
def wordPatternMatch(self, pattern: str, str: str) -> bool:
table = {}
mapped = set()
def dfs(pstart, sstart):
if pstart == len(pattern):
return sstart == len(str)
for i in range(sstart, len(str)):
if len(str) - i < len(pattern) - pstart:
break
temp = str[sstart : i + 1]
if temp in table:
if table[temp] != pattern[pstart]:
continue
elif dfs(pstart + 1, i + 1):
return True
elif pattern[pstart] not in mapped:
table[temp] = pattern[pstart]
mapped.add(pattern[pstart])
if dfs(pstart + 1, i + 1):
return True
del table[temp]
mapped.remove(pattern[pstart])
return False
return dfs(0, 0)
|
"""Rules for running JavaScript programs"""
load(
"//js/private:js_binary.bzl",
_js_binary = "js_binary",
_js_binary_lib = "js_binary_lib",
_js_test = "js_test",
)
load(
"//js/private:js_package.bzl",
_JsPackageInfo = "JsPackageInfo",
_js_package = "js_package",
_js_package_lib = "js_package_lib",
)
load(
"//js/private:link_js_package.bzl",
_link_js_package = "link_js_package",
_link_js_package_dep = "link_js_package_dep",
)
load(
"//js/private:pnpm_utils.bzl",
_pnpm_utils = "pnpm_utils",
)
def js_binary(**kwargs):
_js_binary(
enable_runfiles = select({
"@aspect_rules_js//js/private:enable_runfiles": True,
"//conditions:default": False,
}),
**kwargs
)
def js_test(**kwargs):
_js_test(
enable_runfiles = select({
"@aspect_rules_js//js/private:enable_runfiles": True,
"//conditions:default": False,
}),
**kwargs
)
js_package = _js_package
JsPackageInfo = _JsPackageInfo
link_js_package = _link_js_package
link_js_package_dep = _link_js_package_dep
# export the starlark libraries as a public API
js_binary_lib = _js_binary_lib
js_package_lib = _js_package_lib
# export constants since users might not always have syntax sugar
constants = struct(
# Prefix for link_js_package_direct links
direct_link_prefix = _pnpm_utils.direct_link_prefix,
# Prefix for link_js_package_store links
store_link_prefix = _pnpm_utils.store_link_prefix,
# Suffix for package directory filegroup and alias targets
dir_suffix = _pnpm_utils.dir_suffix,
)
# export utils since users might not always have syntax sugar
utils = struct(
# Prefix for link_js_package_direct links
bazel_name = _pnpm_utils.bazel_name,
)
|
def quick_sort(given_list):
if len(given_list) < 1:
return given_list
else:
pivot_element = given_list[0] #here I am choosing the first element to be a pivot
left = quick_sort([element for element in given_list[1:] if element < pivot_element]) # moving smaller to left
right = quick_sort([element for element in given_list[1:] if element > pivot_element]) #moving greater to right
return left + [pivot_element] + right
#usage
mylist=[8,5,9,4,3,7,2,12,10]
print (quick_sort(mylist))
|
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
target = ''
ordA = ord('A')
ordZ = ord('Z')
orda = ord('a')
for c in s:
if not c.isalnum():
continue
ordC = ord(c)
if ordC >= ordA and ordC <= ordZ:
c = chr(ordC - ordA + orda)
target += c
left = 0
right = len(target) - 1
while left <= right:
if target[left] != target[right]:
return False
left += 1
right -= 1
return True
s = Solution()
print(s.isPalindrome("A man, a plan, a canal: Panama"))
|
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'chromium_code': 1,
},
'includes': [
'ui_resources.gypi',
],
'targets': [
{
'target_name': 'ui',
'type': '<(component)',
'variables': { 'enable_wexit_time_destructors': 1, },
'includes': [
'base/ime/ime.gypi',
],
'dependencies': [
'../base/base.gyp:base',
'../base/base.gyp:base_i18n',
'../base/base.gyp:base_static',
'../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations',
'../build/temp_gyp/googleurl.gyp:googleurl',
'../net/net.gyp:net',
'../skia/skia.gyp:skia',
'../third_party/icu/icu.gyp:icui18n',
'../third_party/icu/icu.gyp:icuuc',
'../third_party/libpng/libpng.gyp:libpng',
'../third_party/zlib/zlib.gyp:zlib',
'base/strings/ui_strings.gyp:ui_strings',
'ui_resources_standard',
'<(libjpeg_gyp_path):libjpeg',
],
'defines': [
'UI_IMPLEMENTATION',
],
# Export these dependencies since text_elider.h includes ICU headers.
'export_dependent_settings': [
'../net/net.gyp:net',
'../third_party/icu/icu.gyp:icui18n',
'../third_party/icu/icu.gyp:icuuc',
],
'sources': [
'base/accelerators/accelerator.cc',
'base/accelerators/accelerator.h',
'base/accelerators/accelerator_cocoa.h',
'base/accelerators/accelerator_cocoa.mm',
'base/accelerators/accelerator_gtk.cc',
'base/accelerators/accelerator_gtk.h',
'base/accelerators/accelerator_manager.cc',
'base/accelerators/accelerator_manager.h',
'base/accessibility/accessibility_types.h',
'base/accessibility/accessible_text_utils.cc',
'base/accessibility/accessible_text_utils.h',
'base/accessibility/accessible_view_state.cc',
'base/accessibility/accessible_view_state.h',
'base/animation/animation.cc',
'base/animation/animation.h',
'base/animation/animation_container.cc',
'base/animation/animation_container.h',
'base/animation/animation_container_element.h',
'base/animation/animation_container_observer.h',
'base/animation/animation_delegate.h',
'base/animation/linear_animation.cc',
'base/animation/linear_animation.h',
'base/animation/multi_animation.cc',
'base/animation/multi_animation.h',
'base/animation/slide_animation.cc',
'base/animation/slide_animation.h',
'base/animation/throb_animation.cc',
'base/animation/throb_animation.h',
'base/animation/tween.cc',
'base/animation/tween.h',
'base/clipboard/clipboard.cc',
'base/clipboard/clipboard.h',
'base/clipboard/clipboard_android.cc',
'base/clipboard/clipboard_aurax11.cc',
'base/clipboard/clipboard_gtk.cc',
'base/clipboard/clipboard_mac.mm',
'base/clipboard/clipboard_util_win.cc',
'base/clipboard/clipboard_util_win.h',
'base/clipboard/clipboard_win.cc',
'base/clipboard/custom_data_helper.cc',
'base/clipboard/custom_data_helper.h',
'base/clipboard/custom_data_helper_mac.mm',
'base/clipboard/custom_data_helper_x.cc',
'base/clipboard/scoped_clipboard_writer.cc',
'base/clipboard/scoped_clipboard_writer.h',
'base/cocoa/base_view.h',
'base/cocoa/base_view.mm',
'base/cocoa/events_mac.mm',
'base/cocoa/find_pasteboard.h',
'base/cocoa/find_pasteboard.mm',
'base/cocoa/focus_tracker.h',
'base/cocoa/focus_tracker.mm',
'base/cocoa/fullscreen_window_manager.h',
'base/cocoa/fullscreen_window_manager.mm',
'base/cocoa/nib_loading.h',
'base/cocoa/nib_loading.mm',
'base/cocoa/underlay_opengl_hosting_window.h',
'base/cocoa/underlay_opengl_hosting_window.mm',
'base/cocoa/window_size_constants.h',
'base/cocoa/window_size_constants.mm',
'base/cursor/cursor.cc',
'base/cursor/cursor.h',
'base/cursor/cursor_win.cc',
'base/cursor/cursor_x11.cc',
'base/dragdrop/cocoa_dnd_util.h',
'base/dragdrop/cocoa_dnd_util.mm',
'base/dragdrop/drag_drop_types_gtk.cc',
'base/dragdrop/drag_drop_types.h',
'base/dragdrop/drag_drop_types_win.cc',
'base/dragdrop/drag_source.cc',
'base/dragdrop/drag_source.h',
'base/dragdrop/drop_target.cc',
'base/dragdrop/drop_target.h',
'base/dragdrop/drag_utils.cc',
'base/dragdrop/drag_utils.h',
'base/dragdrop/drag_utils_aura.cc',
'base/dragdrop/drag_utils_gtk.cc',
'base/dragdrop/drag_utils_win.cc',
'base/dragdrop/gtk_dnd_util.cc',
'base/dragdrop/gtk_dnd_util.h',
'base/dragdrop/os_exchange_data.cc',
'base/dragdrop/os_exchange_data.h',
'base/dragdrop/os_exchange_data_provider_aura.cc',
'base/dragdrop/os_exchange_data_provider_aura.h',
'base/dragdrop/os_exchange_data_provider_gtk.cc',
'base/dragdrop/os_exchange_data_provider_gtk.h',
'base/dragdrop/os_exchange_data_provider_win.cc',
'base/dragdrop/os_exchange_data_provider_win.h',
'base/events.h',
'base/gestures/gesture_configuration.cc',
'base/gestures/gesture_configuration.h',
'base/gestures/gesture_point.cc',
'base/gestures/gesture_point.h',
'base/gestures/gesture_recognizer.h',
'base/gestures/gesture_recognizer_impl.cc',
'base/gestures/gesture_recognizer_impl.h',
'base/gestures/gesture_sequence.cc',
'base/gestures/gesture_sequence.h',
'base/gestures/velocity_calculator.cc',
'base/gestures/velocity_calculator.h',
'base/gtk/event_synthesis_gtk.cc',
'base/gtk/event_synthesis_gtk.h',
'base/gtk/focus_store_gtk.cc',
'base/gtk/focus_store_gtk.h',
'base/gtk/g_object_destructor_filo.cc',
'base/gtk/g_object_destructor_filo.h',
'base/gtk/gtk_expanded_container.cc',
'base/gtk/gtk_expanded_container.h',
'base/gtk/gtk_floating_container.cc',
'base/gtk/gtk_floating_container.h',
'base/gtk/gtk_im_context_util.cc',
'base/gtk/gtk_im_context_util.h',
'base/gtk/gtk_hig_constants.h',
'base/gtk/gtk_screen_util.cc',
'base/gtk/gtk_screen_util.h',
'base/gtk/gtk_signal.h',
'base/gtk/gtk_signal_registrar.cc',
'base/gtk/gtk_signal_registrar.h',
'base/gtk/gtk_windowing.cc',
'base/gtk/gtk_windowing.h',
'base/gtk/menu_label_accelerator_util.cc',
'base/gtk/menu_label_accelerator_util.h',
'base/gtk/owned_widget_gtk.cc',
'base/gtk/owned_widget_gtk.h',
'base/gtk/scoped_gobject.h',
'base/gtk/scoped_region.cc',
'base/gtk/scoped_region.h',
'base/hit_test.h',
'base/keycodes/keyboard_code_conversion.cc',
'base/keycodes/keyboard_code_conversion.h',
'base/keycodes/keyboard_code_conversion_gtk.cc',
'base/keycodes/keyboard_code_conversion_gtk.h',
'base/keycodes/keyboard_code_conversion_mac.h',
'base/keycodes/keyboard_code_conversion_mac.mm',
'base/keycodes/keyboard_code_conversion_win.cc',
'base/keycodes/keyboard_code_conversion_win.h',
'base/keycodes/keyboard_code_conversion_x.cc',
'base/keycodes/keyboard_code_conversion_x.h',
'base/keycodes/keyboard_codes.h',
'base/l10n/l10n_font_util.cc',
'base/l10n/l10n_font_util.h',
'base/l10n/l10n_util.cc',
'base/l10n/l10n_util.h',
'base/l10n/l10n_util_collator.h',
'base/l10n/l10n_util_mac.h',
'base/l10n/l10n_util_mac.mm',
'base/l10n/l10n_util_posix.cc',
'base/l10n/l10n_util_win.cc',
'base/l10n/l10n_util_win.h',
'base/layout.cc',
'base/layout.h',
'base/models/button_menu_item_model.cc',
'base/models/button_menu_item_model.h',
'base/models/combobox_model.h',
'base/models/list_model.h',
'base/models/list_model_observer.h',
'base/models/menu_model.cc',
'base/models/menu_model.h',
'base/models/menu_model_delegate.h',
'base/models/simple_menu_model.cc',
'base/models/simple_menu_model.h',
'base/models/table_model.cc',
'base/models/table_model.h',
'base/models/table_model_observer.h',
'base/models/tree_model.cc',
'base/models/tree_model.h',
'base/models/tree_node_iterator.h',
'base/models/tree_node_model.h',
'base/native_theme/native_theme.cc',
'base/native_theme/native_theme.h',
'base/native_theme/native_theme_android.cc',
'base/native_theme/native_theme_android.h',
'base/native_theme/native_theme_aura.cc',
'base/native_theme/native_theme_aura.h',
'base/native_theme/native_theme_base.cc',
'base/native_theme/native_theme_base.h',
'base/native_theme/native_theme_gtk.cc',
'base/native_theme/native_theme_gtk.h',
'base/native_theme/native_theme_win.cc',
'base/native_theme/native_theme_win.h',
'base/range/range.cc',
'base/range/range.h',
'base/range/range_mac.mm',
'base/range/range_win.cc',
'base/resource/data_pack.cc',
'base/resource/data_pack.h',
'base/resource/resource_bundle.cc',
'base/resource/resource_bundle.h',
'base/resource/resource_bundle_android.cc',
'base/resource/resource_bundle_aurax11.cc',
'base/resource/resource_bundle_gtk.cc',
'base/resource/resource_bundle_mac.mm',
'base/resource/resource_bundle_win.cc',
'base/resource/resource_bundle_win.h',
'base/resource/resource_data_dll_win.cc',
'base/resource/resource_data_dll_win.h',
'base/resource/resource_handle.h',
'base/text/bytes_formatting.cc',
'base/text/bytes_formatting.h',
'base/text/text_elider.cc',
'base/text/text_elider.h',
'base/text/utf16_indexing.cc',
'base/text/utf16_indexing.h',
'base/theme_provider.cc',
'base/theme_provider.h',
'base/touch/touch_factory.cc',
'base/touch/touch_factory.h',
'base/ui_base_exports.cc',
'base/ui_base_paths.cc',
'base/ui_base_paths.h',
'base/ui_base_switches.cc',
'base/ui_base_switches.h',
'base/ui_base_types.h',
'base/ui_export.h',
'base/view_prop.cc',
'base/view_prop.h',
'base/win/accessibility_misc_utils.h',
'base/win/accessibility_misc_utils.cc',
'base/win/atl_module.h',
'base/win/dpi.cc',
'base/win/dpi.h',
'base/win/events_win.cc',
'base/win/extra_sdk_defines.h',
'base/win/foreground_helper.cc',
'base/win/foreground_helper.h',
'base/win/hwnd_util.cc',
'base/win/hwnd_util.h',
'base/win/hwnd_subclass.cc',
'base/win/hwnd_subclass.h',
'base/win/ime_input.cc',
'base/win/ime_input.h',
'base/win/message_box_win.cc',
'base/win/message_box_win.h',
'base/win/mouse_wheel_util.cc',
'base/win/mouse_wheel_util.h',
'base/win/scoped_ole_initializer.cc',
'base/win/scoped_ole_initializer.h',
'base/win/scoped_set_map_mode.h',
'base/win/shell.cc',
'base/win/shell.h',
'base/win/singleton_hwnd.cc',
'base/win/singleton_hwnd.h',
'base/win/window_impl.cc',
'base/win/window_impl.h',
'base/work_area_watcher_observer.h',
'base/x/active_window_watcher_x.cc',
'base/x/active_window_watcher_x.h',
'base/x/active_window_watcher_x_observer.h',
'base/x/events_x.cc',
'base/x/root_window_property_watcher_x.cc',
'base/x/root_window_property_watcher_x.h',
'base/x/valuators.cc',
'base/x/valuators.h',
'base/x/work_area_watcher_x.cc',
'base/x/work_area_watcher_x.h',
'base/x/x11_util.cc',
'base/x/x11_util.h',
'base/x/x11_util_internal.h',
'gfx/blit.cc',
'gfx/blit.h',
'gfx/canvas.cc',
'gfx/canvas.h',
'gfx/canvas_android.cc',
'gfx/canvas_linux.cc',
'gfx/canvas_mac.mm',
'gfx/canvas_paint.h',
'gfx/canvas_paint_win.cc',
'gfx/canvas_skia.cc',
'gfx/canvas_skia_paint.h',
'gfx/canvas_win.cc',
'gfx/codec/jpeg_codec.cc',
'gfx/codec/jpeg_codec.h',
'gfx/codec/png_codec.cc',
'gfx/codec/png_codec.h',
'gfx/color_analysis.cc',
'gfx/color_analysis.h',
'gfx/color_utils.cc',
'gfx/color_utils.h',
'gfx/favicon_size.cc',
'gfx/favicon_size.h',
'gfx/font.h',
'gfx/font.cc',
'gfx/font_list.h',
'gfx/font_list.cc',
'gfx/font_smoothing_win.cc',
'gfx/font_smoothing_win.h',
'gfx/gfx_paths.cc',
'gfx/gfx_paths.h',
'gfx/image/image.cc',
'gfx/image/image.h',
'gfx/image/image_mac.mm',
'gfx/image/image_skia.cc',
'gfx/image/image_skia.h',
'gfx/image/image_util.cc',
'gfx/image/image_util.h',
'gfx/insets.cc',
'gfx/insets.h',
'gfx/interpolated_transform.h',
'gfx/interpolated_transform.cc',
'gfx/mac/nsimage_cache.h',
'gfx/mac/nsimage_cache.mm',
'gfx/mac/scoped_ns_disable_screen_updates.h',
'gfx/monitor.cc',
'gfx/monitor.h',
'gfx/native_widget_types.h',
'gfx/pango_util.h',
'gfx/pango_util.cc',
'gfx/path.cc',
'gfx/path.h',
'gfx/path_aura.cc',
'gfx/path_gtk.cc',
'gfx/path_win.cc',
'gfx/platform_font.h',
'gfx/platform_font_android.cc',
'gfx/platform_font_pango.h',
'gfx/platform_font_pango.cc',
'gfx/platform_font_mac.h',
'gfx/platform_font_mac.mm',
'gfx/platform_font_win.h',
'gfx/platform_font_win.cc',
'gfx/point.cc',
'gfx/point.h',
'gfx/point_base.h',
'gfx/rect.cc',
'gfx/rect.h',
'gfx/rect_base.h',
'gfx/rect_base_impl.h',
'gfx/render_text.cc',
'gfx/render_text.h',
'gfx/render_text_linux.cc',
'gfx/render_text_linux.h',
'gfx/render_text_win.cc',
'gfx/render_text_win.h',
'gfx/screen.h',
'gfx/screen_android.cc',
'gfx/screen_aura.cc',
'gfx/screen_gtk.cc',
'gfx/screen_impl.h',
'gfx/screen_mac.mm',
'gfx/screen_win.cc',
'gfx/scoped_cg_context_save_gstate_mac.h',
'gfx/scoped_ns_graphics_context_save_gstate_mac.h',
'gfx/scoped_ns_graphics_context_save_gstate_mac.mm',
'gfx/scrollbar_size.cc',
'gfx/scrollbar_size.h',
'gfx/selection_model.cc',
'gfx/selection_model.h',
'gfx/shadow_value.cc',
'gfx/shadow_value.h',
'gfx/size.cc',
'gfx/size.h',
'gfx/size_base.h',
'gfx/size_base_impl.h',
'gfx/skbitmap_operations.cc',
'gfx/skbitmap_operations.h',
'gfx/skia_util.cc',
'gfx/skia_util.h',
'gfx/skia_utils_gtk.cc',
'gfx/skia_utils_gtk.h',
'gfx/sys_color_change_listener.cc',
'gfx/sys_color_change_listener.h',
'gfx/transform.cc',
'gfx/transform.h',
'gfx/transform_util.cc',
'gfx/transform_util.h',
'gfx/video_decode_acceleration_support_mac.h',
'gfx/video_decode_acceleration_support_mac.mm',
'ui_controls/ui_controls.h',
'ui_controls/ui_controls_aura.cc',
'ui_controls/ui_controls_internal_win.h',
'ui_controls/ui_controls_internal_win.cc',
'ui_controls/ui_controls_gtk.cc',
'ui_controls/ui_controls_mac.mm',
'ui_controls/ui_controls_win.cc',
],
'conditions': [
# TODO(asvitkine): Switch all platforms to use canvas_skia.cc.
# http://crbug.com/105550
['use_canvas_skia==1', {
'sources!': [
'gfx/canvas_android.cc',
'gfx/canvas_linux.cc',
'gfx/canvas_mac.mm',
'gfx/canvas_win.cc',
],
}, { # use_canvas_skia!=1
'sources!': [
'gfx/canvas_skia.cc',
],
}],
['use_aura==1', {
'sources/': [
['exclude', 'gfx/gtk_'],
['exclude', 'gfx/gtk_util.cc'],
['exclude', 'gfx/gtk_util.h'],
['exclude', 'gfx/screen_gtk.cc'],
['exclude', 'gfx/screen_win.cc'],
['exclude', 'base/dragdrop/drag_utils_win.cc'],
['exclude', 'base/win/mouse_wheel_util.cc'],
['exclude', 'base/win/mouse_wheel_util.h'],
['exclude', 'base/work_area_watcher_observer.h'],
['exclude', 'base/x/active_window_watcher_x.cc'],
['exclude', 'base/x/active_window_watcher_x.h'],
['exclude', 'base/x/active_window_watcher_x_observer.h'],
['exclude', 'base/x/root_window_property_watcher_x.cc'],
['exclude', 'base/x/root_window_property_watcher_x.h'],
['exclude', 'base/x/work_area_watcher_x.cc'],
['exclude', 'base/x/work_area_watcher_x.h'],
['exclude', 'ui_controls_win.cc'],
],
}, { # use_aura!=1
'sources!': [
'base/cursor/cursor.cc',
'base/cursor/cursor.h',
'base/cursor/cursor_win.cc',
'base/cursor/cursor_x11.cc',
'base/native_theme/native_theme_aura.cc',
'base/native_theme/native_theme_aura.h',
]
}],
['use_aura==1 and OS=="win"', {
'sources/': [
['exclude', 'base/dragdrop/os_exchange_data_provider_win.cc'],
['exclude', 'base/dragdrop/os_exchange_data_provider_win.h'],
['exclude', 'base/native_theme/native_theme_win.cc'],
['exclude', 'base/native_theme/native_theme_win.h'],
['exclude', 'gfx/path_win.cc'],
],
}],
['use_aura==0 and toolkit_views==0', {
'sources/': [
['exclude', '^base/gestures/*'],
]
}],
['use_ibus==1', {
'dependencies': [
'../build/linux/system.gyp:ibus',
],
}],
['use_glib == 1', {
'dependencies': [
# font_gtk.cc uses fontconfig.
'../build/linux/system.gyp:fontconfig',
'../build/linux/system.gyp:glib',
'../build/linux/system.gyp:pangocairo',
'../build/linux/system.gyp:x11',
'../build/linux/system.gyp:xext',
'../build/linux/system.gyp:xfixes',
],
'link_settings': {
'libraries': [
'-lXcursor', # For XCursor* function calls in x11_util.cc.
'-lXrender', # For XRender* function calls in x11_util.cc.
],
},
'conditions': [
['toolkit_views==0', {
# Note: because of gyp predence rules this has to be defined as
# 'sources/' rather than 'sources!'.
'sources/': [
['exclude', '^base/dragdrop/drag_drop_types_gtk.cc'],
['exclude', '^base/dragdrop/drag_utils_gtk.cc'],
['exclude', '^base/dragdrop/drag_utils.cc'],
['exclude', '^base/dragdrop/drag_utils.h'],
['exclude', '^base/dragdrop/os_exchange_data.cc'],
['exclude', '^base/dragdrop/os_exchange_data.h'],
['exclude', '^base/dragdrop/os_exchange_data_provider_gtk.cc'],
['exclude', '^base/dragdrop/os_exchange_data_provider_gtk.h'],
],
}, {
# Note: because of gyp predence rules this has to be defined as
# 'sources/' rather than 'sources!'.
'sources/': [
['include', '^base/dragdrop/os_exchange_data.cc'],
],
}],
],
}],
['toolkit_uses_gtk == 1', {
'dependencies': [
'../build/linux/system.gyp:gtk',
],
'sources': [
'gfx/gtk_native_view_id_manager.cc',
'gfx/gtk_native_view_id_manager.h',
'gfx/gtk_preserve_window.cc',
'gfx/gtk_preserve_window.h',
'gfx/gtk_util.cc',
'gfx/gtk_util.h',
'gfx/image/cairo_cached_surface.cc',
'gfx/image/cairo_cached_surface.h',
],
}, { # toolkit_uses_gtk != 1
'sources!': [
'base/native_theme/native_theme_gtk.cc',
'base/native_theme/native_theme_gtk.h',
]
}],
['OS=="win"', {
'sources': [
'gfx/gdi_util.cc',
'gfx/gdi_util.h',
'gfx/icon_util.cc',
'gfx/icon_util.h',
'base/native_theme/native_theme_win.cc',
'base/native_theme/native_theme_win.h',
],
'sources!': [
'base/touch/touch_factory.cc',
'base/touch/touch_factory.h',
'gfx/pango_util.h',
'gfx/pango_util.cc',
'gfx/platform_font_pango.cc',
'gfx/platform_font_pango.h',
],
'include_dirs': [
'../',
'../third_party/wtl/include',
],
'msvs_settings': {
'VCLinkerTool': {
'DelayLoadDLLs': [
'd2d1.dll',
'd3d10_1.dll',
],
'AdditionalDependencies': [
'd2d1.lib',
'd3d10_1.lib',
],
},
},
'link_settings': {
'libraries': [
'-limm32.lib',
'-ld2d1.lib',
'-loleacc.lib',
],
},
},{ # OS!="win"
'conditions': [
['use_aura==0', {
'sources!': [
'base/view_prop.cc',
'base/view_prop.h',
],
}],
],
'sources!': [
'base/dragdrop/drag_source.cc',
'base/dragdrop/drag_source.h',
'base/dragdrop/drag_drop_types.h',
'base/dragdrop/drop_target.cc',
'base/dragdrop/drop_target.h',
'base/dragdrop/os_exchange_data.cc',
'base/native_theme/native_theme_win.cc',
'base/native_theme/native_theme_win.h',
],
'sources/': [
['exclude', '^base/win/*'],
],
}],
['OS=="mac"', {
'sources!': [
'base/dragdrop/drag_utils.cc',
'base/dragdrop/drag_utils.h',
'base/touch/touch_factory.cc',
'base/touch/touch_factory.h',
'gfx/pango_util.h',
'gfx/pango_util.cc',
'gfx/platform_font_pango.h',
'gfx/platform_font_pango.cc',
],
'link_settings': {
'libraries': [
'$(SDKROOT)/System/Library/Frameworks/Accelerate.framework',
'$(SDKROOT)/System/Library/Frameworks/AudioUnit.framework',
'$(SDKROOT)/System/Library/Frameworks/CoreVideo.framework',
],
},
}],
['OS=="android"', {
'sources!': [
'gfx/pango_util.h',
'gfx/pango_util.cc',
'gfx/platform_font_pango.h',
'gfx/platform_font_pango.cc',
],
}],
['use_x11==1', {
'all_dependent_settings': {
'ldflags': [
'-L<(PRODUCT_DIR)',
],
'link_settings': {
'libraries': [
'-lX11 -lXcursor',
],
},
},
}, { # use_x11==0
'sources/': [
['exclude', 'base/keycodes/keyboard_code_conversion_x.*'],
['exclude', 'base/x/*'],
],
}],
['toolkit_views==0', {
'sources!': [
'base/x/events_x.cc',
],
}],
['toolkit_views==0 and use_canvas_skia==0', {
'sources!': [
'gfx/render_text.cc',
'gfx/render_text.h',
'gfx/render_text_linux.cc',
'gfx/render_text_linux.h',
'gfx/render_text_win.cc',
'gfx/render_text_win.h',
],
}],
['OS=="android"', {
'sources!': [
'base/touch/touch_factory.cc',
'base/touch/touch_factory.h',
'gfx/pango_util.h',
'gfx/pango_util.cc',
'gfx/platform_font_pango.cc',
'gfx/platform_font_pango.h',
],
}],
['OS=="linux"', {
'libraries': [
'-ldl',
],
}],
['os_bsd==1 and use_system_libjpeg==1', {
'include_dirs': [
'/usr/local/include',
],
}],
['inside_chromium_build==0', {
'dependencies': [
'<(DEPTH)/webkit/support/setup_third_party.gyp:third_party_headers',
],
}],
],
},
],
'conditions': [
['inside_chromium_build==1', {
'includes': [
'ui_unittests.gypi',
],
'targets': [
{
# TODO(rsesek): Remove this target once ui_unittests is run on the
# waterfall instead of gfx_unittests.
'target_name': 'gfx_unittests',
'type': 'none',
'dependencies': [
'ui_unittests',
],
'actions': [
{
'message': 'TEMPORARY: Copying ui_unittests to gfx_unittests',
'variables': {
'ui_copy_target': '<(PRODUCT_DIR)/ui_unittests<(EXECUTABLE_SUFFIX)',
'ui_copy_dest': '<(PRODUCT_DIR)/gfx_unittests<(EXECUTABLE_SUFFIX)',
},
'inputs': ['<(ui_copy_target)'],
'outputs': ['<(ui_copy_dest)'],
'action_name': 'TEMP_copy_ui_unittests',
'action': [
'python', '-c',
'import os, shutil; ' \
'shutil.copyfile(\'<(ui_copy_target)\', \'<(ui_copy_dest)\'); ' \
'os.chmod(\'<(ui_copy_dest)\', 0700)'
]
}
],
},
],
}],
],
}
|
first = int (input ('First term '))
ratio = int (input ('Ratio '))
tenth = first + (10-1) * ratio
for c in range (first, tenth + ratio, ratio):
print (c, end = '') |
# -*- coding: utf-8 -*-
"""
shepherd.commons
~~~~~
Defines details of the data exchange protocol between PRU0 and the python code.
The various parameters need to be the same on both sides. Refer to the
corresponding implementation in `software/firmware/include/commons.h`
:copyright: (c) 2019 Networked Embedded Systems Lab, TU Dresden.
:license: MIT, see LICENSE for more details.
"""
MAX_GPIO_EVT_PER_BUFFER = 16_384 # 2^14 # TODO: replace by (currently non-existing) sysfs_interface
MSG_BUF_FROM_HOST = 0x01
MSG_BUF_FROM_PRU = 0x02
MSG_DBG_ADC = 0xA0
MSG_DBG_DAC = 0xA1
MSG_DBG_GPI = 0xA2
MSG_DBG_GP_BATOK = 0xA3
MSG_DBG_PRINT = 0xA6
MSG_DBG_VSOURCE_P_INP = 0xA8
MSG_DBG_VSOURCE_P_OUT = 0xA9
MSG_DBG_VSOURCE_V_CAP = 0xAA
MSG_DBG_VSOURCE_V_OUT = 0xAB
MSG_DBG_VSOURCE_INIT = 0xAC
MSG_DBG_VSOURCE_CHARGE = 0xAD
MSG_DBG_VSOURCE_DRAIN = 0xAE
MSG_DBG_FN_TESTS = 0xAF
MSG_DEP_ERR_INCMPLT = 0xE3
MSG_DEP_ERR_INVLDCMD = 0xE4
MSG_DEP_ERR_NOFREEBUF = 0xE5
GPIO_LOG_BIT_POSITIONS = """
pru_reg name linux_pin
r31_00 TARGET_GPIO0 P8_45
r31_01 TARGET_GPIO1 P8_46
r31_02 TARGET_SWD_CLK P8_43
r31_03 TARGET_SWD_IO P8_44
r31_04 TARGET_UART_TX P8_41
r31_05 TARGET_UART_RX P8_42
r31_06 TARGET_GPIO2 P8_39
r31_07 TARGET_GPIO3 P8_40
r31_08 TARGET_GPIO4 P8_27
r30_09/out TARGET_BAT_OK P8_29
"""
# Note: this table is copied (for hdf5-reference) from pru1/main.c
|
# coding: utf-8
"""*****************************************************************************
* Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to comply with third party license terms applicable to your
* use of third party software (including open source software) that may
* accompany Microchip software.
*
* THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
* EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED
* WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
* INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
* WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS
* BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE
* FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN
* ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
* THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
*****************************************************************************"""
################################################################################
#### Business Logic ####
################################################################################
def genDriverHeaderRootFile(symbol, event):
symbol.setEnabled(event["value"])
def genDriverHeaderCommonFile(symbol, event):
symbol.setEnabled(event["value"])
############################################################################
#### Code Generation ####
############################################################################
genDriverCommonFiles = harmonyCoreComponent.createBooleanSymbol("ENABLE_DRV_COMMON", None)
genDriverCommonFiles.setLabel("Generate Harmony Driver Common Files")
genDriverCommonFiles.setVisible(False)
genDriverCommonFiles.setDefaultValue(False)
driverHeaderRootFile = harmonyCoreComponent.createFileSymbol("DRIVER_ROOT", None)
driverHeaderRootFile.setSourcePath("driver/driver.h")
driverHeaderRootFile.setOutputName("driver.h")
driverHeaderRootFile.setDestPath("driver/")
driverHeaderRootFile.setProjectPath("config/" + configName + "/driver/")
driverHeaderRootFile.setType("HEADER")
driverHeaderRootFile.setOverwrite(True)
driverHeaderRootFile.setEnabled(False)
driverHeaderRootFile.setDependencies(genDriverHeaderRootFile, ["ENABLE_DRV_COMMON"])
driverHeaderCommonFile = harmonyCoreComponent.createFileSymbol("DRIVER_COMMON", None)
driverHeaderCommonFile.setSourcePath("driver/driver_common.h")
driverHeaderCommonFile.setOutputName("driver_common.h")
driverHeaderCommonFile.setDestPath("driver/")
driverHeaderCommonFile.setProjectPath("config/" + configName + "/driver/")
driverHeaderCommonFile.setType("HEADER")
driverHeaderCommonFile.setOverwrite(True)
driverHeaderCommonFile.setEnabled(False)
driverHeaderCommonFile.setDependencies(genDriverHeaderCommonFile, ["ENABLE_DRV_COMMON"])
|
#!/usr/bin/python
# -*- coding: UTF-8 -*-
fo_src = open("src/cv.tex", "r")
fo_rev = open("REVISION", "r")
fo_print = open("build/cv_print.tex", "w")
fo_screen = open("build/cv_screen.tex", "w")
try:
content = fo_src.read().replace('__REVISION__', fo_rev.read().strip())
fo_print.write(content.replace('__VERSION__', ',print'))
fo_screen.write(content.replace('__VERSION__', ''))
finally:
fo_src.close()
fo_print.close()
fo_screen.close()
|
# https://atcoder.jp/contests/math-and-algorithm/tasks/abc145_d
M = 10 ** 6 + 1
MOD = 10 ** 9 + 7
f = [0] * M
fi = [0] * M
iv = [0] * M
f[0] = f[1] = 1
fi[0] = fi[1] = 1
iv[1] = 1
for i in range(2, M):
f[i] = f[i - 1] * i % MOD
iv[i] = MOD - iv[MOD % i] * (MOD // i) % MOD
fi[i] = fi[i - 1] * iv[i] % MOD
def comb(n, k):
if n < k or n < 0 or k < 0:
return 0
return f[n] * (fi[k] * fi[n - k] % MOD) % MOD
x, y = map(int, input().split())
if (x + y) % 3 == 0:
a = (x + y) // 3
b = 2 * a - x
print(comb(a, b))
else:
print(0) |
"""
@author: Wenchang Yang (yang.wenchang@uci.edu)
"""
# ######## data paths on the IRI data library.
# surface
pr_cmap = 'http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCEP/.CPC/.Merged_Analysis/.monthly/.latest/.ver2/.prcp_est'
cmap = pr_cmap
pr_gpcc = 'http://iridl.ldeo.columbia.edu/SOURCES/.WCRP/.GCOS/.GPCC/.FDP/.version6/.0p5/.prcp/30/div//units/%28mm/day%29def'
gpcc = pr_gpcc
pr_gpcp = 'http://iridl.ldeo.columbia.edu/SOURCES/.NASA/.GPCP/.V2p2/.satellite-gauge/.prcp'
gpcp = pr_gpcp
pr_cru = 'http://iridl.ldeo.columbia.edu/SOURCES/.UEA/.CRU/.TS3p21/.monthly/.pre/30/div'
cru = pr_cru
pr_echam5 = 'http://iridl.ldeo.columbia.edu/SOURCES/.IRI/.FD/.ECHAM5/.T42/.History/.ensemble24/.MONTHLY/.surface/.prec/24/mul/3600/mul'
pr_echam4p5 = 'http://iridl.ldeo.columbia.edu/SOURCES/.IRI/.FD/.ECHAM4p5/.History/.MONTHLY/.surface/.prcp/1000/mul/24/mul/3600/mul'
pr_ncep2 = 'http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCEP-DOE/.Reanalysis-2/.Monthly/.dg3/.dg3/.pratesfc/24/mul/3600/mul'
pr_ncep = 'http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCEP-NCAR/.CDAS-1/.MONTHLY/.Diagnostic/.surface/.prate/24/mul/3600/mul'
# ocean surface
sst_ersst = 'http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCDC/.ERSST/.version3b/.sst%5Bzlev%5Daverage'
ersst = 'http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCDC/.ERSST/.version3b/.sst[zlev]average'
ersst4 = 'http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCDC/.ERSST/.version4/.sst[zlev]average'
oisst = 'http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCDC/.OISST/.version2/.AVHRR/.sst%5Bzlev%5Daverage/lon/%28X%29renameGRID/lat/%28Y%29renameGRID/T/%28T%29%28days%20since%201960-01-01%29ordered/7933.5/1/20144.5/NewEvenGRID/replaceGRID'
# atmosphere internal
omega_echam5 = 'http://iridl.ldeo.columbia.edu/SOURCES/.IRI/.FD/.ECHAM5/.T42/.History/.ensemble24/.MONTHLY/.PressureLevel/.omg'
omega_echam4p5 = 'http://iridl.ldeo.columbia.edu/SOURCES/.IRI/.FD/.ECHAM4p5/.History/.MONTHLY/.PressureLevel-SF/.omega'
omega_era40 = 'http://iridl.ldeo.columbia.edu/SOURCES/.ECMWF/.ERA-40/.MONTHLY/.PressureLevel/.wa'
omega_ncep2 = 'http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCEP-DOE/.Reanalysis-2/.Monthly/.pgb/.pgb/.vvelprs'
omega_ncep = 'http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCEP-NCAR/.CDAS-1/.MONTHLY/.Intrinsic/.PressureLevel/.vvel'
omega_ncep_daily = 'http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCEP-NCAR/.CDAS-1/.DAILY/.Intrinsic/.PressureLevel/.vvel'
omega_r2 = 'http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCEP-DOE/.Reanalysis-2/.Monthly/.pgb/.pgb/.vvelprs'
phi_ncep = 'http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCEP-NCAR/.CDAS-1/.MONTHLY/.Intrinsic/.PressureLevel/.phi'
phi_r2 = 'http://iridl.ldeo.columbia.eduhttp://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCEP-DOE/.Reanalysis-2/.Monthly/.pgb/.pgb/.hgtprs'
phis_ncep2 = 'http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCEP-DOE/.Reanalysis-2/.Monthly/.pgb/.pgb/.hgtsfc'
pr_era40 = 'http://iridl.ldeo.columbia.edu/SOURCES/.ECMWF/.ERA-40/.MONTHLY/.surface/.prc/SOURCES/.ECMWF/.ERA-40/.MONTHLY/.surface/.prl/add/1000/mul/4/mul'
ps_ncep = 'http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCEP-NCAR/.CDAS-1/.MONTHLY/.Diagnostic/.surface/.pressure'
ps_r2 = 'http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCEP-DOE/.Reanalysis-2/.Monthly/.pgb/.pgb/.pressfc'
q_ncep = 'http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCEP-NCAR/.CDAS-1/.MONTHLY/.Intrinsic/.PressureLevel/.qa'
qs_ncep = 'http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCEP-NCAR/.CDAS-1/.MONTHLY/.Diagnostic/.above_ground/.qa%5BZ%5Daverage'
ssta_rsoi = 'http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCEP/.EMC/.CMB/.GLOBAL/.Reyn_SmithOIv2/.monthly/.ssta'
ta_ncep = 'http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCEP-NCAR/.CDAS-1/.MONTHLY/.Intrinsic/.PressureLevel/.temp'
tas_ncep = 'http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCEP-NCAR/.CDAS-1/.MONTHLY/.Diagnostic/.above_ground/.temp%5BZ%5Daverage'
ta_r2 = 'http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCEP-DOE/.Reanalysis-2/.Monthly/.pgb/.pgb/.tmpprs'
trmm_daily = 'http://iridl.ldeo.columbia.edu/SOURCES/.NASA/.GES-DAAC/.TRMM_L3/.TRMM_3B42/.v7/.daily/.precipitation'
trmm = trmm_daily
u_ncep = 'http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCEP-NCAR/.CDAS-1/.MONTHLY/.Intrinsic/.PressureLevel/.u'
u_r2 = 'http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCEP-DOE/.Reanalysis-2/.Monthly/.pgb/.pgb/.ugrdprs'
us_ncep = 'http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCEP-NCAR/.CDAS-1/.MONTHLY/.Diagnostic/.above_ground/.u%5BZ%5Daverage'
v_ncep = 'http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCEP-NCAR/.CDAS-1/.MONTHLY/.Intrinsic/.PressureLevel/.v'
v_r2 = 'http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCEP-DOE/.Reanalysis-2/.Monthly/.pgb/.pgb/.vgrdprs'
vs_ncep = 'http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCEP-NCAR/.CDAS-1/.MONTHLY/.Diagnostic/.above_ground/.v%5BZ%5Daverage'
# topo and land-sea mask
land_sea_mask = 'http://iridl.ldeo.columbia.edu/SOURCES/.NASA/.ISLSCP/.GDSLAM/.Miscellaneous/.land_sea_mask'
topo = 'http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NGDC/.GLOBE/.topo'
topo_worldbath = 'http://iridl.ldeo.columbia.edu/SOURCES/.WORLDBATH/.bath'
topo_Peltier = 'http://iridl.ldeo.columbia.edu/SOURCES/.PELTIER/.topography/T/0/VALUE%5BT%5Daverage'
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = 'check_coverage'
__author__ = 'JieYuan'
__mtime__ = '19-1-31'
"""
# from gensim.models import KeyedVectors
#
# news_path = '../input/embeddings/GoogleNews-vectors-negative300/GoogleNews-vectors-negative300.bin'
# embeddings_index = KeyedVectors.load_word2vec_format(news_path, binary=True)
#
# import operator
#
#
# def check_coverage(vocab, embeddings_index):
# a = {}
# oov = {}
# k = 0
# i = 0
# for word in tqdm(vocab):
# try:
# a[word] = embeddings_index[word]
# k += vocab[word]
# except:
#
# oov[word] = vocab[word]
# i += vocab[word]
# pass
#
# print('Found embeddings for {:.2%} of vocab'.format(len(a) / len(vocab)))
# print('Found embeddings for {:.2%} of all text'.format(k / (k + i)))
# sorted_x = sorted(oov.items(), key=operator.itemgetter(1))[::-1]
#
# return sorted_x
#
#
# if __name__ == '__main__':
# oov = check_coverage(vocab, embeddings_index)
|
class Ugly:
def isUgly(self, num: int) -> bool:
num=int(num)
while num:
if num==0:
return False
while num%2 ==0:
num=num/2
while num%3 ==0:
num=num/3
while num%5==0:
num=num/5
if num==1:
return True
elif num!=1:
return False
print(Ugly().isUgly(14))
print(Ugly().isUgly(1))
print(Ugly().isUgly(5))
print(Ugly().isUgly(1928263))
print(Ugly().isUgly(900)) |
class Solution:
def peakIndexInMountainArray(self, A: List[int]) -> int:
if not A:
return None
return A.index(max(A)) |
def _res_statement(items):
statements = ""
for variable_name, value in items.items():
statements += """
<string name=\\"{}\\">{}</string>""".format(variable_name, value)
return statements
def _generate_xml(items):
statements = """<?xml version=\\"1.0\\" encoding=\\"utf-8\\"?>
<resources>{}
</resources>
"""
return statements.format(items)
def res_value(
name,
custom_package,
manifest,
strings = {}):
"""Generates an android library target that exposes values specified in strings
as generated resources xml.
Usage:
Provide the string variables in the string dictionary and add a dependency on this target.
Args:
name: name for this target,
custom_package: package used for Android resource processing,
manifest: required when resource_files are defined,
strings: string value of type string
"""
res_value_file = "src/main/res/values/gen_strings.xml"
strings_statements = _res_statement(strings)
xml_generation = _generate_xml(strings_statements)
cmd = """echo "{xml_generation}" > $@""".format(xml_generation = xml_generation)
native.genrule(
name = "_" + name,
outs = [res_value_file],
message = "Generating %s's resources" % (native.package_name()),
cmd = cmd,
)
native.android_library(
name = name,
manifest = manifest,
custom_package = custom_package,
resource_files = [res_value_file],
)
|
class TreeNode:
def __init__(self,key):
self.left = None
self.right = None
self.data = key
# Function to insert node in tree recursively
def insertNode(root,node):
if root is None:
root = node
else:
if root.data < node.data:
if root.right is None:
root.right = node
else:
insertNode(root.right, node)
else:
if root.left is None:
root.left = node
else:
insertNode(root.left, node)
# Function to print inorder traversal recursively
def inOrderTraversal(root, li):
if root:
inOrderTraversal(root.left, li)
li.append(root.data)
inOrderTraversal(root.right, li)
# Creating a new BST with root as 50
r = TreeNode(55)
insertNode(r,TreeNode(35))
insertNode(r,TreeNode(25))
insertNode(r,TreeNode(45))
insertNode(r,TreeNode(75))
insertNode(r,TreeNode(65))
insertNode(r,TreeNode(85))
# Print inoder traversal of the BST
ll =[]
inOrderTraversal(r, ll)
print(ll) |
# Search in a list
def contains(items:[int], x:int) -> bool:
i:int = 0
while i < len(items):
if items[i] == x:
return True
i = i + 1
return False
if contains([4, 8, 15, 16, 23], 15):
print("Item found!") # Prints this
else:
print("Item not found.")
|
class ChannelRaid:
"""Classe definissant le contenu en cours des channels de raid:
- NB_CHANNEL: nombre de channel construites par le bot
- id: numero du cannal
- raid: descripsion du raid en cours, si raid = 0 alors c'est vide
- com: l'objet discord.channel qui permet de communiquer simplement avec le rest du forum
- pinMsg: message decrivant le raid de la channel (c'est plus simple que de le chercher)
- listMsg"""
nb_channel = 0
def __init__(self, com):
"""initialisation d'une channel avec pour seul information son ID, le raid est initialisé à 0"""
ChannelRaid.nb_channel += 1
self.raid = 0
self.id = ChannelRaid.nb_channel
self.com = com
self.pinMsg = 0
self.listMsg = 0
def ajouterRaid(self, raid):
"""ajoute un raid dans une channel libre
retourne le raid si l'ajout a marché
retourn 0 sinon"""
if self.raid == 0:
self.raid = raid
raid.id = self.id
return self
return 0
def retirerRaid(self):
"""retirer le raid en cour dans la channel"""
if self.raid != 0:
self.raid = 0
return 1
def channelLibre(channels):
"""renvoit la channel de plus petit numero libre pour ajouter un nouveau canal
renvoit 0 sinon"""
for channel in channels.values():
if channel.raid == 0:
return channel
return 0
def isRaid(self):
"""renvoit 1 si un raid est présent 0 sinon"""
if self.raid == 0:
return 0
else:
return 1
def updateChannelList(channels):
"""retourne un message contenant les carracteristique des channels"""
message = 0
for channel in channels.values():
if channel.raid == 0:
message += str("Pas de raid en cours sur #raid-%i \n" %(channel.id))
else:
message += channel.raid.afficherList()
return message
|
def standardize_money(value, unit):
std_unit = '元'
lookup_table = {'元':1, '块钱':1, '角':1e-1, '分':1e-2}
std_value = value * lookup_table[unit]
return {'std_value':std_value, 'std_unit':std_unit}
def standardize_weight(value, unit):
std_unit = '克'
lookup_table = {'毫克':1e-3, '克':1, '千克':1e3, 'kg':1e3, '吨':1e6, '斤':5e2, '公斤':1e3}
std_value = value * lookup_table[unit]
return {'std_value':std_value, 'std_unit':std_unit}
def standardize_BAC(value, unit):
std_unit = 'mg/100ml'
lookup_table = {'mg/100ml':1, 'mg/ml':1e2, '毫克/100毫升':1, '毫克/毫升':1e2}
std_value = value * lookup_table[unit]
return {'std_value':std_value, 'std_unit':std_unit}
|
__all__ = ()
class ConnectionKey:
"""
Contains information about a host, like proxy, TLS to prevent reusing wrong connections from the pool.
Attributes
----------
host : `str`
The host's ip address.
is_ssl : `bool`
Whether the connection is secure.
port : `int`
The host's port.
proxy_auth : `None`, ``BasicAuth``
Proxy authorization.
proxy_url : `None`, ``URL``
Proxy's url.
ssl : `None`, ``SSLContext``, `bool`, ``Fingerprint``
The connection's ssl type.
"""
__slots__ = ('host', 'is_ssl', 'port', 'proxy_auth', 'proxy_url', 'ssl',) # + 'proxy_header_hash',
def __init__(self, request):
# proxy_headers = request.proxy_headers
# if request.proxy_headers is not None:
# proxy_header_hash = hash(tuple(proxy_headers.items()))
# else:
# proxy_header_hash = None
self.host = request.host
self.port = request.port
self.is_ssl = request.is_ssl()
self.ssl = request.ssl
self.proxy_auth = request.proxy_auth
self.proxy_url = request.proxy_url
# self.proxy_header_hash = proxy_header_hash
def __repr__(self):
"""Returns the connection key's representation."""
return f'<{self.__class__.__name__} host={self.host!r}, port={self.port!r}>'
def __eq__(self, other):
"""Returns whether the two connection keys are equal."""
if type(self) is not type(other):
return NotImplemented
if self.host != other.host:
return False
if self.port != other.port:
return False
if self.is_ssl != other.is_ssl:
return False
if self.ssl is None:
if other.ssl is not None:
return False
else:
if other.ssl is None:
return False
if self.ssl != other.ssl:
return False
if self.proxy_auth is None:
if other.proxy_auth is not None:
return False
else:
if other.proxy_auth is None:
return False
if self.proxy_auth != other.proxy_auth:
return False
if self.proxy_url is None:
if other.proxy_url is not None:
return False
else:
if other.proxy_url is None:
return False
if self.proxy_url != other.proxy_url:
return False
return True
def __hash__(self):
"""Returns the connection key's hash value."""
return hash(self.host) ^ (self.port << 17) ^ hash(self.is_ssl) ^ hash(self.ssl) ^ hash(self.proxy_auth) ^ \
hash(self.proxy_url)
|
__title__ = 'sec-edgar-financials'
__description__ = 'Extract financial data from the SEC EDGAR database'
__url__ = 'https://github.com/farhadab/sec-edgar-financials'
__version__ = '0.0.1'
__author__ = 'Farhad Abdolhosseini'
__author_email__ = 'farhadab15@gmail.com'
__license__ = 'MIT'
# __copyright__ = 'Copyright 2019 Farhad Abdolhosseini' |
"""Reusable static data."""
COMMIT = """
<lock-configuration/>
<commit/>
<unlock-configuration/>
"""
COMMIT_CHECK = """
<commit-configuration>
<check/>
</commit-configuration>
"""
CONFIG_JSON = """
<lock-configuration/>
<load-configuration format="json">
<configuration-json>
{config}
</configuration-json>
</load-configuration>
<commit/>
<unlock-configuration/>
"""
RESULTS = """<results>{results}</results>"""
|
"""
Calculates the normal distribution's probability density
function (PDF).
Calculates Standard normal pdf for mean=0, std_dev=1.
Equation:
f(x) = 1 / sqrt(2*pi) * e^(-(x-mean)^2/ 2*std_dev^2)
"""
def pdf(x, mean=0, std_dev=1):
PI = 3.141592653589793
E = 2.718281828459045
term1 = 1.0 / ( (2 * PI)**0.5 )
term2 = E**( -1.0* (x-mean)**2.0 / 2.0*(std_dev**2.0) )
return term1 * term2
|
# -*- coding: utf-8 -*-
{
'\n\nThank you!': '\n\nThank you!',
'\n\nWe will wait and let you know when your payment is confirmed.': '\n\nWe will wait and let you know when your payment is confirmed.',
'\n- %s from %s to %s': '\n- %s from %s to %s',
'\nAmount: R$%.2f': '\nAmount: R$%.2f',
"\nSomething happened and we couldn't verify your payment.\n": "\nSomething happened and we couldn't verify your payment.\n",
'\nThank you for your purchase!': '\nThank you for your purchase!',
'\nThank you!': '\nThank you!',
'\nThank you.': '\nThank you.',
'\nThe total amount was R$%.2f.': '\nThe total amount was R$%.2f.',
'\nWe will wait and let you know when your payment is confirmed.\n': '\nWe will wait and let you know when your payment is confirmed.\n',
'\nYou can check your payment history after login in to your profile.': '\nYou can check your payment history after login in to your profile.',
'!langcode!': 'fr',
'!langname!': 'Français',
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" est une expression optionnelle comme "champ1=\'nouvellevaleur\'". Vous ne pouvez mettre à jour ou supprimer les résultats d\'un JOIN',
'%(month)s %(day)sth': '%(month)s %(day)sth',
'%02d/%02d': '%02d/%02d',
'%B %d, %Y': '%B %d, %Y',
'%d%% OFF': '%d%% OFF',
'%d/%d': '%d/%d',
'%m-%d-%Y': '%m-%d-%Y',
'%s %%{row} deleted': '%s lignes supprimées',
'%s %%{row} updated': '%s lignes mises à jour',
'%s %dth': '%s %dth',
'%s Certificate': '%s Certificate',
'%s of %s': '%s of %s',
'%s selected': '%s sélectionné',
'%Y-%m-%d': '%Y-%m-%d',
'%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S',
'- %s from %s to %s': '- %s from %s to %s',
'- %s from %s to %s\n': '- %s from %s to %s\n',
'?': '?',
'About': 'À propos',
'Access': 'Access',
'Access Control': "Contrôle d'accès",
'Access the /appadmin to make at least one teacher user:': 'Access the /appadmin to make at least one teacher user:',
'Actions': 'Actions',
'Add more': 'Add more',
'Administrative interface': "Interface d'administration",
'Administrative Interface': "Interface d'administration",
'Ajax Recipes': 'Recettes Ajax',
'All certificates sent!': 'All certificates sent!',
'All Classes': 'All Classes',
'Alternative A': 'Alternative A',
'Alternative B': 'Alternative B',
'Alternative C': 'Alternative C',
'Alternative D': 'Alternative D',
'Amount': 'Amount',
'Amount: R$%.2f': 'Amount: R$%.2f',
'Amount: R$%.2f\n': 'Amount: R$%.2f\n',
'and enroll!': 'and enroll!',
'and go to': 'and go to',
'Announcements': 'Announcements',
'appadmin is disabled because insecure channel': "appadmin est désactivée parce que le canal n'est pas sécurisé",
'Are you sure you want to delete this object?': 'Êtes-vous sûr de vouloir supprimer cet objet?',
'Authentication': 'Authentification',
'Available Databases and Tables': 'Bases de données et tables disponibles',
'Available Until': 'Available Until',
'Banner': 'Banner',
'Body': 'Body',
'Buy Now': 'Buy Now',
'Buy this book': 'Acheter ce livre',
'Cache': 'Cache',
'cache': 'cache',
'Cache Cleared': 'Cache Cleared',
'Cache Keys': 'Clés de cache',
'Calendar': 'Calendar',
'Cannot be empty': 'Ne peut pas être vide',
'Certificates': 'Certificates',
'change password': 'changer le mot de passe',
'Check to delete': 'Cliquez pour supprimer',
'Check to delete:': 'Cliquez pour supprimer:',
'Class %s': 'Class %s',
'Class Id': 'Class Id',
'Classes': 'Classes',
'Clear CACHE?': 'Vider le CACHE?',
'Clear DISK': 'Vider le DISQUE',
'Clear RAM': 'Vider la RAM',
'Client IP': 'IP client',
'Closed': 'Closed',
'Community': 'Communauté',
'Components and Plugins': 'Composants et Plugins',
'Confirmation Time': 'Confirmation Time',
'Confirmed': 'Confirmed',
'Contact': 'Contact',
'Continue Shopping': 'Continue Shopping',
'Controller': 'Contrôleur',
'Copyright': 'Copyright',
'Correct Alternative': 'Correct Alternative',
'Course': 'Course',
'Course Announcements': 'Course Announcements',
'Course Id': 'Course Id',
"Course's end": "Course's end",
"Course's start": "Course's start",
'Courses': 'Courses',
'Created By': 'Créé par',
'Created On': 'Créé le',
'Current request': 'Demande actuelle',
'Current response': 'Réponse actuelle',
'Current session': 'Session en cours',
'customize me!': 'personnalisez-moi!',
'DASHBOARD': 'DASHBOARD',
'Dashboard': 'Dashboard',
'data uploaded': 'données téléchargées',
'Database': 'base de données',
'Database %s select': 'base de données %s selectionnée',
'Database Administration (appadmin)': 'Database Administration (appadmin)',
'Date': 'Date',
'db': 'bdd',
'DB Model': 'Modèle BDD',
'Delete': 'Delete',
'Delete:': 'Supprimer:',
'Demo': 'Démo',
'Denied': 'Denied',
'Deployment Recipes': 'Recettes de déploiement',
'Description': 'Description',
'design': 'design',
'Details': 'Details',
'Discount': 'Discount',
'DISK': 'DISQUE',
'Disk Cache Keys': 'Clés de cache du disque',
'Disk Cleared': 'Disque vidé',
'Documentation': 'Documentation',
"Don't know what to do?": 'Vous ne savez pas quoi faire?',
'done!': 'fait!',
'Download': 'Téléchargement',
'E-mail': 'E-mail',
'Edit': 'Éditer',
'Edit current record': "Modifier l'enregistrement courant",
'edit profile': 'modifier le profil',
'Edit This App': 'Modifier cette application',
'Email and SMS': 'Email et SMS',
'End': 'End',
'End date': 'End date',
'End Date': 'End Date',
'Enroll now!': 'Enroll now!',
'enter an integer between %(min)g and %(max)g': 'entrez un entier entre %(min)g et %(max)g',
'Enter the auth_membership table and associate your new user to the "Teacher" group': 'Enter the auth_membership table and associate your new user to the "Teacher" group',
'Enter the auth_user table and create a new record': 'Enter the auth_user table and create a new record',
'Enter with your teacher user and create your course, classes and lessons': 'Enter with your teacher user and create your course, classes and lessons',
'Errors': 'Erreurs',
'Erros no formulário!': 'Erros no formulário!',
'export as csv file': 'exporter sous forme de fichier csv',
'FAQ': 'FAQ',
'First name': 'Prénom',
'First, import a template and signature!': 'First, import a template and signature!',
'Form has errors!': 'Form has errors!',
'Forms and Validators': 'Formulaires et Validateurs',
'Forum': 'Forum',
'FREE': 'FREE',
'Free Applications': 'Applications gratuites',
'from %s to %s': 'from %s to %s',
'FULL!': 'FULL!',
'Function disabled': 'Fonction désactivée',
'Generate Certificate': 'Generate Certificate',
'Graph Model': 'Graph Model',
'Group ID': 'Groupe ID',
'Groups': 'Groupes',
'has satisfactorily completed the course': 'has satisfactorily completed the course',
'Hello World': 'Bonjour le monde',
'Home': 'Accueil',
'hours': 'hours',
'How did you get here?': 'Comment êtes-vous arrivé ici?',
'Icon': 'Icon',
'If you want to test, just': 'If you want to test, just',
"If you're sure you paid the order, please contact us. Otherwise, try to pay again later.": "If you're sure you paid the order, please contact us. Otherwise, try to pay again later.",
"If you're sure you paid the order, please contact us. Otherwise, try to pay again later.\n": "If you're sure you paid the order, please contact us. Otherwise, try to pay again later.\n",
'import': 'import',
'Import/Export': 'Importer/Exporter',
'in a total of %d hours.': 'in a total of %d hours.',
'In Progress': 'In Progress',
'Index': 'Index',
'insert new': 'insérer un nouveau',
'insert new %s': 'insérer un nouveau %s',
'Interested? Submit your email below to be notified for the next open class.': 'Interested? Submit your email below to be notified for the next open class.',
'Interests': 'Interests',
'Internal State': 'État interne',
'Introduction': 'Introduction',
'Invalid email': 'E-mail invalide',
'Invalid Query': 'Requête Invalide',
'invalid request': 'requête invalide',
'Is Active': 'Est actif',
'Key': 'Clé',
'Last name': 'Nom',
'Layout': 'Mise en page',
'Layout Plugins': 'Plugins de mise en page',
'Layouts': 'Mises en page',
'Lesson': 'Lesson',
'Lesson Id': 'Lesson Id',
'Lesson scheduled for:': 'Lesson scheduled for:',
'Lesson Type': 'Lesson Type',
'Limit date:': 'Limit date:',
'limited to': 'limited to',
'Live chat': 'Chat en direct',
'Live Chat': 'Chat en direct',
'Log In': 'Log In',
'Login': 'Connectez-vous',
'login': 'connectez-vous',
'logout': 'déconnectez-vous',
'Logout': 'Logout',
'Lost Password': 'Mot de passe perdu',
'lost password': 'mot de passe perdu',
'Lost password?': 'Mot de passe perdu?',
'lost password?': 'mot de passe perdu?',
'Main Menu': 'Menu principal',
'Manage %(action)s': 'Manage %(action)s',
'Manage Access Control': 'Manage Access Control',
'Manage Cache': 'Gérer le Cache',
'Manage courses': 'Manage courses',
'Max Students': 'Max Students',
'Max. Students': 'Max. Students',
'Memberships': 'Memberships',
'Menu Model': 'Menu modèle',
'Modified By': 'Modifié par',
'Modified On': 'Modifié le',
'Module': 'Module',
'Modules': 'Modules',
'My Calendar': 'My Calendar',
'My Certificates': 'My Certificates',
'My Courses': 'My Courses',
'My courses': 'My courses',
'My Sites': 'Mes sites',
'My Work': 'My Work',
'Name': 'Nom',
'New': 'New',
'New announcement': 'New announcement',
'New announcement on %s class': 'New announcement on %s class',
'New Class': 'New Class',
'New Course': 'New Course',
'New lesson': 'New lesson',
'New module': 'New module',
'New Record': 'Nouvel enregistrement',
'new record inserted': 'nouvel enregistrement inséré',
'New Topic': 'New Topic',
'New topic': 'New topic',
'next %s rows': 'next %s rows',
'next 100 rows': '100 prochaines lignes',
'No announcements yet!': 'No announcements yet!',
'No databases in this application': "Cette application n'a pas de bases de données",
"Now, you won't be able to see the lessons anymore. But the forum, announcements and other resources are still available.": "Now, you won't be able to see the lessons anymore. But the forum, announcements and other resources are still available.",
'Object or table name': 'Objet ou nom de table',
'Online examples': 'Exemples en ligne',
'Open classes': 'Open classes',
'Open Enrollment': 'Open Enrollment',
'or import from csv file': "ou importer d'un fichier CSV",
'Order': 'Order',
'Order Date': 'Order Date',
'Order date': 'Order date',
'Order details': 'Order details',
'Order Id': 'Order Id',
'Order Nº': 'Order Nº',
'Origin': 'Origine',
'Other Plugins': 'Autres Plugins',
'Other Recipes': 'Autres recettes',
'Overview': 'Présentation',
'Owner': 'Owner',
'Password': 'Mot de passe',
"Password fields don't match": 'Les mots de passe ne correspondent pas',
'Payment completed! Congratulations for your purchase!': 'Payment completed! Congratulations for your purchase!',
'Payment confirmed!': 'Payment confirmed!',
'Payment History': 'Payment History',
'Pending': 'Pending',
'Pending Id': 'Pending Id',
'Permission': 'Permission',
'Permissions': 'Permissions',
'Place': 'Place',
'Please, select which type of lesson you want to create.': 'Please, select which type of lesson you want to create.',
'Plugins': 'Plugins',
'Post': 'Post',
'Powered by': 'Alimenté par',
'Preface': 'Préface',
'Preview': 'Preview',
'previous %s rows': 'previous %s rows',
'previous 100 rows': '100 lignes précédentes',
'Price': 'Price',
'Products': 'Products',
'Professor': 'Professor',
'pygraphviz library not found': 'pygraphviz library not found',
'Python': 'Python',
'Query:': 'Requête:',
'Question': 'Question',
'Quick Examples': 'Exemples Rapides',
'RAM': 'RAM',
'RAM Cache Keys': 'Clés de cache de la RAM',
'Ram Cleared': 'Ram vidée',
'Readme': 'Lisez-moi',
'Recipes': 'Recettes',
'Record': 'enregistrement',
'record does not exist': "l'archive n'existe pas",
'Record ID': "ID d'enregistrement",
'Record id': "id d'enregistrement",
'register': "s'inscrire",
'Register': "S'inscrire",
'register a normal user': 'register a normal user',
'Registered On': 'Registered On',
'Registration identifier': "Identifiant d'enregistrement",
'Registration key': "Clé d'enregistrement",
'Release Date': 'Release Date',
'Remember me (for 30 days)': 'Se souvenir de moi (pendant 30 jours)',
'Replies': 'Replies',
'Reply this user': 'Reply this user',
'Request reset password': 'Demande de réinitialiser le mot clé',
'Reset Password key': 'Réinitialiser le mot clé',
'Resources': 'Ressources',
'Role': 'Rôle',
'Roles': 'Roles',
'Rows in Table': 'Lignes du tableau',
'Rows selected': 'Lignes sélectionnées',
'said': 'said',
'Save model as...': 'Save model as...',
'Schedule Date': 'Schedule Date',
'Schedule event': 'Schedule event',
'Semantic': 'Sémantique',
'Send to Students': 'Send to Students',
'Services': 'Services',
'Settings': 'Settings',
'Shopping Cart': 'Shopping Cart',
'Short Description': 'Short Description',
'Sign Up': 'Sign Up',
'Signature': 'Signature',
'Size of cache:': 'Taille du cache:',
"Something happened and we couldn't verify your payment.": "Something happened and we couldn't verify your payment.",
'Something went wrong!': 'Something went wrong!',
'Sorry! Something bad happened!': 'Sorry! Something bad happened!',
'Start': 'Start',
'Start date': 'Start date',
'Start Date': 'Start Date',
'Starting on': 'Starting on',
'state': 'état',
'Statistics': 'Statistiques',
'Status': 'Status',
'Student': 'Student',
'students max': 'students max',
'Stylesheet': 'Feuille de style',
'Submit': 'Soumettre',
'submit': 'soumettre',
'Support': 'Support',
'Sure you want to delete this object?': 'Êtes-vous sûr de vouloir supprimer cet objet?',
'Table': 'tableau',
'Table name': 'Nom du tableau',
'Take a look at our Courses': 'Take a look at our Courses',
'Template': 'Template',
'Text': 'Text',
'Thank you for your purchase!': 'Thank you for your purchase!',
'Thank you!': 'Thank you!',
'Thank you.': 'Thank you.',
'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'La "requête" est une condition comme "db.table1.champ1==\'valeur\'". Quelque chose comme "db.table1.champ1==db.table2.champ2" résulte en un JOIN SQL.',
'The Core': 'Le noyau',
'The following classes have a limit date of conclusion:': 'The following classes have a limit date of conclusion:',
'The output of the file is a dictionary that was rendered by the view %s': 'La sortie de ce fichier est un dictionnaire qui été restitué par la vue %s',
'The total amount was R$%.2f.': 'The total amount was R$%.2f.',
'The total amount was R$%.2f.\n': 'The total amount was R$%.2f.\n',
'The Views': 'Les Vues',
'There is a new announcement on %s class.': 'There is a new announcement on %s class.',
'There was a problem with this video!': 'There was a problem with this video!',
'There was a problem with your payment!': 'There was a problem with your payment!',
'There was a problem with your payment!\n': 'There was a problem with your payment!\n',
'These people are interested in your course %s': 'These people are interested in your course %s',
'This App': 'Cette Appli',
'This class has a limit date for conclusion.': 'This class has a limit date for conclusion.',
'This class reached the limit date': 'This class reached the limit date',
'This course is already on your shopping cart!': 'This course is already on your shopping cart!',
'This is a copy of the scaffolding application': "Ceci est une copie de l'application échafaudage",
'This is to certify that': 'This is to certify that',
"This means that, after the limit date, you won't be able to see the lessons anymore. Forum, announcements and other resources will still be available.": "This means that, after the limit date, you won't be able to see the lessons anymore. Forum, announcements and other resources will still be available.",
'Time in Cache (h:m:s)': 'Temps en Cache (h:m:s)',
'Timestamp': 'Horodatage',
'Title': 'Title',
'to finish your payment.': 'to finish your payment.',
'Token': 'Token',
'Total': 'Total',
'Total Hours': 'Total Hours',
'Traceback': 'Traceback',
'Twitter': 'Twitter',
'unable to parse csv file': "incapable d'analyser le fichier cvs",
'Update:': 'Mise à jour:',
'Upload Video': 'Upload Video',
'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Employez (...)&(...) pour AND, (...)|(...) pour OR, and ~(...) pour NOT afin de construire des requêtes plus complexes.',
'User': 'User',
'User %(id)s Logged-in': 'Utilisateur %(id)s connecté',
'User %(id)s Registered': 'Utilisateur %(id)s enregistré',
'User Area - Courses': 'User Area - Courses',
'User avatar': 'User avatar',
'User Class': 'User Class',
'User Id': 'User Id',
'User ID': 'ID utilisateur',
'User Lesson': 'User Lesson',
'User Voice': "Voix de l'utilisateur",
'Users': 'Users',
'Verify Password': 'Vérifiez le mot de passe',
'Video': 'Video',
'Video file': 'Video file',
'Video URL': 'Video URL',
'Videos': 'Vidéos',
'View': 'Présentation',
'View course': 'View course',
'Wait a few seconds.': 'Wait a few seconds.',
"We couldn't find any video here. Please, alert your instructor about this problem!": "We couldn't find any video here. Please, alert your instructor about this problem!",
'We just confirmed your payment for order number %s.': 'We just confirmed your payment for order number %s.',
'We just confirmed your payment for order number %s.\n': 'We just confirmed your payment for order number %s.\n',
'We just received your order number %s:': 'We just received your order number %s:',
'We just received your order number %s:\n': 'We just received your order number %s:\n',
'We received your order!': 'We received your order!',
'We will wait and let you know when your payment is confirmed.': 'We will wait and let you know when your payment is confirmed.',
'Web2py': 'Web2py',
'Welcome': 'Bienvenue',
'Welcome %s': 'Bienvenue %s',
'Welcome to web2py': 'Bienvenue à web2py',
'Welcome to web2py!': 'Bienvenue à web2py!',
'Which called the function %s located in the file %s': 'Qui a appelé la fonction %s se trouvant dans le fichier %s',
"Why don't you follow this steps to start making your courses?": "Why don't you follow this steps to start making your courses?",
'Working...': 'Working...',
'You are already enrolled in this class to %s, so we removed it from your shopping cart.': 'You are already enrolled in this class to %s, so we removed it from your shopping cart.',
'You are already on the list for this course!': 'You are already on the list for this course!',
'You are already on this class!': 'You are already on this class!',
'You are already registered!': 'You are already registered!',
'You are successfully running web2py': 'Vous exécutez avec succès web2py',
'You can access it here: %s': 'You can access it here: %s',
'You can check your payment history after login in to your profile.': 'You can check your payment history after login in to your profile.',
'You can check your payment history after login in to your profile.\n': 'You can check your payment history after login in to your profile.\n',
'You can modify this application and adapt it to your needs': "Vous pouvez modifier cette application et l'adapter à vos besoins",
'You have nothing in your shopping cart yet!': 'You have nothing in your shopping cart yet!',
'You visited the url %s': "Vous avez visité l'URL %s",
"You're beeing redirected to a secure enviroment on Paypal": "You're beeing redirected to a secure enviroment on Paypal",
'Your browser does not support the video tag.': 'Your browser does not support the video tag.',
'Your Certificate of Conclusion of %s is attached to this email. For more info, contact your teacher.\n\nCongratulations!': 'Your Certificate of Conclusion of %s is attached to this email. For more info, contact your teacher.\n\nCongratulations!',
'Your email': 'Your email',
}
|
def binary_search(a,x):
first_pos=0
last_pos=len(a)-1
flag=0
count=0
while(first_pos<=last_pos and flag==0):
count=count+1
mid=(first_pos+last_pos)//2
if(x==a[mid]):
flag==1
print("The element is present at position:",str(mid))
print("Number of iterations:",str(count))
return
else:
if(x<a[mid]):
last_pos=mid-1
else:
first_pos=mid+1
print("The number is not present")
a=[]
for i in range(1,1001):
a.append(i)
binary_search(a,1000) |
#
# PySNMP MIB module Juniper-REDUNDANCY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-REDUNDANCY-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:53:26 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ConstraintsIntersection, SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ConstraintsUnion", "ValueSizeConstraint")
juniMibs, = mibBuilder.importSymbols("Juniper-MIBs", "juniMibs")
NotificationGroup, ObjectGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ObjectGroup", "ModuleCompliance")
sysUpTime, = mibBuilder.importSymbols("SNMPv2-MIB", "sysUpTime")
MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, Gauge32, TimeTicks, IpAddress, iso, ObjectIdentity, Counter32, Integer32, Bits, ModuleIdentity, Counter64, MibIdentifier, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32", "Gauge32", "TimeTicks", "IpAddress", "iso", "ObjectIdentity", "Counter32", "Integer32", "Bits", "ModuleIdentity", "Counter64", "MibIdentifier", "NotificationType")
TextualConvention, RowStatus, DisplayString, DateAndTime, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "RowStatus", "DisplayString", "DateAndTime", "TruthValue")
juniRedundancyMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74))
juniRedundancyMIB.setRevisions(('2003-12-12 00:00',))
if mibBuilder.loadTexts: juniRedundancyMIB.setLastUpdated('200312122104Z')
if mibBuilder.loadTexts: juniRedundancyMIB.setOrganization('Juniper Networks, Inc.')
class JuniRedundancyState(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))
namedValues = NamedValues(("notKnown", 1), ("fileSystemSyncing", 2), ("disabled", 3), ("initializing", 4), ("pending", 5), ("active", 6))
class JuniRedundancyMode(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("fileSystemSynchronization", 1), ("highAvailability", 2))
class JuniRedundancyResetReason(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3))
namedValues = NamedValues(("none", 1), ("notKnown", 2), ("userInitiated", 3))
class JuniRedundancySystemActivationType(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3))
namedValues = NamedValues(("reload", 1), ("coldSwitch", 2), ("warmSwitch", 3))
class JuniRedundancyResetType(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))
namedValues = NamedValues(("notKnown", 1), ("srpReload", 2), ("srpSwitchover", 3), ("linecardReload", 4), ("linecardSwitchover", 5))
class JuniRedundancyHistoryCommand(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("keep", 1), ("clear", 2))
juniRedundancyNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 0))
juniRedundancyObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1))
juniRedundancyMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 2))
juniRedundancyStatus = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1, 1))
juniRedundancyCfg = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1, 2))
juniRedundancyHistory = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1, 3))
juniRedundancyActiveSlot = MibScalar((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: juniRedundancyActiveSlot.setStatus('current')
juniRedundancyActiveSlotState = MibScalar((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1, 1, 2), JuniRedundancyState()).setMaxAccess("readonly")
if mibBuilder.loadTexts: juniRedundancyActiveSlotState.setStatus('current')
juniRedundancyStandbySlot = MibScalar((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: juniRedundancyStandbySlot.setStatus('current')
juniRedundancyStandbySlotState = MibScalar((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1, 1, 4), JuniRedundancyState()).setMaxAccess("readonly")
if mibBuilder.loadTexts: juniRedundancyStandbySlotState.setStatus('current')
juniRedundancyLastResetReason = MibScalar((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1, 1, 5), JuniRedundancyResetReason()).setMaxAccess("readonly")
if mibBuilder.loadTexts: juniRedundancyLastResetReason.setStatus('current')
juniRedundancyLastSystemActivationTime = MibScalar((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1, 1, 6), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: juniRedundancyLastSystemActivationTime.setStatus('current')
juniRedundancyLastSystemActivationType = MibScalar((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1, 1, 7), JuniRedundancySystemActivationType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: juniRedundancyLastSystemActivationType.setStatus('current')
juniRedundancyHaActiveTime = MibScalar((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1, 1, 8), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: juniRedundancyHaActiveTime.setStatus('current')
juniRedundancyNotifsEnabled = MibScalar((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1, 2, 1), TruthValue().clone('true')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniRedundancyNotifsEnabled.setStatus('current')
juniRedundancyCfgRedundancyMode = MibScalar((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1, 2, 2), JuniRedundancyMode().clone('fileSystemSynchronization')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniRedundancyCfgRedundancyMode.setStatus('current')
juniRedundancySystemActivationHistoryTableMaxLength = MibScalar((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1, 3, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 50))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniRedundancySystemActivationHistoryTableMaxLength.setStatus('current')
juniRedundancySystemActivationHistoryCommand = MibScalar((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1, 3, 2), JuniRedundancyHistoryCommand().clone('keep')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: juniRedundancySystemActivationHistoryCommand.setStatus('current')
juniRedundancySystemActivationHistoryTable = MibTable((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1, 3, 3), )
if mibBuilder.loadTexts: juniRedundancySystemActivationHistoryTable.setStatus('current')
juniRedundancySystemActivationHistoryEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1, 3, 3, 1), ).setIndexNames((0, "Juniper-REDUNDANCY-MIB", "juniRedundancySystemActivationHistoryIndex"))
if mibBuilder.loadTexts: juniRedundancySystemActivationHistoryEntry.setStatus('current')
juniRedundancySystemActivationHistoryIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1, 3, 3, 1, 1), Integer32())
if mibBuilder.loadTexts: juniRedundancySystemActivationHistoryIndex.setStatus('current')
juniRedundancyHistoryResetType = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1, 3, 3, 1, 2), JuniRedundancyResetType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: juniRedundancyHistoryResetType.setStatus('current')
juniRedundancyHistoryActivationType = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1, 3, 3, 1, 3), JuniRedundancySystemActivationType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: juniRedundancyHistoryActivationType.setStatus('current')
juniRedundancyHistoryPrevActiveSlot = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1, 3, 3, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: juniRedundancyHistoryPrevActiveSlot.setStatus('current')
juniRedundancyHistoryPrevActiveRelease = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1, 3, 3, 1, 5), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: juniRedundancyHistoryPrevActiveRelease.setStatus('current')
juniRedundancyHistoryCurrActiveSlot = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1, 3, 3, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: juniRedundancyHistoryCurrActiveSlot.setStatus('current')
juniRedundancyHistoryCurrActiveRelease = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1, 3, 3, 1, 7), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: juniRedundancyHistoryCurrActiveRelease.setStatus('current')
juniRedundancyHistoryResetReason = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1, 3, 3, 1, 8), JuniRedundancyResetReason()).setMaxAccess("readonly")
if mibBuilder.loadTexts: juniRedundancyHistoryResetReason.setStatus('current')
juniRedundancyHistoryActivationTime = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1, 3, 3, 1, 9), DateAndTime()).setMaxAccess("readonly")
if mibBuilder.loadTexts: juniRedundancyHistoryActivationTime.setStatus('current')
juniRedundancyHistoryReloads = MibScalar((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1, 3, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: juniRedundancyHistoryReloads.setStatus('current')
juniRedundancyHistoryColdSwitchovers = MibScalar((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1, 3, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: juniRedundancyHistoryColdSwitchovers.setStatus('current')
juniRedundancyHistoryWarmSwitchovers = MibScalar((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 1, 3, 6), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: juniRedundancyHistoryWarmSwitchovers.setStatus('current')
juniRedundancyColdSwitchoverNotification = NotificationType((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 0, 1)).setObjects(("Juniper-REDUNDANCY-MIB", "juniRedundancyActiveSlot"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyLastResetReason"))
if mibBuilder.loadTexts: juniRedundancyColdSwitchoverNotification.setStatus('current')
juniRedundancyWarmSwitchoverNotification = NotificationType((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 0, 2)).setObjects(("Juniper-REDUNDANCY-MIB", "juniRedundancyActiveSlot"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyLastResetReason"))
if mibBuilder.loadTexts: juniRedundancyWarmSwitchoverNotification.setStatus('current')
juniRedundancyStateEnabledNotification = NotificationType((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 0, 3)).setObjects(("Juniper-REDUNDANCY-MIB", "juniRedundancyActiveSlot"))
if mibBuilder.loadTexts: juniRedundancyStateEnabledNotification.setStatus('current')
juniRedundancyStateDisabledNotification = NotificationType((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 0, 4)).setObjects(("Juniper-REDUNDANCY-MIB", "juniRedundancyActiveSlot"))
if mibBuilder.loadTexts: juniRedundancyStateDisabledNotification.setStatus('current')
juniRedundancyStatePendingNotification = NotificationType((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 0, 5)).setObjects(("Juniper-REDUNDANCY-MIB", "juniRedundancyActiveSlot"))
if mibBuilder.loadTexts: juniRedundancyStatePendingNotification.setStatus('current')
juniRedundancyModeNotification = NotificationType((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 0, 6)).setObjects(("Juniper-REDUNDANCY-MIB", "juniRedundancyActiveSlot"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyCfgRedundancyMode"))
if mibBuilder.loadTexts: juniRedundancyModeNotification.setStatus('current')
juniRedundancyMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 2, 1))
juniRedundancyMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 2, 2))
juniRedundancyMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 2, 1, 1)).setObjects(("Juniper-REDUNDANCY-MIB", "juniRedundancyStatusGroup"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyCfgGroup"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyHistoryGroup"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyNotificationGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniRedundancyMIBCompliance = juniRedundancyMIBCompliance.setStatus('current')
juniRedundancyStatusGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 2, 2, 1)).setObjects(("Juniper-REDUNDANCY-MIB", "juniRedundancyActiveSlot"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyActiveSlotState"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyStandbySlot"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyStandbySlotState"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyLastResetReason"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyLastSystemActivationTime"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyLastSystemActivationType"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyHaActiveTime"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniRedundancyStatusGroup = juniRedundancyStatusGroup.setStatus('current')
juniRedundancyCfgGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 2, 2, 2)).setObjects(("Juniper-REDUNDANCY-MIB", "juniRedundancyNotifsEnabled"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyCfgRedundancyMode"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniRedundancyCfgGroup = juniRedundancyCfgGroup.setStatus('current')
juniRedundancyHistoryGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 2, 2, 3)).setObjects(("Juniper-REDUNDANCY-MIB", "juniRedundancySystemActivationHistoryTableMaxLength"), ("Juniper-REDUNDANCY-MIB", "juniRedundancySystemActivationHistoryCommand"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyHistoryResetType"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyHistoryActivationType"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyHistoryPrevActiveSlot"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyHistoryPrevActiveRelease"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyHistoryCurrActiveSlot"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyHistoryCurrActiveRelease"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyHistoryResetReason"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyHistoryActivationTime"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyHistoryReloads"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyHistoryColdSwitchovers"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyHistoryWarmSwitchovers"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniRedundancyHistoryGroup = juniRedundancyHistoryGroup.setStatus('current')
juniRedundancyNotificationGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 4874, 2, 2, 74, 2, 2, 4)).setObjects(("Juniper-REDUNDANCY-MIB", "juniRedundancyColdSwitchoverNotification"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyWarmSwitchoverNotification"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyStateEnabledNotification"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyStateDisabledNotification"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyStatePendingNotification"), ("Juniper-REDUNDANCY-MIB", "juniRedundancyModeNotification"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
juniRedundancyNotificationGroup = juniRedundancyNotificationGroup.setStatus('current')
mibBuilder.exportSymbols("Juniper-REDUNDANCY-MIB", juniRedundancyStatusGroup=juniRedundancyStatusGroup, juniRedundancyHistoryGroup=juniRedundancyHistoryGroup, JuniRedundancyHistoryCommand=JuniRedundancyHistoryCommand, juniRedundancyStatePendingNotification=juniRedundancyStatePendingNotification, juniRedundancySystemActivationHistoryCommand=juniRedundancySystemActivationHistoryCommand, juniRedundancyStateEnabledNotification=juniRedundancyStateEnabledNotification, juniRedundancySystemActivationHistoryIndex=juniRedundancySystemActivationHistoryIndex, PYSNMP_MODULE_ID=juniRedundancyMIB, juniRedundancyMIBCompliance=juniRedundancyMIBCompliance, JuniRedundancyState=JuniRedundancyState, juniRedundancyStateDisabledNotification=juniRedundancyStateDisabledNotification, juniRedundancyMIBConformance=juniRedundancyMIBConformance, juniRedundancyNotifsEnabled=juniRedundancyNotifsEnabled, juniRedundancySystemActivationHistoryTable=juniRedundancySystemActivationHistoryTable, juniRedundancyCfgGroup=juniRedundancyCfgGroup, juniRedundancyModeNotification=juniRedundancyModeNotification, juniRedundancyCfg=juniRedundancyCfg, juniRedundancyHistoryColdSwitchovers=juniRedundancyHistoryColdSwitchovers, juniRedundancyLastSystemActivationTime=juniRedundancyLastSystemActivationTime, juniRedundancyColdSwitchoverNotification=juniRedundancyColdSwitchoverNotification, juniRedundancyActiveSlotState=juniRedundancyActiveSlotState, juniRedundancyHistoryActivationType=juniRedundancyHistoryActivationType, JuniRedundancyMode=JuniRedundancyMode, juniRedundancyHistoryCurrActiveRelease=juniRedundancyHistoryCurrActiveRelease, juniRedundancyHistoryPrevActiveSlot=juniRedundancyHistoryPrevActiveSlot, juniRedundancyStatus=juniRedundancyStatus, juniRedundancyHistoryResetType=juniRedundancyHistoryResetType, juniRedundancyNotificationGroup=juniRedundancyNotificationGroup, juniRedundancyHistoryReloads=juniRedundancyHistoryReloads, juniRedundancyNotifications=juniRedundancyNotifications, juniRedundancyObjects=juniRedundancyObjects, juniRedundancyMIB=juniRedundancyMIB, juniRedundancyHistory=juniRedundancyHistory, juniRedundancySystemActivationHistoryEntry=juniRedundancySystemActivationHistoryEntry, JuniRedundancyResetReason=JuniRedundancyResetReason, juniRedundancyCfgRedundancyMode=juniRedundancyCfgRedundancyMode, juniRedundancySystemActivationHistoryTableMaxLength=juniRedundancySystemActivationHistoryTableMaxLength, juniRedundancyHistoryWarmSwitchovers=juniRedundancyHistoryWarmSwitchovers, juniRedundancyLastResetReason=juniRedundancyLastResetReason, juniRedundancyStandbySlot=juniRedundancyStandbySlot, juniRedundancyHistoryResetReason=juniRedundancyHistoryResetReason, juniRedundancyMIBGroups=juniRedundancyMIBGroups, JuniRedundancyResetType=JuniRedundancyResetType, juniRedundancyMIBCompliances=juniRedundancyMIBCompliances, JuniRedundancySystemActivationType=JuniRedundancySystemActivationType, juniRedundancyHistoryCurrActiveSlot=juniRedundancyHistoryCurrActiveSlot, juniRedundancyHaActiveTime=juniRedundancyHaActiveTime, juniRedundancyHistoryPrevActiveRelease=juniRedundancyHistoryPrevActiveRelease, juniRedundancyHistoryActivationTime=juniRedundancyHistoryActivationTime, juniRedundancyWarmSwitchoverNotification=juniRedundancyWarmSwitchoverNotification, juniRedundancyLastSystemActivationType=juniRedundancyLastSystemActivationType, juniRedundancyStandbySlotState=juniRedundancyStandbySlotState, juniRedundancyActiveSlot=juniRedundancyActiveSlot)
|
# -*- coding: utf-8 -*-
# AtCoder Beginner Contest
if __name__ == '__main__':
n = int(input())
if n == 100:
print('Perfect')
elif 90 <= n <= 99:
print('Great')
elif 60 <= n <= 89:
print('Good')
else:
print('Bad')
|
n = int(input('DIGITE UM NÚMERO INTEIRO '))
suc = n+1
ant = n-1
print ('O SUCESSOR É {}\nE O ANTECESSOR É {}'.format(suc,ant))
|
# -*- coding: utf-8 -*-
"""
collection
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
class StatusEnum(object):
"""Implementation of the 'Status' enum.
TODO: type enum description here.
Attributes:
PENDING: TODO: type description here.
SUCCESSFUL: TODO: type description here.
FAILED: TODO: type description here.
"""
PENDING = 'PENDING'
SUCCESSFUL = 'SUCCESSFUL'
FAILED = 'FAILED'
|
"""
The complete list of SCF level wavefunction quantities.
"""
scf_wavefunction = {}
# Orbitals
scf_wavefunction["scf_orbitals_a"] = {
"type": "array",
"description": "SCF alpha-spin orbitals in the AO basis.",
"items": {"type": "number"},
"shape": {"nao", "nmo"}
}
scf_wavefunction["scf_orbitals_b"] = {
"type": "array",
"description": "SCF beta-spin orbitals in the AO basis.",
"items": {"type": "number"},
"shape": {"nao", "nmo"}
}
# Density
scf_wavefunction["scf_density_a"] = {
"type": "array",
"description": "SCF alpha-spin density in the AO basis.",
"items": {"type": "number"},
"shape": {"nao", "nao"}
}
scf_wavefunction["scf_density_b"] = {
"type": "array",
"description": "SCF beta-spin density in the AO basis.",
"items": {"type": "number"},
"shape": {"nao", "nao"}
}
# Fock matrix
scf_wavefunction["scf_fock_a"] = {
"type": "array",
"description": "SCF alpha-spin Fock matrix in the AO basis.",
"items": {"type": "number"},
"shape": {"nao", "nao"}
}
scf_wavefunction["scf_fock_b"] = {
"type": "array",
"description": "SCF beta-spin Fock matrix in the AO basis.",
"items": {"type": "number"},
"shape": {"nao", "nao"}
}
scf_wavefunction["scf_coulomb_a"] = {
"type": "array",
"description": "SCF alpha-spin Coulomb matrix in the AO basis.",
"items": {"type": "number"},
"shape": {"nao", "nao"}
}
scf_wavefunction["scf_coulomb_b"] = {
"type": "array",
"description": "SCF beta-spin Coulomb matrix in the AO basis.",
"items": {"type": "number"},
"shape": {"nao", "nao"}
}
scf_wavefunction["scf_exchange_a"] = {
"type": "array",
"description": "SCF alpha-spin exchange matrix in the AO basis.",
"items": {"type": "number"},
"shape": {"nao", "nao"}
}
scf_wavefunction["scf_exchange_b"] = {
"type": "array",
"description": "SCF beta-spin exchange matrix in the AO basis.",
"items": {"type": "number"},
"shape": {"nao", "nao"}
}
# Eigenvalues
scf_wavefunction["scf_eigenvalues_a"] = {
"type": "array",
"description": "SCF alpha-spin orbital eigenvalues.",
"items": {"type": "number"},
"shape": {"nmo"}
}
scf_wavefunction["scf_eigenvalues_b"] = {
"type": "array",
"description": "SCF beta-spin orbital eigenvalues.",
"items": {"type": "number"},
"shape": {"nmo"}
}
# Occupations
scf_wavefunction["scf_occupations_a"] = {
"type": "array",
"description": "SCF alpha-spin orbital occupations.",
"items": {"type": "number"},
"shape": {"nmo"}
}
scf_wavefunction["scf_occupations_b"] = {
"type": "array",
"description": "SCF beta-spin orbital occupations.",
"items": {"type": "number"},
"shape": {"nmo"}
}
|
# coding=utf-8
"""Utility functions"""
class Utils(object):
"""Utility functions"""
@staticmethod
def combine_dicts(dict_1, dict_2):
"""Creates a new dictionary which is the union of two dictionaries with
a shallow copy of the elements"""
combined = {}
for key, value in (dict_1 or {}).items():
combined[key] = value
for key, value in (dict_2 or {}).items():
combined[key] = value
return combined
@staticmethod
def optional_params(params):
"""Creates a new dictionary by making a shallow copy of an existing
dictionary, but exclude entries from the final dictionary if their
value is None"""
optional_params = {}
for key, value in params.items():
if value is not None:
optional_params[key] = value
return optional_params
|
MCTS_CONFIG = {
"c_puct": 5.0,
"c_iterations": 400,
}
DATA_CONFIG = {
# one of "random", "botzone", "mcts", "alpha_zero"
"schedule": {
"supervisor": ("traditional_mcts", {
"c_puct": MCTS_CONFIG["c_puct"],
"c_iterations": 20000
}),
"candidates": [
("random_mcts", MCTS_CONFIG),
("rave_mcts", MCTS_CONFIG),
("botzone", {"program": "deeeeep"}),
("botzone", {"program": "genm"}),
None
]
},
"process_num": 2,
"buffer_size": 10000,
"data_path": "./data/training_data",
"data_files": [
# after read out,
# file name will be marked ".consumed"
]
}
TRAINING_CONFIG = {
"num_epoches": 5,
"batch_size": 512,
"learning_rate": 2e-3,
"momentum": 0.9,
"kl_target": 0.02,
"eval_period": 100,
"eval_rounds": 11,
"model_file": "latest",
"model_path": "./data/trained_models"
}
|
# Copyright 2017 The Forseti Security Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Util Errors module."""
class Error(Exception):
"""Base error class for the module."""
class EmailSendError(Error):
"""Unable to send email."""
pass
class InvalidFileExtensionError(Error):
"""No parser exists for the given file extension."""
pass
class InvalidParserTypeError(Error):
"""No parser exists for the given parser type."""
pass
class MetadataServerHttpError(Error):
"""An error for handling HTTP errors with the metadata server."""
pass
|
# https://www.interviewbit.com/problems/mathbug01/
# MATH_BUG01
class Solution:
# @param A : integer
# @return an integer
def isPrime(self,A):
upperLimit = int(A**0.5)
for i in range(2, upperLimit + 1):
if i < A and A % i == 0:
return 0
return 1
|
n=7
mid=(n+1)/2
for i in range(1,n+1):
for j in range(1,n+1):
condition= i + j>=mid + 1 and i + j<=mid + n and i-j<=mid-1 and j-i<=mid-1 and j<=mid
if condition:
print("0",end="")
else:
print(" ",end="")
print() |
# Calculadora em Python
# Desenvolva uma calculadora em Python com tudo que você aprendeu nos capítulos 2 e 3.
# A solução será apresentada no próximo capítulo!
# Assista o vídeo com a execução do programa!
print("\n******************* Python Calculator *******************")
print("\nObserve as operações matemáticas a seguir:")
#Solicitar operação matemática do usuário.
print("\n1- Adição;")
print("\n2- Subtração;")
print("\n3- Multiplicação;")
print("\n4- Divisão;")
op = int(input("\nDigite a função desejada: "))
#Definir valores válidos para as operações matemáticas econstrução da calculadora.
if(op == 1 or op == 2 or op == 3 or op == 4):
#Primeira operação válida.
if(op == 1):
print(" --- Adição ---")
a1 = float(input("Informe a primeira variável: "))
a2 = float(input("Informe a segunda variável: "))
soma = a1 + a2
print( a1, " + ", a2, " = ", soma)
#Segunda operação válida.
elif(op == 2):
print(" --- Subtração ---")
s1 = float(input("Informe a primeira variável: "))
s2 = float(input("Informe a segunda variável: "))
sub = s1 - s2
print( s1, " - ", s2, " = ", sub)
#Terceira operação válida.
elif(op == 3):
print(" --- Multiplicação ---")
m1 = float(input("Informe a primeira variável: "))
m2 = float(input("Informe a segunda variável: "))
mult = m1 * m2
print(m1, " * ", m2, " = ", mult)
#Quarta operação válida.
elif(op == 4):
print(" --- Divisão ---")
d1 = float(input("Informe a primeira variável: "))
d2 = float(input("Informe a segunda variável: "))
div = d1 / d2
print( d1, " / ", d2, " = ", div)
#Caso a entrada não seja identificada, informar:
else:
print("\nOperação inválida!") |
_base_ = [
'../../_base_/models/vgg19bn.py',
'./dataset.py',
'./schedule.py',
'./default_runtime.py',
]
model = dict(
backbone=dict(
num_classes=20,
)
)
|
print('\033[1;32mBANCO DE DADOS\033[m')
lista = list()
dados = list()
quantidade = maior_peso = menor_peso = 0
while True:
print('-=' * 30)
dados.append(str(input('Digite o nome: ')))
dados.append(float(input('Digite o peso: ')))
if len(lista) == 0:
maior_peso = menor_peso = dados[1]
else:
if dados[1] > maior_peso:
maior_peso = dados[1]
if dados[1] < menor_peso:
menor_peso = dados[1]
quantidade += 1
lista.append(dados[:])
dados.clear()
escolha = str(input('Quer continuar [S/N]: ')).upper().strip()[0]
if escolha == 'N':
break
while escolha not in 'SN':
print('Escolha inválida.')
escolha = str(input('Quer continuar [S/N]: ')).upper().strip()[0]
print('-=' * 30)
print(f'Foram cadastradas: {quantidade} pessoas.')
print(f'As pessoas mais pesadas tiveram {maior_peso}KG e elas foram:')
for cont in lista:
if cont[1] == maior_peso:
print(f'{cont[0]}', end='...')
print(f'\nAs pessoas mais leves tiveram {menor_peso}KG e elas foram:')
for cont in lista:
if cont[1] == menor_peso:
print(f'{cont[0]}', end='...') |
def load(h):
return ({'abbr': 0, 'code': 0, 'title': 'Wave spectra (1)', 'units': '-'},
{'abbr': 1, 'code': 1, 'title': 'Wave spectra (2)', 'units': '-'},
{'abbr': 2, 'code': 2, 'title': 'Wave spectra (3)', 'units': '-'},
{'abbr': 3,
'code': 3,
'title': 'Significant height of combined wind waves and swell',
'units': 'm'},
{'abbr': 4,
'code': 4,
'title': 'Direction of wind waves',
'units': 'degree true'},
{'abbr': 5,
'code': 5,
'title': 'Significant height of wind waves',
'units': 'm'},
{'abbr': 6, 'code': 6, 'title': 'Mean period of wind waves', 'units': 's'},
{'abbr': 7,
'code': 7,
'title': 'Direction of swell waves',
'units': 'degree true'},
{'abbr': 8,
'code': 8,
'title': 'Significant height of swell waves',
'units': 'm'},
{'abbr': 9, 'code': 9, 'title': 'Mean period of swell waves', 'units': 's'},
{'abbr': 10,
'code': 10,
'title': 'Primary wave direction',
'units': 'degree true'},
{'abbr': 11, 'code': 11, 'title': 'Primary wave mean period', 'units': 's'},
{'abbr': 12,
'code': 12,
'title': 'Secondary wave direction',
'units': 'degree true'},
{'abbr': 13, 'code': 13, 'title': 'Secondary wave mean period', 'units': 's'},
{'abbr': 14,
'code': 14,
'title': 'Direction of combined wind waves and swell',
'units': 'degree true'},
{'abbr': 15,
'code': 15,
'title': 'Mean period of combined wind waves and swell',
'units': 's'},
{'abbr': 16,
'code': 16,
'title': 'Coefficient of drag with waves',
'units': '-'},
{'abbr': 17, 'code': 17, 'title': 'Friction velocity', 'units': 'm/s'},
{'abbr': 18, 'code': 18, 'title': 'Wave stress', 'units': 'N m-2'},
{'abbr': 19, 'code': 19, 'title': 'Normalized wave stress', 'units': '-'},
{'abbr': 20, 'code': 20, 'title': 'Mean square slope of waves', 'units': '-'},
{'abbr': 21,
'code': 21,
'title': 'u-component surface Stokes drift',
'units': 'm/s'},
{'abbr': 22,
'code': 22,
'title': 'v-component surface Stokes drift',
'units': 'm/s'},
{'abbr': 23,
'code': 23,
'title': 'Period of maximum individual wave height',
'units': 's'},
{'abbr': 24,
'code': 24,
'title': 'Maximum individual wave height',
'units': 'm'},
{'abbr': 25, 'code': 25, 'title': 'Inverse mean wave frequency', 'units': 's'},
{'abbr': 26,
'code': 26,
'title': 'Inverse mean frequency of wind waves',
'units': 's'},
{'abbr': 27,
'code': 27,
'title': 'Inverse mean frequency of total swell',
'units': 's'},
{'abbr': 28,
'code': 28,
'title': 'Mean zero-crossing wave period',
'units': 's'},
{'abbr': 29,
'code': 29,
'title': 'Mean zero-crossing period of wind waves',
'units': 's'},
{'abbr': 30,
'code': 30,
'title': 'Mean zero-crossing period of total swell',
'units': 's'},
{'abbr': 31, 'code': 31, 'title': 'Wave directional width', 'units': '-'},
{'abbr': 32,
'code': 32,
'title': 'Directional width of wind waves',
'units': '-'},
{'abbr': 33,
'code': 33,
'title': 'Directional width of total swell',
'units': '-'},
{'abbr': 34, 'code': 34, 'title': 'Peak wave period', 'units': 's'},
{'abbr': 35, 'code': 35, 'title': 'Peak period of wind waves', 'units': 's'},
{'abbr': 36, 'code': 36, 'title': 'Peak period of total swell', 'units': 's'},
{'abbr': 37, 'code': 37, 'title': 'Altimeter wave height', 'units': 'm'},
{'abbr': 38,
'code': 38,
'title': 'Altimeter corrected wave height',
'units': 'm'},
{'abbr': 39,
'code': 39,
'title': 'Altimeter range relative correction',
'units': '-'},
{'abbr': 40,
'code': 40,
'title': '10-metre neutral wind speed over waves',
'units': 'm/s'},
{'abbr': 41,
'code': 41,
'title': '10-metre wind direction over waves',
'units': 'deg'},
{'abbr': 42,
'code': 42,
'title': 'Wave energy spectrum',
'units': 'm2 s rad-1'},
{'abbr': 43,
'code': 43,
'title': 'Kurtosis of the sea-surface elevation due to waves',
'units': '-'},
{'abbr': 44, 'code': 44, 'title': 'Benjamin-Feir index', 'units': '-'},
{'abbr': 45, 'code': 45, 'title': 'Spectral peakedness factor', 'units': '/s'},
{'abbr': 46, 'code': 46, 'title': 'Peak wave direction', 'units': 'deg'},
{'abbr': 47,
'code': 47,
'title': 'Significant wave height of first swell partition',
'units': 'm'},
{'abbr': 48,
'code': 48,
'title': 'Significant wave height of second swell partition',
'units': 'm'},
{'abbr': 49,
'code': 49,
'title': 'Significant wave height of third swell partition',
'units': 'm'},
{'abbr': 50,
'code': 50,
'title': 'Mean wave period of first swell partition',
'units': 's'},
{'abbr': 51,
'code': 51,
'title': 'Mean wave period of second swell partition',
'units': 's'},
{'abbr': 52,
'code': 52,
'title': 'Mean wave period of third swell partition',
'units': 's'},
{'abbr': 53,
'code': 53,
'title': 'Mean wave direction of first swell partition',
'units': 'deg'},
{'abbr': 54,
'code': 54,
'title': 'Mean wave direction of second swell partition',
'units': 'deg'},
{'abbr': 55,
'code': 55,
'title': 'Mean wave direction of third swell partition',
'units': 'deg'},
{'abbr': 56,
'code': 56,
'title': 'Wave directional width of first swell partition',
'units': '-'},
{'abbr': 57,
'code': 57,
'title': 'Wave directional width of second swell partition',
'units': '-'},
{'abbr': 58,
'code': 58,
'title': 'Wave directional width of third swell partition',
'units': '-'},
{'abbr': 59,
'code': 59,
'title': 'Wave frequency width of first swell partition',
'units': '-'},
{'abbr': 60,
'code': 60,
'title': 'Wave frequency width of second swell partition',
'units': '-'},
{'abbr': 61,
'code': 61,
'title': 'Wave frequency width of third swell partition',
'units': '-'},
{'abbr': 62, 'code': 62, 'title': 'Wave frequency width', 'units': '-'},
{'abbr': 63,
'code': 63,
'title': 'Frequency width of wind waves',
'units': '-'},
{'abbr': 64,
'code': 64,
'title': 'Frequency width of total swell',
'units': '-'},
{'abbr': None, 'code': 255, 'title': 'Missing'})
|
#SOLUTION FOR P32
'''P32 (**) Determine the greatest common divisor of two positive integer numbers.
Use Euclid's algorithm.
Example:
* (gcd 36 63)
9'''
num1 = int(input('enter first number = '))
num2 = int(input('enter second number = '))
#CREATE A FUNCTION TO CALCULATE GCD
def find_gcd(n1,n2):
while n2!=0: #BASE CASE IS - gcd(a,0) = a ; SO CHECK TILL N2 IS NOT ZERO
n1,n2= n2,n1%n2 #ACCORDING TO ALGORITH gcd(a,b)=gcd(b,r) where r=a%b
find_gcd(n1,n2) #CONTINUE TO CALCULATE GCD FOR NEW N1 AND N2
return n1 #WHEN BASE CASE SATISFIES, RETURN N1
res= find_gcd(num1,num2) #CALL THE FUNCTION AND PASS TWO NUMBERS
print(F'GCD of {num1} & {num2} = {res}') |
# enumerate
# Funções equivalentes
lista = ['Maçã', 'Abacate', 'Pera', 'Uva', 'Morango']
for i in range(len(lista)):
print(i, lista[i])
for idx, nome in enumerate(lista):
print(idx, nome)
|
class Type:
def __init__(self, name, members: list = None):
self.name = name
self.members = members or ['*']
|
def calculation(command, b, c):
calculations = {
'multiply': b * c,
'divide': b / c,
'add': b + c,
'subtract': b - c,
}
return calculations[command]
operator = input()
parameter_one = int(input())
parameter_two = int(input())
print(calculation(operator, parameter_one, parameter_two))
|
# -*- coding: utf-8 -*-
__version__ = '1.1.0'
default_app_config = 'aldryn_search.apps.AldrynSearchConfig'
|
print ("Salve...Dovrebbe inserire il suo reddito per avviare lo script-calcolo delle aliquota 2015/2016")
reddito = float (input ("Digiti di seguito il suo reddito: "))
if reddito < 20000 and reddito > 0 :
aliquota2 = 2/100
print ("L'aliquota è del",aliquota2,"%")
tassa1 = (reddito * aliquota2)
print ("La tassa ammonta a:",tassa1)
elif reddito > 2001 and reddito < 50000 and reddito != 0 :
aliquota5 = 5/100
print ("L'aliquota è del",aliquota5,"%")
tassa2 = (reddito * aliquota5)
print ("La tassa ammonta a:",tassa2)
elif reddito > 50000 and reddito < 1000000000 :
aliquota9 = 9/100
print ("L'aliquota è del",aliquota9,"%")
tassa3 = (reddito * aliquota9)
print ("La tassa ammonta a:",tassa3)
elif reddito > 1000000000 :
print ("E chi ssi...Bill Gates !?")
else:
print ("Povero...")
|
"""
File: largest_digit.py
Name: Rebecca
----------------------------------
This file recursively prints the biggest digit in
5 different integers, 12345, 281, 6, -111, -9453
If your implementation is correct, you should see
5, 8, 6, 1, 9 on Console.
"""
def main():
print(find_largest_digit(12345)) # 5
print(find_largest_digit(281)) # 8
print(find_largest_digit(6)) # 6
print(find_largest_digit(-111)) # 1
print(find_largest_digit(-9453)) # 9
def find_largest_digit(n):
return find_largest_digit_helper(n, 0)
def find_largest_digit_helper(n, largest_num):
"""
:param n: integer
:param largest_num: first data
:return largest_num: the biggest digit in integer
"""
n = abs(n)
a = n % 10
if n / 10 == 0 and n % 10 == 0:
return largest_num
else:
if a > largest_num:
largest_num = a
return find_largest_digit_helper(n//10, largest_num)
if __name__ == '__main__':
main()
|
class Node:
pass
class Void(Node):
def __init__(self):
self.computedType = 'Void'
class ProgramNode(Node):
def __init__(self, classList):
self.classList = classList
class ExpressionNode(Node):
pass
class Arithmetic(ExpressionNode):
def __init__(self, left, right):
self.left = left
self.right = right
class Assignment(ExpressionNode): #llrga la variable en id
def __init__(self, asid, expr):
self.id = asid
self.expr = expr
class Conditional(ExpressionNode):
def __init__(self, ifexpr, thenexpr,elseexpr):
self.ifexpr = ifexpr
self.thenexpr = thenexpr
self.elseexpr = elseexpr
class Loop(ExpressionNode):
def __init__(self, whileexpr, loopexpr):
self.whileexpr = whileexpr
self.loopexpr = loopexpr
class Block(ExpressionNode):
def __init__(self, exprlist):
self.exprlist = exprlist
class Compare(ExpressionNode):
def __init__(self, left, right):
self.left = left
self.right = right
class Equal(Compare):
# def __init__(self, left, right):
# self.left = left
# self.right = right
pass
class CompareNotEqual(Compare):
pass
class LessThan(CompareNotEqual):
pass
class LessEqualThan(CompareNotEqual):
pass
class PlusNode(Arithmetic):
# def __init__(self, left, right):
# Arithmetic.__init__(self, left, right)
pass
class MinusNode(Arithmetic):
pass
class StarNode(Arithmetic):
pass
class DivNode(Arithmetic):
pass
class IsVoid(ExpressionNode):
def __init__(self, expr):
self.expr = expr
class New(ExpressionNode):
def __init__(self, newType):
self.newType = newType
class Not(ExpressionNode):
def __init__(self,expr):
self.expr = expr
class Neg(ExpressionNode):
def __init__(self, expr):
self.expr = expr
class Let(ExpressionNode):
def __init__(self, letAttrList,body):
self.letAttrList = letAttrList
self.body = body
# class LetAttr_Init(ExpressionNode):
# def __init__(self, name_AttrType, expr):
# self.name = name_AttrType[0]
# self.attrType = name_AttrType[1]
# self.expr = expr
# class LetAttr_Declaration(ExpressionNode):
# def __init__(self, name_attrType):
# self.name = name_attrType[0]
# self.attrType = name_attrType[1]
class Declaration(ExpressionNode):
def __init__(self, attrName, attrType, expr):
self.attrName = attrName
self.attrType = attrType
self.expr = expr
class DeclarationWithInitialization(Declaration):
def __init__(self, decl_only, expr):
super(DeclarationWithInitialization,self).__init__(decl_only.attrName,decl_only.attrType,expr)
# self.expr = expr
class DeclarationOnly(Declaration):
def __init__(self, name_attrType):
thetype = name_attrType[1]
default = Void()
if thetype == "Bool":
default = Ctes(False,"Bool")
elif thetype == "Int":
default = Ctes(0,"Int")
elif thetype == "String":
default = Ctes("","String")
super(DeclarationOnly,self).__init__(name_attrType[0],name_attrType[1],default)
class Case(ExpressionNode):
def __init__(self, case0,exprList):
self.case0 = case0
self.exprList = exprList
class CaseExpr(ExpressionNode):
def __init__(self, decl,expr):
self.decl = decl # tupla name,type
self.expr = expr
class CoolClass(ExpressionNode):
def __init__(self, name,parent,attrs,methods):
self.name = name
# self.expr = expr
self.attrs = attrs
self.methods = methods
self.parent = parent
class ClassDecl(CoolClass):
def __init__(self, name,attrs,methods):
super(ClassDecl,self).__init__(name,"Object",attrs,methods)
# self.name = name
# # self.expr = expr
# self.attrs = attrs
# self.methods = methods
class ClassInh(CoolClass):
pass
# def __init__(self, name,parent,methods,attrs):
# self.name = name
# # self.expr = expr
# self.attrs = attrs
# self.methods = methods
# self.parent = parent
class Method(ExpressionNode):
def __init__(self, name, paramsList, returnType, exprbody):
self.name = name
self.returnType = returnType
self.paramsList = paramsList
self.exprbody = exprbody
class DispatchSelf(ExpressionNode):
def __init__(self, methodName, paramsList):
self.methodName = methodName
self.paramsList = paramsList
class DispatchDot(ExpressionNode):
def __init__(self, expr0, methodName, paramsList):
self.expr0 = expr0
self.methodName = methodName
self.paramsList = paramsList
class StaticDispatch(ExpressionNode):
def __init__(self, dispObject, className,methodName,paramsList):
self.dispObject = dispObject
self.className = className
self.methodName = methodName
self.paramsList = paramsList
class Attribute(ExpressionNode):
def __init__(self, name_attrType,expr):
self.attrName = name_attrType.attrName
self.attrType = name_attrType.attrType
self.expr = expr
class Attr_Init(Attribute):
def __init__(self, name_attrType, expr):
super(Attr_Init,self).__init__(name_attrType,expr)
class Attr_Declaration(Attribute):
def __init__(self, name_attrType):
super(Attr_Declaration,self).__init__(name_attrType,name_attrType.expr)
class Ctes(ExpressionNode):
def __init__(self, value,ctetype):
self.value = value
self.type = ctetype
class Variable(ExpressionNode):
def __init__(self, name):
self.name = name
|
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
_RCLONE_VERSION="v1.50.0"
def _add_rclone_build(platform, architecture, sha256=None):
rule_name = "rclone_{platform}_{arch}".format(platform=platform, arch=architecture)
if not native.existing_rule(rule_name):
package_name = "rclone-{version}-{platform}-{arch}".format(version=_RCLONE_VERSION, platform=platform, arch=architecture)
http_archive(
name = rule_name,
strip_prefix = package_name,
urls = ["https://downloads.rclone.org/{version}/{package}.zip".format(version=_RCLONE_VERSION, package=package_name)],
build_file_content = """exports_files(glob(["**"]))""",
sha256 = sha256,
)
def rclone_binaries():
_add_rclone_build(
platform = "linux",
architecture = "amd64",
sha256 = "3eb57540b5846f5812500243c37a34ef4bc90d608760e29f57cb82fef0a93f82",
)
_add_rclone_build(
platform = "linux",
architecture = "386",
sha256 = "ba48abc1cfa528da347d66bef9a490a0e398dcd1c77fca13368c3a106f481176",
)
_add_rclone_build(
platform = "osx",
architecture = "amd64",
sha256 = "15b399f923e7f16311263581cffdf9d49a1f1ff48ba8929637f2c555dc2541d3",
)
_add_rclone_build(
platform = "osx",
architecture = "386",
sha256 = "f84dfeeabfd32aac4e8cbe0d230cd50ed70c2e8770770e429ed43f6f78aa52c0",
)
|
# 141, Суптеля Владислав
# 【Дата】:「09.03.20」
# 7. Написати рекурсивну функцію, що визначає, чи є симетричною частина рядка S, починаючи з i-го елемента і закінчуючи j-м.
def simline(S, i, j):
if (i == j or j-1 == i): # парное или непарное кол-во элементов
return 1 # тру
if S[i] == S[j]:
return simline(S, i+1, j-1) # с каждой итерацией сдвигаемся на элемент вправо с левой и в лево с правой (к центру)
return 0
S = input("「Введите строку」: ")
i = int(input("「Введите начало среза」: "))-1 # вводим от 1, а читается эл с 0-вым индексом
j = int(input("「Введите конец среза」: "))-1 # аналогично
if simline(S, i, j):
print("Срез симметричен.")
else:
print("Срез не симметричен.")
|
reddit = dict(
client_id="",
client_secret="",
username="",
password="",
user_agent="Daltonism Helper Bot (created by /u/OffDutyHuman)")
imgur = dict(
client_id="",
client_secret="",
access_token="",
refresh_token="")
|
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 10 14:55:16 2016
@author: Stuart
"""
version = "0.8.0"
|
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = ''.join(ch.lower() for ch in s if ch.isalnum())
half = len(s) // 2
return not half or s[:half] == s[-half:][::-1] |
"""Madoop Exception Types.
Andrew DeOrio <awdeorio@umich.edu>
"""
class MadoopError(Exception):
"""Top level exception raised by Madoop functions."""
|
class TestConfig:
def test_config(self, config):
pass
|
COLOR_PALETTES = {
"lisk": {
"bg0": "#FEF1E2",
"bg1": "#FEDBAB",
"bg2": "#FEC478",
"fg0": "#FE9923",
"fg1": "#FE8821",
"fg2": "#E5741A",
"text0": "#827F85",
"text1": "#57555C",
"text2": "#3C3A41",
"accent0": "#21D8FF",
"accent1": "#185B66",
"gray0": "#DCC09B",
"gray1": "#9E8E7D",
"warning": "#FF3D14",
"error": "#FF0000",
},
"solarized": {
"bg0": "#FDF6E3",
"bg1": "#EEE8D5",
"bg2": "#DBD3BB",
"fg0": "#C2BBA5",
"fg1": "#A8A28F",
"fg2": "#8F8979",
"text0": "#586E75",
"text1": "#073642",
"text2": "#002B36",
"accent0": "#268BD2",
"accent1": "#2AA198",
"gray0": "#93A1A1",
"gray1": "#657B83",
"warning": "#CB4B16",
"error": "#DC322F",
},
}
COLOR_PALETTES["default"] = COLOR_PALETTES.get("lisk")
|
""" OneGov uses a very simple permissions model by default. There are no
read/write permissions, just intents. That means a permission shows the
intended audience.
This is the default however, any application building on top of onegov.core
may of course introduce its own byzantine permission system.
"""
class Public(object):
""" The general public is allowed to do this. """
class Private(object):
""" Trusted people are allowed to do this. """
class Personal(object):
""" Registered members are allowed to do this. """
class Secret(object):
""" Only Demi-Gods are allowed to do this. """
|
# author: Zhongyuan Sun
# Storing the loop numbers will help improving performance from 0.63% to 93.93%
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
if n <= 0:
return False
x = self.cal(n)
# loop_numbers = self.all_loop_numbers()
loop_numbers = [2, 3, 4, 5, 6, 8, 9,
11, 12, 14, 15, 16, 17, 18,
20, 21, 22, 24, 25, 26, 27, 29,
30, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 45, 46, 47, 48,
50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
60, 61, 62, 63, 64, 65, 66, 67, 69,
71, 72, 73, 74, 75, 76, 77, 78,
80, 81, 83, 84, 85, 87, 88, 89,
90, 92, 93, 95, 96, 98, 99,
106, 113, 117, 128, 145, 162]
while x != 1 and x not in loop_numbers:
x = self.cal(x)
return x == 1
def cal(self, n):
res = 0
while n:
res += (n % 10) ** 2
n /= 10
return res
# return sum([int(c)**2 for c in str(n)])
def all_loop_numbers(self):
res = []
for i in range(1, 100):
tmp = [i]
next = self.cal(i)
while next not in res and next not in tmp and next != 1:
tmp.append(next)
next = self.cal(next)
if next != 1:
res += tmp
res = list(set(res))
return res
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.